gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.bcel.generic; import org.apache.bcel.Const; /** * This interface contains shareable instruction objects. * * In order to save memory you can use some instructions multiply, * since they have an immutable state and are directly derived from * Instruction. I.e. they have no instance fields that could be * changed. Since some of these instructions like ICONST_0 occur * very frequently this can save a lot of time and space. This * feature is an adaptation of the FlyWeight design pattern, we * just use an array instead of a factory. * * The Instructions can also accessed directly under their names, so * it's possible to write il.append(Instruction.ICONST_0); * * @deprecated (since 6.0) Do not use. Use InstructionConst instead. */ @Deprecated public interface InstructionConstants { /** Predefined instruction objects */ /* * NOTE these are not currently immutable, because Instruction * has mutable protected fields opcode and length. */ Instruction NOP = new NOP(); Instruction ACONST_NULL = new ACONST_NULL(); Instruction ICONST_M1 = new ICONST(-1); Instruction ICONST_0 = new ICONST(0); Instruction ICONST_1 = new ICONST(1); Instruction ICONST_2 = new ICONST(2); Instruction ICONST_3 = new ICONST(3); Instruction ICONST_4 = new ICONST(4); Instruction ICONST_5 = new ICONST(5); Instruction LCONST_0 = new LCONST(0); Instruction LCONST_1 = new LCONST(1); Instruction FCONST_0 = new FCONST(0); Instruction FCONST_1 = new FCONST(1); Instruction FCONST_2 = new FCONST(2); Instruction DCONST_0 = new DCONST(0); Instruction DCONST_1 = new DCONST(1); ArrayInstruction IALOAD = new IALOAD(); ArrayInstruction LALOAD = new LALOAD(); ArrayInstruction FALOAD = new FALOAD(); ArrayInstruction DALOAD = new DALOAD(); ArrayInstruction AALOAD = new AALOAD(); ArrayInstruction BALOAD = new BALOAD(); ArrayInstruction CALOAD = new CALOAD(); ArrayInstruction SALOAD = new SALOAD(); ArrayInstruction IASTORE = new IASTORE(); ArrayInstruction LASTORE = new LASTORE(); ArrayInstruction FASTORE = new FASTORE(); ArrayInstruction DASTORE = new DASTORE(); ArrayInstruction AASTORE = new AASTORE(); ArrayInstruction BASTORE = new BASTORE(); ArrayInstruction CASTORE = new CASTORE(); ArrayInstruction SASTORE = new SASTORE(); StackInstruction POP = new POP(); StackInstruction POP2 = new POP2(); StackInstruction DUP = new DUP(); StackInstruction DUP_X1 = new DUP_X1(); StackInstruction DUP_X2 = new DUP_X2(); StackInstruction DUP2 = new DUP2(); StackInstruction DUP2_X1 = new DUP2_X1(); StackInstruction DUP2_X2 = new DUP2_X2(); StackInstruction SWAP = new SWAP(); ArithmeticInstruction IADD = new IADD(); ArithmeticInstruction LADD = new LADD(); ArithmeticInstruction FADD = new FADD(); ArithmeticInstruction DADD = new DADD(); ArithmeticInstruction ISUB = new ISUB(); ArithmeticInstruction LSUB = new LSUB(); ArithmeticInstruction FSUB = new FSUB(); ArithmeticInstruction DSUB = new DSUB(); ArithmeticInstruction IMUL = new IMUL(); ArithmeticInstruction LMUL = new LMUL(); ArithmeticInstruction FMUL = new FMUL(); ArithmeticInstruction DMUL = new DMUL(); ArithmeticInstruction IDIV = new IDIV(); ArithmeticInstruction LDIV = new LDIV(); ArithmeticInstruction FDIV = new FDIV(); ArithmeticInstruction DDIV = new DDIV(); ArithmeticInstruction IREM = new IREM(); ArithmeticInstruction LREM = new LREM(); ArithmeticInstruction FREM = new FREM(); ArithmeticInstruction DREM = new DREM(); ArithmeticInstruction INEG = new INEG(); ArithmeticInstruction LNEG = new LNEG(); ArithmeticInstruction FNEG = new FNEG(); ArithmeticInstruction DNEG = new DNEG(); ArithmeticInstruction ISHL = new ISHL(); ArithmeticInstruction LSHL = new LSHL(); ArithmeticInstruction ISHR = new ISHR(); ArithmeticInstruction LSHR = new LSHR(); ArithmeticInstruction IUSHR = new IUSHR(); ArithmeticInstruction LUSHR = new LUSHR(); ArithmeticInstruction IAND = new IAND(); ArithmeticInstruction LAND = new LAND(); ArithmeticInstruction IOR = new IOR(); ArithmeticInstruction LOR = new LOR(); ArithmeticInstruction IXOR = new IXOR(); ArithmeticInstruction LXOR = new LXOR(); ConversionInstruction I2L = new I2L(); ConversionInstruction I2F = new I2F(); ConversionInstruction I2D = new I2D(); ConversionInstruction L2I = new L2I(); ConversionInstruction L2F = new L2F(); ConversionInstruction L2D = new L2D(); ConversionInstruction F2I = new F2I(); ConversionInstruction F2L = new F2L(); ConversionInstruction F2D = new F2D(); ConversionInstruction D2I = new D2I(); ConversionInstruction D2L = new D2L(); ConversionInstruction D2F = new D2F(); ConversionInstruction I2B = new I2B(); ConversionInstruction I2C = new I2C(); ConversionInstruction I2S = new I2S(); Instruction LCMP = new LCMP(); Instruction FCMPL = new FCMPL(); Instruction FCMPG = new FCMPG(); Instruction DCMPL = new DCMPL(); Instruction DCMPG = new DCMPG(); ReturnInstruction IRETURN = new IRETURN(); ReturnInstruction LRETURN = new LRETURN(); ReturnInstruction FRETURN = new FRETURN(); ReturnInstruction DRETURN = new DRETURN(); ReturnInstruction ARETURN = new ARETURN(); ReturnInstruction RETURN = new RETURN(); Instruction ARRAYLENGTH = new ARRAYLENGTH(); Instruction ATHROW = new ATHROW(); Instruction MONITORENTER = new MONITORENTER(); Instruction MONITOREXIT = new MONITOREXIT(); /** You can use these constants in multiple places safely, if you can guarantee * that you will never alter their internal values, e.g. call setIndex(). */ LocalVariableInstruction THIS = new ALOAD(0); LocalVariableInstruction ALOAD_0 = THIS; LocalVariableInstruction ALOAD_1 = new ALOAD(1); LocalVariableInstruction ALOAD_2 = new ALOAD(2); LocalVariableInstruction ILOAD_0 = new ILOAD(0); LocalVariableInstruction ILOAD_1 = new ILOAD(1); LocalVariableInstruction ILOAD_2 = new ILOAD(2); LocalVariableInstruction ASTORE_0 = new ASTORE(0); LocalVariableInstruction ASTORE_1 = new ASTORE(1); LocalVariableInstruction ASTORE_2 = new ASTORE(2); LocalVariableInstruction ISTORE_0 = new ISTORE(0); LocalVariableInstruction ISTORE_1 = new ISTORE(1); LocalVariableInstruction ISTORE_2 = new ISTORE(2); /** Get object via its opcode, for immutable instructions like * branch instructions entries are set to null. */ Instruction[] INSTRUCTIONS = new Instruction[256]; /** Interfaces may have no static initializers, so we simulate this * with an inner class. */ Clinit bla = new Clinit(); class Clinit { Clinit() { INSTRUCTIONS[Const.NOP] = NOP; INSTRUCTIONS[Const.ACONST_NULL] = ACONST_NULL; INSTRUCTIONS[Const.ICONST_M1] = ICONST_M1; INSTRUCTIONS[Const.ICONST_0] = ICONST_0; INSTRUCTIONS[Const.ICONST_1] = ICONST_1; INSTRUCTIONS[Const.ICONST_2] = ICONST_2; INSTRUCTIONS[Const.ICONST_3] = ICONST_3; INSTRUCTIONS[Const.ICONST_4] = ICONST_4; INSTRUCTIONS[Const.ICONST_5] = ICONST_5; INSTRUCTIONS[Const.LCONST_0] = LCONST_0; INSTRUCTIONS[Const.LCONST_1] = LCONST_1; INSTRUCTIONS[Const.FCONST_0] = FCONST_0; INSTRUCTIONS[Const.FCONST_1] = FCONST_1; INSTRUCTIONS[Const.FCONST_2] = FCONST_2; INSTRUCTIONS[Const.DCONST_0] = DCONST_0; INSTRUCTIONS[Const.DCONST_1] = DCONST_1; INSTRUCTIONS[Const.IALOAD] = IALOAD; INSTRUCTIONS[Const.LALOAD] = LALOAD; INSTRUCTIONS[Const.FALOAD] = FALOAD; INSTRUCTIONS[Const.DALOAD] = DALOAD; INSTRUCTIONS[Const.AALOAD] = AALOAD; INSTRUCTIONS[Const.BALOAD] = BALOAD; INSTRUCTIONS[Const.CALOAD] = CALOAD; INSTRUCTIONS[Const.SALOAD] = SALOAD; INSTRUCTIONS[Const.IASTORE] = IASTORE; INSTRUCTIONS[Const.LASTORE] = LASTORE; INSTRUCTIONS[Const.FASTORE] = FASTORE; INSTRUCTIONS[Const.DASTORE] = DASTORE; INSTRUCTIONS[Const.AASTORE] = AASTORE; INSTRUCTIONS[Const.BASTORE] = BASTORE; INSTRUCTIONS[Const.CASTORE] = CASTORE; INSTRUCTIONS[Const.SASTORE] = SASTORE; INSTRUCTIONS[Const.POP] = POP; INSTRUCTIONS[Const.POP2] = POP2; INSTRUCTIONS[Const.DUP] = DUP; INSTRUCTIONS[Const.DUP_X1] = DUP_X1; INSTRUCTIONS[Const.DUP_X2] = DUP_X2; INSTRUCTIONS[Const.DUP2] = DUP2; INSTRUCTIONS[Const.DUP2_X1] = DUP2_X1; INSTRUCTIONS[Const.DUP2_X2] = DUP2_X2; INSTRUCTIONS[Const.SWAP] = SWAP; INSTRUCTIONS[Const.IADD] = IADD; INSTRUCTIONS[Const.LADD] = LADD; INSTRUCTIONS[Const.FADD] = FADD; INSTRUCTIONS[Const.DADD] = DADD; INSTRUCTIONS[Const.ISUB] = ISUB; INSTRUCTIONS[Const.LSUB] = LSUB; INSTRUCTIONS[Const.FSUB] = FSUB; INSTRUCTIONS[Const.DSUB] = DSUB; INSTRUCTIONS[Const.IMUL] = IMUL; INSTRUCTIONS[Const.LMUL] = LMUL; INSTRUCTIONS[Const.FMUL] = FMUL; INSTRUCTIONS[Const.DMUL] = DMUL; INSTRUCTIONS[Const.IDIV] = IDIV; INSTRUCTIONS[Const.LDIV] = LDIV; INSTRUCTIONS[Const.FDIV] = FDIV; INSTRUCTIONS[Const.DDIV] = DDIV; INSTRUCTIONS[Const.IREM] = IREM; INSTRUCTIONS[Const.LREM] = LREM; INSTRUCTIONS[Const.FREM] = FREM; INSTRUCTIONS[Const.DREM] = DREM; INSTRUCTIONS[Const.INEG] = INEG; INSTRUCTIONS[Const.LNEG] = LNEG; INSTRUCTIONS[Const.FNEG] = FNEG; INSTRUCTIONS[Const.DNEG] = DNEG; INSTRUCTIONS[Const.ISHL] = ISHL; INSTRUCTIONS[Const.LSHL] = LSHL; INSTRUCTIONS[Const.ISHR] = ISHR; INSTRUCTIONS[Const.LSHR] = LSHR; INSTRUCTIONS[Const.IUSHR] = IUSHR; INSTRUCTIONS[Const.LUSHR] = LUSHR; INSTRUCTIONS[Const.IAND] = IAND; INSTRUCTIONS[Const.LAND] = LAND; INSTRUCTIONS[Const.IOR] = IOR; INSTRUCTIONS[Const.LOR] = LOR; INSTRUCTIONS[Const.IXOR] = IXOR; INSTRUCTIONS[Const.LXOR] = LXOR; INSTRUCTIONS[Const.I2L] = I2L; INSTRUCTIONS[Const.I2F] = I2F; INSTRUCTIONS[Const.I2D] = I2D; INSTRUCTIONS[Const.L2I] = L2I; INSTRUCTIONS[Const.L2F] = L2F; INSTRUCTIONS[Const.L2D] = L2D; INSTRUCTIONS[Const.F2I] = F2I; INSTRUCTIONS[Const.F2L] = F2L; INSTRUCTIONS[Const.F2D] = F2D; INSTRUCTIONS[Const.D2I] = D2I; INSTRUCTIONS[Const.D2L] = D2L; INSTRUCTIONS[Const.D2F] = D2F; INSTRUCTIONS[Const.I2B] = I2B; INSTRUCTIONS[Const.I2C] = I2C; INSTRUCTIONS[Const.I2S] = I2S; INSTRUCTIONS[Const.LCMP] = LCMP; INSTRUCTIONS[Const.FCMPL] = FCMPL; INSTRUCTIONS[Const.FCMPG] = FCMPG; INSTRUCTIONS[Const.DCMPL] = DCMPL; INSTRUCTIONS[Const.DCMPG] = DCMPG; INSTRUCTIONS[Const.IRETURN] = IRETURN; INSTRUCTIONS[Const.LRETURN] = LRETURN; INSTRUCTIONS[Const.FRETURN] = FRETURN; INSTRUCTIONS[Const.DRETURN] = DRETURN; INSTRUCTIONS[Const.ARETURN] = ARETURN; INSTRUCTIONS[Const.RETURN] = RETURN; INSTRUCTIONS[Const.ARRAYLENGTH] = ARRAYLENGTH; INSTRUCTIONS[Const.ATHROW] = ATHROW; INSTRUCTIONS[Const.MONITORENTER] = MONITORENTER; INSTRUCTIONS[Const.MONITOREXIT] = MONITOREXIT; } } }
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.jt400; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class Jt400EndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("userID", java.lang.String.class); map.put("password", java.lang.String.class); map.put("systemName", java.lang.String.class); map.put("objectPath", java.lang.String.class); map.put("type", org.apache.camel.component.jt400.Jt400Type.class); map.put("ccsid", int.class); map.put("format", org.apache.camel.component.jt400.Jt400Configuration.Format.class); map.put("guiAvailable", boolean.class); map.put("keyed", boolean.class); map.put("searchKey", java.lang.String.class); map.put("bridgeErrorHandler", boolean.class); map.put("messageAction", org.apache.camel.component.jt400.Jt400Configuration.MessageAction.class); map.put("readTimeout", int.class); map.put("searchType", org.apache.camel.component.jt400.Jt400Configuration.SearchType.class); map.put("sendEmptyMessageWhenIdle", boolean.class); map.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class); map.put("exchangePattern", org.apache.camel.ExchangePattern.class); map.put("pollStrategy", org.apache.camel.spi.PollingConsumerPollStrategy.class); map.put("lazyStartProducer", boolean.class); map.put("outputFieldsIdxArray", java.lang.Integer[].class); map.put("outputFieldsLengthArray", java.lang.Integer[].class); map.put("procedureName", java.lang.String.class); map.put("basicPropertyBinding", boolean.class); map.put("synchronous", boolean.class); map.put("backoffErrorThreshold", int.class); map.put("backoffIdleThreshold", int.class); map.put("backoffMultiplier", int.class); map.put("delay", long.class); map.put("greedy", boolean.class); map.put("initialDelay", long.class); map.put("repeatCount", long.class); map.put("runLoggingLevel", org.apache.camel.LoggingLevel.class); map.put("scheduledExecutorService", java.util.concurrent.ScheduledExecutorService.class); map.put("scheduler", java.lang.Object.class); map.put("schedulerProperties", java.util.Map.class); map.put("startScheduler", boolean.class); map.put("timeUnit", java.util.concurrent.TimeUnit.class); map.put("useFixedDelay", boolean.class); map.put("secured", boolean.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { Jt400Endpoint target = (Jt400Endpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "backofferrorthreshold": case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true; case "backoffidlethreshold": case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true; case "backoffmultiplier": case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true; case "basicpropertybinding": case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "ccsid": target.getConfiguration().setCcsid(property(camelContext, int.class, value)); return true; case "delay": target.setDelay(property(camelContext, long.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "format": target.getConfiguration().setFormat(property(camelContext, org.apache.camel.component.jt400.Jt400Configuration.Format.class, value)); return true; case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true; case "guiavailable": case "guiAvailable": target.getConfiguration().setGuiAvailable(property(camelContext, boolean.class, value)); return true; case "initialdelay": case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true; case "keyed": target.getConfiguration().setKeyed(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "messageaction": case "messageAction": target.getConfiguration().setMessageAction(property(camelContext, org.apache.camel.component.jt400.Jt400Configuration.MessageAction.class, value)); return true; case "outputfieldsidxarray": case "outputFieldsIdxArray": target.getConfiguration().setOutputFieldsIdxArray(property(camelContext, java.lang.Integer[].class, value)); return true; case "outputfieldslengtharray": case "outputFieldsLengthArray": target.getConfiguration().setOutputFieldsLengthArray(property(camelContext, java.lang.Integer[].class, value)); return true; case "pollstrategy": case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true; case "procedurename": case "procedureName": target.getConfiguration().setProcedureName(property(camelContext, java.lang.String.class, value)); return true; case "readtimeout": case "readTimeout": target.getConfiguration().setReadTimeout(property(camelContext, int.class, value)); return true; case "repeatcount": case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true; case "runlogginglevel": case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true; case "scheduledexecutorservice": case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true; case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true; case "schedulerproperties": case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true; case "searchkey": case "searchKey": target.getConfiguration().setSearchKey(property(camelContext, java.lang.String.class, value)); return true; case "searchtype": case "searchType": target.getConfiguration().setSearchType(property(camelContext, org.apache.camel.component.jt400.Jt400Configuration.SearchType.class, value)); return true; case "secured": target.getConfiguration().setSecured(property(camelContext, boolean.class, value)); return true; case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true; case "startscheduler": case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true; case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true; case "timeunit": case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true; case "usefixeddelay": case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { Jt400Endpoint target = (Jt400Endpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "backofferrorthreshold": case "backoffErrorThreshold": return target.getBackoffErrorThreshold(); case "backoffidlethreshold": case "backoffIdleThreshold": return target.getBackoffIdleThreshold(); case "backoffmultiplier": case "backoffMultiplier": return target.getBackoffMultiplier(); case "basicpropertybinding": case "basicPropertyBinding": return target.isBasicPropertyBinding(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "ccsid": return target.getConfiguration().getCcsid(); case "delay": return target.getDelay(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "format": return target.getConfiguration().getFormat(); case "greedy": return target.isGreedy(); case "guiavailable": case "guiAvailable": return target.getConfiguration().isGuiAvailable(); case "initialdelay": case "initialDelay": return target.getInitialDelay(); case "keyed": return target.getConfiguration().isKeyed(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "messageaction": case "messageAction": return target.getConfiguration().getMessageAction(); case "outputfieldsidxarray": case "outputFieldsIdxArray": return target.getConfiguration().getOutputFieldsIdxArray(); case "outputfieldslengtharray": case "outputFieldsLengthArray": return target.getConfiguration().getOutputFieldsLengthArray(); case "pollstrategy": case "pollStrategy": return target.getPollStrategy(); case "procedurename": case "procedureName": return target.getConfiguration().getProcedureName(); case "readtimeout": case "readTimeout": return target.getConfiguration().getReadTimeout(); case "repeatcount": case "repeatCount": return target.getRepeatCount(); case "runlogginglevel": case "runLoggingLevel": return target.getRunLoggingLevel(); case "scheduledexecutorservice": case "scheduledExecutorService": return target.getScheduledExecutorService(); case "scheduler": return target.getScheduler(); case "schedulerproperties": case "schedulerProperties": return target.getSchedulerProperties(); case "searchkey": case "searchKey": return target.getConfiguration().getSearchKey(); case "searchtype": case "searchType": return target.getConfiguration().getSearchType(); case "secured": return target.getConfiguration().isSecured(); case "sendemptymessagewhenidle": case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle(); case "startscheduler": case "startScheduler": return target.isStartScheduler(); case "synchronous": return target.isSynchronous(); case "timeunit": case "timeUnit": return target.getTimeUnit(); case "usefixeddelay": case "useFixedDelay": return target.isUseFixedDelay(); default: return null; } } }
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package ch.boye.httpclientandroidlib.impl.io; import java.io.IOException; import java.util.ArrayList; import java.util.List; import ch.boye.httpclientandroidlib.Header; import ch.boye.httpclientandroidlib.HttpException; import ch.boye.httpclientandroidlib.HttpMessage; import ch.boye.httpclientandroidlib.ParseException; import ch.boye.httpclientandroidlib.ProtocolException; import ch.boye.httpclientandroidlib.io.HttpMessageParser; import ch.boye.httpclientandroidlib.io.SessionInputBuffer; import ch.boye.httpclientandroidlib.message.LineParser; import ch.boye.httpclientandroidlib.message.BasicLineParser; import ch.boye.httpclientandroidlib.params.CoreConnectionPNames; import ch.boye.httpclientandroidlib.params.HttpParams; import ch.boye.httpclientandroidlib.util.CharArrayBuffer; /** * Abstract base class for HTTP message parsers that obtain input from * an instance of {@link SessionInputBuffer}. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link ch.boye.httpclientandroidlib.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link ch.boye.httpclientandroidlib.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ public abstract class AbstractMessageParser implements HttpMessageParser { private static final int HEAD_LINE = 0; private static final int HEADERS = 1; private final SessionInputBuffer sessionBuffer; private final int maxHeaderCount; private final int maxLineLen; private final List headerLines; protected final LineParser lineParser; private int state; private HttpMessage message; /** * Creates an instance of this class. * * @param buffer the session input buffer. * @param parser the line parser. * @param params HTTP parameters. */ public AbstractMessageParser( final SessionInputBuffer buffer, final LineParser parser, final HttpParams params) { super(); if (buffer == null) { throw new IllegalArgumentException("Session input buffer may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.sessionBuffer = buffer; this.maxHeaderCount = params.getIntParameter( CoreConnectionPNames.MAX_HEADER_COUNT, -1); this.maxLineLen = params.getIntParameter( CoreConnectionPNames.MAX_LINE_LENGTH, -1); this.lineParser = (parser != null) ? parser : BasicLineParser.DEFAULT; this.headerLines = new ArrayList(); this.state = HEAD_LINE; } /** * Parses HTTP headers from the data receiver stream according to the generic * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. * * @param inbuffer Session input buffer * @param maxHeaderCount maximum number of headers allowed. If the number * of headers received from the data stream exceeds maxCount value, an * IOException will be thrown. Setting this parameter to a negative value * or zero will disable the check. * @param maxLineLen maximum number of characters for a header line, * including the continuation lines. Setting this parameter to a negative * value or zero will disable the check. * @return array of HTTP headers * @param parser line parser to use. Can be <code>null</code>, in which case * the default implementation of this interface will be used. * * @throws IOException in case of an I/O error * @throws HttpException in case of HTTP protocol violation */ public static Header[] parseHeaders( final SessionInputBuffer inbuffer, int maxHeaderCount, int maxLineLen, LineParser parser) throws HttpException, IOException { if (parser == null) { parser = BasicLineParser.DEFAULT; } List headerLines = new ArrayList(); return parseHeaders(inbuffer, maxHeaderCount, maxLineLen, parser, headerLines); } /** * Parses HTTP headers from the data receiver stream according to the generic * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. * * @param inbuffer Session input buffer * @param maxHeaderCount maximum number of headers allowed. If the number * of headers received from the data stream exceeds maxCount value, an * IOException will be thrown. Setting this parameter to a negative value * or zero will disable the check. * @param maxLineLen maximum number of characters for a header line, * including the continuation lines. Setting this parameter to a negative * value or zero will disable the check. * @param parser line parser to use. * @param headerLines List of header lines. This list will be used to store * intermediate results. This makes it possible to resume parsing of * headers in case of a {@link java.io.InterruptedIOException}. * * @return array of HTTP headers * * @throws IOException in case of an I/O error * @throws HttpException in case of HTTP protocol violation * * @since 4.1 */ public static Header[] parseHeaders( final SessionInputBuffer inbuffer, int maxHeaderCount, int maxLineLen, final LineParser parser, final List headerLines) throws HttpException, IOException { if (inbuffer == null) { throw new IllegalArgumentException("Session input buffer may not be null"); } if (parser == null) { throw new IllegalArgumentException("Line parser may not be null"); } if (headerLines == null) { throw new IllegalArgumentException("Header line list may not be null"); } CharArrayBuffer current = null; CharArrayBuffer previous = null; for (;;) { if (current == null) { current = new CharArrayBuffer(64); } else { current.clear(); } int l = inbuffer.readLine(current); if (l == -1 || current.length() < 1) { break; } // Parse the header name and value // Check for folded headers first // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 // discussion on folded headers if ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) { // we have continuation folded header // so append value int i = 0; while (i < current.length()) { char ch = current.charAt(i); if (ch != ' ' && ch != '\t') { break; } i++; } if (maxLineLen > 0 && previous.length() + 1 + current.length() - i > maxLineLen) { throw new IOException("Maximum line length limit exceeded"); } previous.append(' '); previous.append(current, i, current.length() - i); } else { headerLines.add(current); previous = current; current = null; } if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) { throw new IOException("Maximum header count exceeded"); } } Header[] headers = new Header[headerLines.size()]; for (int i = 0; i < headerLines.size(); i++) { CharArrayBuffer buffer = (CharArrayBuffer) headerLines.get(i); try { headers[i] = parser.parseHeader(buffer); } catch (ParseException ex) { throw new ProtocolException(ex.getMessage()); } } return headers; } /** * Subclasses must override this method to generate an instance of * {@link HttpMessage} based on the initial input from the session buffer. * <p> * Usually this method is expected to read just the very first line or * the very first valid from the data stream and based on the input generate * an appropriate instance of {@link HttpMessage}. * * @param sessionBuffer the session input buffer. * @return HTTP message based on the input from the session buffer. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation. * @throws ParseException in case of a parse error. */ protected abstract HttpMessage parseHead(SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException; public HttpMessage parse() throws IOException, HttpException { int st = this.state; switch (st) { case HEAD_LINE: try { this.message = parseHead(this.sessionBuffer); } catch (ParseException px) { throw new ProtocolException(px.getMessage(), px); } this.state = HEADERS; //$FALL-THROUGH$ case HEADERS: Header[] headers = AbstractMessageParser.parseHeaders( this.sessionBuffer, this.maxHeaderCount, this.maxLineLen, this.lineParser, this.headerLines); this.message.setHeaders(headers); HttpMessage result = this.message; this.message = null; this.headerLines.clear(); this.state = HEAD_LINE; return result; default: throw new IllegalStateException("Inconsistent parser state"); } } }
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.model; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.interfaces.RoomAvailabilityInterface.TimeBlock; import org.unitime.timetable.model.base.BaseExamPeriod; import org.unitime.timetable.model.dao.EventDAO; import org.unitime.timetable.model.dao.ExamPeriodDAO; import org.unitime.timetable.util.Constants; import org.unitime.timetable.util.Formats; /** * @author Tomas Muller, Stephanie Schluttenhofer */ public class ExamPeriod extends BaseExamPeriod implements Comparable<ExamPeriod> { private static final long serialVersionUID = 1L; /*[CONSTRUCTOR MARKER BEGIN]*/ public ExamPeriod () { super(); } /** * Constructor for primary key */ public ExamPeriod (java.lang.Long uniqueId) { super(uniqueId); } /*[CONSTRUCTOR MARKER END]*/ public static String PERIOD_ATTR_NAME = "periodList"; public Date getStartDate() { Calendar c = Calendar.getInstance(Locale.US); c.setTime(getSession().getExamBeginDate()); c.add(Calendar.DAY_OF_YEAR, getDateOffset()); return c.getTime(); } public void setStartDate(Date startDate) { long diff = startDate.getTime()-getSession().getExamBeginDate().getTime(); setDateOffset((int)Math.round(diff/(1000.0 * 60 * 60 * 24))); } public int getStartHour() { return (Constants.SLOT_LENGTH_MIN*getStartSlot()+Constants.FIRST_SLOT_TIME_MIN) / 60; } public int getStartMinute() { return (Constants.SLOT_LENGTH_MIN*getStartSlot()+Constants.FIRST_SLOT_TIME_MIN) % 60; } public Date getStartTime() { Calendar c = Calendar.getInstance(Locale.US); c.setTime(getSession().getExamBeginDate()); c.add(Calendar.DAY_OF_YEAR, getDateOffset()); c.set(Calendar.HOUR, getStartHour()); c.set(Calendar.MINUTE, getStartMinute()); return c.getTime(); } public int getEndSlot() { return getStartSlot() + getLength(); } public int getEndHour() { return (Constants.SLOT_LENGTH_MIN*getEndSlot()+Constants.FIRST_SLOT_TIME_MIN) / 60; } public int getEndMinute() { return (Constants.SLOT_LENGTH_MIN*getEndSlot()+Constants.FIRST_SLOT_TIME_MIN) % 60; } public Date getEndTime() { Calendar c = Calendar.getInstance(Locale.US); c.setTime(getSession().getExamBeginDate()); c.add(Calendar.DAY_OF_YEAR, getDateOffset()); c.set(Calendar.HOUR, getEndHour()); c.set(Calendar.MINUTE, getEndMinute()); return c.getTime(); } public String getStartDateLabel() { return Formats.getDateFormat(Formats.Pattern.DATE_EXAM_PERIOD).format(getStartDate()); } public String getStartTimeLabel() { int min = getStartSlot()*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN; return Constants.toTime(min); } public String getStartTimeLabel(int printOffset) { int min = getStartSlot()*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN + printOffset; return Constants.toTime(min); } public String getEndTimeLabel() { int min = (getStartSlot()+getLength())*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN; return Constants.toTime(min); } public String getEndTimeLabel(int length, int printOffset) { int min = getStartSlot()*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN + length + printOffset; return Constants.toTime(min); } public String getName() { return getStartDateLabel()+" "+getStartTimeLabel()+" - "+getEndTimeLabel(); } public String getAbbreviation() { return getStartDateLabel()+" "+getStartTimeLabel(); } public int compareTo(ExamPeriod period) { int cmp = getExamType().compareTo(period.getExamType()); if (cmp!=0) return cmp; cmp = getDateOffset().compareTo(period.getDateOffset()); if (cmp!=0) return cmp; return getStartSlot().compareTo(period.getStartSlot()); } public static TreeSet findAll(Long sessionId, ExamType type) { return findAll(sessionId, type == null ? null : type.getUniqueId()); } public static TreeSet findAll(Long sessionId, Long examTypeId) { TreeSet ret = new TreeSet(); if (examTypeId==null) ret.addAll(new ExamPeriodDAO().getSession(). createQuery("select ep from ExamPeriod ep where ep.session.uniqueId=:sessionId"). setLong("sessionId", sessionId). setCacheable(true). list()); else ret.addAll(new ExamPeriodDAO().getSession(). createQuery("select ep from ExamPeriod ep where ep.session.uniqueId=:sessionId and ep.examType.uniqueId=:typeId"). setLong("sessionId", sessionId). setLong("typeId", examTypeId). setCacheable(true). list()); return ret; } public static ExamPeriod findByDateStart(Long sessionId, int dateOffset, int startSlot) { return (ExamPeriod)new ExamPeriodDAO().getSession().createQuery( "select ep from ExamPeriod ep where " + "ep.session.uniqueId=:sessionId and ep.dateOffset=:dateOffset and ep.startSlot=:startSlot"). setLong("sessionId", sessionId). setInteger("dateOffset", dateOffset). setInteger("startSlot", startSlot).setCacheable(true).uniqueResult(); } public static ExamPeriod findByIndex(Long sessionId, ExamType type, Integer idx) { if (idx==null || idx<0) return null; int x = 0; TreeSet periods = findAll(sessionId, type); for (Iterator i=periods.iterator();i.hasNext();x++) { ExamPeriod period = (ExamPeriod)i.next(); if (x==idx) return period; } return (periods.isEmpty()?null:(ExamPeriod)periods.last()); } public String toString() { return getAbbreviation(); } public boolean isBackToBack(ExamPeriod period, boolean isDayBreakBackToBack) { if (!isDayBreakBackToBack && !period.getDateOffset().equals(getDateOffset())) return false; for (Iterator i=findAll(getSession().getUniqueId(), getExamType()).iterator();i.hasNext();) { ExamPeriod p = (ExamPeriod)i.next(); if (compareTo(p)<0 && p.compareTo(period)<0) return false; if (compareTo(p)>0 && p.compareTo(period)>0) return false; } return true; } public boolean overlap(Assignment assignment) { return overlap(assignment, ApplicationProperty.ExaminationTravelTimeClass.intValue()); } public boolean overlap(Assignment assignment, int nrTravelSlots) { //check date pattern DatePattern dp = assignment.getDatePattern(); int dpIndex = getDateOffset()-getSession().getExamBeginOffset()-(dp.getOffset()==null?0:dp.getOffset()); if (dp.getPattern()==null || dpIndex<0 || dpIndex>=dp.getPattern().length() || dp.getPattern().charAt(dpIndex)!='1') return false; //check day of week Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(getSession().getExamBeginDate()); cal.add(Calendar.DAY_OF_YEAR, getDateOffset()); switch (cal.get(Calendar.DAY_OF_WEEK)) { case Calendar.MONDAY : if ((assignment.getDays() & Constants.DAY_CODES[Constants.DAY_MON])==0) return false; break; case Calendar.TUESDAY : if ((assignment.getDays() & Constants.DAY_CODES[Constants.DAY_TUE])==0) return false; break; case Calendar.WEDNESDAY : if ((assignment.getDays() & Constants.DAY_CODES[Constants.DAY_WED])==0) return false; break; case Calendar.THURSDAY : if ((assignment.getDays() & Constants.DAY_CODES[Constants.DAY_THU])==0) return false; break; case Calendar.FRIDAY : if ((assignment.getDays() & Constants.DAY_CODES[Constants.DAY_FRI])==0) return false; break; case Calendar.SATURDAY : if ((assignment.getDays() & Constants.DAY_CODES[Constants.DAY_SAT])==0) return false; break; case Calendar.SUNDAY : if ((assignment.getDays() & Constants.DAY_CODES[Constants.DAY_SUN])==0) return false; break; } //check time return getStartSlot() - nrTravelSlots < assignment.getStartSlot() + assignment.getSlotPerMtg() && assignment.getStartSlot() < getStartSlot() + getLength() + nrTravelSlots; } public boolean overlap(Meeting meeting) { return overlap(meeting, ApplicationProperty.ExaminationTravelTimeClass.intValue()); } public boolean overlap(Meeting meeting, int nrTravelSlots) { if (!meeting.getMeetingDate().equals(getStartDate())) return false; return getStartSlot() - nrTravelSlots < meeting.getStopPeriod() && meeting.getStartPeriod() < getStartSlot() + getLength() + nrTravelSlots; } public List<Meeting> findOverlappingClassMeetings() { return findOverlappingClassMeetings(ApplicationProperty.ExaminationTravelTimeClass.intValue()); } public List<Meeting> findOverlappingClassMeetings(int nrTravelSlots) { return new ExamPeriodDAO().getSession().createQuery( "select m from ClassEvent e inner join e.meetings m where " + "m.meetingDate=:startDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot") .setDate("startDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setCacheable(true) .list(); } public List<Meeting> findOverlappingClassMeetings(Long classId) { return findOverlappingClassMeetings(classId, ApplicationProperty.ExaminationTravelTimeClass.intValue()); } public List<Meeting> findOverlappingClassMeetings(Long classId, int nrTravelSlots) { return new ExamPeriodDAO().getSession().createQuery( "select m from ClassEvent e inner join e.meetings m where " + "m.meetingDate=:startDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and " + "e.clazz.uniqueId=:classId") .setDate("startDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setLong("classId", classId) .setCacheable(true) .list(); } public Hashtable<Meeting,Set<Long>> findOverlappingCourseMeetingsWithReqAttendence(Set<Long> studentIds) { return findOverlappingCourseMeetingsWithReqAttendence(studentIds, ApplicationProperty.ExaminationTravelTimeCourse.intValue()); } public Hashtable<Meeting,Set<Long>> findOverlappingCourseMeetingsWithReqAttendence(Set<Long> studentIds, int nrTravelSlots) { Hashtable<Meeting,Set<Long>> ret = new Hashtable(); if (studentIds==null || studentIds.isEmpty()) return ret; String students = ""; int nrStudents = 0; for (Long studentId: studentIds) { students += (students.length()==0?"":",")+studentId; nrStudents++; if (nrStudents==1000) { for (Iterator i=EventDAO.getInstance().getSession().createQuery( "select m, s.student.uniqueId from "+ "CourseEvent e inner join e.meetings m inner join e.relatedCourses o, StudentClassEnrollment s where e.reqAttendance=true and m.approvalStatus = 1 and "+ "m.meetingDate=:meetingDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and s.student.uniqueId in ("+students+") and "+ "o.ownerType=:classType and s.clazz.uniqueId=o.ownerId") .setDate("meetingDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setInteger("classType", ExamOwner.sOwnerTypeClass) .setCacheable(true).list().iterator();i.hasNext();) { Object[] o = (Object[])i.next(); Meeting meeting = (Meeting)o[0]; long xstudentId = (Long)o[1]; Set<Long> conf = ret.get(meeting); if (conf==null) { conf = new HashSet(); ret.put(meeting, conf); } conf.add(xstudentId); } for (Iterator i=EventDAO.getInstance().getSession().createQuery( "select m, s.student.uniqueId from "+ "CourseEvent e inner join e.meetings m inner join e.relatedCourses o, StudentClassEnrollment s where e.reqAttendance=true and m.approvalStatus = 1 and "+ "m.meetingDate=:meetingDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and s.student.uniqueId in ("+students+") and "+ "o.ownerType=:configType and s.clazz.schedulingSubpart.instrOfferingConfig.uniqueId=o.ownerId") .setDate("meetingDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setInteger("configType", ExamOwner.sOwnerTypeConfig) .setCacheable(true).list().iterator();i.hasNext();) { Object[] o = (Object[])i.next(); Meeting meeting = (Meeting)o[0]; long xstudentId = (Long)o[1]; Set<Long> conf = ret.get(meeting); if (conf==null) { conf = new HashSet(); ret.put(meeting, conf); } conf.add(xstudentId); } for (Iterator i=EventDAO.getInstance().getSession().createQuery( "select m, s.student.uniqueId from "+ "CourseEvent e inner join e.meetings m inner join e.relatedCourses o, StudentClassEnrollment s where e.reqAttendance=true and m.approvalStatus = 1 and "+ "m.meetingDate=:meetingDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and s.student.uniqueId in ("+students+") and "+ "o.ownerType=:courseType and s.courseOffering.uniqueId=o.ownerId") .setDate("meetingDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setInteger("courseType", ExamOwner.sOwnerTypeCourse) .setCacheable(true).list().iterator();i.hasNext();) { Object[] o = (Object[])i.next(); Meeting meeting = (Meeting)o[0]; long xstudentId = (Long)o[1]; Set<Long> conf = ret.get(meeting); if (conf==null) { conf = new HashSet(); ret.put(meeting, conf); } conf.add(xstudentId); } for (Iterator i=EventDAO.getInstance().getSession().createQuery( "select m, s.student.uniqueId from "+ "CourseEvent e inner join e.meetings m inner join e.relatedCourses o, StudentClassEnrollment s where e.reqAttendance=true and m.approvalStatus = 1 and "+ "m.meetingDate=:meetingDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and s.student.uniqueId in ("+students+") and "+ "o.ownerType=:offeringType and s.courseOffering.instructionalOffering.uniqueId=o.ownerId") .setDate("meetingDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setInteger("offeringType", ExamOwner.sOwnerTypeOffering) .setCacheable(true).list().iterator();i.hasNext();) { Object[] o = (Object[])i.next(); Meeting meeting = (Meeting)o[0]; long xstudentId = (Long)o[1]; Set<Long> conf = ret.get(meeting); if (conf==null) { conf = new HashSet(); ret.put(meeting, conf); } conf.add(xstudentId); } students = ""; nrStudents = 0; } } if (nrStudents > 0 && students.trim().length() > 0) { for (Iterator i=EventDAO.getInstance().getSession().createQuery( "select m, s.student.uniqueId from "+ "CourseEvent e inner join e.meetings m inner join e.relatedCourses o, StudentClassEnrollment s where e.reqAttendance=true and m.approvalStatus = 1 and "+ "m.meetingDate=:meetingDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and s.student.uniqueId in ("+students+") and "+ "o.ownerType=:classType and s.clazz.uniqueId=o.ownerId") .setDate("meetingDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setInteger("classType", ExamOwner.sOwnerTypeClass) .setCacheable(true).list().iterator();i.hasNext();) { Object[] o = (Object[])i.next(); Meeting meeting = (Meeting)o[0]; long xstudentId = (Long)o[1]; Set<Long> conf = ret.get(meeting); if (conf==null) { conf = new HashSet(); ret.put(meeting, conf); } conf.add(xstudentId); } for (Iterator i=EventDAO.getInstance().getSession().createQuery( "select m, s.student.uniqueId from "+ "CourseEvent e inner join e.meetings m inner join e.relatedCourses o, StudentClassEnrollment s where e.reqAttendance=true and m.approvalStatus = 1 and "+ "m.meetingDate=:meetingDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and s.student.uniqueId in ("+students+") and "+ "o.ownerType=:configType and s.clazz.schedulingSubpart.instrOfferingConfig.uniqueId=o.ownerId") .setDate("meetingDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setInteger("configType", ExamOwner.sOwnerTypeConfig) .setCacheable(true).list().iterator();i.hasNext();) { Object[] o = (Object[])i.next(); Meeting meeting = (Meeting)o[0]; long xstudentId = (Long)o[1]; Set<Long> conf = ret.get(meeting); if (conf==null) { conf = new HashSet(); ret.put(meeting, conf); } conf.add(xstudentId); } for (Iterator i=EventDAO.getInstance().getSession().createQuery( "select m, s.student.uniqueId from "+ "CourseEvent e inner join e.meetings m inner join e.relatedCourses o, StudentClassEnrollment s where e.reqAttendance=true and m.approvalStatus = 1 and "+ "m.meetingDate=:meetingDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and s.student.uniqueId in ("+students+") and "+ "o.ownerType=:courseType and s.courseOffering.uniqueId=o.ownerId") .setDate("meetingDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setInteger("courseType", ExamOwner.sOwnerTypeCourse) .setCacheable(true).list().iterator();i.hasNext();) { Object[] o = (Object[])i.next(); Meeting meeting = (Meeting)o[0]; long xstudentId = (Long)o[1]; Set<Long> conf = ret.get(meeting); if (conf==null) { conf = new HashSet(); ret.put(meeting, conf); } conf.add(xstudentId); } for (Iterator i=EventDAO.getInstance().getSession().createQuery( "select m, s.student.uniqueId from "+ "CourseEvent e inner join e.meetings m inner join e.relatedCourses o, StudentClassEnrollment s where e.reqAttendance=true and m.approvalStatus = 1 and "+ "m.meetingDate=:meetingDate and m.startPeriod < :endSlot and m.stopPeriod > :startSlot and s.student.uniqueId in ("+students+") and "+ "o.ownerType=:offeringType and s.courseOffering.instructionalOffering.uniqueId=o.ownerId") .setDate("meetingDate", getStartDate()) .setInteger("startSlot", getStartSlot()-nrTravelSlots) .setInteger("endSlot", getEndSlot()+nrTravelSlots) .setInteger("offeringType", ExamOwner.sOwnerTypeOffering) .setCacheable(true).list().iterator();i.hasNext();) { Object[] o = (Object[])i.next(); Meeting meeting = (Meeting)o[0]; long xstudentId = (Long)o[1]; Set<Long> conf = ret.get(meeting); if (conf==null) { conf = new HashSet(); ret.put(meeting, conf); } conf.add(xstudentId); } } return ret; } public int getIndex() { int index = 0; for (Iterator i=findAll(getSession().getUniqueId(), getExamType()).iterator();i.hasNext();) { if (compareTo((ExamPeriod)i.next())>0) index++; } return index; } public Object clone(){ ExamPeriod newExamPeriod = new ExamPeriod(); newExamPeriod.setExamType(getExamType()); newExamPeriod.setDateOffset(getDateOffset()); newExamPeriod.setLength(getLength()); newExamPeriod.setPrefLevel(getPrefLevel()); newExamPeriod.setStartSlot(getStartSlot()); newExamPeriod.setSession(getSession()); newExamPeriod.setEventStartOffset(getEventStartOffset()); newExamPeriod.setEventStopOffset(getEventStopOffset()); return(newExamPeriod); } public ExamPeriod findSameExamPeriodInSession(Session session){ if (session == null) { return(null); } return((ExamPeriod)(new ExamPeriodDAO()).getQuery("select distinct ep from ExamPeriod ep where ep.session.uniqueId = :sessionId" + " and ep.examType.uniqueId = :examTypeId" + " and ep.dateOffset = :dateOffset" + " and ep.length = :length" + " and ep.prefLevel.uniqueId = :prefLevelId" + " and ep.startSlot = :startSlot") .setLong("sessionId", session.getUniqueId().longValue()) .setLong("examTypeId", getExamType().getUniqueId()) .setInteger("dateOffset", getDateOffset().intValue()) .setInteger("length", getLength().intValue()) .setLong("prefLevelId", getPrefLevel().getUniqueId().longValue()) .setInteger("startSlot", getStartSlot().intValue()) .setCacheable(true) .uniqueResult()); } public int getDayOfWeek() { Calendar c = Calendar.getInstance(Locale.US); c.setTime(getSession().getExamBeginDate()); c.add(Calendar.DAY_OF_YEAR, getDateOffset()); return c.get(Calendar.DAY_OF_WEEK); } public boolean weakOverlap(Meeting meeting) { return getDayOfWeek()==meeting.getDayOfWeek() && getStartSlot() < meeting.getStopPeriod() && meeting.getStartPeriod() < getStartSlot() + getLength(); } public boolean overlap(TimeBlock time) { // int breakTimeStart = Integer.parseInt(ApplicationProperties.getProperty("tmtbl.room.availability."+Exam.sExamTypes[getExamType()].toLowerCase()+".breakTime.start", "0")); // int breakTimeStop = Integer.parseInt(ApplicationProperties.getProperty("tmtbl.room.availability."+Exam.sExamTypes[getExamType()].toLowerCase()+".breakTime.stop", "0")); int breakTimeStart = getEventStartOffset().intValue() * Constants.SLOT_LENGTH_MIN; int breakTimeStop = getEventStopOffset().intValue() * Constants.SLOT_LENGTH_MIN; Date start = time.getStartTime(); if (breakTimeStart!=0) { Calendar c = Calendar.getInstance(Locale.US); c.setTime(start); c.add(Calendar.MINUTE, -breakTimeStart); start = c.getTime(); } Date stop = time.getEndTime(); if (breakTimeStop!=0) { Calendar c = Calendar.getInstance(Locale.US); c.setTime(stop); c.add(Calendar.MINUTE, breakTimeStop); stop = c.getTime(); } return getStartTime().compareTo(stop)<0 && start.compareTo(getEndTime()) < 0; } public static Date[] getBounds(Session session, Long examTypeId) { return getBounds(session.getUniqueId(), session.getExamBeginDate(), examTypeId); } public static Date[] getBounds(Long sessionId, Date examBeginDate, Long examTypeId) { Object[] bounds = (Object[])new ExamPeriodDAO().getQuery("select min(ep.dateOffset), min(ep.startSlot - ep.eventStartOffset), max(ep.dateOffset), max(ep.startSlot+ep.length+ep.eventStopOffset) " + "from ExamPeriod ep where ep.session.uniqueId = :sessionId and ep.examType.uniqueId = :examTypeId") .setLong("sessionId", sessionId) .setLong("examTypeId", examTypeId) .setCacheable(true).uniqueResult(); if (bounds == null || bounds[0] == null) return null; int minDateOffset = ((Number)bounds[0]).intValue(); int minSlot = ((Number)bounds[1]).intValue(); int minHour = (Constants.SLOT_LENGTH_MIN*minSlot+Constants.FIRST_SLOT_TIME_MIN) / 60; int minMin = (Constants.SLOT_LENGTH_MIN*minSlot+Constants.FIRST_SLOT_TIME_MIN) % 60; int maxDateOffset = ((Number)bounds[2]).intValue(); int maxSlot = ((Number)bounds[3]).intValue(); int maxHour = (Constants.SLOT_LENGTH_MIN*maxSlot+Constants.FIRST_SLOT_TIME_MIN) / 60; int maxMin = (Constants.SLOT_LENGTH_MIN*maxSlot+Constants.FIRST_SLOT_TIME_MIN) % 60; Calendar c = Calendar.getInstance(Locale.US); c.setTime(examBeginDate); c.add(Calendar.DAY_OF_YEAR, minDateOffset); c.set(Calendar.HOUR, minHour); c.set(Calendar.MINUTE, minMin); Date min = c.getTime(); c.setTime(examBeginDate); c.add(Calendar.DAY_OF_YEAR, maxDateOffset); c.set(Calendar.HOUR, maxHour); c.set(Calendar.MINUTE, maxMin); Date max = c.getTime(); return new Date[] {min, max}; } public int getExamEventStartSlot(){ return(getStartSlot().intValue() - getEventStartOffset().intValue()); } public int getExamEventStopSlot(){ return(getEndSlot() + getEventStopOffset().intValue()); } public int getExamEventStartOffsetForExam(Exam exam){ int startOffset = getEventStartOffset() * Constants.SLOT_LENGTH_MIN; if (exam.getPrintOffset() != null && exam.getPrintOffset().intValue() > 0){ startOffset += exam.getPrintOffset().intValue(); } return(startOffset); } public boolean isUsed() { return ((Number)ExamPeriodDAO.getInstance().getSession().createQuery("select count(x) from Exam x where x.assignedPeriod.uniqueId = :id").setLong("id", getUniqueId()).setCacheable(true).uniqueResult()).intValue() > 0; } public int getExamEventStopOffsetForExam(Exam exam){ return(exam.getLength() - (Constants.SLOT_LENGTH_MIN*getLength()) - (getEventStopOffset()*Constants.SLOT_LENGTH_MIN) + exam.examOffset()); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.service.nonpersistent; import io.netty.buffer.ByteBuf; import io.netty.util.Recycler; import io.netty.util.Recycler.Handle; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.Position; import org.apache.pulsar.broker.service.AbstractReplicator; import org.apache.pulsar.broker.service.BrokerService; import org.apache.pulsar.broker.service.BrokerServiceException.NamingException; import org.apache.pulsar.broker.service.Replicator; import org.apache.pulsar.broker.service.persistent.PersistentReplicator; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.impl.MessageImpl; import org.apache.pulsar.client.impl.ProducerImpl; import org.apache.pulsar.client.impl.SendCallback; import org.apache.pulsar.common.policies.data.NonPersistentReplicatorStats; import org.apache.pulsar.common.stats.Rate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NonPersistentReplicator extends AbstractReplicator implements Replicator { private final Rate msgOut = new Rate(); private final Rate msgDrop = new Rate(); private final NonPersistentReplicatorStats stats = new NonPersistentReplicatorStats(); public NonPersistentReplicator(NonPersistentTopic topic, String localCluster, String remoteCluster, BrokerService brokerService) throws NamingException { super(topic.getName(), topic.getReplicatorPrefix(), localCluster, remoteCluster, brokerService); producerBuilder.blockIfQueueFull(false); startProducer(); } @Override protected void readEntries(Producer<byte[]> producer) { this.producer = (ProducerImpl) producer; if (STATE_UPDATER.compareAndSet(this, State.Starting, State.Started)) { log.info("[{}][{} -> {}] Created replicator producer", topicName, localCluster, remoteCluster); backOff.reset(); } else { log.info( "[{}][{} -> {}] Replicator was stopped while creating the producer." + " Closing it. Replicator state: {}", topicName, localCluster, remoteCluster, STATE_UPDATER.get(this)); STATE_UPDATER.set(this, State.Stopping); closeProducerAsync(); return; } } public void sendMessage(Entry entry) { if ((STATE_UPDATER.get(this) == State.Started) && isWritable()) { int length = entry.getLength(); ByteBuf headersAndPayload = entry.getDataBuffer(); MessageImpl msg; try { msg = MessageImpl.deserializeSkipBrokerEntryMetaData(headersAndPayload); } catch (Throwable t) { log.error("[{}][{} -> {}] Failed to deserialize message at {} (buffer size: {}): {}", topicName, localCluster, remoteCluster, entry.getPosition(), length, t.getMessage(), t); entry.release(); return; } if (msg.isReplicated()) { // Discard messages that were already replicated into this region entry.release(); msg.recycle(); return; } if (msg.hasReplicateTo() && !msg.getReplicateTo().contains(remoteCluster)) { if (log.isDebugEnabled()) { log.debug("[{}][{} -> {}] Skipping message at {} / msg-id: {}: replicateTo {}", topicName, localCluster, remoteCluster, entry.getPosition(), msg.getMessageId(), msg.getReplicateTo()); } entry.release(); msg.recycle(); return; } msgOut.recordEvent(headersAndPayload.readableBytes()); msg.setReplicatedFrom(localCluster); headersAndPayload.retain(); producer.sendAsync(msg, ProducerSendCallback.create(this, entry, msg)); } else { if (log.isDebugEnabled()) { log.debug("[{}][{} -> {}] dropping message because replicator producer is not started/writable", topicName, localCluster, remoteCluster); } msgDrop.recordEvent(); entry.release(); } } @Override public void updateRates() { msgOut.calculateRate(); msgDrop.calculateRate(); stats.msgRateOut = msgOut.getRate(); stats.msgThroughputOut = msgOut.getValueRate(); stats.msgDropRate = msgDrop.getRate(); } @Override public NonPersistentReplicatorStats getStats() { stats.connected = producer != null && producer.isConnected(); stats.replicationDelayInSeconds = getReplicationDelayInSeconds(); ProducerImpl producer = this.producer; if (producer != null) { stats.outboundConnection = producer.getConnectionId(); stats.outboundConnectedSince = producer.getConnectedSince(); } else { stats.outboundConnection = null; stats.outboundConnectedSince = null; } return stats; } private long getReplicationDelayInSeconds() { if (producer != null) { return TimeUnit.MILLISECONDS.toSeconds(producer.getDelayInMillis()); } return 0L; } private static final class ProducerSendCallback implements SendCallback { private NonPersistentReplicator replicator; private Entry entry; private MessageImpl msg; @Override public void sendComplete(Exception exception) { if (exception != null) { log.error("[{}][{} -> {}] Error producing on remote broker", replicator.topicName, replicator.localCluster, replicator.remoteCluster, exception); } else { if (log.isDebugEnabled()) { log.debug("[{}][{} -> {}] Message persisted on remote broker", replicator.topicName, replicator.localCluster, replicator.remoteCluster); } } entry.release(); recycle(); } private final Handle<ProducerSendCallback> recyclerHandle; private ProducerSendCallback(Handle<ProducerSendCallback> recyclerHandle) { this.recyclerHandle = recyclerHandle; } static ProducerSendCallback create(NonPersistentReplicator replicator, Entry entry, MessageImpl msg) { ProducerSendCallback sendCallback = RECYCLER.get(); sendCallback.replicator = replicator; sendCallback.entry = entry; sendCallback.msg = msg; return sendCallback; } private void recycle() { replicator = null; entry = null; // already released and recycled on sendComplete if (msg != null) { msg.recycle(); msg = null; } recyclerHandle.recycle(this); } private static final Recycler<ProducerSendCallback> RECYCLER = new Recycler<ProducerSendCallback>() { @Override protected ProducerSendCallback newObject(Handle<ProducerSendCallback> handle) { return new ProducerSendCallback(handle); } }; @Override public void addCallback(MessageImpl<?> msg, SendCallback scb) { // noop } @Override public SendCallback getNextSendCallback() { return null; } @Override public MessageImpl<?> getNextMessage() { return null; } @Override public CompletableFuture<MessageId> getFuture() { return null; } } private static final Logger log = LoggerFactory.getLogger(PersistentReplicator.class); @Override protected Position getReplicatorReadPosition() { // No-op return null; } @Override protected long getNumberOfEntriesInBacklog() { // No-op return 0; } @Override protected void disableReplicatorRead() { // No-op } @Override public boolean isConnected() { ProducerImpl<?> producer = this.producer; return producer != null && producer.isConnected(); } }
// // typica - A client library for Amazon Web Services // Copyright (C) 2007 Xerox Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.xerox.amazonws.sqs; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.xml.bind.JAXBException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.methods.GetMethod; import com.xerox.amazonws.common.AWSException; import com.xerox.amazonws.common.AWSQueryConnection; import com.xerox.amazonws.typica.jaxb.CreateQueueResponse; import com.xerox.amazonws.typica.jaxb.ListQueuesResponse; /** * This class provides an interface with the Amazon SQS service. It provides high level * methods for listing and creating message queues. * * @author D. Kavanagh * @author developer@dotech.com */ public class QueueService extends AWSQueryConnection { private static Log logger = LogFactory.getLog(QueueService.class); /** * Initializes the queue service with your AWS login information. * * @param awsAccessId The your user key into AWS * @param awsSecretKey The secret string used to generate signatures for authentication. */ public QueueService(String awsAccessId, String awsSecretKey) { this(awsAccessId, awsSecretKey, true); } /** * Initializes the queue service with your AWS login information. * * @param awsAccessId The your user key into AWS * @param awsSecretKey The secret string used to generate signatures for authentication. * @param isSecure True if the data should be encrypted on the wire on the way to or from SQS. */ public QueueService(String awsAccessId, String awsSecretKey, boolean isSecure) { this(awsAccessId, awsSecretKey, isSecure, "queue.amazonaws.com"); } /** * Initializes the queue service with your AWS login information. * * @param awsAccessId The your user key into AWS * @param awsSecretKey The secret string used to generate signatures for authentication. * @param isSecure True if the data should be encrypted on the wire on the way to or from SQS. * @param server Which host to connect to. Usually, this will be queue.amazonaws.com */ public QueueService(String awsAccessId, String awsSecretKey, boolean isSecure, String server) { this(awsAccessId, awsSecretKey, isSecure, server, isSecure ? 443 : 80); } /** * Initializes the queue service with your AWS login information. * * @param awsAccessId The your user key into AWS * @param awsSecretKey The secret string used to generate signatures for authentication. * @param isSecure True if the data should be encrypted on the wire on the way to or from SQS. * @param server Which host to connect to. Usually, this will be queue.amazonaws.com * @param port Which port to use. */ public QueueService(String awsAccessId, String awsSecretKey, boolean isSecure, String server, int port) { super(awsAccessId, awsSecretKey, isSecure, server, port); setVersionHeader(this); } /** * Creates a new message queue. The queue name must be unique within the scope of the * queues you own. Optionaly, you can supply a queue that might be one that belongs to * another user that has granted you access to the queue. In that case, supply the fully * qualified queue name (i.e. "/A98KKI3K0RJ7Q/grantedQueue"). * * @param queueName name of queue to be created * @return object representing the message queue */ public MessageQueue getOrCreateMessageQueue(String queueName) throws SQSException { if ((queueName.charAt(0) == '/' && queueName.lastIndexOf('/') > 0) || queueName.startsWith("http")) { return getMessageQueue(queueName); } else { Map<String, String> params = new HashMap<String, String>(); params.put("QueueName", queueName); GetMethod method = new GetMethod(); try { CreateQueueResponse response = makeRequestInt(method, "CreateQueue", params, CreateQueueResponse.class); MessageQueue mq = new MessageQueue(response.getQueueUrl(), getAwsAccessKeyId(), getSecretAccessKey(), isSecure(), getServer()); mq.setHttpClient(getHttpClient()); return mq; } finally { method.releaseConnection(); } } } /** * Returns a new message queue. The queue name must be of a queue already created and/or * accessible to your account. (i.e. "https://queue.amazonaws.com/A98KKI3K0RJ7Q/myQueue", * "/B38IZ53W0RU2X/grantedQueue"). * * @param queueName qualified name of queue * @return object representing the message queue */ public MessageQueue getMessageQueue(String queueName) throws SQSException { if (!(queueName.charAt(0) == '/' && queueName.lastIndexOf('/') > 0) && !queueName.startsWith("http")) { throw new IllegalArgumentException("Queue name must be more fuly specified or use getOrCreateMessageQueue()."); } MessageQueue mq = new MessageQueue(queueName, getAwsAccessKeyId(), getSecretAccessKey(), isSecure(), getServer()); mq.setHttpClient(getHttpClient()); return mq; } /** * Retrieves a list of message queues. A maximum of 1,000 queue URLs are returned. * If a value is specified for the optional queueNamePrefix parameter, only those queues * with a queue name beginning with the value specified are returned. The queue name is * specified in the QueueName parameter when a queue is created. * * @param queueNamePrefix the optional prefix for filtering results. can be null. * @return a list of objects representing the message queues defined for this account */ public List<MessageQueue> listMessageQueues(String queueNamePrefix) throws SQSException { Map<String, String> params = new HashMap<String, String>(); if (queueNamePrefix != null && !queueNamePrefix.trim().equals("")) { params.put("QueueNamePrefix", queueNamePrefix); } GetMethod method = new GetMethod(); try { ListQueuesResponse response = makeRequestInt(method, "ListQueues", params, ListQueuesResponse.class); return MessageQueue.createList(response.getQueueUrls().toArray(new String[] {}), getAwsAccessKeyId(), getSecretAccessKey(), isSecure(), getServer(), getHttpClient()); } finally { method.releaseConnection(); } } protected <T> T makeRequestInt(HttpMethodBase method, String action, Map<String, String> params, Class<T> respType) throws SQSException { try { return makeRequest(method, action, params, respType); } catch (AWSException ex) { throw new SQSException(ex); } catch (JAXBException ex) { throw new SQSException("Problem parsing returned message.", ex); } catch (HttpException ex) { throw new SQSException(ex.getMessage(), ex); } catch (IOException ex) { throw new SQSException(ex.getMessage(), ex); } } static void setVersionHeader(AWSQueryConnection connection) { ArrayList vals = new ArrayList(); vals.add("2007-05-01"); connection.getHeaders().put("Version", vals); } }
/** */ package substationStandard.Dataclasses.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import substationStandard.Dataclasses.BCR; import substationStandard.Dataclasses.DataclassesPackage; import substationStandard.Dataclasses.Quality; import substationStandard.Dataclasses.TimeStamp; import substationStandard.Dataclasses.Units; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>BCR</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#getActVal <em>Act Val</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#getFrVal <em>Fr Val</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#getFrTm <em>Fr Tm</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#getQ <em>Q</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#getUnits <em>Units</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#getPulsQty <em>Puls Qty</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#isFrEna <em>Fr Ena</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#getStrTm <em>Str Tm</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#getFrPd <em>Fr Pd</em>}</li> * <li>{@link substationStandard.Dataclasses.impl.BCRImpl#isFrRs <em>Fr Rs</em>}</li> * </ul> * * @generated */ public class BCRImpl extends MinimalEObjectImpl.Container implements BCR { /** * The default value of the '{@link #getActVal() <em>Act Val</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getActVal() * @generated * @ordered */ protected static final int ACT_VAL_EDEFAULT = 0; /** * The cached value of the '{@link #getActVal() <em>Act Val</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getActVal() * @generated * @ordered */ protected int actVal = ACT_VAL_EDEFAULT; /** * The default value of the '{@link #getFrVal() <em>Fr Val</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFrVal() * @generated * @ordered */ protected static final int FR_VAL_EDEFAULT = 0; /** * The cached value of the '{@link #getFrVal() <em>Fr Val</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFrVal() * @generated * @ordered */ protected int frVal = FR_VAL_EDEFAULT; /** * The cached value of the '{@link #getFrTm() <em>Fr Tm</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFrTm() * @generated * @ordered */ protected TimeStamp frTm; /** * The cached value of the '{@link #getQ() <em>Q</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getQ() * @generated * @ordered */ protected Quality q; /** * The cached value of the '{@link #getUnits() <em>Units</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUnits() * @generated * @ordered */ protected Units units; /** * The default value of the '{@link #getPulsQty() <em>Puls Qty</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPulsQty() * @generated * @ordered */ protected static final float PULS_QTY_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getPulsQty() <em>Puls Qty</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPulsQty() * @generated * @ordered */ protected float pulsQty = PULS_QTY_EDEFAULT; /** * The default value of the '{@link #isFrEna() <em>Fr Ena</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isFrEna() * @generated * @ordered */ protected static final boolean FR_ENA_EDEFAULT = false; /** * The cached value of the '{@link #isFrEna() <em>Fr Ena</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isFrEna() * @generated * @ordered */ protected boolean frEna = FR_ENA_EDEFAULT; /** * The cached value of the '{@link #getStrTm() <em>Str Tm</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStrTm() * @generated * @ordered */ protected TimeStamp strTm; /** * The default value of the '{@link #getFrPd() <em>Fr Pd</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFrPd() * @generated * @ordered */ protected static final int FR_PD_EDEFAULT = 0; /** * The cached value of the '{@link #getFrPd() <em>Fr Pd</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFrPd() * @generated * @ordered */ protected int frPd = FR_PD_EDEFAULT; /** * The default value of the '{@link #isFrRs() <em>Fr Rs</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isFrRs() * @generated * @ordered */ protected static final boolean FR_RS_EDEFAULT = false; /** * The cached value of the '{@link #isFrRs() <em>Fr Rs</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isFrRs() * @generated * @ordered */ protected boolean frRs = FR_RS_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BCRImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DataclassesPackage.Literals.BCR; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getActVal() { return actVal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setActVal(int newActVal) { int oldActVal = actVal; actVal = newActVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__ACT_VAL, oldActVal, actVal)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getFrVal() { return frVal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFrVal(int newFrVal) { int oldFrVal = frVal; frVal = newFrVal; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__FR_VAL, oldFrVal, frVal)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TimeStamp getFrTm() { if (frTm != null && frTm.eIsProxy()) { InternalEObject oldFrTm = (InternalEObject)frTm; frTm = (TimeStamp)eResolveProxy(oldFrTm); if (frTm != oldFrTm) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, DataclassesPackage.BCR__FR_TM, oldFrTm, frTm)); } } return frTm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TimeStamp basicGetFrTm() { return frTm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFrTm(TimeStamp newFrTm) { TimeStamp oldFrTm = frTm; frTm = newFrTm; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__FR_TM, oldFrTm, frTm)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Quality getQ() { if (q != null && q.eIsProxy()) { InternalEObject oldQ = (InternalEObject)q; q = (Quality)eResolveProxy(oldQ); if (q != oldQ) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, DataclassesPackage.BCR__Q, oldQ, q)); } } return q; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Quality basicGetQ() { return q; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setQ(Quality newQ) { Quality oldQ = q; q = newQ; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__Q, oldQ, q)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Units getUnits() { if (units != null && units.eIsProxy()) { InternalEObject oldUnits = (InternalEObject)units; units = (Units)eResolveProxy(oldUnits); if (units != oldUnits) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, DataclassesPackage.BCR__UNITS, oldUnits, units)); } } return units; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Units basicGetUnits() { return units; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUnits(Units newUnits) { Units oldUnits = units; units = newUnits; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__UNITS, oldUnits, units)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getPulsQty() { return pulsQty; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPulsQty(float newPulsQty) { float oldPulsQty = pulsQty; pulsQty = newPulsQty; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__PULS_QTY, oldPulsQty, pulsQty)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isFrEna() { return frEna; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFrEna(boolean newFrEna) { boolean oldFrEna = frEna; frEna = newFrEna; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__FR_ENA, oldFrEna, frEna)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TimeStamp getStrTm() { if (strTm != null && strTm.eIsProxy()) { InternalEObject oldStrTm = (InternalEObject)strTm; strTm = (TimeStamp)eResolveProxy(oldStrTm); if (strTm != oldStrTm) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, DataclassesPackage.BCR__STR_TM, oldStrTm, strTm)); } } return strTm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TimeStamp basicGetStrTm() { return strTm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStrTm(TimeStamp newStrTm) { TimeStamp oldStrTm = strTm; strTm = newStrTm; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__STR_TM, oldStrTm, strTm)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getFrPd() { return frPd; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFrPd(int newFrPd) { int oldFrPd = frPd; frPd = newFrPd; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__FR_PD, oldFrPd, frPd)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isFrRs() { return frRs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFrRs(boolean newFrRs) { boolean oldFrRs = frRs; frRs = newFrRs; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DataclassesPackage.BCR__FR_RS, oldFrRs, frRs)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DataclassesPackage.BCR__ACT_VAL: return getActVal(); case DataclassesPackage.BCR__FR_VAL: return getFrVal(); case DataclassesPackage.BCR__FR_TM: if (resolve) return getFrTm(); return basicGetFrTm(); case DataclassesPackage.BCR__Q: if (resolve) return getQ(); return basicGetQ(); case DataclassesPackage.BCR__UNITS: if (resolve) return getUnits(); return basicGetUnits(); case DataclassesPackage.BCR__PULS_QTY: return getPulsQty(); case DataclassesPackage.BCR__FR_ENA: return isFrEna(); case DataclassesPackage.BCR__STR_TM: if (resolve) return getStrTm(); return basicGetStrTm(); case DataclassesPackage.BCR__FR_PD: return getFrPd(); case DataclassesPackage.BCR__FR_RS: return isFrRs(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case DataclassesPackage.BCR__ACT_VAL: setActVal((Integer)newValue); return; case DataclassesPackage.BCR__FR_VAL: setFrVal((Integer)newValue); return; case DataclassesPackage.BCR__FR_TM: setFrTm((TimeStamp)newValue); return; case DataclassesPackage.BCR__Q: setQ((Quality)newValue); return; case DataclassesPackage.BCR__UNITS: setUnits((Units)newValue); return; case DataclassesPackage.BCR__PULS_QTY: setPulsQty((Float)newValue); return; case DataclassesPackage.BCR__FR_ENA: setFrEna((Boolean)newValue); return; case DataclassesPackage.BCR__STR_TM: setStrTm((TimeStamp)newValue); return; case DataclassesPackage.BCR__FR_PD: setFrPd((Integer)newValue); return; case DataclassesPackage.BCR__FR_RS: setFrRs((Boolean)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case DataclassesPackage.BCR__ACT_VAL: setActVal(ACT_VAL_EDEFAULT); return; case DataclassesPackage.BCR__FR_VAL: setFrVal(FR_VAL_EDEFAULT); return; case DataclassesPackage.BCR__FR_TM: setFrTm((TimeStamp)null); return; case DataclassesPackage.BCR__Q: setQ((Quality)null); return; case DataclassesPackage.BCR__UNITS: setUnits((Units)null); return; case DataclassesPackage.BCR__PULS_QTY: setPulsQty(PULS_QTY_EDEFAULT); return; case DataclassesPackage.BCR__FR_ENA: setFrEna(FR_ENA_EDEFAULT); return; case DataclassesPackage.BCR__STR_TM: setStrTm((TimeStamp)null); return; case DataclassesPackage.BCR__FR_PD: setFrPd(FR_PD_EDEFAULT); return; case DataclassesPackage.BCR__FR_RS: setFrRs(FR_RS_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case DataclassesPackage.BCR__ACT_VAL: return actVal != ACT_VAL_EDEFAULT; case DataclassesPackage.BCR__FR_VAL: return frVal != FR_VAL_EDEFAULT; case DataclassesPackage.BCR__FR_TM: return frTm != null; case DataclassesPackage.BCR__Q: return q != null; case DataclassesPackage.BCR__UNITS: return units != null; case DataclassesPackage.BCR__PULS_QTY: return pulsQty != PULS_QTY_EDEFAULT; case DataclassesPackage.BCR__FR_ENA: return frEna != FR_ENA_EDEFAULT; case DataclassesPackage.BCR__STR_TM: return strTm != null; case DataclassesPackage.BCR__FR_PD: return frPd != FR_PD_EDEFAULT; case DataclassesPackage.BCR__FR_RS: return frRs != FR_RS_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (actVal: "); result.append(actVal); result.append(", frVal: "); result.append(frVal); result.append(", pulsQty: "); result.append(pulsQty); result.append(", frEna: "); result.append(frEna); result.append(", frPd: "); result.append(frPd); result.append(", frRs: "); result.append(frRs); result.append(')'); return result.toString(); } } //BCRImpl
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.sort; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.join.BitDocIdSetFilter; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.core.LongFieldMapper; import org.elasticsearch.index.mapper.core.NumberFieldMapper; import org.elasticsearch.index.mapper.object.ObjectMapper; import org.elasticsearch.index.query.support.NestedInnerQueryParseSupport; import org.elasticsearch.index.search.nested.NonNestedDocsFilter; import org.elasticsearch.search.MultiValueMode; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SubSearchContext; import java.io.IOException; import java.util.List; /** * */ public class SortParseElement implements SearchParseElement { public static final SortField SORT_SCORE = new SortField(null, SortField.Type.SCORE); private static final SortField SORT_SCORE_REVERSE = new SortField(null, SortField.Type.SCORE, true); private static final SortField SORT_DOC = new SortField(null, SortField.Type.DOC); private static final SortField SORT_DOC_REVERSE = new SortField(null, SortField.Type.DOC, true); public static final ParseField IGNORE_UNMAPPED = new ParseField("ignore_unmapped"); public static final ParseField UNMAPPED_TYPE = new ParseField("unmapped_type"); public static final String SCORE_FIELD_NAME = "_score"; public static final String DOC_FIELD_NAME = "_doc"; private final ImmutableMap<String, SortParser> parsers; public SortParseElement() { ImmutableMap.Builder<String, SortParser> builder = ImmutableMap.builder(); addParser(builder, new ScriptSortParser()); addParser(builder, new GeoDistanceSortParser()); this.parsers = builder.build(); } private void addParser(ImmutableMap.Builder<String, SortParser> parsers, SortParser parser) { for (String name : parser.names()) { parsers.put(name, parser); } } @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); List<SortField> sortFields = Lists.newArrayListWithCapacity(2); if (token == XContentParser.Token.START_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.START_OBJECT) { addCompoundSortField(parser, context, sortFields); } else if (token == XContentParser.Token.VALUE_STRING) { addSortField(context, sortFields, parser.text(), false, null, null, null, null); } else { throw new ElasticsearchIllegalArgumentException("malformed sort format, within the sort array, an object, or an actual string are allowed"); } } } else if (token == XContentParser.Token.VALUE_STRING) { addSortField(context, sortFields, parser.text(), false, null, null, null, null); } else if (token == XContentParser.Token.START_OBJECT) { addCompoundSortField(parser, context, sortFields); } else { throw new ElasticsearchIllegalArgumentException("malformed sort format, either start with array, object, or an actual string"); } if (!sortFields.isEmpty()) { // optimize if we just sort on score non reversed, we don't really need sorting boolean sort; if (sortFields.size() > 1) { sort = true; } else { SortField sortField = sortFields.get(0); if (sortField.getType() == SortField.Type.SCORE && !sortField.getReverse()) { sort = false; } else { sort = true; } } if (sort) { context.sort(new Sort(sortFields.toArray(new SortField[sortFields.size()]))); } } } private void addCompoundSortField(XContentParser parser, SearchContext context, List<SortField> sortFields) throws Exception { XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { String fieldName = parser.currentName(); boolean reverse = false; String missing = null; String innerJsonName = null; String unmappedType = null; MultiValueMode sortMode = null; NestedInnerQueryParseSupport nestedFilterParseHelper = null; token = parser.nextToken(); if (token == XContentParser.Token.VALUE_STRING) { String direction = parser.text(); if (direction.equals("asc")) { reverse = SCORE_FIELD_NAME.equals(fieldName); } else if (direction.equals("desc")) { reverse = !SCORE_FIELD_NAME.equals(fieldName); } else { throw new ElasticsearchIllegalArgumentException("sort direction [" + fieldName + "] not supported"); } addSortField(context, sortFields, fieldName, reverse, unmappedType, missing, sortMode, nestedFilterParseHelper); } else { if (parsers.containsKey(fieldName)) { sortFields.add(parsers.get(fieldName).parse(parser, context)); } else { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { innerJsonName = parser.currentName(); } else if (token.isValue()) { if ("reverse".equals(innerJsonName)) { reverse = parser.booleanValue(); } else if ("order".equals(innerJsonName)) { if ("asc".equals(parser.text())) { reverse = SCORE_FIELD_NAME.equals(fieldName); } else if ("desc".equals(parser.text())) { reverse = !SCORE_FIELD_NAME.equals(fieldName); } } else if ("missing".equals(innerJsonName)) { missing = parser.textOrNull(); } else if (IGNORE_UNMAPPED.match(innerJsonName)) { // backward compatibility: ignore_unmapped has been replaced with unmapped_type if (unmappedType == null // don't override if unmapped_type has been provided too && parser.booleanValue()) { unmappedType = LongFieldMapper.CONTENT_TYPE; } } else if (UNMAPPED_TYPE.match(innerJsonName)) { unmappedType = parser.textOrNull(); } else if ("mode".equals(innerJsonName)) { sortMode = MultiValueMode.fromString(parser.text()); } else if ("nested_path".equals(innerJsonName) || "nestedPath".equals(innerJsonName)) { if (nestedFilterParseHelper == null) { nestedFilterParseHelper = new NestedInnerQueryParseSupport(parser, context); } nestedFilterParseHelper.setPath(parser.text()); } else { throw new ElasticsearchIllegalArgumentException("sort option [" + innerJsonName + "] not supported"); } } else if (token == XContentParser.Token.START_OBJECT) { if ("nested_filter".equals(innerJsonName) || "nestedFilter".equals(innerJsonName)) { if (nestedFilterParseHelper == null) { nestedFilterParseHelper = new NestedInnerQueryParseSupport(parser, context); } nestedFilterParseHelper.filter(); } else { throw new ElasticsearchIllegalArgumentException("sort option [" + innerJsonName + "] not supported"); } } } addSortField(context, sortFields, fieldName, reverse, unmappedType, missing, sortMode, nestedFilterParseHelper); } } } } } private void addSortField(SearchContext context, List<SortField> sortFields, String fieldName, boolean reverse, String unmappedType, @Nullable final String missing, MultiValueMode sortMode, NestedInnerQueryParseSupport nestedHelper) throws IOException { if (SCORE_FIELD_NAME.equals(fieldName)) { if (reverse) { sortFields.add(SORT_SCORE_REVERSE); } else { sortFields.add(SORT_SCORE); } } else if (DOC_FIELD_NAME.equals(fieldName)) { if (reverse) { sortFields.add(SORT_DOC_REVERSE); } else { sortFields.add(SORT_DOC); } } else { FieldMapper<?> fieldMapper = context.smartNameFieldMapper(fieldName); if (fieldMapper == null) { if (unmappedType != null) { fieldMapper = context.mapperService().unmappedFieldMapper(unmappedType); } else { throw new SearchParseException(context, "No mapping found for [" + fieldName + "] in order to sort on"); } } if (!fieldMapper.isSortable()) { throw new SearchParseException(context, "Sorting not supported for field[" + fieldName + "]"); } // Enable when we also know how to detect fields that do tokenize, but only emit one token /*if (fieldMapper instanceof StringFieldMapper) { StringFieldMapper stringFieldMapper = (StringFieldMapper) fieldMapper; if (stringFieldMapper.fieldType().tokenized()) { // Fail early throw new SearchParseException(context, "Can't sort on tokenized string field[" + fieldName + "]"); } }*/ // We only support AVG and SUM on number based fields if (!(fieldMapper instanceof NumberFieldMapper) && (sortMode == MultiValueMode.SUM || sortMode == MultiValueMode.AVG)) { sortMode = null; } if (sortMode == null) { sortMode = resolveDefaultSortMode(reverse); } // TODO: remove this in master, we should be explicit when we want to sort on nested fields and don't do anything automatically if (!(context instanceof SubSearchContext)) { // Only automatically resolve nested path when sort isn't defined for top_hits if (nestedHelper == null || nestedHelper.getNestedObjectMapper() == null) { ObjectMapper objectMapper = context.mapperService().resolveClosestNestedObjectMapper(fieldName); if (objectMapper != null && objectMapper.nested().isNested()) { if (nestedHelper == null) { nestedHelper = new NestedInnerQueryParseSupport(context.queryParserService().getParseContext()); } nestedHelper.setPath(objectMapper.fullPath()); } } } final Nested nested; if (nestedHelper != null && nestedHelper.getPath() != null) { BitDocIdSetFilter rootDocumentsFilter = context.bitsetFilterCache().getBitDocIdSetFilter(NonNestedDocsFilter.INSTANCE); Filter innerDocumentsFilter; if (nestedHelper.filterFound()) { innerDocumentsFilter = context.filterCache().cache(nestedHelper.getInnerFilter(), null, context.queryParserService().autoFilterCachePolicy()); } else { innerDocumentsFilter = context.filterCache().cache(nestedHelper.getNestedObjectMapper().nestedTypeFilter(), null, context.queryParserService().autoFilterCachePolicy()); } nested = new Nested(rootDocumentsFilter, innerDocumentsFilter); } else { nested = null; } IndexFieldData.XFieldComparatorSource fieldComparatorSource = context.fieldData().getForField(fieldMapper) .comparatorSource(missing, sortMode, nested); sortFields.add(new SortField(fieldMapper.names().indexName(), fieldComparatorSource, reverse)); } } private static MultiValueMode resolveDefaultSortMode(boolean reverse) { return reverse ? MultiValueMode.MAX : MultiValueMode.MIN; } }
package de.intarsys.tools.tree; import de.intarsys.tools.attribute.AttributeMap; import de.intarsys.tools.attribute.IAttributeSupport; import de.intarsys.tools.event.AttributeChangedEvent; import de.intarsys.tools.event.DestroyedEvent; import de.intarsys.tools.event.Event; import de.intarsys.tools.event.EventDispatcher; import de.intarsys.tools.event.EventType; import de.intarsys.tools.event.INotificationListener; import de.intarsys.tools.event.INotificationSupport; import de.intarsys.tools.presentation.IPresentationSupport; /** * A common implementation for a node in a tree. This node wraps a POJO for use * in presentation or other contexts. * <p> * The node factory acts as the "role" in which the POJO wants to be wrapped or * seen. This allows a POJO to be seen differently in different usage contexts * by simply using another factory (role). * <p> * There are two main usage scenarios: * <p> * Implement a concrete {@link CommonNode} and {@link CommonNodeFactory} * subclass to determine node behavior. This results in quick and easy to * understand solution. The drawback is the static behavior - if you want to * change some implementation detail down the hierarchy level you have to create * subclasses according to this change up to the root level to ensure the * changed leaf node factory is used. * <p> * The second scenario involves a callback to a strategy object * {@link INodeHandler} where the node behavior is encapsulated. This allows for * a more generic node implementation with the drawback of a "instanceof" style * of coding in the callback handler. * * @param <T> * The type of the wrapped POJO */ abstract public class CommonNode<T> implements IPresentationSupport, INotificationSupport, IAttributeSupport { private static final CommonNode<?>[] NODES_EMPTY = new CommonNode[0]; /** * Return the node associated with object. If no such node exists it will be * created as a child of parent. * <p> * The strategy of associating an object o a node is up to the factory. * * @param parent * @param role * @param object * @return Return the UNIQUE node associated with object. */ synchronized public static CommonNode<?> getNode(CommonNode<?> parent, CommonNodeFactory<?> role, Object object) { CommonNode<?> result = role.lookupNode(parent, object); if (result == null) { CommonNodeFactory<?> factory = role.lookupFactory(object); result = factory.createNode(parent, object); role.registerNode(parent, result); } return result; } private AttributeMap attributes; private CommonNode<?>[] cachedChildren; final private EventDispatcher eventDispatcher; final private INotificationListener listenObjectChange = new INotificationListener() { public void handleEvent(Event event) { onEvent(event); } }; final private INotificationListener listenObjectDestroy = new INotificationListener() { public void handleEvent(Event event) { onDestroy(event); } }; final private T object; final private CommonNode<?> parent; private INodeHandler nodeHandler; protected CommonNode(CommonNode<?> parent, T object) { super(); this.parent = parent; if (parent != null) { this.nodeHandler = parent.nodeHandler; } this.object = object; this.eventDispatcher = new EventDispatcher(this); arm(); } /* * (non-Javadoc) * * @see * de.intarsys.tools.event.INotificationSupport#addNotificationListener( * de.intarsys.tools.event.EventType, * de.intarsys.tools.event.INotificationListener) */ public void addNotificationListener(EventType type, INotificationListener listener) { eventDispatcher.addNotificationListener(type, listener); } protected void arm() { if (object instanceof INotificationSupport) { ((INotificationSupport) object).addNotificationListener( AttributeChangedEvent.ID, listenObjectChange); ((INotificationSupport) object).addNotificationListener( DestroyedEvent.ID, listenObjectDestroy); } } protected CommonNode<?>[] basicCreateChildren() { return NODES_EMPTY; } protected String basicGetDescription() { return getTip(); } protected String basicGetIconName() { return null; } protected String basicGetLabel() { return object.toString(); } protected String basicGetObjectDescription() { if (getObject() instanceof IPresentationSupport) { return ((IPresentationSupport) getObject()).getDescription(); } else { return basicGetDescription(); } } protected String basicGetObjectIconName() { if (getObject() instanceof IPresentationSupport) { return ((IPresentationSupport) getObject()).getIconName(); } else { return basicGetIconName(); } } protected String basicGetObjectLabel() { if (getObject() instanceof IPresentationSupport) { return ((IPresentationSupport) getObject()).getLabel(); } else { return basicGetLabel(); } } protected String basicGetObjectTip() { if (getObject() instanceof IPresentationSupport) { return ((IPresentationSupport) getObject()).getTip(); } else { return basicGetTip(); } } protected String basicGetTip() { return getLabel(); } protected boolean basicHasChildren() { return cachedChildren == null || cachedChildren.length != 0; } protected void disarm() { if (object instanceof INotificationSupport) { ((INotificationSupport) object).removeNotificationListener( AttributeChangedEvent.ID, listenObjectChange); ((INotificationSupport) object).removeNotificationListener( DestroyedEvent.ID, listenObjectDestroy); } } /** * Dispose all resources and associations. This object is not reused any * more */ protected void dispose() { disarm(); disposeChildren(); if (attributes != null) { attributes.clear(); } if (eventDispatcher != null) { eventDispatcher.clear(); } } protected void disposeChildren() { if (cachedChildren == null) { return; } for (CommonNode<?> child : cachedChildren) { child.dispose(); } updateChildren(); } synchronized public Object getAttribute(Object key) { if (attributes == null) { return null; } return attributes.getAttribute(key); } /** * Return all child nodes of this. * * @return Return all child nodes of this. */ public CommonNode<?>[] getChildren() { if (cachedChildren == null) { if (nodeHandler == null) { cachedChildren = basicCreateChildren(); } else { cachedChildren = nodeHandler.createChildren(this); } } return cachedChildren; } /* * (non-Javadoc) * * @see de.intarsys.tools.presentation.IPresentationSupport#getDescription() */ public String getDescription() { if (nodeHandler != null) { return nodeHandler.getDescription(this); } return basicGetObjectDescription(); } /* * (non-Javadoc) * * @see de.intarsys.tools.presentation.IPresentationSupport#getIconName() */ public String getIconName() { if (nodeHandler != null) { return nodeHandler.getIconName(this); } return basicGetObjectIconName(); } /* * (non-Javadoc) * * @see de.intarsys.tools.presentation.IPresentationSupport#getLabel() */ public String getLabel() { if (nodeHandler != null) { return nodeHandler.getLabel(this); } return basicGetObjectLabel(); } public INodeHandler getNodeHandler() { return nodeHandler; } /** * The object represented by this node. * * @return The object represented by this node. */ public T getObject() { return object; } /** * The optional parent node. * * @return The optional parent node. */ public CommonNode<?> getParent() { return parent; } /* * (non-Javadoc) * * @see de.intarsys.tools.presentation.IPresentationSupport#getTip() */ public String getTip() { if (nodeHandler != null) { return nodeHandler.getTip(this); } return basicGetObjectTip(); } /** * <code>true</code> if this node has children. * * @return <code>true</code> if this node has children. */ public boolean hasChildren() { if (nodeHandler == null) { return basicHasChildren(); } else { return nodeHandler.hasChildren(this); } } protected boolean isReusable() { return true; } protected void onAttributeChanged(AttributeChangedEvent event) { // redefine to update whatever attribute / children have changed... triggerChange("label", null, null); //$NON-NLS-1$ } protected void onDestroy(Event event) { dispose(); } protected void onEvent(Event event) { if (event instanceof AttributeChangedEvent) { onAttributeChanged((AttributeChangedEvent) event); } } synchronized public Object removeAttribute(Object key) { if (attributes == null) { return null; } return attributes.removeAttribute(key); } /* * (non-Javadoc) * * @see * de.intarsys.tools.event.INotificationSupport#removeNotificationListener * (de.intarsys.tools.event.EventType, * de.intarsys.tools.event.INotificationListener) */ public void removeNotificationListener(EventType type, INotificationListener listener) { eventDispatcher.removeNotificationListener(type, listener); } synchronized public Object setAttribute(Object key, Object value) { if (attributes == null) { attributes = new AttributeMap(); } return attributes.setAttribute(key, value); } public void setNodeHandler(INodeHandler nodeHandler) { this.nodeHandler = nodeHandler; unlinkChildren(); } protected void triggerChange(Object attribute, Object oldValue, Object newValue) { eventDispatcher.triggerEvent(new AttributeChangedEvent(this, attribute, oldValue, newValue)); } protected void unlink() { if (!isReusable()) { dispose(); } } protected void unlinkChildren() { if (cachedChildren == null) { return; } for (CommonNode<?> child : cachedChildren) { child.unlink(); } updateChildren(); } protected void updateChildren() { if (cachedChildren == null) { return; } cachedChildren = null; triggerChange("children", null, null); //$NON-NLS-1$ } }
package nl.vu.datalayer.hbase.loader; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import nl.vu.datalayer.hbase.connection.HBaseConnection; import nl.vu.datalayer.hbase.connection.NativeJavaConnection; import nl.vu.datalayer.hbase.exceptions.NonNumericalException; import nl.vu.datalayer.hbase.exceptions.NumericalRangeException; import nl.vu.datalayer.hbase.id.BaseId; import nl.vu.datalayer.hbase.id.HBaseValue; import nl.vu.datalayer.hbase.id.Id; import nl.vu.datalayer.hbase.id.TypedId; import nl.vu.datalayer.hbase.operations.IHBaseOperationManager; import nl.vu.datalayer.hbase.retrieve.IHBasePrefixMatchRetrieveOpsManager; import nl.vu.datalayer.hbase.schema.HBPrefixMatchSchema; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import org.openrdf.model.Literal; import org.openrdf.model.Statement; import org.openrdf.model.Value; import org.openrdf.model.impl.URIImpl; public class HBaseLoader { public static final String DEFAULT_CONTEXT = "http://DEFAULT_CONTEXT"; private static long idCounter; //private static HashMap<Value, ValueIdPair> dictionary; private static List<Put> spocTableData; private IHBasePrefixMatchRetrieveOpsManager retOpsManager; private MessageDigest mDigest; private HBaseValue hbaseValue; private ByteArrayOutputStream byteStream; private DataOutputStream dataOutputStream; private HTableInterface id2StringTable; private HBaseConnection con; private String schemaSuffix; private HTableInterface string2IdTable; public HBaseLoader(IHBasePrefixMatchRetrieveOpsManager retOpsManager, HBaseConnection con, String schemaSuffix) { super(); this.retOpsManager = retOpsManager; try { mDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } this.con = con; this.schemaSuffix = schemaSuffix; hbaseValue = new HBaseValue(); byteStream = new ByteArrayOutputStream(100); dataOutputStream = new DataOutputStream(byteStream); try { id2StringTable = con.getTable(HBPrefixMatchSchema.ID2STRING+schemaSuffix); ((HTable)id2StringTable).setAutoFlush(false); string2IdTable = con.getTable(HBPrefixMatchSchema.STRING2ID+schemaSuffix); ((HTable)string2IdTable).setAutoFlush(false); } catch (IOException e) { e.printStackTrace(); } } //assuming all triples can fit into memory public void load(ArrayList<Statement> statements) throws Exception{ if (!(con instanceof NativeJavaConnection)){ throw new Exception("Expected NativeJavaConnection upon loading"); } Configuration configuration = ((NativeJavaConnection)con).getConfiguration(); long lastCounterCol = HBPrefixMatchSchema.getLastCounter(configuration, schemaSuffix); idCounter = HBPrefixMatchSchema.getCounterValue(lastCounterCol, configuration, schemaSuffix); //dictionary = new HashMap<Value, HBaseLoader.ValueIdPair>(); spocTableData = new ArrayList<Put>(statements.size()); quadBreakDown(statements); //loadDictionaryTables(con, schemaSuffix); loadIndexTables(); HBPrefixMatchSchema.updateCounter((int)(lastCounterCol-1), idCounter, schemaSuffix); } private void loadIndexTables() throws IOException { HTableInterface spocTable = con.getTable(HBPrefixMatchSchema.TABLE_NAMES[HBPrefixMatchSchema.SPOC]+schemaSuffix); HTableInterface pocsTable = con.getTable(HBPrefixMatchSchema.TABLE_NAMES[HBPrefixMatchSchema.POCS]+schemaSuffix); HTableInterface ospcTable = con.getTable(HBPrefixMatchSchema.TABLE_NAMES[HBPrefixMatchSchema.OSPC]+schemaSuffix); ((HTable)spocTable).setAutoFlush(false); ((HTable)pocsTable).setAutoFlush(false); ((HTable)ospcTable).setAutoFlush(false); spocTable.put(spocTableData); for (Put put : spocTableData) { Put pocsPut = build(25, 0, 8, 17, put.getRow()); pocsTable.put(pocsPut); Put ospcPut = build(9, 17, 0, 25, put.getRow()); ospcTable.put(ospcPut); } } private void quadBreakDown(ArrayList<Statement> statements) throws IOException, NumericalRangeException { for (Statement statement : statements) { Value subject = statement.getSubject(); Id subjectId = generateId(idCounter, subject, Id.BASE_ID); Value predicate = statement.getPredicate(); Id predicateId = generateId(idCounter, predicate, Id.BASE_ID); Value object = statement.getObject(); Id objectId; if (object instanceof Literal){ Literal l = (Literal)object; if (l.getDatatype() == null){//the Literals with no datatype are considered Strings objectId = generateId(idCounter, object, Id.TYPED_ID); } else{//we have a datatype try { objectId = TypedId.createNumerical(l); } catch (NonNumericalException e) { objectId = generateId(idCounter, object, Id.TYPED_ID); } } } else{ objectId = generateId(idCounter, object, Id.TYPED_ID); } Value context = statement.getContext(); if (context == null){ context = new URIImpl(DEFAULT_CONTEXT); } Id contextId = generateId(idCounter, context, Id.BASE_ID); byte [] spoc = Bytes.add(Bytes.add(subjectId.getBytes(), predicateId.getBytes(), objectId.getBytes()), contextId.getBytes()); spoc = buildSPOCKey(subjectId, predicateId, objectId, contextId); Put spocPut = new Put(spoc); spocPut.add(HBPrefixMatchSchema.COLUMN_FAMILY, HBPrefixMatchSchema.COLUMN_NAME, null); spocTableData.add(spocPut); } } private byte[] buildSPOCKey(Id subjectId, Id predicateId, Id objectId, Id contextId) { byte []spoc = new byte[HBPrefixMatchSchema.KEY_LENGTH]; System.arraycopy(subjectId.getBytes(), subjectId.getContentOffset(), spoc, 0, BaseId.SIZE); System.arraycopy(predicateId.getBytes(), predicateId.getContentOffset(), spoc, 8, BaseId.SIZE); if (objectId instanceof TypedId){ System.arraycopy(objectId.getBytes(), 0, spoc, 16, TypedId.SIZE); } else{ System.arraycopy(objectId.getBytes(), 0, spoc, 17, BaseId.SIZE); } System.arraycopy(contextId.getBytes(), contextId.getContentOffset(), spoc, 25, BaseId.SIZE); return spoc; } public Put build(int sOffset, int pOffset, int oOffset, int cOffset, byte []source) throws IOException { byte []outBytes = new byte[HBPrefixMatchSchema.KEY_LENGTH]; Bytes.putBytes(outBytes, sOffset, source, 0, 8);//put S Bytes.putBytes(outBytes, pOffset, source, 8, 8);//put P Bytes.putBytes(outBytes, oOffset, source, 16, 9);//put O Bytes.putBytes(outBytes, cOffset, source, 25, 8);//put C Put put = new Put(outBytes); put.add(HBPrefixMatchSchema.COLUMN_FAMILY, HBPrefixMatchSchema.COLUMN_NAME, null); return put; } public Id generateId(long oldCounter, Value value, byte idType) throws IOException{ Id retId; byte []idBytes; if ((idBytes=retOpsManager.retrieveId(value)) == null) { retId = Id.build(oldCounter, idType); //ValueIdPair valueIdPair = new ValueIdPair(value, retId); addValue2IdMapping(value, retId); addId2ValueMapping(retId, value); //dictionary.put(value, valueIdPair); idCounter = oldCounter + 1; } else{ retId = Id.build(idBytes); } return retId; } private void addValue2IdMapping(Value val, Id id) throws IOException{ byte []valBytes = val.toString().getBytes("UTF-8"); byte []md5Hash = mDigest.digest(valBytes); Put string2IdPut = new Put(md5Hash); string2IdPut.add(HBPrefixMatchSchema.COLUMN_FAMILY, HBPrefixMatchSchema.COLUMN_NAME, id.getContent()); string2IdTable.put(string2IdPut); } public void addId2ValueMapping(Id id, Value val) throws IOException{ byteStream.reset(); hbaseValue.setValue(val); hbaseValue.write(dataOutputStream); byte []serializedValue = byteStream.toByteArray(); Put id2StringPut = new Put(id.getContent()); id2StringPut.add(HBPrefixMatchSchema.COLUMN_FAMILY, HBPrefixMatchSchema.COLUMN_NAME, serializedValue); id2StringTable.put(id2StringPut); } /*static class ValueIdPair{ public Value value; public Id id; public ValueIdPair(Value value, Id id) { super(); this.value = value; this.id = id; } }*/ }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.zookeeper; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.Random; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import org.apache.jute.BinaryInputArchive; import org.apache.jute.BinaryOutputArchive; import org.apache.jute.Record; import org.apache.log4j.Logger; import org.apache.zookeeper.AsyncCallback.ACLCallback; import org.apache.zookeeper.AsyncCallback.Children2Callback; import org.apache.zookeeper.AsyncCallback.ChildrenCallback; import org.apache.zookeeper.AsyncCallback.DataCallback; import org.apache.zookeeper.AsyncCallback.StatCallback; import org.apache.zookeeper.AsyncCallback.StringCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.apache.zookeeper.Watcher.Event; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.OpCode; import org.apache.zookeeper.ZooKeeper.States; import org.apache.zookeeper.ZooKeeper.WatchRegistration; import org.apache.zookeeper.common.PathUtils; import org.apache.zookeeper.proto.AuthPacket; import org.apache.zookeeper.proto.ConnectRequest; import org.apache.zookeeper.proto.CreateResponse; import org.apache.zookeeper.proto.ExistsResponse; import org.apache.zookeeper.proto.GetACLResponse; import org.apache.zookeeper.proto.GetChildren2Response; import org.apache.zookeeper.proto.GetChildrenResponse; import org.apache.zookeeper.proto.GetDataResponse; import org.apache.zookeeper.proto.ReplyHeader; import org.apache.zookeeper.proto.RequestHeader; import org.apache.zookeeper.proto.SetACLResponse; import org.apache.zookeeper.proto.SetDataResponse; import org.apache.zookeeper.proto.SetWatches; import org.apache.zookeeper.proto.WatcherEvent; import org.apache.zookeeper.server.ByteBufferInputStream; import org.apache.zookeeper.server.ZooTrace; /** * This class manages the socket i/o for the client. ClientCnxn maintains a list * of available servers to connect to and "transparently" switches servers it is * connected to as needed. * */ public class ClientCnxn { private static final Logger LOG = Logger.getLogger(ClientCnxn.class); /** This controls whether automatic watch resetting is enabled. * Clients automatically reset watches during session reconnect, this * option allows the client to turn off this behavior by setting * the environment variable "zookeeper.disableAutoWatchReset" to "true" */ private static boolean disableAutoWatchReset; static { // this var should not be public, but otw there is no easy way // to test disableAutoWatchReset = Boolean.getBoolean("zookeeper.disableAutoWatchReset"); if (LOG.isDebugEnabled()) { LOG.debug("zookeeper.disableAutoWatchReset is " + disableAutoWatchReset); } } private final ArrayList<InetSocketAddress> serverAddrs = new ArrayList<InetSocketAddress>(); static class AuthData { AuthData(String scheme, byte data[]) { this.scheme = scheme; this.data = data; } String scheme; byte data[]; } private final ArrayList<AuthData> authInfo = new ArrayList<AuthData>(); /** * These are the packets that have been sent and are waiting for a response. */ private final LinkedList<Packet> pendingQueue = new LinkedList<Packet>(); /** * These are the packets that need to be sent. */ private final LinkedList<Packet> outgoingQueue = new LinkedList<Packet>(); private int nextAddrToTry = 0; private int connectTimeout; /** The timeout in ms the client negotiated with the server. This is the * "real" timeout, not the timeout request by the client (which may * have been increased/decreased by the server which applies bounds * to this value. */ private volatile int negotiatedSessionTimeout; private int readTimeout; private final int sessionTimeout; private final ZooKeeper zooKeeper; private final ClientWatchManager watcher; private long sessionId; private byte sessionPasswd[] = new byte[16]; final String chrootPath; final SendThread sendThread; final EventThread eventThread; /** * Set to true when close is called. Latches the connection such that we * don't attempt to re-connect to the server if in the middle of closing the * connection (client sends session disconnect to server as part of close * operation) */ private volatile boolean closing = false; public long getSessionId() { return sessionId; } public byte[] getSessionPasswd() { return sessionPasswd; } public int getSessionTimeout() { return negotiatedSessionTimeout; } @Override public String toString() { StringBuilder sb = new StringBuilder(); SocketAddress local = sendThread.getSocket().getLocalSocketAddress(); SocketAddress remote = sendThread.getSocket().getRemoteSocketAddress(); sb .append("sessionid:0x").append(Long.toHexString(getSessionId())) .append(" local:").append(local) .append(" remoteserver:").append(remote) .append(" lastZxid:").append(lastZxid) .append(" xid:").append(xid) .append(" sent:").append(sendThread.getSocket().getSentCount()) .append(" recv:").append(sendThread.getSocket().getRecvCount()) .append(" queuedpkts:").append(outgoingQueue.size()) .append(" pendingresp:").append(pendingQueue.size()) .append(" queuedevents:").append(eventThread.waitingEvents.size()); return sb.toString(); } /** * This class allows us to pass the headers and the relevant records around. */ static class Packet { RequestHeader header; ByteBuffer bb; /** Client's view of the path (may differ due to chroot) **/ String clientPath; /** Servers's view of the path (may differ due to chroot) **/ String serverPath; ReplyHeader replyHeader; Record request; Record response; boolean finished; AsyncCallback cb; Object ctx; WatchRegistration watchRegistration; Packet(RequestHeader header, ReplyHeader replyHeader, Record record, Record response, ByteBuffer bb, WatchRegistration watchRegistration) { this.header = header; this.replyHeader = replyHeader; this.request = record; this.response = response; if (bb != null) { this.bb = bb; } else { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BinaryOutputArchive boa = BinaryOutputArchive .getArchive(baos); boa.writeInt(-1, "len"); // We'll fill this in later header.serialize(boa, "header"); if (record != null) { record.serialize(boa, "request"); } baos.close(); this.bb = ByteBuffer.wrap(baos.toByteArray()); this.bb.putInt(this.bb.capacity() - 4); this.bb.rewind(); } catch (IOException e) { LOG.warn("Ignoring unexpected exception", e); } } this.watchRegistration = watchRegistration; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("clientPath:" + clientPath); sb.append(" serverPath:" + serverPath); sb.append(" finished:" + finished); sb.append(" header:: " + header); sb.append(" replyHeader:: " + replyHeader); sb.append(" request:: " + request); sb.append(" response:: " + response); // jute toString is horrible, remove unnecessary newlines return sb.toString().replaceAll("\r*\n+", " "); } } /** * Creates a connection object. The actual network connect doesn't get * established until needed. The start() instance method must be called * subsequent to construction. * * @param hosts * a comma separated list of hosts that can be connected to. * @param sessionTimeout * the timeout for connections. * @param zooKeeper * the zookeeper object that this connection is related to. * @param watcher watcher for this connection * @throws IOException */ public ClientCnxn(String hosts, int sessionTimeout, ZooKeeper zooKeeper, ClientWatchManager watcher, ClientCnxnSocket socket) throws IOException { this(hosts, sessionTimeout, zooKeeper, watcher, socket, 0, new byte[16]); } /** * Creates a connection object. The actual network connect doesn't get * established until needed. The start() instance method must be called * subsequent to construction. * * @param hosts * a comma separated list of hosts that can be connected to. * @param sessionTimeout * the timeout for connections. * @param zooKeeper * the zookeeper object that this connection is related to. * @param watcher watcher for this connection * @param sessionId session id if re-establishing session * @param sessionPasswd session passwd if re-establishing session * @throws IOException */ public ClientCnxn(String hosts, int sessionTimeout, ZooKeeper zooKeeper, ClientWatchManager watcher, ClientCnxnSocket socket, long sessionId, byte[] sessionPasswd) throws IOException { this.zooKeeper = zooKeeper; this.watcher = watcher; this.sessionId = sessionId; this.sessionPasswd = sessionPasswd; // parse out chroot, if any int off = hosts.indexOf('/'); if (off >= 0) { String chrootPath = hosts.substring(off); // ignore "/" chroot spec, same as null if (chrootPath.length() == 1) { this.chrootPath = null; } else { PathUtils.validatePath(chrootPath); this.chrootPath = chrootPath; } hosts = hosts.substring(0, off); } else { this.chrootPath = null; } String hostsList[] = hosts.split(","); for (String host : hostsList) { int port = 2181; int pidx = host.lastIndexOf(':'); if (pidx >= 0) { // otherwise : is at the end of the string, ignore if (pidx < host.length() - 1) { port = Integer.parseInt(host.substring(pidx + 1)); } host = host.substring(0, pidx); } InetAddress addrs[] = InetAddress.getAllByName(host); for (InetAddress addr : addrs) { serverAddrs.add(new InetSocketAddress(addr, port)); } } this.sessionTimeout = sessionTimeout; connectTimeout = sessionTimeout / hostsList.length; readTimeout = sessionTimeout * 2 / 3; Collections.shuffle(serverAddrs); sendThread = new SendThread(socket); eventThread = new EventThread(); } /** * tests use this to check on reset of watches * @return if the auto reset of watches are disabled */ public static boolean getDisableAutoResetWatch() { return disableAutoWatchReset; } /** * tests use this to set the auto reset * @param b the vaued to set disable watches to */ public static void setDisableAutoResetWatch(boolean b) { disableAutoWatchReset = b; } public void start() { sendThread.start(); eventThread.start(); } private Object eventOfDeath = new Object(); private final static UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOG.error("from " + t.getName(), e); } }; private static class WatcherSetEventPair { private final Set<Watcher> watchers; private final WatchedEvent event; public WatcherSetEventPair(Set<Watcher> watchers, WatchedEvent event) { this.watchers = watchers; this.event = event; } } /** * Guard against creating "-EventThread-EventThread-EventThread-..." thread * names when ZooKeeper object is being created from within a watcher. * See ZOOKEEPER-795 for details. */ private static String makeThreadName(String suffix) { String name = Thread.currentThread().getName(). replaceAll("-EventThread", ""); return name + suffix; } class EventThread extends Thread { private final LinkedBlockingQueue<Object> waitingEvents = new LinkedBlockingQueue<Object>(); /** This is really the queued session state until the event * thread actually processes the event and hands it to the watcher. * But for all intents and purposes this is the state. */ private volatile KeeperState sessionState = KeeperState.Disconnected; EventThread() { super(makeThreadName("-EventThread")); setUncaughtExceptionHandler(uncaughtExceptionHandler); setDaemon(true); } public void queueEvent(WatchedEvent event) { if (event.getType() == EventType.None && sessionState == event.getState()) { return; } sessionState = event.getState(); // materialize the watchers based on the event WatcherSetEventPair pair = new WatcherSetEventPair( watcher.materialize(event.getState(), event.getType(), event.getPath()), event); // queue the pair (watch set & event) for later processing waitingEvents.add(pair); } public void queuePacket(Packet packet) { waitingEvents.add(packet); } public void queueEventOfDeath() { waitingEvents.add(eventOfDeath); } @Override public void run() { try { while (true) { Object event = waitingEvents.take(); try { if (event == eventOfDeath) { return; } if (event instanceof WatcherSetEventPair) { // each watcher will process the event WatcherSetEventPair pair = (WatcherSetEventPair) event; for (Watcher watcher : pair.watchers) { try { watcher.process(pair.event); } catch (Throwable t) { LOG.error("Error while calling watcher ", t); } } } else { Packet p = (Packet) event; int rc = 0; String clientPath = p.clientPath; if (p.replyHeader.getErr() != 0) { rc = p.replyHeader.getErr(); } if (p.cb == null) { LOG.warn("Somehow a null cb got to EventThread!"); } else if (p.response instanceof ExistsResponse || p.response instanceof SetDataResponse || p.response instanceof SetACLResponse) { StatCallback cb = (StatCallback) p.cb; if (rc == 0) { if (p.response instanceof ExistsResponse) { cb.processResult(rc, clientPath, p.ctx, ((ExistsResponse) p.response) .getStat()); } else if (p.response instanceof SetDataResponse) { cb.processResult(rc, clientPath, p.ctx, ((SetDataResponse) p.response) .getStat()); } else if (p.response instanceof SetACLResponse) { cb.processResult(rc, clientPath, p.ctx, ((SetACLResponse) p.response) .getStat()); } } else { cb.processResult(rc, clientPath, p.ctx, null); } } else if (p.response instanceof GetDataResponse) { DataCallback cb = (DataCallback) p.cb; GetDataResponse rsp = (GetDataResponse) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, rsp .getData(), rsp.getStat()); } else { cb.processResult(rc, clientPath, p.ctx, null, null); } } else if (p.response instanceof GetACLResponse) { ACLCallback cb = (ACLCallback) p.cb; GetACLResponse rsp = (GetACLResponse) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, rsp .getAcl(), rsp.getStat()); } else { cb.processResult(rc, clientPath, p.ctx, null, null); } } else if (p.response instanceof GetChildrenResponse) { ChildrenCallback cb = (ChildrenCallback) p.cb; GetChildrenResponse rsp = (GetChildrenResponse) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, rsp .getChildren()); } else { cb.processResult(rc, clientPath, p.ctx, null); } } else if (p.response instanceof GetChildren2Response) { Children2Callback cb = (Children2Callback) p.cb; GetChildren2Response rsp = (GetChildren2Response) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, rsp .getChildren(), rsp.getStat()); } else { cb.processResult(rc, clientPath, p.ctx, null, null); } } else if (p.response instanceof CreateResponse) { StringCallback cb = (StringCallback) p.cb; CreateResponse rsp = (CreateResponse) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, (chrootPath == null ? rsp.getPath() : rsp.getPath() .substring(chrootPath.length()))); } else { cb.processResult(rc, clientPath, p.ctx, null); } } else if (p.cb instanceof VoidCallback) { VoidCallback cb = (VoidCallback) p.cb; cb.processResult(rc, clientPath, p.ctx); } } } catch (Throwable t) { LOG.error("Caught unexpected throwable", t); } } } catch (InterruptedException e) { LOG.error("Event thread exiting due to interruption", e); } LOG.info("EventThread shut down"); } } private void finishPacket(Packet p) { if (p.watchRegistration != null) { p.watchRegistration.register(p.replyHeader.getErr()); } if (p.cb == null) { synchronized (p) { p.finished = true; p.notifyAll(); } } else { p.finished = true; eventThread.queuePacket(p); } } private void conLossPacket(Packet p) { if (p.replyHeader == null) { return; } switch(state) { case AUTH_FAILED: p.replyHeader.setErr(KeeperException.Code.AUTHFAILED.intValue()); break; case CLOSED: p.replyHeader.setErr(KeeperException.Code.SESSIONEXPIRED.intValue()); break; default: p.replyHeader.setErr(KeeperException.Code.CONNECTIONLOSS.intValue()); } finishPacket(p); } private volatile long lastZxid; static class EndOfStreamException extends IOException { private static final long serialVersionUID = -5438877188796231422L; public EndOfStreamException(String msg) { super(msg); } @Override public String toString() { return "EndOfStreamException: " + getMessage(); } } private static class SessionTimeoutException extends IOException { private static final long serialVersionUID = 824482094072071178L; public SessionTimeoutException(String msg) { super(msg); } } private static class SessionExpiredException extends IOException { private static final long serialVersionUID = -1388816932076193249L; public SessionExpiredException(String msg) { super(msg); } } public static final int packetLen = Integer.getInteger("jute.maxbuffer", 4096 * 1024); /** * This class services the outgoing request queue and generates the heart * beats. It also spawns the ReadThread. */ class SendThread extends Thread { private long lastPingSentNs; private final ClientCnxnSocket socket; private int lastConnectIndex = -1; private int currentConnectIndex; private Random r = new Random(System.nanoTime()); SendThread(ClientCnxnSocket socket) { super(currentThread().getName() + "-SendThread()"); state = States.CONNECTING; this.socket = socket; socket.introduce(this, outgoingQueue, sessionId); setUncaughtExceptionHandler(uncaughtExceptionHandler); setDaemon(true); } @Override public void run() { socket.updateNow(); socket.updateLastSendAndHeard(); while (state.isAlive()) { try { if (!socket.isConnected()) { // don't re-establish connection if we are closing if (closing) { break; } startConnect(); socket.updateLastSendAndHeard(); } int to = readTimeout - socket.getIdleRecv(); if (state != States.CONNECTED) { to = connectTimeout - socket.getIdleRecv(); } if (LOG.isTraceEnabled()) { LOG.trace("TO=" + to); } if (to <= 0) { throw new SessionTimeoutException( "Client session timed out, have not heard from server in " + socket.getIdleRecv() + "ms" + " for sessionid 0x" + Long.toHexString(sessionId)); } if (state == States.CONNECTED) { int timeToNextPing = readTimeout / 2 - socket.getIdleSend(); if (LOG.isTraceEnabled()) { LOG.trace("timeToNextPing=" + timeToNextPing); } if (timeToNextPing <= 0) { if (LOG.isTraceEnabled()) { LOG.trace("timeToNextPing=" + timeToNextPing); } sendPing(); socket.updateLastSend(); socket.enableWrite(); } else { if (timeToNextPing < to) { to = timeToNextPing; } } } socket.doTransport(to, pendingQueue); } catch (Exception e) { if (closing) { if (LOG.isDebugEnabled()) { // closing so this is expected LOG.debug("An exception was thrown while closing send thread for session 0x" + Long.toHexString(getSessionId()) + " : " + e.getMessage()); } break; } else { // this is ugly, you have a better way speak up if (e instanceof SessionExpiredException) { LOG.info(e.getMessage() + ", closing socket connection"); } else if (e instanceof SessionTimeoutException) { LOG.info(e.getMessage() + RETRY_CONN_MSG); } else if (e instanceof EndOfStreamException) { LOG.info(e.getMessage() + RETRY_CONN_MSG); } else { LOG.warn("Session 0x" + Long.toHexString(getSessionId()) + " for server " // TODO: this is different in Netty // and NIO // Netty: // + getRemoteSocketAddress() // NIO: // + // ((SocketChannel)sockKey.channel()) // .socket().getRemoteSocketAddress() + socket.getRemoteSocketAddress() + ", unexpected error" + RETRY_CONN_MSG, e); } socket.cleanup(); if (state.isAlive()) { eventThread.queueEvent(new WatchedEvent( Event.EventType.None, Event.KeeperState.Disconnected, null)); } socket.updateNow(); socket.updateLastSendAndHeard(); } } // catch } // while socket.cleanup(); socket.close(); if (state.isAlive()) { eventThread.queueEvent(new WatchedEvent(Event.EventType.None, Event.KeeperState.Disconnected, null)); } ZooTrace.logTraceMessage(LOG, ZooTrace.getTextTraceLevel(), "SendThread exitedloop."); } // TODO: can not name this method getState since Thread.getState() // already exists // It would be cleaner to make class SendThread an implementation of // Runnable /** * Used by ClientCnxnSocket * * @return */ ZooKeeper.States getZkState() { return state; } ClientCnxnSocket getSocket() { return socket; } void primeConnection() throws IOException { LOG.info("Socket connection established to " + socket.getRemoteSocketAddress() + ", initiating session"); lastConnectIndex = currentConnectIndex; ConnectRequest conReq = new ConnectRequest(0, lastZxid, sessionTimeout, sessionId, sessionPasswd); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos); boa.writeInt(-1, "len"); conReq.serialize(boa, "connect"); baos.close(); ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray()); bb.putInt(bb.capacity() - 4); bb.rewind(); synchronized (outgoingQueue) { // We add backwards since we are pushing into the front // Only send if there's a pending watch // TODO: here we have the only remaining use of zooKeeper in // this class. It's to be eliminated! if (!disableAutoWatchReset && (!zooKeeper.getDataWatches().isEmpty() || !zooKeeper.getExistWatches().isEmpty() || !zooKeeper.getChildWatches().isEmpty())) { SetWatches sw = new SetWatches(lastZxid, zooKeeper.getDataWatches(), zooKeeper.getExistWatches(), zooKeeper.getChildWatches()); RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.setWatches); h.setXid(-8); Packet packet = new Packet(h, new ReplyHeader(), sw, null, null, null); outgoingQueue.addFirst(packet); } synchronized (authInfo) { for (AuthData id : authInfo) { outgoingQueue.addFirst(new Packet(new RequestHeader(-4, OpCode.auth), null, new AuthPacket(0, id.scheme, id.data), null, null, null)); } } outgoingQueue.addFirst((new Packet(null, null, null, null, bb, null))); } synchronized(socket) { socket.enableReadWriteOnly(); } if (LOG.isDebugEnabled()) { LOG.debug("Session establishment request sent on " + socket.getRemoteSocketAddress()); } } private void sendPing() { lastPingSentNs = System.nanoTime(); RequestHeader h = new RequestHeader(-2, OpCode.ping); queuePacket(h, null, null, null, null, null, null, null, null); } private void startConnect() throws IOException { if (lastConnectIndex == -1) { // We don't want to delay the first try at a connect, so we // start with -1 the first time around lastConnectIndex = 0; } else { try { Thread.sleep(r.nextInt(1000)); } catch (InterruptedException e1) { LOG.warn("Unexpected exception", e1); } if (nextAddrToTry == lastConnectIndex) { try { // Try not to spin too fast! Thread.sleep(1000); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } } state = States.CONNECTING; currentConnectIndex = nextAddrToTry; InetSocketAddress addr = serverAddrs.get(nextAddrToTry); nextAddrToTry++; if (nextAddrToTry == serverAddrs.size()) { nextAddrToTry = 0; } LOG.info("Opening socket connection to server " + addr); setName(getName().replaceAll("\\(.*\\)", "(" + addr.getHostName() + ":" + addr.getPort() + ")")); socket.connect(addr); } private static final String RETRY_CONN_MSG = ", closing socket connection and attempting reconnect"; void cleanup() { synchronized (pendingQueue) { for (Packet p : pendingQueue) { conLossPacket(p); } pendingQueue.clear(); } synchronized (outgoingQueue) { for (Packet p : outgoingQueue) { conLossPacket(p); } outgoingQueue.clear(); } } void onConnected(int _negotiatedSessionTimeout, long _sessionId, byte[] _sessionPasswd) throws IOException { negotiatedSessionTimeout = _negotiatedSessionTimeout; if (negotiatedSessionTimeout <= 0) { state = States.CLOSED; eventThread.queueEvent(new WatchedEvent( Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null)); eventThread.queueEventOfDeath(); throw new SessionExpiredException( "Unable to reconnect to ZooKeeper service, session 0x" + Long.toHexString(sessionId) + " has expired"); } readTimeout = negotiatedSessionTimeout * 2 / 3; connectTimeout = negotiatedSessionTimeout / serverAddrs.size(); sessionId = _sessionId; sessionPasswd = _sessionPasswd; state = States.CONNECTED; LOG.info("Session establishment complete on server " + socket.getRemoteSocketAddress() + ", sessionid = 0x" + Long.toHexString(sessionId) + ", negotiated timeout = " + negotiatedSessionTimeout); eventThread.queueEvent(new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.SyncConnected, null)); } void readResponse(ByteBuffer incomingBuffer) throws IOException { ByteBufferInputStream bbis = new ByteBufferInputStream( incomingBuffer); BinaryInputArchive bbia = BinaryInputArchive.getArchive(bbis); ReplyHeader replyHdr = new ReplyHeader(); replyHdr.deserialize(bbia, "header"); if (replyHdr.getXid() == -2) { // -2 is the xid for pings if (LOG.isDebugEnabled()) { LOG.debug("Got ping response for sessionid: 0x" + Long.toHexString(sessionId) + " after " + ((System.nanoTime() - lastPingSentNs) / 1000000) + "ms"); } return; } if (replyHdr.getXid() == -4) { // -4 is the xid for AuthPacket if(replyHdr.getErr() == KeeperException.Code.AUTHFAILED.intValue()) { state = States.AUTH_FAILED; eventThread.queueEvent( new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.AuthFailed, null) ); } if (LOG.isDebugEnabled()) { LOG.debug("Got auth sessionid:0x" + Long.toHexString(sessionId)); } return; } if (replyHdr.getXid() == -1) { // -1 means notification if (LOG.isDebugEnabled()) { LOG.debug("Got notification sessionid:0x" + Long.toHexString(sessionId)); } WatcherEvent event = new WatcherEvent(); event.deserialize(bbia, "response"); // convert from a server path to a client path if (chrootPath != null) { String serverPath = event.getPath(); if(serverPath.compareTo(chrootPath)==0) event.setPath("/"); else event.setPath(serverPath.substring(chrootPath.length())); } WatchedEvent we = new WatchedEvent(event); if (LOG.isDebugEnabled()) { LOG.debug("Got " + we + " for sessionid 0x" + Long.toHexString(sessionId)); } eventThread.queueEvent( we ); return; } Packet packet; synchronized (pendingQueue) { if (pendingQueue.size() == 0) { throw new IOException("Nothing in the queue, but got " + replyHdr.getXid()); } packet = pendingQueue.remove(); } /* * Since requests are processed in order, we better get a response * to the first request! */ try { if (packet.header.getXid() != replyHdr.getXid()) { packet.replyHeader.setErr( KeeperException.Code.CONNECTIONLOSS.intValue()); throw new IOException("Xid out of order. Got Xid " + replyHdr.getXid() + " with err " + + replyHdr.getErr() + " expected Xid " + packet.header.getXid() + " for a packet with details: " + packet ); } packet.replyHeader.setXid(replyHdr.getXid()); packet.replyHeader.setErr(replyHdr.getErr()); packet.replyHeader.setZxid(replyHdr.getZxid()); if (replyHdr.getZxid() > 0) { lastZxid = replyHdr.getZxid(); } if (packet.response != null && replyHdr.getErr() == 0) { packet.response.deserialize(bbia, "response"); } if (LOG.isDebugEnabled()) { LOG.debug("Reading reply sessionid:0x" + Long.toHexString(sessionId) + ", packet:: " + packet); } } finally { finishPacket(packet); } } void close() { if (LOG.isTraceEnabled()) { LOG.trace("close called sessionId:0x" + Long.toHexString(sessionId)); } state = States.CLOSED; socket.wakeupCnxn(); } void testableCloseSocket() throws IOException { socket.testableCloseSocket(); } } /** * Shutdown the send/event threads. This method should not be called * directly - rather it should be called as part of close operation. This * method is primarily here to allow the tests to verify disconnection * behavior. */ public void disconnect() { if (LOG.isDebugEnabled()) { LOG.debug("Disconnecting client for session: 0x" + Long.toHexString(getSessionId())); } sendThread.close(); eventThread.queueEventOfDeath(); } /** * Close the connection, which includes; send session disconnect to the * server, shutdown the send/event threads. * * @throws IOException */ public void close() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Closing client for session: 0x" + Long.toHexString(getSessionId())); } try { RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.closeSession); submitRequest(h, null, null, null); } catch (InterruptedException e) { // ignore, close the send/event threads } finally { disconnect(); } } private int xid = 1; private volatile States state; synchronized private int getXid() { return xid++; } public ReplyHeader submitRequest(RequestHeader h, Record request, Record response, WatchRegistration watchRegistration) throws InterruptedException { ReplyHeader r = new ReplyHeader(); Packet packet = queuePacket(h, r, request, response, null, null, null, null, watchRegistration); synchronized (packet) { while (!packet.finished) { packet.wait(); } } return r; } Packet queuePacket(RequestHeader h, ReplyHeader r, Record request, Record response, AsyncCallback cb, String clientPath, String serverPath, Object ctx, WatchRegistration watchRegistration) { Packet packet = null; synchronized (outgoingQueue) { if (h.getType() != OpCode.ping && h.getType() != OpCode.auth) { h.setXid(getXid()); } packet = new Packet(h, r, request, response, null, watchRegistration); packet.cb = cb; packet.ctx = ctx; packet.clientPath = clientPath; packet.serverPath = serverPath; if (!state.isAlive() || closing) { conLossPacket(packet); } else { // If the client is asking to close the session then // mark as closing if (h.getType() == OpCode.closeSession) { closing = true; } outgoingQueue.add(packet); } } sendThread.getSocket().wakeupCnxn(); return packet; } public void addAuthInfo(String scheme, byte auth[]) { if (!state.isAlive()) { return; } synchronized (authInfo) { authInfo.add(new AuthData(scheme, auth)); } queuePacket(new RequestHeader(-4, OpCode.auth), null, new AuthPacket(0, scheme, auth), null, null, null, null, null, null); } States getState() { return state; } }
/** */ package COSEM.impl; import COSEM.COSEMObjects.AutoConnectObject; import COSEM.COSEMObjects.BillingPeriodValues; import COSEM.COSEMObjects.CurrentAssociation; import COSEM.COSEMObjects.CurrentlyActiveTariff; import COSEM.COSEMObjects.ElectricityHarmonics; import COSEM.COSEMObjects.ElectricityID; import COSEM.COSEMObjects.ElectricityNominalValues; import COSEM.COSEMObjects.ElectricityProgramEntries; import COSEM.COSEMObjects.ElectricityRelatedStatusData; import COSEM.COSEMObjects.ElectricityValues; import COSEM.COSEMObjects.ExtendedPhaseAngleMeasurement; import COSEM.COSEMObjects.InputPulseValuesOrConstants; import COSEM.COSEMObjects.MeasurementMethods; import COSEM.COSEMObjects.MeasurementPeriod_recordingInterval_billingPeriodDuration; import COSEM.COSEMObjects.MeasurementValues; import COSEM.COSEMObjects.MeteringPointID; import COSEM.COSEMObjects.OutputPulseValues_constants; import COSEM.COSEMObjects.ReadingFactorAndCT_VTratio; import COSEM.COSEMObjects.RegisterMonitorObject; import COSEM.COSEMObjects.TimeEntries; import COSEM.COSEMObjects.TransformerAndLineLosses; import COSEM.COSEMPackage; import COSEM.LogicalDevice; import COSEM.ManagementLogicalDevice; import COSEM.PhysicalDevice; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectResolvingEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Physical Device</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getManagementLogicalDevice <em>Management Logical Device</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getID <em>ID</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getLogicalDevice <em>Logical Device</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getElectricityRelatedStatus <em>Electricity Related Status</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getAA <em>AA</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getAutoConnect <em>Auto Connect</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getBillingPeriodValues <em>Billing Period Values</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getElectricityID <em>Electricity ID</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getProgramEntries <em>Program Entries</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getOutputPulse <em>Output Pulse</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getReadingFactor <em>Reading Factor</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getNominalValues <em>Nominal Values</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getInputPulse <em>Input Pulse</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getMeasurementPeriod <em>Measurement Period</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getTimeEntries <em>Time Entries</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getTransformerLineLosses <em>Transformer Line Losses</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getMeasurementAlgorithm <em>Measurement Algorithm</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getMeteringPoint <em>Metering Point</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getRegisterMonitor <em>Register Monitor</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getElectricityValues <em>Electricity Values</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getMeasurementValueTypes <em>Measurement Value Types</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getHarmonics <em>Harmonics</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getTariffs <em>Tariffs</em>}</li> * <li>{@link COSEM.impl.PhysicalDeviceImpl#getPhaseangles <em>Phaseangles</em>}</li> * </ul> * * @generated */ public class PhysicalDeviceImpl extends MinimalEObjectImpl.Container implements PhysicalDevice { /** * The cached value of the '{@link #getManagementLogicalDevice() <em>Management Logical Device</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getManagementLogicalDevice() * @generated * @ordered */ protected ManagementLogicalDevice managementLogicalDevice; /** * The default value of the '{@link #getID() <em>ID</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getID() * @generated * @ordered */ protected static final String ID_EDEFAULT = null; /** * The cached value of the '{@link #getID() <em>ID</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getID() * @generated * @ordered */ protected String id = ID_EDEFAULT; /** * The cached value of the '{@link #getLogicalDevice() <em>Logical Device</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLogicalDevice() * @generated * @ordered */ protected EList<LogicalDevice> logicalDevice; /** * The cached value of the '{@link #getElectricityRelatedStatus() <em>Electricity Related Status</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getElectricityRelatedStatus() * @generated * @ordered */ protected ElectricityRelatedStatusData electricityRelatedStatus; /** * The cached value of the '{@link #getAA() <em>AA</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAA() * @generated * @ordered */ protected CurrentAssociation aa; /** * The cached value of the '{@link #getAutoConnect() <em>Auto Connect</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAutoConnect() * @generated * @ordered */ protected AutoConnectObject autoConnect; /** * The cached value of the '{@link #getBillingPeriodValues() <em>Billing Period Values</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBillingPeriodValues() * @generated * @ordered */ protected BillingPeriodValues billingPeriodValues; /** * The cached value of the '{@link #getElectricityID() <em>Electricity ID</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getElectricityID() * @generated * @ordered */ protected ElectricityID electricityID; /** * The cached value of the '{@link #getProgramEntries() <em>Program Entries</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getProgramEntries() * @generated * @ordered */ protected ElectricityProgramEntries programEntries; /** * The cached value of the '{@link #getOutputPulse() <em>Output Pulse</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOutputPulse() * @generated * @ordered */ protected OutputPulseValues_constants outputPulse; /** * The cached value of the '{@link #getReadingFactor() <em>Reading Factor</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReadingFactor() * @generated * @ordered */ protected ReadingFactorAndCT_VTratio readingFactor; /** * The cached value of the '{@link #getNominalValues() <em>Nominal Values</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNominalValues() * @generated * @ordered */ protected ElectricityNominalValues nominalValues; /** * The cached value of the '{@link #getInputPulse() <em>Input Pulse</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInputPulse() * @generated * @ordered */ protected InputPulseValuesOrConstants inputPulse; /** * The cached value of the '{@link #getMeasurementPeriod() <em>Measurement Period</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMeasurementPeriod() * @generated * @ordered */ protected MeasurementPeriod_recordingInterval_billingPeriodDuration measurementPeriod; /** * The cached value of the '{@link #getTimeEntries() <em>Time Entries</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTimeEntries() * @generated * @ordered */ protected TimeEntries timeEntries; /** * The cached value of the '{@link #getTransformerLineLosses() <em>Transformer Line Losses</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTransformerLineLosses() * @generated * @ordered */ protected TransformerAndLineLosses transformerLineLosses; /** * The cached value of the '{@link #getMeasurementAlgorithm() <em>Measurement Algorithm</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMeasurementAlgorithm() * @generated * @ordered */ protected MeasurementMethods measurementAlgorithm; /** * The cached value of the '{@link #getMeteringPoint() <em>Metering Point</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMeteringPoint() * @generated * @ordered */ protected MeteringPointID meteringPoint; /** * The cached value of the '{@link #getRegisterMonitor() <em>Register Monitor</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRegisterMonitor() * @generated * @ordered */ protected RegisterMonitorObject registerMonitor; /** * The cached value of the '{@link #getElectricityValues() <em>Electricity Values</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getElectricityValues() * @generated * @ordered */ protected ElectricityValues electricityValues; /** * The cached value of the '{@link #getMeasurementValueTypes() <em>Measurement Value Types</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMeasurementValueTypes() * @generated * @ordered */ protected MeasurementValues measurementValueTypes; /** * The cached value of the '{@link #getHarmonics() <em>Harmonics</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHarmonics() * @generated * @ordered */ protected ElectricityHarmonics harmonics; /** * The cached value of the '{@link #getTariffs() <em>Tariffs</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTariffs() * @generated * @ordered */ protected CurrentlyActiveTariff tariffs; /** * The cached value of the '{@link #getPhaseangles() <em>Phaseangles</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPhaseangles() * @generated * @ordered */ protected ExtendedPhaseAngleMeasurement phaseangles; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected PhysicalDeviceImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return COSEMPackage.Literals.PHYSICAL_DEVICE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ManagementLogicalDevice getManagementLogicalDevice() { if (managementLogicalDevice != null && managementLogicalDevice.eIsProxy()) { InternalEObject oldManagementLogicalDevice = (InternalEObject)managementLogicalDevice; managementLogicalDevice = (ManagementLogicalDevice)eResolveProxy(oldManagementLogicalDevice); if (managementLogicalDevice != oldManagementLogicalDevice) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, COSEMPackage.PHYSICAL_DEVICE__MANAGEMENT_LOGICAL_DEVICE, oldManagementLogicalDevice, managementLogicalDevice)); } } return managementLogicalDevice; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ManagementLogicalDevice basicGetManagementLogicalDevice() { return managementLogicalDevice; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setManagementLogicalDevice(ManagementLogicalDevice newManagementLogicalDevice) { ManagementLogicalDevice oldManagementLogicalDevice = managementLogicalDevice; managementLogicalDevice = newManagementLogicalDevice; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__MANAGEMENT_LOGICAL_DEVICE, oldManagementLogicalDevice, managementLogicalDevice)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getID() { return id; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setID(String newID) { String oldID = id; id = newID; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__ID, oldID, id)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<LogicalDevice> getLogicalDevice() { if (logicalDevice == null) { logicalDevice = new EObjectResolvingEList<LogicalDevice>(LogicalDevice.class, this, COSEMPackage.PHYSICAL_DEVICE__LOGICAL_DEVICE); } return logicalDevice; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ElectricityRelatedStatusData getElectricityRelatedStatus() { return electricityRelatedStatus; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetElectricityRelatedStatus(ElectricityRelatedStatusData newElectricityRelatedStatus, NotificationChain msgs) { ElectricityRelatedStatusData oldElectricityRelatedStatus = electricityRelatedStatus; electricityRelatedStatus = newElectricityRelatedStatus; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS, oldElectricityRelatedStatus, newElectricityRelatedStatus); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setElectricityRelatedStatus(ElectricityRelatedStatusData newElectricityRelatedStatus) { if (newElectricityRelatedStatus != electricityRelatedStatus) { NotificationChain msgs = null; if (electricityRelatedStatus != null) msgs = ((InternalEObject)electricityRelatedStatus).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS, null, msgs); if (newElectricityRelatedStatus != null) msgs = ((InternalEObject)newElectricityRelatedStatus).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS, null, msgs); msgs = basicSetElectricityRelatedStatus(newElectricityRelatedStatus, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS, newElectricityRelatedStatus, newElectricityRelatedStatus)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CurrentAssociation getAA() { return aa; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetAA(CurrentAssociation newAA, NotificationChain msgs) { CurrentAssociation oldAA = aa; aa = newAA; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__AA, oldAA, newAA); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setAA(CurrentAssociation newAA) { if (newAA != aa) { NotificationChain msgs = null; if (aa != null) msgs = ((InternalEObject)aa).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__AA, null, msgs); if (newAA != null) msgs = ((InternalEObject)newAA).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__AA, null, msgs); msgs = basicSetAA(newAA, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__AA, newAA, newAA)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AutoConnectObject getAutoConnect() { return autoConnect; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetAutoConnect(AutoConnectObject newAutoConnect, NotificationChain msgs) { AutoConnectObject oldAutoConnect = autoConnect; autoConnect = newAutoConnect; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT, oldAutoConnect, newAutoConnect); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setAutoConnect(AutoConnectObject newAutoConnect) { if (newAutoConnect != autoConnect) { NotificationChain msgs = null; if (autoConnect != null) msgs = ((InternalEObject)autoConnect).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT, null, msgs); if (newAutoConnect != null) msgs = ((InternalEObject)newAutoConnect).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT, null, msgs); msgs = basicSetAutoConnect(newAutoConnect, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT, newAutoConnect, newAutoConnect)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BillingPeriodValues getBillingPeriodValues() { return billingPeriodValues; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetBillingPeriodValues(BillingPeriodValues newBillingPeriodValues, NotificationChain msgs) { BillingPeriodValues oldBillingPeriodValues = billingPeriodValues; billingPeriodValues = newBillingPeriodValues; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES, oldBillingPeriodValues, newBillingPeriodValues); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setBillingPeriodValues(BillingPeriodValues newBillingPeriodValues) { if (newBillingPeriodValues != billingPeriodValues) { NotificationChain msgs = null; if (billingPeriodValues != null) msgs = ((InternalEObject)billingPeriodValues).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES, null, msgs); if (newBillingPeriodValues != null) msgs = ((InternalEObject)newBillingPeriodValues).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES, null, msgs); msgs = basicSetBillingPeriodValues(newBillingPeriodValues, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES, newBillingPeriodValues, newBillingPeriodValues)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ElectricityID getElectricityID() { return electricityID; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetElectricityID(ElectricityID newElectricityID, NotificationChain msgs) { ElectricityID oldElectricityID = electricityID; electricityID = newElectricityID; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID, oldElectricityID, newElectricityID); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setElectricityID(ElectricityID newElectricityID) { if (newElectricityID != electricityID) { NotificationChain msgs = null; if (electricityID != null) msgs = ((InternalEObject)electricityID).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID, null, msgs); if (newElectricityID != null) msgs = ((InternalEObject)newElectricityID).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID, null, msgs); msgs = basicSetElectricityID(newElectricityID, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID, newElectricityID, newElectricityID)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ElectricityProgramEntries getProgramEntries() { return programEntries; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetProgramEntries(ElectricityProgramEntries newProgramEntries, NotificationChain msgs) { ElectricityProgramEntries oldProgramEntries = programEntries; programEntries = newProgramEntries; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES, oldProgramEntries, newProgramEntries); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setProgramEntries(ElectricityProgramEntries newProgramEntries) { if (newProgramEntries != programEntries) { NotificationChain msgs = null; if (programEntries != null) msgs = ((InternalEObject)programEntries).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES, null, msgs); if (newProgramEntries != null) msgs = ((InternalEObject)newProgramEntries).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES, null, msgs); msgs = basicSetProgramEntries(newProgramEntries, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES, newProgramEntries, newProgramEntries)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OutputPulseValues_constants getOutputPulse() { return outputPulse; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetOutputPulse(OutputPulseValues_constants newOutputPulse, NotificationChain msgs) { OutputPulseValues_constants oldOutputPulse = outputPulse; outputPulse = newOutputPulse; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE, oldOutputPulse, newOutputPulse); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOutputPulse(OutputPulseValues_constants newOutputPulse) { if (newOutputPulse != outputPulse) { NotificationChain msgs = null; if (outputPulse != null) msgs = ((InternalEObject)outputPulse).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE, null, msgs); if (newOutputPulse != null) msgs = ((InternalEObject)newOutputPulse).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE, null, msgs); msgs = basicSetOutputPulse(newOutputPulse, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE, newOutputPulse, newOutputPulse)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ReadingFactorAndCT_VTratio getReadingFactor() { return readingFactor; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetReadingFactor(ReadingFactorAndCT_VTratio newReadingFactor, NotificationChain msgs) { ReadingFactorAndCT_VTratio oldReadingFactor = readingFactor; readingFactor = newReadingFactor; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR, oldReadingFactor, newReadingFactor); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setReadingFactor(ReadingFactorAndCT_VTratio newReadingFactor) { if (newReadingFactor != readingFactor) { NotificationChain msgs = null; if (readingFactor != null) msgs = ((InternalEObject)readingFactor).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR, null, msgs); if (newReadingFactor != null) msgs = ((InternalEObject)newReadingFactor).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR, null, msgs); msgs = basicSetReadingFactor(newReadingFactor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR, newReadingFactor, newReadingFactor)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ElectricityNominalValues getNominalValues() { return nominalValues; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetNominalValues(ElectricityNominalValues newNominalValues, NotificationChain msgs) { ElectricityNominalValues oldNominalValues = nominalValues; nominalValues = newNominalValues; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES, oldNominalValues, newNominalValues); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setNominalValues(ElectricityNominalValues newNominalValues) { if (newNominalValues != nominalValues) { NotificationChain msgs = null; if (nominalValues != null) msgs = ((InternalEObject)nominalValues).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES, null, msgs); if (newNominalValues != null) msgs = ((InternalEObject)newNominalValues).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES, null, msgs); msgs = basicSetNominalValues(newNominalValues, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES, newNominalValues, newNominalValues)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InputPulseValuesOrConstants getInputPulse() { return inputPulse; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetInputPulse(InputPulseValuesOrConstants newInputPulse, NotificationChain msgs) { InputPulseValuesOrConstants oldInputPulse = inputPulse; inputPulse = newInputPulse; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE, oldInputPulse, newInputPulse); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInputPulse(InputPulseValuesOrConstants newInputPulse) { if (newInputPulse != inputPulse) { NotificationChain msgs = null; if (inputPulse != null) msgs = ((InternalEObject)inputPulse).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE, null, msgs); if (newInputPulse != null) msgs = ((InternalEObject)newInputPulse).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE, null, msgs); msgs = basicSetInputPulse(newInputPulse, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE, newInputPulse, newInputPulse)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MeasurementPeriod_recordingInterval_billingPeriodDuration getMeasurementPeriod() { return measurementPeriod; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetMeasurementPeriod(MeasurementPeriod_recordingInterval_billingPeriodDuration newMeasurementPeriod, NotificationChain msgs) { MeasurementPeriod_recordingInterval_billingPeriodDuration oldMeasurementPeriod = measurementPeriod; measurementPeriod = newMeasurementPeriod; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD, oldMeasurementPeriod, newMeasurementPeriod); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMeasurementPeriod(MeasurementPeriod_recordingInterval_billingPeriodDuration newMeasurementPeriod) { if (newMeasurementPeriod != measurementPeriod) { NotificationChain msgs = null; if (measurementPeriod != null) msgs = ((InternalEObject)measurementPeriod).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD, null, msgs); if (newMeasurementPeriod != null) msgs = ((InternalEObject)newMeasurementPeriod).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD, null, msgs); msgs = basicSetMeasurementPeriod(newMeasurementPeriod, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD, newMeasurementPeriod, newMeasurementPeriod)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TimeEntries getTimeEntries() { return timeEntries; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTimeEntries(TimeEntries newTimeEntries, NotificationChain msgs) { TimeEntries oldTimeEntries = timeEntries; timeEntries = newTimeEntries; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES, oldTimeEntries, newTimeEntries); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTimeEntries(TimeEntries newTimeEntries) { if (newTimeEntries != timeEntries) { NotificationChain msgs = null; if (timeEntries != null) msgs = ((InternalEObject)timeEntries).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES, null, msgs); if (newTimeEntries != null) msgs = ((InternalEObject)newTimeEntries).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES, null, msgs); msgs = basicSetTimeEntries(newTimeEntries, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES, newTimeEntries, newTimeEntries)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TransformerAndLineLosses getTransformerLineLosses() { return transformerLineLosses; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTransformerLineLosses(TransformerAndLineLosses newTransformerLineLosses, NotificationChain msgs) { TransformerAndLineLosses oldTransformerLineLosses = transformerLineLosses; transformerLineLosses = newTransformerLineLosses; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES, oldTransformerLineLosses, newTransformerLineLosses); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTransformerLineLosses(TransformerAndLineLosses newTransformerLineLosses) { if (newTransformerLineLosses != transformerLineLosses) { NotificationChain msgs = null; if (transformerLineLosses != null) msgs = ((InternalEObject)transformerLineLosses).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES, null, msgs); if (newTransformerLineLosses != null) msgs = ((InternalEObject)newTransformerLineLosses).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES, null, msgs); msgs = basicSetTransformerLineLosses(newTransformerLineLosses, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES, newTransformerLineLosses, newTransformerLineLosses)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MeasurementMethods getMeasurementAlgorithm() { return measurementAlgorithm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetMeasurementAlgorithm(MeasurementMethods newMeasurementAlgorithm, NotificationChain msgs) { MeasurementMethods oldMeasurementAlgorithm = measurementAlgorithm; measurementAlgorithm = newMeasurementAlgorithm; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM, oldMeasurementAlgorithm, newMeasurementAlgorithm); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMeasurementAlgorithm(MeasurementMethods newMeasurementAlgorithm) { if (newMeasurementAlgorithm != measurementAlgorithm) { NotificationChain msgs = null; if (measurementAlgorithm != null) msgs = ((InternalEObject)measurementAlgorithm).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM, null, msgs); if (newMeasurementAlgorithm != null) msgs = ((InternalEObject)newMeasurementAlgorithm).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM, null, msgs); msgs = basicSetMeasurementAlgorithm(newMeasurementAlgorithm, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM, newMeasurementAlgorithm, newMeasurementAlgorithm)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MeteringPointID getMeteringPoint() { return meteringPoint; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetMeteringPoint(MeteringPointID newMeteringPoint, NotificationChain msgs) { MeteringPointID oldMeteringPoint = meteringPoint; meteringPoint = newMeteringPoint; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__METERING_POINT, oldMeteringPoint, newMeteringPoint); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMeteringPoint(MeteringPointID newMeteringPoint) { if (newMeteringPoint != meteringPoint) { NotificationChain msgs = null; if (meteringPoint != null) msgs = ((InternalEObject)meteringPoint).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__METERING_POINT, null, msgs); if (newMeteringPoint != null) msgs = ((InternalEObject)newMeteringPoint).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__METERING_POINT, null, msgs); msgs = basicSetMeteringPoint(newMeteringPoint, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__METERING_POINT, newMeteringPoint, newMeteringPoint)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RegisterMonitorObject getRegisterMonitor() { return registerMonitor; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetRegisterMonitor(RegisterMonitorObject newRegisterMonitor, NotificationChain msgs) { RegisterMonitorObject oldRegisterMonitor = registerMonitor; registerMonitor = newRegisterMonitor; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR, oldRegisterMonitor, newRegisterMonitor); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRegisterMonitor(RegisterMonitorObject newRegisterMonitor) { if (newRegisterMonitor != registerMonitor) { NotificationChain msgs = null; if (registerMonitor != null) msgs = ((InternalEObject)registerMonitor).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR, null, msgs); if (newRegisterMonitor != null) msgs = ((InternalEObject)newRegisterMonitor).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR, null, msgs); msgs = basicSetRegisterMonitor(newRegisterMonitor, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR, newRegisterMonitor, newRegisterMonitor)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ElectricityValues getElectricityValues() { return electricityValues; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetElectricityValues(ElectricityValues newElectricityValues, NotificationChain msgs) { ElectricityValues oldElectricityValues = electricityValues; electricityValues = newElectricityValues; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES, oldElectricityValues, newElectricityValues); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setElectricityValues(ElectricityValues newElectricityValues) { if (newElectricityValues != electricityValues) { NotificationChain msgs = null; if (electricityValues != null) msgs = ((InternalEObject)electricityValues).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES, null, msgs); if (newElectricityValues != null) msgs = ((InternalEObject)newElectricityValues).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES, null, msgs); msgs = basicSetElectricityValues(newElectricityValues, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES, newElectricityValues, newElectricityValues)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MeasurementValues getMeasurementValueTypes() { return measurementValueTypes; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetMeasurementValueTypes(MeasurementValues newMeasurementValueTypes, NotificationChain msgs) { MeasurementValues oldMeasurementValueTypes = measurementValueTypes; measurementValueTypes = newMeasurementValueTypes; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES, oldMeasurementValueTypes, newMeasurementValueTypes); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMeasurementValueTypes(MeasurementValues newMeasurementValueTypes) { if (newMeasurementValueTypes != measurementValueTypes) { NotificationChain msgs = null; if (measurementValueTypes != null) msgs = ((InternalEObject)measurementValueTypes).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES, null, msgs); if (newMeasurementValueTypes != null) msgs = ((InternalEObject)newMeasurementValueTypes).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES, null, msgs); msgs = basicSetMeasurementValueTypes(newMeasurementValueTypes, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES, newMeasurementValueTypes, newMeasurementValueTypes)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ElectricityHarmonics getHarmonics() { return harmonics; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetHarmonics(ElectricityHarmonics newHarmonics, NotificationChain msgs) { ElectricityHarmonics oldHarmonics = harmonics; harmonics = newHarmonics; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__HARMONICS, oldHarmonics, newHarmonics); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setHarmonics(ElectricityHarmonics newHarmonics) { if (newHarmonics != harmonics) { NotificationChain msgs = null; if (harmonics != null) msgs = ((InternalEObject)harmonics).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__HARMONICS, null, msgs); if (newHarmonics != null) msgs = ((InternalEObject)newHarmonics).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__HARMONICS, null, msgs); msgs = basicSetHarmonics(newHarmonics, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__HARMONICS, newHarmonics, newHarmonics)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CurrentlyActiveTariff getTariffs() { return tariffs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetTariffs(CurrentlyActiveTariff newTariffs, NotificationChain msgs) { CurrentlyActiveTariff oldTariffs = tariffs; tariffs = newTariffs; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__TARIFFS, oldTariffs, newTariffs); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTariffs(CurrentlyActiveTariff newTariffs) { if (newTariffs != tariffs) { NotificationChain msgs = null; if (tariffs != null) msgs = ((InternalEObject)tariffs).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__TARIFFS, null, msgs); if (newTariffs != null) msgs = ((InternalEObject)newTariffs).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__TARIFFS, null, msgs); msgs = basicSetTariffs(newTariffs, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__TARIFFS, newTariffs, newTariffs)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ExtendedPhaseAngleMeasurement getPhaseangles() { return phaseangles; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetPhaseangles(ExtendedPhaseAngleMeasurement newPhaseangles, NotificationChain msgs) { ExtendedPhaseAngleMeasurement oldPhaseangles = phaseangles; phaseangles = newPhaseangles; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES, oldPhaseangles, newPhaseangles); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPhaseangles(ExtendedPhaseAngleMeasurement newPhaseangles) { if (newPhaseangles != phaseangles) { NotificationChain msgs = null; if (phaseangles != null) msgs = ((InternalEObject)phaseangles).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES, null, msgs); if (newPhaseangles != null) msgs = ((InternalEObject)newPhaseangles).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES, null, msgs); msgs = basicSetPhaseangles(newPhaseangles, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES, newPhaseangles, newPhaseangles)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS: return basicSetElectricityRelatedStatus(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__AA: return basicSetAA(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT: return basicSetAutoConnect(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES: return basicSetBillingPeriodValues(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID: return basicSetElectricityID(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES: return basicSetProgramEntries(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE: return basicSetOutputPulse(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR: return basicSetReadingFactor(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES: return basicSetNominalValues(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE: return basicSetInputPulse(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD: return basicSetMeasurementPeriod(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES: return basicSetTimeEntries(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES: return basicSetTransformerLineLosses(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM: return basicSetMeasurementAlgorithm(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__METERING_POINT: return basicSetMeteringPoint(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR: return basicSetRegisterMonitor(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES: return basicSetElectricityValues(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES: return basicSetMeasurementValueTypes(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__HARMONICS: return basicSetHarmonics(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__TARIFFS: return basicSetTariffs(null, msgs); case COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES: return basicSetPhaseangles(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case COSEMPackage.PHYSICAL_DEVICE__MANAGEMENT_LOGICAL_DEVICE: if (resolve) return getManagementLogicalDevice(); return basicGetManagementLogicalDevice(); case COSEMPackage.PHYSICAL_DEVICE__ID: return getID(); case COSEMPackage.PHYSICAL_DEVICE__LOGICAL_DEVICE: return getLogicalDevice(); case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS: return getElectricityRelatedStatus(); case COSEMPackage.PHYSICAL_DEVICE__AA: return getAA(); case COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT: return getAutoConnect(); case COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES: return getBillingPeriodValues(); case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID: return getElectricityID(); case COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES: return getProgramEntries(); case COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE: return getOutputPulse(); case COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR: return getReadingFactor(); case COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES: return getNominalValues(); case COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE: return getInputPulse(); case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD: return getMeasurementPeriod(); case COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES: return getTimeEntries(); case COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES: return getTransformerLineLosses(); case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM: return getMeasurementAlgorithm(); case COSEMPackage.PHYSICAL_DEVICE__METERING_POINT: return getMeteringPoint(); case COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR: return getRegisterMonitor(); case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES: return getElectricityValues(); case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES: return getMeasurementValueTypes(); case COSEMPackage.PHYSICAL_DEVICE__HARMONICS: return getHarmonics(); case COSEMPackage.PHYSICAL_DEVICE__TARIFFS: return getTariffs(); case COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES: return getPhaseangles(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case COSEMPackage.PHYSICAL_DEVICE__MANAGEMENT_LOGICAL_DEVICE: setManagementLogicalDevice((ManagementLogicalDevice)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__ID: setID((String)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__LOGICAL_DEVICE: getLogicalDevice().clear(); getLogicalDevice().addAll((Collection<? extends LogicalDevice>)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS: setElectricityRelatedStatus((ElectricityRelatedStatusData)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__AA: setAA((CurrentAssociation)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT: setAutoConnect((AutoConnectObject)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES: setBillingPeriodValues((BillingPeriodValues)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID: setElectricityID((ElectricityID)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES: setProgramEntries((ElectricityProgramEntries)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE: setOutputPulse((OutputPulseValues_constants)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR: setReadingFactor((ReadingFactorAndCT_VTratio)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES: setNominalValues((ElectricityNominalValues)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE: setInputPulse((InputPulseValuesOrConstants)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD: setMeasurementPeriod((MeasurementPeriod_recordingInterval_billingPeriodDuration)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES: setTimeEntries((TimeEntries)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES: setTransformerLineLosses((TransformerAndLineLosses)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM: setMeasurementAlgorithm((MeasurementMethods)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__METERING_POINT: setMeteringPoint((MeteringPointID)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR: setRegisterMonitor((RegisterMonitorObject)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES: setElectricityValues((ElectricityValues)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES: setMeasurementValueTypes((MeasurementValues)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__HARMONICS: setHarmonics((ElectricityHarmonics)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__TARIFFS: setTariffs((CurrentlyActiveTariff)newValue); return; case COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES: setPhaseangles((ExtendedPhaseAngleMeasurement)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case COSEMPackage.PHYSICAL_DEVICE__MANAGEMENT_LOGICAL_DEVICE: setManagementLogicalDevice((ManagementLogicalDevice)null); return; case COSEMPackage.PHYSICAL_DEVICE__ID: setID(ID_EDEFAULT); return; case COSEMPackage.PHYSICAL_DEVICE__LOGICAL_DEVICE: getLogicalDevice().clear(); return; case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS: setElectricityRelatedStatus((ElectricityRelatedStatusData)null); return; case COSEMPackage.PHYSICAL_DEVICE__AA: setAA((CurrentAssociation)null); return; case COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT: setAutoConnect((AutoConnectObject)null); return; case COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES: setBillingPeriodValues((BillingPeriodValues)null); return; case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID: setElectricityID((ElectricityID)null); return; case COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES: setProgramEntries((ElectricityProgramEntries)null); return; case COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE: setOutputPulse((OutputPulseValues_constants)null); return; case COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR: setReadingFactor((ReadingFactorAndCT_VTratio)null); return; case COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES: setNominalValues((ElectricityNominalValues)null); return; case COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE: setInputPulse((InputPulseValuesOrConstants)null); return; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD: setMeasurementPeriod((MeasurementPeriod_recordingInterval_billingPeriodDuration)null); return; case COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES: setTimeEntries((TimeEntries)null); return; case COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES: setTransformerLineLosses((TransformerAndLineLosses)null); return; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM: setMeasurementAlgorithm((MeasurementMethods)null); return; case COSEMPackage.PHYSICAL_DEVICE__METERING_POINT: setMeteringPoint((MeteringPointID)null); return; case COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR: setRegisterMonitor((RegisterMonitorObject)null); return; case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES: setElectricityValues((ElectricityValues)null); return; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES: setMeasurementValueTypes((MeasurementValues)null); return; case COSEMPackage.PHYSICAL_DEVICE__HARMONICS: setHarmonics((ElectricityHarmonics)null); return; case COSEMPackage.PHYSICAL_DEVICE__TARIFFS: setTariffs((CurrentlyActiveTariff)null); return; case COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES: setPhaseangles((ExtendedPhaseAngleMeasurement)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case COSEMPackage.PHYSICAL_DEVICE__MANAGEMENT_LOGICAL_DEVICE: return managementLogicalDevice != null; case COSEMPackage.PHYSICAL_DEVICE__ID: return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id); case COSEMPackage.PHYSICAL_DEVICE__LOGICAL_DEVICE: return logicalDevice != null && !logicalDevice.isEmpty(); case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_RELATED_STATUS: return electricityRelatedStatus != null; case COSEMPackage.PHYSICAL_DEVICE__AA: return aa != null; case COSEMPackage.PHYSICAL_DEVICE__AUTO_CONNECT: return autoConnect != null; case COSEMPackage.PHYSICAL_DEVICE__BILLING_PERIOD_VALUES: return billingPeriodValues != null; case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_ID: return electricityID != null; case COSEMPackage.PHYSICAL_DEVICE__PROGRAM_ENTRIES: return programEntries != null; case COSEMPackage.PHYSICAL_DEVICE__OUTPUT_PULSE: return outputPulse != null; case COSEMPackage.PHYSICAL_DEVICE__READING_FACTOR: return readingFactor != null; case COSEMPackage.PHYSICAL_DEVICE__NOMINAL_VALUES: return nominalValues != null; case COSEMPackage.PHYSICAL_DEVICE__INPUT_PULSE: return inputPulse != null; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_PERIOD: return measurementPeriod != null; case COSEMPackage.PHYSICAL_DEVICE__TIME_ENTRIES: return timeEntries != null; case COSEMPackage.PHYSICAL_DEVICE__TRANSFORMER_LINE_LOSSES: return transformerLineLosses != null; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_ALGORITHM: return measurementAlgorithm != null; case COSEMPackage.PHYSICAL_DEVICE__METERING_POINT: return meteringPoint != null; case COSEMPackage.PHYSICAL_DEVICE__REGISTER_MONITOR: return registerMonitor != null; case COSEMPackage.PHYSICAL_DEVICE__ELECTRICITY_VALUES: return electricityValues != null; case COSEMPackage.PHYSICAL_DEVICE__MEASUREMENT_VALUE_TYPES: return measurementValueTypes != null; case COSEMPackage.PHYSICAL_DEVICE__HARMONICS: return harmonics != null; case COSEMPackage.PHYSICAL_DEVICE__TARIFFS: return tariffs != null; case COSEMPackage.PHYSICAL_DEVICE__PHASEANGLES: return phaseangles != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (ID: "); result.append(id); result.append(')'); return result.toString(); } } //PhysicalDeviceImpl
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). package org.rocksdb; import java.nio.ByteBuffer; /** * WriteBatch holds a collection of updates to apply atomically to a DB. * * The updates are applied in the order in which they are added * to the WriteBatch. For example, the value of "key" will be "v3" * after the following batch is written: * * batch.put("key", "v1"); * batch.remove("key"); * batch.put("key", "v2"); * batch.put("key", "v3"); * * Multiple threads can invoke const methods on a WriteBatch without * external synchronization, but if any of the threads may call a * non-const method, all threads accessing the same WriteBatch must use * external synchronization. */ public class WriteBatch extends AbstractWriteBatch { /** * Constructs a WriteBatch instance. */ public WriteBatch() { this(0); } /** * Constructs a WriteBatch instance with a given size. * * @param reserved_bytes reserved size for WriteBatch */ public WriteBatch(final int reserved_bytes) { super(newWriteBatch(reserved_bytes)); } /** * Constructs a WriteBatch instance from a serialized representation * as returned by {@link #data()}. * * @param serialized the serialized representation. */ public WriteBatch(final byte[] serialized) { super(newWriteBatch(serialized, serialized.length)); } /** * Support for iterating over the contents of a batch. * * @param handler A handler that is called back for each * update present in the batch * * @throws RocksDBException If we cannot iterate over the batch */ public void iterate(final Handler handler) throws RocksDBException { iterate(nativeHandle_, handler.nativeHandle_); } /** * Retrieve the serialized version of this batch. * * @return the serialized representation of this write batch. * * @throws RocksDBException if an error occurs whilst retrieving * the serialized batch data. */ public byte[] data() throws RocksDBException { return data(nativeHandle_); } /** * Retrieve data size of the batch. * * @return the serialized data size of the batch. */ public long getDataSize() { return getDataSize(nativeHandle_); } /** * Returns true if Put will be called during Iterate. * * @return true if Put will be called during Iterate. */ public boolean hasPut() { return hasPut(nativeHandle_); } /** * Returns true if Delete will be called during Iterate. * * @return true if Delete will be called during Iterate. */ public boolean hasDelete() { return hasDelete(nativeHandle_); } /** * Returns true if SingleDelete will be called during Iterate. * * @return true if SingleDelete will be called during Iterate. */ public boolean hasSingleDelete() { return hasSingleDelete(nativeHandle_); } /** * Returns true if DeleteRange will be called during Iterate. * * @return true if DeleteRange will be called during Iterate. */ public boolean hasDeleteRange() { return hasDeleteRange(nativeHandle_); } /** * Returns true if Merge will be called during Iterate. * * @return true if Merge will be called during Iterate. */ public boolean hasMerge() { return hasMerge(nativeHandle_); } /** * Returns true if MarkBeginPrepare will be called during Iterate. * * @return true if MarkBeginPrepare will be called during Iterate. */ public boolean hasBeginPrepare() { return hasBeginPrepare(nativeHandle_); } /** * Returns true if MarkEndPrepare will be called during Iterate. * * @return true if MarkEndPrepare will be called during Iterate. */ public boolean hasEndPrepare() { return hasEndPrepare(nativeHandle_); } /** * Returns true if MarkCommit will be called during Iterate. * * @return true if MarkCommit will be called during Iterate. */ public boolean hasCommit() { return hasCommit(nativeHandle_); } /** * Returns true if MarkRollback will be called during Iterate. * * @return true if MarkRollback will be called during Iterate. */ public boolean hasRollback() { return hasRollback(nativeHandle_); } @Override public WriteBatch getWriteBatch() { return this; } /** * Marks this point in the WriteBatch as the last record to * be inserted into the WAL, provided the WAL is enabled. */ public void markWalTerminationPoint() { markWalTerminationPoint(nativeHandle_); } /** * Gets the WAL termination point. * * See {@link #markWalTerminationPoint()} * * @return the WAL termination point */ public SavePoint getWalTerminationPoint() { return getWalTerminationPoint(nativeHandle_); } @Override WriteBatch getWriteBatch(final long handle) { return this; } /** * <p>Private WriteBatch constructor which is used to construct * WriteBatch instances from C++ side. As the reference to this * object is also managed from C++ side the handle will be disowned.</p> * * @param nativeHandle address of native instance. */ WriteBatch(final long nativeHandle) { this(nativeHandle, false); } /** * <p>Private WriteBatch constructor which is used to construct * WriteBatch instances. </p> * * @param nativeHandle address of native instance. * @param owningNativeHandle whether to own this reference from the C++ side or not */ WriteBatch(final long nativeHandle, final boolean owningNativeHandle) { super(nativeHandle); if(!owningNativeHandle) disOwnNativeHandle(); } @Override protected final native void disposeInternal(final long handle); @Override final native int count0(final long handle); @Override final native void put(final long handle, final byte[] key, final int keyLen, final byte[] value, final int valueLen); @Override final native void put(final long handle, final byte[] key, final int keyLen, final byte[] value, final int valueLen, final long cfHandle); @Override final native void putDirect(final long handle, final ByteBuffer key, final int keyOffset, final int keyLength, final ByteBuffer value, final int valueOffset, final int valueLength, final long cfHandle); @Override final native void merge(final long handle, final byte[] key, final int keyLen, final byte[] value, final int valueLen); @Override final native void merge(final long handle, final byte[] key, final int keyLen, final byte[] value, final int valueLen, final long cfHandle); @Override final native void delete(final long handle, final byte[] key, final int keyLen) throws RocksDBException; @Override final native void delete(final long handle, final byte[] key, final int keyLen, final long cfHandle) throws RocksDBException; @Override final native void singleDelete(final long handle, final byte[] key, final int keyLen) throws RocksDBException; @Override final native void singleDelete(final long handle, final byte[] key, final int keyLen, final long cfHandle) throws RocksDBException; @Override final native void removeDirect(final long handle, final ByteBuffer key, final int keyOffset, final int keyLength, final long cfHandle) throws RocksDBException; @Override final native void deleteRange(final long handle, final byte[] beginKey, final int beginKeyLen, final byte[] endKey, final int endKeyLen); @Override final native void deleteRange(final long handle, final byte[] beginKey, final int beginKeyLen, final byte[] endKey, final int endKeyLen, final long cfHandle); @Override final native void putLogData(final long handle, final byte[] blob, final int blobLen) throws RocksDBException; @Override final native void clear0(final long handle); @Override final native void setSavePoint0(final long handle); @Override final native void rollbackToSavePoint0(final long handle); @Override final native void popSavePoint(final long handle) throws RocksDBException; @Override final native void setMaxBytes(final long nativeHandle, final long maxBytes); private native static long newWriteBatch(final int reserved_bytes); private native static long newWriteBatch(final byte[] serialized, final int serializedLength); private native void iterate(final long handle, final long handlerHandle) throws RocksDBException; private native byte[] data(final long nativeHandle) throws RocksDBException; private native long getDataSize(final long nativeHandle); private native boolean hasPut(final long nativeHandle); private native boolean hasDelete(final long nativeHandle); private native boolean hasSingleDelete(final long nativeHandle); private native boolean hasDeleteRange(final long nativeHandle); private native boolean hasMerge(final long nativeHandle); private native boolean hasBeginPrepare(final long nativeHandle); private native boolean hasEndPrepare(final long nativeHandle); private native boolean hasCommit(final long nativeHandle); private native boolean hasRollback(final long nativeHandle); private native void markWalTerminationPoint(final long nativeHandle); private native SavePoint getWalTerminationPoint(final long nativeHandle); /** * Handler callback for iterating over the contents of a batch. */ public static abstract class Handler extends RocksCallbackObject { public Handler() { super(null); } @Override protected long initializeNative(final long... nativeParameterHandles) { return createNewHandler0(); } public abstract void put(final int columnFamilyId, final byte[] key, final byte[] value) throws RocksDBException; public abstract void put(final byte[] key, final byte[] value); public abstract void merge(final int columnFamilyId, final byte[] key, final byte[] value) throws RocksDBException; public abstract void merge(final byte[] key, final byte[] value); public abstract void delete(final int columnFamilyId, final byte[] key) throws RocksDBException; public abstract void delete(final byte[] key); public abstract void singleDelete(final int columnFamilyId, final byte[] key) throws RocksDBException; public abstract void singleDelete(final byte[] key); public abstract void deleteRange(final int columnFamilyId, final byte[] beginKey, final byte[] endKey) throws RocksDBException; public abstract void deleteRange(final byte[] beginKey, final byte[] endKey); public abstract void logData(final byte[] blob); public abstract void putBlobIndex(final int columnFamilyId, final byte[] key, final byte[] value) throws RocksDBException; public abstract void markBeginPrepare() throws RocksDBException; public abstract void markEndPrepare(final byte[] xid) throws RocksDBException; public abstract void markNoop(final boolean emptyBatch) throws RocksDBException; public abstract void markRollback(final byte[] xid) throws RocksDBException; public abstract void markCommit(final byte[] xid) throws RocksDBException; /** * shouldContinue is called by the underlying iterator * {@link WriteBatch#iterate(Handler)}. If it returns false, * iteration is halted. Otherwise, it continues * iterating. The default implementation always * returns true. * * @return boolean value indicating if the * iteration is halted. */ public boolean shouldContinue() { return true; } private native long createNewHandler0(); } /** * A structure for describing the save point in the Write Batch. */ public static class SavePoint { private long size; private long count; private long contentFlags; public SavePoint(final long size, final long count, final long contentFlags) { this.size = size; this.count = count; this.contentFlags = contentFlags; } public void clear() { this.size = 0; this.count = 0; this.contentFlags = 0; } /** * Get the size of the serialized representation. * * @return the size of the serialized representation. */ public long getSize() { return size; } /** * Get the number of elements. * * @return the number of elements. */ public long getCount() { return count; } /** * Get the content flags. * * @return the content flags. */ public long getContentFlags() { return contentFlags; } public boolean isCleared() { return (size | count | contentFlags) == 0; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.infrastructure.service; import java.io.Serializable; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Logger; import com.facebook.infrastructure.concurrent.DebuggableScheduledThreadPoolExecutor; import com.facebook.infrastructure.concurrent.DebuggableThreadPoolExecutor; import com.facebook.infrastructure.concurrent.SingleThreadedStage; import com.facebook.infrastructure.concurrent.StageManager; import com.facebook.infrastructure.concurrent.ThreadFactoryImpl; import com.facebook.infrastructure.gms.ApplicationState; import com.facebook.infrastructure.gms.EndPointState; import com.facebook.infrastructure.gms.Gossiper; import com.facebook.infrastructure.gms.IEndPointStateChangeSubscriber; import com.facebook.infrastructure.net.*; import com.facebook.infrastructure.utils.*; /* * The load balancing algorithm here is an implementation of * the algorithm as described in the paper "Scalable range query * processing for large-scale distributed database applications". * This class keeps track of load information across the system. * It registers itself with the Gossiper for ApplicationState namely * load information i.e number of requests processed w.r.t distinct * keys at an Endpoint. Monitor load infomation for a 20 minute * interval and then do load balancing operations if necessary. * * Author : Avinash Lakshman ( alakshman@facebook.com) & Prashant Malik ( pmalik@facebook.com ) */ final class StorageLoadBalancer implements IEndPointStateChangeSubscriber, IComponentShutdown { class LoadBalancer implements Runnable { LoadBalancer() { /* Copy the entries in loadInfo_ into loadInfo2_ and use it for all calculations */ loadInfo2_.putAll(loadInfo_); } public void run() { int threshold = (int)(StorageLoadBalancer.ratio_ * averageSystemLoad()); int myLoad = localLoad(); /* * Obtain a node which is a potential target. Start with * the neighbours i.e either successor or predecessor. * Send the target a MoveMessage. If the node cannot be * relocated on the ring then we pick another candidate for * relocation. */ EndPoint predecessor = storageService_.getPredecessor(StorageService.getLocalStorageEndPoint()); logger_.debug("Trying to relocate the predecessor " + predecessor); boolean value = tryThisNode(myLoad, threshold, predecessor); if ( !value ) { loadInfo2_.remove(predecessor); EndPoint successor = storageService_.getSuccessor(StorageService.getLocalStorageEndPoint()); logger_.debug("Trying to relocate the successor " + successor); value = tryThisNode(myLoad, threshold, successor); if ( !value ) { loadInfo2_.remove(successor); while ( !loadInfo2_.isEmpty() ) { EndPoint target = findARandomLightNode(); if ( target != null ) { logger_.debug("Trying to relocate the random node " + target); value = tryThisNode(myLoad, threshold, target); if ( !value ) { loadInfo2_.remove(target); } else { break; } } else { /* No light nodes available - this is NOT good. */ logger_.warn("Not even a single lightly loaded node is available ..."); break; } } loadInfo2_.clear(); /* * If we are here and no node was available to * perform load balance with we need to report and bail. */ if ( !value ) { logger_.warn("Load Balancing operations weren't performed for this node"); } } } } private boolean tryThisNode(int myLoad, int threshold, EndPoint target) { boolean value = false; LoadInfo li = loadInfo2_.get(target); int pLoad = li.count(); if ( ((myLoad + pLoad) >> 1) <= threshold ) { /* calculate the number of keys to be transferred */ int keyCount = ( (myLoad - pLoad) >> 1 ); logger_.debug("Number of keys we attempt to transfer to " + target + " " + keyCount); /* * Determine the token that the target should join at. */ BigInteger targetToken = BootstrapAndLbHelper.getTokenBasedOnPrimaryCount(keyCount); /* Send a MoveMessage and see if this node is relocateable */ MoveMessage moveMessage = new MoveMessage(targetToken); Message message = new Message(StorageService.getLocalStorageEndPoint(), StorageLoadBalancer.lbStage_, StorageLoadBalancer.moveMessageVerbHandler_, new Object[]{moveMessage}); logger_.debug("Sending a move message to " + target); IAsyncResult result = MessagingService.getMessagingInstance().sendRR(message, target); value = (Boolean)result.get()[0]; logger_.debug("Response for query to relocate " + target + " is " + value); } return value; } } class MoveMessageVerbHandler implements IVerbHandler { public void doVerb(Message message) { Message reply = message.getReply(StorageService.getLocalStorageEndPoint(), new Object[]{isMoveable_.get()}); MessagingService.getMessagingInstance().sendOneWay(reply, message.getFrom()); if ( isMoveable_.get() ) { MoveMessage moveMessage = (MoveMessage)message.getMessageBody()[0]; BigInteger targetToken = moveMessage.getTargetToken(); /* Start the leave operation and join the ring at the position specified */ lbOperations_.submit( new RunnableImpl(targetToken) ); isMoveable_.set(false); } } } /* * This class performs the actual leave/join operation * for this node. * TODO: A better name is in order. */ class RunnableImpl implements Runnable { private BigInteger targetToken_; RunnableImpl(BigInteger targetToken) { targetToken_ = targetToken; } public void run() { try { /* Store the new token in the SystemTable */ StorageService.instance().updateLocalToken(targetToken_); /* Perform the "leave" operations which involves streaming relevant data */ } catch (Throwable ex) { logger_.debug( LogUtil.throwableToString(ex) ); } } } private static final Logger logger_ = Logger.getLogger(StorageLoadBalancer.class); private static final String lbStage_ = "LOAD-BALANCER-STAGE"; private static final String moveMessageVerbHandler_ = "MOVE-MESSAGE-VERB-HANDLER"; /* time to delay in minutes the actual load balance procedure if heavily loaded */ private static final int delay_ = 5; /* Ratio of highest loaded node and the average load. */ private static final double ratio_ = 1.5; private StorageService storageService_; /* this indicates whether this node is already helping someone else */ private AtomicBoolean isMoveable_ = new AtomicBoolean(false); private Map<EndPoint, LoadInfo> loadInfo_ = new HashMap<EndPoint, LoadInfo>(); /* This map is a clone of the one above and is used for various calculations during LB operation */ private Map<EndPoint, LoadInfo> loadInfo2_ = new HashMap<EndPoint, LoadInfo>(); /* This thread pool is used for initiating load balancing operations */ private ScheduledThreadPoolExecutor lb_ = new DebuggableScheduledThreadPoolExecutor( 1, new ThreadFactoryImpl("LB-OPERATIONS") ); /* This thread pool is used by target node to leave the ring. */ private ExecutorService lbOperations_ = new DebuggableThreadPoolExecutor(1, 1, Integer.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactoryImpl("LB-TARGET") ); StorageLoadBalancer(StorageService storageService) { storageService_ = storageService; /* register the load balancer stage */ StageManager.registerStage(StorageLoadBalancer.lbStage_, new SingleThreadedStage(StorageLoadBalancer.lbStage_)); /* register the load balancer verb handler */ MessagingService.getMessagingInstance().registerVerbHandlers(StorageLoadBalancer.moveMessageVerbHandler_, new MoveMessageVerbHandler()); /* register with the StorageService */ storageService_.registerComponentForShutdown(this); } public void start() { /* Register with the Gossiper for EndPointState notifications */ Gossiper.instance().register(this); } public void shutdown() { lbOperations_.shutdownNow(); lb_.shutdownNow(); } public void onChange(EndPoint endpoint, EndPointState epState) { logger_.debug("CHANGE IN STATE FOR @ StorageLoadBalancer " + endpoint); // load information for this specified endpoint for load balancing ApplicationState loadInfoState = epState.getApplicationState(RequestCountSampler.loadInfo_); if ( loadInfoState != null ) { String lInfoState = loadInfoState.getState(); LoadInfo lInfo = new LoadInfo(lInfoState); loadInfo_.put(endpoint, lInfo); /* int currentLoad = Integer.parseInt(loadInfoState.getState()); // update load information for this endpoint loadInfo_.put(endpoint, currentLoad); // clone load information to perform calculations loadInfo2_.putAll(loadInfo_); // Perform the analysis for load balance operations if ( isHeavyNode() ) { logger_.debug(StorageService.getLocalStorageEndPoint() + " is a heavy node with load " + localLoad()); // lb_.schedule( new LoadBalancer(), StorageLoadBalancer.delay_, TimeUnit.MINUTES ); } */ } } /* * Load information associated with a given endpoint. */ LoadInfo getLoad(EndPoint ep) { LoadInfo li = loadInfo_.get(ep); return li; } private boolean isMoveable() { if ( !isMoveable_.get() ) return false; int myload = localLoad(); EndPoint successor = storageService_.getSuccessor(StorageService.getLocalStorageEndPoint()); LoadInfo li = loadInfo2_.get(successor); /* * "load" is NULL means that the successor node has not * yet gossiped its load information. We should return * false in this case since we want to err on the side * of caution. */ if ( li == null ) return false; else { /* l(i) + l(j) > el(av) */ if ( ( myload + li.count() ) > StorageLoadBalancer.ratio_*averageSystemLoad() ) return false; else return true; } } private int localLoad() { LoadInfo value = loadInfo2_.get(StorageService.getLocalStorageEndPoint()); return (value == null) ? 0 : value.count(); } private int averageSystemLoad() { int nodeCount = loadInfo2_.size(); int systemLoad = 0; for ( LoadInfo load : loadInfo2_.values() ) { if ( load != null ) systemLoad += load.count(); } int averageLoad = (nodeCount > 0) ? (systemLoad / nodeCount) : 0; logger_.debug("Average system load should be " + averageLoad); return averageLoad; } private boolean isHeavyNode() { return ( localLoad() > ( StorageLoadBalancer.ratio_ * averageSystemLoad() ) ); } private boolean isMoveable(EndPoint target) { int threshold = (int)(StorageLoadBalancer.ratio_ * averageSystemLoad()); if ( isANeighbour(target) ) { /* * If the target is a neighbour then it is * moveable if by averaging our load with it will * cause both nodes to fall under the system "heavy" threshold */ LoadInfo load = loadInfo2_.get(target); if ( load == null ) return false; else { int myload = localLoad(); int avgLoad = (load.count() + myload) >> 1; return ( avgLoad <= threshold ); } } else { EndPoint successor = storageService_.getSuccessor(target); LoadInfo sLoad = loadInfo2_.get(successor); LoadInfo targetLoad = loadInfo2_.get(target); if ( (sLoad.count() + targetLoad.count()) > threshold ) return false; else return true; } } private boolean isANeighbour(EndPoint neighbour) { EndPoint predecessor = storageService_.getPredecessor(StorageService.getLocalStorageEndPoint()); if ( predecessor.equals(neighbour) ) return true; EndPoint successor = storageService_.getSuccessor(StorageService.getLocalStorageEndPoint()); if ( successor.equals(neighbour) ) return true; return false; } /* * Determine the nodes that are lightly loaded. Choose at * random one of the lightly loaded nodes and use it as * a potential target for load balance. */ private EndPoint findARandomLightNode() { List<EndPoint> potentialCandidates = new ArrayList<EndPoint>(); int avgLoad = averageSystemLoad(); for( Map.Entry<EndPoint, LoadInfo> entry : loadInfo2_.entrySet() ) { LoadInfo load = entry.getValue(); if ( load.count() < avgLoad ) potentialCandidates.add(entry.getKey()); } if ( !potentialCandidates.isEmpty() ) { Random random = new Random(); int index = random.nextInt(potentialCandidates.size()); return potentialCandidates.get(index); } return null; } } class MoveMessage implements Serializable { private BigInteger targetToken_; private MoveMessage() { } MoveMessage(BigInteger targetToken) { targetToken_ = targetToken; } BigInteger getTargetToken() { return targetToken_; } }
/* * Copyright 2012 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.appinventor.components.runtime; import static com.google.appinventor.components.runtime.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.appinventor.components.runtime.GCMConstants.EXTRA_ERROR; import static com.google.appinventor.components.runtime.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.appinventor.components.runtime.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.appinventor.components.runtime.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.appinventor.components.runtime.GCMConstants.EXTRA_UNREGISTERED; import static com.google.appinventor.components.runtime.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.appinventor.components.runtime.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.appinventor.components.runtime.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.appinventor.components.runtime.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. * <p> * Subclasses must provide a public no-arg constructor. */ public abstract class GCMBaseIntentService extends IntentService { public static final String TAG = "GCMBaseIntentService"; // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private String[] mSenderIds; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour // token used to check intent origin private static final String TOKEN = Long.toBinaryString(sRandom.nextLong()); private static final String EXTRA_TOKEN = "token"; /** * Constructor that does not set a sender id, useful when the sender id * is context-specific. * <p> * When using this constructor, the subclass <strong>must</strong> * override {@link #getSenderIds(Context)}, otherwise methods such as * {@link #onHandleIntent(Intent)} will throw an * {@link IllegalStateException} on runtime. */ protected GCMBaseIntentService() { this(getName("DynamicSenderIds"), null); Log.v(TAG, "GCMBaseIntentService()"); } /** * Constructor used when the sender id(s) is fixed. */ protected GCMBaseIntentService(String... senderIds) { this(getName(senderIds), senderIds); Log.v(TAG, "GCMBaseIntentService(String... senderIds)"); } /** * We need to change this method since we need to change the sender id according to the preference * For the intent service now, we only accept one sender id * * @param name * @param senderIds */ private GCMBaseIntentService(String name, String[] senderIds) { super(name); // name is used as base name for threads, etc. Log.i(TAG,"within the super constructor"); mSenderIds = senderIds; } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); Log.v(TAG, "Intent service name: " + name); return name; } private static String getName(String[] senderIds) { String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds); return getName(flatSenderIds); } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * @return * * @throws IllegalStateException if sender id was not set on constructor. */ protected void setSenderIds(String... senderIds) { if (senderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } mSenderIds = senderIds; } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * * @throws IllegalStateException if sender id was not set on constructor. */ protected String[] getSenderIds(Context context) { if (mSenderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } return mSenderIds; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); Log.i(TAG,"onHandleIntent @action"); String action = intent.getAction(); Log.i(TAG,"onHandleIntent before"); Log.i(TAG,"action is "+action.toString()); if (action.equals(GoogleCloudMessaging.INIT_INTENTSERVICE_ACTION)){ //this action is passed when we first time bind the service in GoogleCloudMessaging component //do nothing. return; } else if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { Log.i(TAG,"onHandleIntent after"); GCMRegistrar.setRetryBroadcastReceiver(context); handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); Log.v(TAG, "Received deleted messages " + "notification: " + total); onDeletedMessages(context, total); } catch (NumberFormatException e) { Log.e(TAG, "GCM returned invalid number of " + "deleted messages: " + sTotal); } } } else { // application is not using the latest GCM library Log.e(TAG, "Received unknown special message: " + messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String token = intent.getStringExtra(EXTRA_TOKEN); if (!TOKEN.equals(token)) { // make sure intent was generated by this class, not by a // malicious app. Log.e(TAG, "Received invalid token: " + token); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { String[] senderIds = getSenderIds(context); GCMRegistrar.internalRegister(context, senderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { Log.v(TAG, "Releasing wakelock"); sWakeLock.release(); } else { // should never happen during normal workflow Log.e(TAG, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } Log.v(TAG, "Acquiring wakelock"); sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; Log.d(TAG, "Registration error: " + error); // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); Log.d(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")"); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.putExtra(EXTRA_TOKEN, TOKEN); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { Log.d(TAG, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author acer */ public class view_inventaris extends javax.swing.JFrame { /** * Creates new form view_peminjaman */ public view_inventaris() { initComponents(); } public void SetName(String text) { Nametag.setText(text); } public void KlikBack(ActionListener a) { btnback.addActionListener(a); } public String Getname() { String name; name = Nametag.getText(); return name; } public void setEditable (boolean x) { btnpinjam.setEnabled(x); } public void setTableModel(DefaultTableModel table) { this.tabel.setModel(table); } public int getSelectedRow() { return this.tabel.getSelectedRow(); } public String GetIDTable() { return this.tabel.getValueAt(this.getSelectedRow(), 0).toString(); } // public String[] GetData() { // String Data[] = new String[6]; // Data[0] = this.id_transpinjaman.getText(); // Data[1] = this.tgl_pinjaman.getText(); // Data[2] = this.id_nasabah.getText(); // Data[3] = this.besar_pinjaman.getText(); // Data[4] = clogin.datapetugas[0]; // Data[5] = this.cicil.getText(); // return Data; // } public void klikexit(ActionListener action) { tombolexit.addActionListener(action); } public void klikminimize(ActionListener action) { tombolminimize.addActionListener(action); } public void klikpinjam(ActionListener action) { btnpinjam.addActionListener(action); } public void klikcari(ActionListener action) { btncari.addActionListener(action); } public void klikdaftar(ActionListener action) { btndaftar.addActionListener(action); } public String getButtonText() { String text = btndaftar.getText(); return text; } public void setButtonText(String t){ btndaftar.setText(t); } public void message(String message) { JOptionPane.showMessageDialog(this, message); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { tombolexit = new javax.swing.JButton(); tombolminimize = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tabel = new javax.swing.JTable(); btnpinjam = new javax.swing.JButton(); btncari = new javax.swing.JButton(); btndaftar = new javax.swing.JButton(); Nametag = new javax.swing.JLabel(); btnback = new javax.swing.JButton(); background = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); tombolexit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/Login_Close.png"))); // NOI18N tombolexit.setBorderPainted(false); tombolexit.setContentAreaFilled(false); tombolexit.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/Login_CloseMouseOver.png"))); // NOI18N getContentPane().add(tombolexit, new org.netbeans.lib.awtextra.AbsoluteConstraints(1320, 0, 50, 20)); tombolminimize.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/All_Minimize.png"))); // NOI18N tombolminimize.setBorder(null); tombolminimize.setBorderPainted(false); tombolminimize.setContentAreaFilled(false); tombolminimize.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/All_MinimizeMouseOver.png"))); // NOI18N getContentPane().add(tombolminimize, new org.netbeans.lib.awtextra.AbsoluteConstraints(1290, 0, -1, 20)); tabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); tabel.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tabel.setOpaque(false); jScrollPane1.setViewportView(tabel); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 220, 820, 380)); btnpinjam.setText("pinjam barang"); getContentPane().add(btnpinjam, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 180, -1, -1)); btncari.setText("cari"); getContentPane().add(btncari, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 180, -1, -1)); btndaftar.setText("daftar pinjaman"); getContentPane().add(btndaftar, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 180, -1, -1)); Nametag.setFont(new java.awt.Font("Caviar Dreams", 0, 18)); // NOI18N Nametag.setForeground(new java.awt.Color(255, 255, 255)); Nametag.setToolTipText(""); getContentPane().add(Nametag, new org.netbeans.lib.awtextra.AbsoluteConstraints(1220, 140, 120, 20)); btnback.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/back.png"))); // NOI18N btnback.setBorder(null); btnback.setBorderPainted(false); btnback.setContentAreaFilled(false); btnback.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/backmouseover.png"))); // NOI18N getContentPane().add(btnback, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 120, -1, -1)); background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gambar/HomeAnggotaKelompok.png"))); // NOI18N background.setText("jLabel1"); getContentPane().add(background, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1370, 770)); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(view_inventaris.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(view_inventaris.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(view_inventaris.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(view_inventaris.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new view_inventaris().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Nametag; private javax.swing.JLabel background; private javax.swing.JButton btnback; private javax.swing.JButton btncari; private javax.swing.JButton btndaftar; private javax.swing.JButton btnpinjam; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tabel; private javax.swing.JButton tombolexit; private javax.swing.JButton tombolminimize; // End of variables declaration//GEN-END:variables }
/* Derby - Class org.apache.derby.impl.store.raw.data.RAFContainer4 Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.impl.store.raw.data; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.reference.SQLState; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.store.raw.ContainerKey; import org.apache.derby.iapi.util.InterruptStatus; import org.apache.derby.iapi.util.InterruptDetectedException; import java.io.EOFException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ClosedChannelException; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.AsynchronousCloseException; import org.apache.derby.io.StorageRandomAccessFile; /** * RAFContainer4 overrides a few methods in FileContainer/RAFContainer in order * to use FileChannel from Java 1.4's New IO framework to issue multiple IO * operations to the same file concurrently instead of strictly serializing IO * operations using a mutex on the container object. Since we compile with Java * 1.4, the override "annotations" are inside the method javadoc headers. * <p> * Note that our requests for multiple concurrent IOs may be serialized further * down in the IO stack - this is entirely up to the JVM and OS. However, at * least in Linux on Sun's 1.4.2_09 JVM we see the desired behavior: * The FileChannel.read/write(ByteBuffer buf, long position) calls map to * pread/pwrite system calls, which enable efficient IO to the same file * descriptor by multiple threads. * <p> * This whole class should be merged back into RAFContainer when Derby * officially stops supporting Java 1.3. * <p> * Significant behavior changes from RAFContainer: * <ol> * <li> Multiple concurrent IOs permitted. * <li> State changes to the container (create, open, close) can now happen while * IO is in progress due to the lack of locking. Closing a container while * IO is in progress will cause IOExceptions in the thread calling readPage * or writePage. If this happens something is probably amiss anyway. * The iosInProgress variable is used in an attempt to detect this should it * happen while running a debug build. * </ol> * * @see java.nio.channels.FileChannel */ class RAFContainer4 extends RAFContainer { /** * This channel will be retrieved from RAFContainer's fileData * member when fileData is set. We wrap a couple of RAFContainer's methods * to accomplish this. */ private FileChannel ourChannel = null; private final Object channelCleanupMonitor = new Object(); // channelCleanupMonitor protects next three state variables: // volatile on threadsInPageIO, is just to ensure that we get a correct // value for debugging: we can't always use channelCleanupMonitor // then. Otherwise protected by channelCleanupMonitor. Debugging value not // safe on 1.4, but who cares.. private volatile int threadsInPageIO = 0; // volatile on restoreChannelInProgress: corner case where we can't use // channelCleanupMonitor: the corner case should not happen if NIO works as // specified: thats is, uniquely only one thread sees // ClosedByInterruptException, always. Unfortunately, we sometimes get // AsynchronousCloseException, which another thread could theoretically // also see it it were interrupted at the same time inside NIO. In this // case, we could get two threads competing to do recovery. This is // normally OK, unless the thread owns allocCache or "this", in which case // we risk dead-lock if we synchronize on restoreChannelInProgress // (explained below). So, we have to rely on volatile, which isn't safe in // Java 1.4 (old memory model), private volatile boolean restoreChannelInProgress = false; // In case the recovering thread can't successfully recover the container // for some reason, it will throw, so other waiting threads need to give up // as well. private boolean giveUpIO = false; private final Object giveUpIOm = new Object(); // its monitor /** * For debugging - will be incremented when an IO is started, decremented * when it is done. Should be == 0 when container state is changed. */ private int iosInProgress = 0; // protected by monitor on "this" public RAFContainer4(BaseDataFileFactory factory) { super(factory); } /** * Return the {@code FileChannel} for the specified * {@code StorageRandomAccessFile} if it is a {@code RandomAccessFile}. * Otherwise, return {@code null}. * * @param file the file to get the channel for * @return a {@code FileChannel} if {@code file} is an instance of * {@code RandomAccessFile}, {@code null} otherwise */ private FileChannel getChannel(StorageRandomAccessFile file) { if (file instanceof RandomAccessFile) { /** XXX - this cast isn't testing friendly. * A testing class that implements StorageRandomAccessFile but isn't * a RandomAccessFile will be "worked around" by this class. An * example of such a class is * functionTests/util/corruptio/CorruptRandomAccessFile.java. * An interface rework may be necessary. */ return ((RandomAccessFile) file).getChannel(); } return null; } /** * <p> * Return the file channel for the current value of the {@code fileData} * field. If {@code fileData} doesn't support file channels, return * {@code null}. * </p> * * <p> * Callers of this method must synchronize on the container object since * two shared fields ({@code fileData} and {@code ourChannel}) are * accessed. * </p> * * @return a {@code FileChannel} object, if supported, or {@code null} */ private FileChannel getChannel() { if (ourChannel == null) { ourChannel = getChannel(fileData); } return ourChannel; } private ContainerKey currentIdentity; /* * Wrapping methods that retrieve the FileChannel from RAFContainer's * fileData after calling the real methods in RAFContainer. * * override of RAFContainer#openContainer */ synchronized boolean openContainer(ContainerKey newIdentity) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(iosInProgress == 0, "Container opened while IO operations are in progress. " + "This should not happen."); SanityManager.ASSERT(fileData == null, "fileData isn't null"); SanityManager.ASSERT(ourChannel == null, "ourChannel isn't null"); } currentIdentity = newIdentity; return super.openContainer(newIdentity); } /** * override of RAFContainer#createContainer */ synchronized void createContainer(ContainerKey newIdentity) throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(iosInProgress == 0, "Container created while IO operations are in progress. " + "This should not happen."); SanityManager.ASSERT(fileData == null, "fileData isn't null"); SanityManager.ASSERT(ourChannel == null, "ourChannel isn't null"); } currentIdentity = newIdentity; super.createContainer(newIdentity); } /** * When the existing channel ({@code ourChannel}) has been closed due to * interrupt, we need to reopen the underlying RAF to get a fresh channel * so we can resume IO. */ private void reopen() throws StandardException { if (SanityManager.DEBUG) { SanityManager.ASSERT(!ourChannel.isOpen()); } ourChannel = null; reopenContainer(currentIdentity); } /** * override of RAFContainer#closeContainer */ synchronized void closeContainer() { if (SanityManager.DEBUG) { // Any IOs in progress to a container being dropped will be // ignored, so we should not complain about starting a close // while there are IOs in progress if it is being dropped // anyway. SanityManager.ASSERT( (iosInProgress == 0) || getCommittedDropState(), "Container closed while IO operations are in progress. " + " This should not happen."); } if(ourChannel != null) { try { ourChannel.close(); } catch (IOException e) { // nevermind. } finally { ourChannel=null; } } super.closeContainer(); } /** * These are the methods that were rewritten to use FileChannel. **/ /** * Read a page into the supplied array. * <p/> * override of RAFContainer#readPage * <p/> * <BR> MT - thread safe * @exception IOException exception reading page * @exception StandardException Standard Derby error policy */ protected void readPage(long pageNumber, byte[] pageData) throws IOException, StandardException { readPage(pageNumber, pageData, -1L); } /** * Read a page into the supplied array. * <p/> * override of RAFContainer#readPage * <p/> * <BR> MT - thread safe * @param pageNumber the page number to read data from, or -1 (called from * getEmbryonicPage) * @param pageData the buffer to read data into * @param offset -1 normally (not used since offset is computed from * pageNumber), but used if pageNumber == -1 * (getEmbryonicPage) * @exception IOException exception reading page * @exception StandardException Standard Derby error policy */ private void readPage(long pageNumber, byte[] pageData, long offset) throws IOException, StandardException { // Interrupt recovery "stealthMode": If this thread holds a monitor on // // a) "this" (when RAFContainer#clean calls getEmbryonicPage via // writeRAFHEader) or // b) "allocCache" (e.g. FileContainer#newPage, // #pageValid) // // we cannot grab channelCleanupMonitor lest another thread is one // doing recovery, since the recovery thread will try to grab both // those monitors during container recovery. So, just forge ahead // in stealth mode (i.e. the recovery thread doesn't see us). If we see // ClosedChannelException, throw InterruptDetectedException, so we can // retry from RAFContainer releasing "this", or FileContainer // (releasing allocCache) as the case may be, so the recovery thread // can do its thing. final boolean holdsThis = Thread.holdsLock(this); final boolean holdsAllocCache = Thread.holdsLock(allocCache); final boolean stealthMode = holdsThis || holdsAllocCache; if (SanityManager.DEBUG) { // getEmbryonicPage only if (pageNumber == -1) { SanityManager.ASSERT(holdsThis); } if (holdsThis) { SanityManager.ASSERT(pageNumber == -1); } } if (stealthMode) { // We go into stealth mode. If we see an // CloseChannelExceptionexception, we will get out of here anyway, // so we don't need to increment threadsInPageIO (nor can we, // without risking dead-lock), } else { synchronized (channelCleanupMonitor) { // Gain entry int retries = MAX_INTERRUPT_RETRIES; while (restoreChannelInProgress) { if (retries-- == 0) { throw StandardException.newException( SQLState.FILE_IO_INTERRUPTED); } try { channelCleanupMonitor.wait(INTERRUPT_RETRY_SLEEP); } catch (InterruptedException e) { InterruptStatus.setInterrupted(); } } threadsInPageIO++; } } boolean success = false; int retries = MAX_INTERRUPT_RETRIES; try { while (!success) { try { if (pageNumber == FIRST_ALLOC_PAGE_NUMBER) { // If this is the first alloc page, there may be another // thread accessing the container information in the // borrowed space on the same page. In that case, we // synchronize the entire method call, just like // RAFContainer.readPage() does, in order to avoid // conflicts. For all other pages it is safe to skip the // synchronization, since concurrent threads will access // different pages and therefore don't interfere with each // other: synchronized (this) { readPage0(pageNumber, pageData, offset); } } else { // Normal case. readPage0(pageNumber, pageData, offset); } success = true; } catch (ClosedChannelException e) { handleClosedChannel(e, stealthMode, retries--); } } } finally { if (stealthMode) { // don't touch threadsInPageIO } else { synchronized (channelCleanupMonitor) { threadsInPageIO--; } } } } private void readPage0(long pageNumber, byte[] pageData, long offset) throws IOException, StandardException { FileChannel ioChannel; synchronized (this) { if (SanityManager.DEBUG) { if (pageNumber != -1L) { SanityManager.ASSERT(!getCommittedDropState()); } // else: can happen from getEmbryonicPage } ioChannel = getChannel(); } if (SanityManager.DEBUG) { if (pageNumber == -1L || pageNumber == FIRST_ALLOC_PAGE_NUMBER) { // can happen from getEmbryonicPage SanityManager.ASSERT(Thread.holdsLock(this)); } else { SanityManager.ASSERT(!Thread.holdsLock(this)); } } if(ioChannel != null) { long pageOffset = pageNumber * pageSize; ByteBuffer pageBuf = ByteBuffer.wrap(pageData); // I hope the try/finally is optimized away by the // compiler/jvm when SanityManager.DEBUG == false? try { if (SanityManager.DEBUG) { synchronized(this) { iosInProgress++; } } if (offset == -1L) { // Normal page read doesn't specify offset, // so use one computed from page number. readFull(pageBuf, ioChannel, pageOffset); } else { // getEmbryonicPage specifies it own offset, so use that if (SanityManager.DEBUG) { SanityManager.ASSERT(pageNumber == -1L); } readFull(pageBuf, ioChannel, offset); } } finally { if (SanityManager.DEBUG) { synchronized(this) { iosInProgress--; } } } if (dataFactory.databaseEncrypted() && pageNumber != FIRST_ALLOC_PAGE_NUMBER && pageNumber != -1L /* getEmbryonicPage */) { decryptPage(pageData, pageSize); } } else { // iochannel was not initialized, fall back to original method. super.readPage(pageNumber, pageData); } } /** * Write a page from the supplied array. * <p/> * override of RAFContainer#writePage * <p/> * <BR> MT - thread safe * * @exception StandardException Standard Derby error policy * @exception IOException IO error accessing page */ protected void writePage(long pageNumber, byte[] pageData, boolean syncPage) throws IOException, StandardException { // Interrupt recovery "stealthMode": If this thread holds a monitor on // // a) "allocCache" (e.g. FileContainer#newPage, #pageValid), // // we cannot grab channelCleanupMonitor lest another thread is one // doing recovery, since the recovery thread will try to grab both // those monitors during container recovery. So, just forge ahead // in stealth mode (i.e. the recovery thread doesn't see us). If we see // ClosedChannelException, throw InterruptDetectedException, so we can // retry from FileContainer releasing allocCache, so the recovery // thread can do its thing. boolean stealthMode = Thread.holdsLock(allocCache); if (SanityManager.DEBUG) { SanityManager.ASSERT(!Thread.holdsLock(this)); } if (stealthMode) { // We go into stealth mode. If we see an // CloseChannelExceptionexception, we will get out of here anyway, // so we don't need to increment threadsInPageIO (nor can we, // without risking dead-lock), } else { synchronized (channelCleanupMonitor) { // Gain entry int retries = MAX_INTERRUPT_RETRIES; while (restoreChannelInProgress) { if (retries-- == 0) { throw StandardException.newException( SQLState.FILE_IO_INTERRUPTED); } try { channelCleanupMonitor.wait(INTERRUPT_RETRY_SLEEP); } catch (InterruptedException e) { InterruptStatus.setInterrupted(); } } threadsInPageIO++; } } boolean success = false; int retries = MAX_INTERRUPT_RETRIES; try { while (!success) { try { if (pageNumber == FIRST_ALLOC_PAGE_NUMBER) { // If this is the first alloc page, there may be // another thread accessing the container information // in the borrowed space on the same page. In that // case, we synchronize the entire method call, just // like RAFContainer.writePage() does, in order to // avoid conflicts. For all other pages it is safe to // skip the synchronization, since concurrent threads // will access different pages and therefore don't // interfere with each other. synchronized (this) { writePage0(pageNumber, pageData, syncPage); } } else { writePage0(pageNumber, pageData, syncPage); } success = true; } catch (ClosedChannelException e) { handleClosedChannel(e, stealthMode, retries--); } } } finally { if (stealthMode) { // don't touch threadsInPageIO } else { synchronized (channelCleanupMonitor) { threadsInPageIO--; } } } } /** * This method handles what to do when, during a NIO operation we receive a * {@code ClosedChannelException}. Note the specialization hierarchy: * <p/> * {@code ClosedChannelException} -> {@code AsynchronousCloseException} -> * {@code ClosedByInterruptException} * <p/> * If {@code e} is a ClosedByInterruptException, we normally start * container recovery, i.e. we need to reopen the random access file so we * get get a new interruptible channel and continue IO. * <p/> * If {@code e} is a {@code AsynchronousCloseException} or a plain {@code * ClosedChannelException}, the behavior depends of {@code stealthMode}: * <p/> * If {@code stealthMode == false}, the method will wait for * another thread tp finish recovering the IO channel before returning. * <p/> * If {@code stealthMode == true}, the method throws {@code * InterruptDetectedException}, allowing retry at a higher level in the * code. The reason for this is that we sometimes need to release monitors * on objects needed by the recovery thread. * * @param e Should be an instance of {@code ClosedChannelException}. * @param stealthMode If {@code true}, do retry at a higher level * @param retries Give up waiting for another thread to reopen the channel * when {@code retries} reaches 0. Only applicable if {@code * stealthMode == false}. * @throws InterruptDetectedException if retry at higher level is required * {@code stealthMode == true}. * @throws StandardException standard error policy, incl. when we give up * waiting for another thread to reopen channel */ private void handleClosedChannel(ClosedChannelException e, boolean stealthMode, int retries) throws StandardException { // if (e instanceof ClosedByInterruptException e) { // Java NIO Bug 6979009: // http://bugs.sun.com/view_bug.do?bug_id=6979009 // Sometimes NIO throws AsynchronousCloseException instead of // ClosedByInterruptException if (e instanceof AsynchronousCloseException) { // Subsumes ClosedByInterruptException // The interrupted thread may or may not get back here to try // recovery before other concurrent IO threads will see (the // secondary) ClosedChannelException, but we have logic to handle // that, cf threadsInPageIO. if (Thread.currentThread().isInterrupted()) { if (recoverContainerAfterInterrupt( e.toString(), stealthMode)) { return; // do I/O over again } } // Recovery is in progress, wait for another interrupted thread to // clean up. awaitRestoreChannel(e, stealthMode); } else { // According to the exception type, We are not the thread that // first saw the channel interrupt, so no recovery attempt. InterruptStatus.noteAndClearInterrupt( "ClosedChannelException", threadsInPageIO, hashCode()); awaitRestoreChannel(e, stealthMode); if (retries == 0) { throw StandardException.newException( SQLState.FILE_IO_INTERRUPTED); } } } /** * Use when seeing an exception during IO and when another thread is * presumably doing the recovery. * <p/> * If {@code stealthMode == false}, wait for another thread to recover the * container after an interrupt. If {@code stealthMode == true}, throw * internal exception {@code InterruptDetectedException} to do retry from * higher in the stack. * <p/> * If {@code stealthMode == false}, maximum wait time for the container to * become available again is determined by the product {@code * FileContainer#MAX_INTERRUPT_RETRIES * FileContainer#INTERRUPT_RETRY_SLEEP}. * There is a chance this thread will not see any recovery occuring (yet), * in which case it waits for a bit and just returns, so the caller must * retry IO until success. * <p/> * If for some reason the recovering thread has given up on resurrecting * the container, cf {@code #giveUpIO}, the method throws {@code * FILE_IO_INTERRUPTED}. * * @param e the exception we saw during IO * @param stealthMode true if the thread doing IO in stealth mode * * @throws StandardException {@code InterruptDetectedException} and normal * error policy */ private void awaitRestoreChannel (Exception e, boolean stealthMode) throws StandardException { if (stealthMode) { // Retry handled at FileContainer or RAFContainer level // // This is necessary since recovery needs the monitor on allocCache // or "this" to clean up, so we need to back out all the way so // this thread can release the monitor to allow recovery to // proceed. if (SanityManager.DEBUG) { debugTrace( "thread does stealth mode retry"); } synchronized (giveUpIOm) { if (giveUpIO) { if (SanityManager.DEBUG) { debugTrace( "giving up retry, another thread gave up " + "resurrecting container "); } throw StandardException.newException( SQLState.FILE_IO_INTERRUPTED); } } throw new InterruptDetectedException(); } synchronized (channelCleanupMonitor) { // Pave way for the thread that received the interrupt that caused // the channel close to clean up, by signaling we are waiting (no // longer doing IO): threadsInPageIO--; } // Wait here till the interrupted thread does container recovery. // If we get a channel exception for some other reason, this will never // happen, so throw after waiting long enough (60s). int timesWaited = -1; while (true) { synchronized(channelCleanupMonitor) { while (restoreChannelInProgress) { timesWaited++; if (SanityManager.DEBUG) { debugTrace( "thread needs to wait for container recovery: " + "already waited " + timesWaited + " times"); } if (timesWaited > MAX_INTERRUPT_RETRIES) { // Max, give up, probably way too long anyway, // but doesn't hurt? throw StandardException.newException( SQLState.FILE_IO_INTERRUPTED, e); } try { channelCleanupMonitor.wait(INTERRUPT_RETRY_SLEEP); } catch (InterruptedException we) { InterruptStatus.setInterrupted(); } } // Since the channel is presumably ok (lest giveUpIO is set, // see below), we put ourselves back in the IO set of threads: threadsInPageIO++; break; } } synchronized (giveUpIOm) { if (giveUpIO) { if (SanityManager.DEBUG) { debugTrace( "giving up retry, another thread gave up " + "resurrecting container "); } threadsInPageIO--; throw StandardException.newException( SQLState.FILE_IO_INTERRUPTED); } } if (timesWaited == -1) { // We have not seen restoreChannelInProgress, so we may // have raced past the interrupted thread, so let's wait a // bit before we attempt a new I/O. try { Thread.sleep(INTERRUPT_RETRY_SLEEP); } catch (InterruptedException we) { // This thread is getting hit, too.. InterruptStatus.setInterrupted(); } } } /** * Use this when the thread has received a ClosedByInterruptException (or, * prior to JDK 1.7 it may also be AsynchronousCloseException - a bug) * exception during IO and its interruped flag is also set. This makes this * thread a likely candicate to do container recovery, unless another * thread started it already, cf. return value. * * @param whence caller site (debug info) * @param stealthMode don't update threadsInPageIO if true * @return true if we did recovery, false if we saw someone else do it and * abstained */ private boolean recoverContainerAfterInterrupt( String whence, boolean stealthMode) throws StandardException { if (stealthMode && restoreChannelInProgress) { // 1) Another interrupted thread got to do the cleanup before us, so // yield. // This should not happen, but since // we had to "fix" NIO, cf. the code marked (**), we could // theoretically see two: // // - the thread that got AsynchronousCloseException, but was the // one that caused the channel close: it will decide (correctly) // it is the one to do recovery. // // - another thread that got an interrupt after doing successful IO // but seeing a closed channel: it will decide (incorrectly) it // is the one to do recovery. But since we had to fix NIO, this // case gets conflated with the case that this was *really* the // thread the caused the channel close. // // Not safe for Java 1.4 (only volatile protection for // restoreChannelInProgress here), compare safe test below (not // stealthMode). // // 2) The other way to end up here is if we get interrupted during // getEmbryonicPage called during container recovery from the same // thread (restoreChannelInProgress is set then, and // getEmbryonicPage is stealthMode) InterruptStatus.noteAndClearInterrupt( whence, threadsInPageIO, hashCode()); return false; } synchronized (channelCleanupMonitor) { if (restoreChannelInProgress) { // Another interrupted thread got to do the cleanup before us, // so yield, see above explanation. InterruptStatus.noteAndClearInterrupt( whence, threadsInPageIO, hashCode()); return false; } if (stealthMode) { // don't touch threadsInPageIO } else { threadsInPageIO--; } // All new writers will now wait till we're done, see "Gain entry" // in writePage above. Any concurrent threads already inside will // also wait till we're done, see below restoreChannelInProgress = true; } // Wait till other concurrent threads hit the wall // (ClosedChannelException) and are a ready waiting for us to clean up, // so we can set them loose when we're done. int retries = MAX_INTERRUPT_RETRIES; while (true) { synchronized (channelCleanupMonitor) { if (threadsInPageIO == 0) { // Either no concurrent threads, or they are now waiting // for us to clean up (see ClosedChannelException case) break; } if (retries-- == 0) { // Clean up state and throw restoreChannelInProgress = false; channelCleanupMonitor.notifyAll(); throw StandardException.newException( SQLState.FILE_IO_INTERRUPTED); } } try { Thread.sleep(INTERRUPT_RETRY_SLEEP); } catch (InterruptedException te) { InterruptStatus.setInterrupted(); } } // Initiate recovery synchronized (channelCleanupMonitor) { try { InterruptStatus.noteAndClearInterrupt( whence, threadsInPageIO, hashCode()); synchronized(this) { if (SanityManager.DEBUG) { SanityManager.ASSERT(ourChannel != null, "ourChannel is null"); SanityManager.ASSERT(!ourChannel.isOpen(), "ourChannel is open"); } } while (true) { synchronized(this) { try { reopen(); } catch (Exception newE) { // Something else failed - shutdown happening? synchronized(giveUpIOm) { // Make sure other threads will give up and // throw, too. giveUpIO = true; if (SanityManager.DEBUG) { debugTrace( "can't resurrect container: " + newE); } throw StandardException.newException( SQLState.FILE_IO_INTERRUPTED, newE); } } break; } } if (stealthMode) { // don't touch threadsInPageIO } else { threadsInPageIO++; } // retry IO } finally { // Recovery work done (or failed), now set other threads free // to retry or give up as the case may be, cf. giveUpIO. restoreChannelInProgress = false; channelCleanupMonitor.notifyAll(); } } // end channelCleanupMonitor region return true; } private void writePage0(long pageNumber, byte[] pageData, boolean syncPage) throws IOException, StandardException { FileChannel ioChannel; synchronized (this) { // committed and dropped, do nothing. // This file container may only be a stub if (getCommittedDropState()) return; ioChannel = getChannel(); } if (SanityManager.DEBUG) { if (pageNumber == FIRST_ALLOC_PAGE_NUMBER) { // page 0 SanityManager.ASSERT(Thread.holdsLock(this)); } else { SanityManager.ASSERT(!Thread.holdsLock(this)); } } if(ioChannel != null) { /////////////////////////////////////////////////// // // RESOLVE: right now, no logical -> physical mapping. // We can calculate the offset. In the future, we may need to // look at the allocation page or the in memory translation table // to figure out where the page should go // ///////////////////////////////////////////////// long pageOffset = pageNumber * pageSize; byte[] encryptionBuf = null; // We only need to allocate the encryptionBuf if updatePageArray is // actually going to use it. if (dataFactory.databaseEncrypted()) { encryptionBuf = new byte[pageSize]; } byte[] dataToWrite = updatePageArray(pageNumber, pageData, encryptionBuf, false); if (SanityManager.DEBUG) { SanityManager.ASSERT(dataToWrite != null, "RAFContainer4: dataToWrite is null after updatePageArray()"); } ByteBuffer writeBuffer = ByteBuffer.wrap(dataToWrite); dataFactory.writeInProgress(); try { if (SanityManager.DEBUG) { synchronized(this) { iosInProgress++; } } writeFull(writeBuffer, ioChannel, pageOffset); } catch (ClosedChannelException ioe) { synchronized(this) { /* If the write failed because the container has been closed * for deletion between the start of this method and the * write, we'll just ignore that, as this container is going * away anyway. * This could possibly happen if the Cache is cleaning this * container while it is dropped - BaseDataFileFactory holds * an exclusive lock on the container while dropping it to * avoid other interference. * See the getCommittedDropState() check at the top of this * method. */ if (getCommittedDropState()) { if (SanityManager.DEBUG) { debugTrace( "write to a dropped and " + "closed container discarded."); } return; } else { // This should not happen, better let the exception // hurt where it's supposed to. throw ioe; } } } finally { if (SanityManager.DEBUG) { synchronized(this) { iosInProgress--; } } dataFactory.writeFinished(); } /* Note that the original "try {write} catch IOException { pad file, * write again }" in RAFContainer is removed here, because the * FileChannel Javadoc specifies that the file will be grown to * accommodate the new bytes. */ if (syncPage) { dataFactory.writeInProgress(); try{ if (SanityManager.DEBUG) { synchronized(this) { iosInProgress++; } } if (!dataFactory.dataNotSyncedAtAllocation) { ioChannel.force(false); } } finally { if (SanityManager.DEBUG) { synchronized(this) { iosInProgress--; } } dataFactory.writeFinished(); } } else { synchronized(this) { needsSync = true; } } } else { // iochannel was not initialized, fall back to original method. super.writePage(pageNumber, pageData, syncPage); } } /** * Write a sequence of bytes at the given offset in a file. This method * operates in <em>stealth mode</em>, see doc for {@link * #handleClosedChannel handleClosedChannel}. * This presumes that IO retry happens at a higher level, i.e. the * caller(s) must be prepared to handle {@code InterruptDetectedException}. * <p/> * This method overrides FileContainer#writeAtOffset. * <p/> * @param file the file to write to * @param bytes the bytes to write * @param offset the offset to start writing at * @throws IOException if an I/O error occurs while writing */ void writeAtOffset(StorageRandomAccessFile file, byte[] bytes, long offset) throws IOException, StandardException { FileChannel ioChannel = getChannel(file); if (ioChannel == null) { super.writeAtOffset(file, bytes, offset); return; } ourChannel = ioChannel; boolean success = false; final boolean stealthMode = true; while (!success) { synchronized (this) { // don't use ourChannel directly, could need re-initilization // after interrupt and container reopening: ioChannel = getChannel(); } try { writeFull(ByteBuffer.wrap(bytes), ioChannel, offset); success = true; } catch (ClosedChannelException e) { handleClosedChannel(e, stealthMode, -1 /* NA */); } } } /** * Read an embryonic page (that is, a section of the first alloc page that * is so large that we know all the borrowed space is included in it) from * the specified offset in a {@code StorageRandomAccessFile}. * <p/> * override of FileContainer#getEmbryonicPage * <p/> * @param file the file to read from * @param offset where to start reading (normally * {@code FileContainer.FIRST_ALLOC_PAGE_OFFSET}) * @return a byte array containing the embryonic page * @throws IOException if an I/O error occurs while reading * @throws StandardException if thread is interrupted. */ byte[] getEmbryonicPage(StorageRandomAccessFile file, long offset) throws IOException, StandardException { FileChannel ioChannel = getChannel(file); if (ioChannel != null) { byte[] buffer = new byte[AllocPage.MAX_BORROWED_SPACE]; readPage(-1L, buffer, offset); return buffer; } else { return super.getEmbryonicPage(file, offset); } } /** * Attempts to fill buf completely from start until it's full. * <p/> * FileChannel has no readFull() method, so we roll our own. * <p/> * @param dstBuffer buffer to read into * @param srcChannel channel to read from * @param position file position from where to read * * @throws IOException if an I/O error occurs while reading * @throws StandardException If thread is interrupted. */ private void readFull(ByteBuffer dstBuffer, FileChannel srcChannel, long position) throws IOException, StandardException { while(dstBuffer.remaining() > 0) { if (srcChannel.read(dstBuffer, position + dstBuffer.position()) == -1) { throw new EOFException( "Reached end of file while attempting to read a " + "whole page."); } // (**) Sun Java NIO is weird: it can close the channel due to an // interrupt without throwing if bytes got transferred. Compensate, // so we can clean up. Bug 6979009, // http://bugs.sun.com/view_bug.do?bug_id=6979009 if (Thread.currentThread().isInterrupted() && !srcChannel.isOpen()) { throw new ClosedByInterruptException(); } } } /** * Attempts to write buf completely from start until end, at the given * position in the destination fileChannel. * <p/> * FileChannel has no writeFull() method, so we roll our own. * <p/> * @param srcBuffer buffer to write * @param dstChannel channel to write to * @param position file position to start writing at * * @throws IOException if an I/O error occurs while writing * @throws StandardException If thread is interrupted. */ private void writeFull(ByteBuffer srcBuffer, FileChannel dstChannel, long position) throws IOException { while(srcBuffer.remaining() > 0) { dstChannel.write(srcBuffer, position + srcBuffer.position()); // (**) Sun JAVA NIO is weird: it can close the channel due to an // interrupt without throwing if bytes got transferred. Compensate, // so we can clean up. Bug 6979009, // http://bugs.sun.com/view_bug.do?bug_id=6979009 if (Thread.currentThread().isInterrupted() && !dstChannel.isOpen()) { throw new ClosedByInterruptException(); } } } private static void debugTrace (String msg) { if (SanityManager.DEBUG) { // redundant, just to remove code in insane if (SanityManager.DEBUG_ON("RAF4")) { SanityManager.DEBUG_PRINT( "RAF4", Thread.currentThread().getName() + " " + msg); } } } }
/* * Copyright (C) 2013 readyState Software Ltd * * 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.work.cjh.gifttalk.utils; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout.LayoutParams; import java.lang.reflect.Method; /** * Class to manage status and navigation bar tint effects when using KitKat * translucent system UI modes. * */ public class SystemBarTintManager { static { // Android allows a system property to override the presence of the navigation bar. // Used by the emulator. // See https://github.com/android/platform_frameworks_base/blob/master/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java#L1076 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { try { Class c = Class.forName("android.os.SystemProperties"); Method m = c.getDeclaredMethod("get", String.class); m.setAccessible(true); sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys"); } catch (Throwable e) { sNavBarOverride = null; } } } /** * The default system bar tint color value. */ public static final int DEFAULT_TINT_COLOR = 0x99000000; private static String sNavBarOverride; private final SystemBarConfig mConfig; private boolean mStatusBarAvailable; private boolean mNavBarAvailable; private boolean mStatusBarTintEnabled; private boolean mNavBarTintEnabled; private View mStatusBarTintView; private View mNavBarTintView; /** * Constructor. Call this in the host activity onCreate method after its * content view has been set. You should always create new instances when * the host activity is recreated. * * @param activity The host activity. */ @TargetApi(19) public SystemBarTintManager(Activity activity) { Window win = activity.getWindow(); ViewGroup decorViewGroup = (ViewGroup) win.getDecorView(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // check theme attrs int[] attrs = {android.R.attr.windowTranslucentStatus, android.R.attr.windowTranslucentNavigation}; TypedArray a = activity.obtainStyledAttributes(attrs); try { mStatusBarAvailable = a.getBoolean(0, false); mNavBarAvailable = a.getBoolean(1, false); } finally { a.recycle(); } // check window flags WindowManager.LayoutParams winParams = win.getAttributes(); int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if ((winParams.flags & bits) != 0) { mStatusBarAvailable = true; } bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION; if ((winParams.flags & bits) != 0) { mNavBarAvailable = true; } } mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable); // device might not have virtual navigation keys if (!mConfig.hasNavigtionBar()) { mNavBarAvailable = false; } if (mStatusBarAvailable) { setupStatusBarView(activity, decorViewGroup); } if (mNavBarAvailable) { setupNavBarView(activity, decorViewGroup); } } /** * Enable tinting of the system status bar. * * If the platform is running Jelly Bean or earlier, or translucent system * UI modes have not been enabled in either the theme or via window flags, * then this method does nothing. * * @param enabled True to enable tinting, false to disable it (default). */ public void setStatusBarTintEnabled(boolean enabled) { mStatusBarTintEnabled = enabled; // if (mStatusBarAvailable) { mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE); // } } /** * Enable tinting of the system navigation bar. * * If the platform does not have soft navigation keys, is running Jelly Bean * or earlier, or translucent system UI modes have not been enabled in either * the theme or via window flags, then this method does nothing. * * @param enabled True to enable tinting, false to disable it (default). */ public void setNavigationBarTintEnabled(boolean enabled) { mNavBarTintEnabled = enabled; if (mNavBarAvailable) { mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE); } } /** * Apply the specified color tint to all system UI bars. * * @param color The color of the background tint. */ public void setTintColor(int color) { setStatusBarTintColor(color); setNavigationBarTintColor(color); } /** * Apply the specified drawable or color resource to all system UI bars. * * @param res The identifier of the resource. */ public void setTintResource(int res) { setStatusBarTintResource(res); setNavigationBarTintResource(res); } /** * Apply the specified drawable to all system UI bars. * * @param drawable The drawable to use as the background, or null to remove it. */ public void setTintDrawable(Drawable drawable) { setStatusBarTintDrawable(drawable); setNavigationBarTintDrawable(drawable); } /** * Apply the specified alpha to all system UI bars. * * @param alpha The alpha to use */ public void setTintAlpha(float alpha) { setStatusBarAlpha(alpha); setNavigationBarAlpha(alpha); } /** * Apply the specified color tint to the system status bar. * * @param color The color of the background tint. */ public void setStatusBarTintColor(int color) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundColor(color); } } /** * Apply the specified drawable or color resource to the system status bar. * * @param res The identifier of the resource. */ public void setStatusBarTintResource(int res) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundResource(res); } } /** * Apply the specified drawable to the system status bar. * * @param drawable The drawable to use as the background, or null to remove it. */ @SuppressWarnings("deprecation") public void setStatusBarTintDrawable(Drawable drawable) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundDrawable(drawable); } } /** * Apply the specified alpha to the system status bar. * * @param alpha The alpha to use */ @TargetApi(11) public void setStatusBarAlpha(float alpha) { if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mStatusBarTintView.setAlpha(alpha); } } /** * Apply the specified color tint to the system navigation bar. * * @param color The color of the background tint. */ public void setNavigationBarTintColor(int color) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundColor(color); } } /** * Apply the specified drawable or color resource to the system navigation bar. * * @param res The identifier of the resource. */ public void setNavigationBarTintResource(int res) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundResource(res); } } /** * Apply the specified drawable to the system navigation bar. * * @param drawable The drawable to use as the background, or null to remove it. */ @SuppressWarnings("deprecation") public void setNavigationBarTintDrawable(Drawable drawable) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundDrawable(drawable); } } /** * Apply the specified alpha to the system navigation bar. * * @param alpha The alpha to use */ @TargetApi(11) public void setNavigationBarAlpha(float alpha) { if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mNavBarTintView.setAlpha(alpha); } } /** * Get the system bar configuration. * * @return The system bar configuration for the current device configuration. */ public SystemBarConfig getConfig() { return mConfig; } /** * Is tinting enabled for the system status bar? * * @return True if enabled, False otherwise. */ public boolean isStatusBarTintEnabled() { return mStatusBarTintEnabled; } /** * Is tinting enabled for the system navigation bar? * * @return True if enabled, False otherwise. */ public boolean isNavBarTintEnabled() { return mNavBarTintEnabled; } private void setupStatusBarView(Context context, ViewGroup decorViewGroup) { mStatusBarTintView = new View(context); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight()); params.gravity = Gravity.TOP; if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) { params.rightMargin = mConfig.getNavigationBarWidth(); } mStatusBarTintView.setLayoutParams(params); mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR); mStatusBarTintView.setVisibility(View.GONE); decorViewGroup.addView(mStatusBarTintView); } private void setupNavBarView(Context context, ViewGroup decorViewGroup) { mNavBarTintView = new View(context); LayoutParams params; if (mConfig.isNavigationAtBottom()) { params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight()); params.gravity = Gravity.BOTTOM; } else { params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT); params.gravity = Gravity.RIGHT; } mNavBarTintView.setLayoutParams(params); mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR); mNavBarTintView.setVisibility(View.GONE); decorViewGroup.addView(mNavBarTintView); } /** * Class which describes system bar sizing and other characteristics for the current * device configuration. * */ public static class SystemBarConfig { private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height"; private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height"; private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape"; private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width"; private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar"; private final boolean mTranslucentStatusBar; private final boolean mTranslucentNavBar; private final int mStatusBarHeight; private final int mActionBarHeight; private final boolean mHasNavigationBar; private final int mNavigationBarHeight; private final int mNavigationBarWidth; private final boolean mInPortrait; private final float mSmallestWidthDp; private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) { Resources res = activity.getResources(); mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT); mSmallestWidthDp = getSmallestWidthDp(activity); mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME); mActionBarHeight = getActionBarHeight(activity); mNavigationBarHeight = getNavigationBarHeight(activity); mNavigationBarWidth = getNavigationBarWidth(activity); mHasNavigationBar = (mNavigationBarHeight > 0); mTranslucentStatusBar = translucentStatusBar; mTranslucentNavBar = traslucentNavBar; } @TargetApi(14) private int getActionBarHeight(Context context) { int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true); result = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics()); } return result; } @TargetApi(14) private int getNavigationBarHeight(Context context) { Resources res = context.getResources(); int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (hasNavBar(context)) { String key; if (mInPortrait) { key = NAV_BAR_HEIGHT_RES_NAME; } else { key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME; } return getInternalDimensionSize(res, key); } } return result; } @TargetApi(14) private int getNavigationBarWidth(Context context) { Resources res = context.getResources(); int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (hasNavBar(context)) { return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME); } } return result; } @TargetApi(14) private boolean hasNavBar(Context context) { Resources res = context.getResources(); int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android"); if (resourceId != 0) { boolean hasNav = res.getBoolean(resourceId); // check override flag (see static block) if ("1".equals(sNavBarOverride)) { hasNav = false; } else if ("0".equals(sNavBarOverride)) { hasNav = true; } return hasNav; } else { // fallback return !ViewConfiguration.get(context).hasPermanentMenuKey(); } } private int getInternalDimensionSize(Resources res, String key) { int result = 0; int resourceId = res.getIdentifier(key, "dimen", "android"); if (resourceId > 0) { result = res.getDimensionPixelSize(resourceId); } return result; } @SuppressLint("NewApi") private float getSmallestWidthDp(Activity activity) { DisplayMetrics metrics = new DisplayMetrics(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); } else { // TODO this is not correct, but we don't really care pre-kitkat activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); } float widthDp = metrics.widthPixels / metrics.density; float heightDp = metrics.heightPixels / metrics.density; return Math.min(widthDp, heightDp); } /** * Should a navigation bar appear at the bottom of the screen in the current * device configuration? A navigation bar may appear on the right side of * the screen in certain configurations. * * @return True if navigation should appear at the bottom of the screen, False otherwise. */ public boolean isNavigationAtBottom() { return (mSmallestWidthDp >= 600 || mInPortrait); } /** * Get the height of the system status bar. * * @return The height of the status bar (in pixels). */ public int getStatusBarHeight() { return mStatusBarHeight; } /** * Get the height of the action bar. * * @return The height of the action bar (in pixels). */ public int getActionBarHeight() { return mActionBarHeight; } /** * Does this device have a system navigation bar? * * @return True if this device uses soft key navigation, False otherwise. */ public boolean hasNavigtionBar() { return mHasNavigationBar; } /** * Get the height of the system navigation bar. * * @return The height of the navigation bar (in pixels). If the device does not have * soft navigation keys, this will always return 0. */ public int getNavigationBarHeight() { return mNavigationBarHeight; } /** * Get the width of the system navigation bar when it is placed vertically on the screen. * * @return The width of the navigation bar (in pixels). If the device does not have * soft navigation keys, this will always return 0. */ public int getNavigationBarWidth() { return mNavigationBarWidth; } /** * Get the layout inset for any system UI that appears at the top of the screen. * * @param withActionBar True to include the height of the action bar, False otherwise. * @return The layout inset (in pixels). */ public int getPixelInsetTop(boolean withActionBar) { return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0); } /** * Get the layout inset for any system UI that appears at the bottom of the screen. * * @return The layout inset (in pixels). */ public int getPixelInsetBottom() { if (mTranslucentNavBar && isNavigationAtBottom()) { return mNavigationBarHeight; } else { return 0; } } /** * Get the layout inset for any system UI that appears at the right of the screen. * * @return The layout inset (in pixels). */ public int getPixelInsetRight() { if (mTranslucentNavBar && !isNavigationAtBottom()) { return mNavigationBarWidth; } else { return 0; } } } }
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.intellij.util.containers; import com.intellij.util.GCUtil; import org.junit.Test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import static org.junit.Assert.*; public class WeakListTest { private static final String HARD_REFERENCED = "xxx"; private final WeakList<Object> myWeakList = new WeakList<>(); private final List<Object> myHolder = new ArrayList<>(); @Test public void testCompresses() { fillWithObjects(20); assertEquals(20, myWeakList.listSize()); addElement(HARD_REFERENCED); assertEquals(21, myWeakList.listSize()); myHolder.clear(); while (myWeakList.toStrongList().size() == 21) { synchronized (myWeakList) { gc(); } } synchronized (myWeakList) { boolean processed = myWeakList.processQueue(); assertTrue(myWeakList.toStrongList().toString(), processed); // some refs must be in the queue } //HARD_REFERENCED is held there assertEquals(1, myWeakList.listSize()); assertSame(HARD_REFERENCED, myWeakList.iterator().next()); } @Test public void testClear() { fillWithObjects(20); assertEquals(20, myWeakList.listSize()); myHolder.clear(); gc(); myWeakList.clear(); assertFalse(myWeakList.iterator().hasNext()); } @Test public void testIterator() { int N = 10; fillWithInts(N); gc(); Iterator<?> iterator = myWeakList.iterator(); for (int i = 0; i < N; i++) { assertTrue(iterator.hasNext()); assertTrue(iterator.hasNext()); int element = (Integer)iterator.next(); assertEquals(i, element); } assertFalse(iterator.hasNext()); int elementCount = 0; for (Object element : myWeakList) { assertEquals(elementCount, element); elementCount++; } assertEquals(N, elementCount); } @Test public void testRemoveViaIterator() { addElement(new Object()); addElement(new Object()); addElement(new Object()); Iterator<Object> iterator = myWeakList.iterator(); assertSame(myHolder.get(0), iterator.next()); iterator.remove(); gc(); assertEquals(2, myWeakList.toStrongList().size()); iterator.next(); gc(); assertEquals(2, myWeakList.toStrongList().size()); assertSame(myHolder.get(2), iterator.next()); assertFalse(iterator.hasNext()); myHolder.remove(1); } @Test public void testRemoveAllViaIterator() { int N = 10; fillWithInts(N); gc(); Iterator<Object> iterator = myWeakList.iterator(); for (int i = 0; i < N; i++) { assertTrue(iterator.hasNext()); int element = (Integer)iterator.next(); assertEquals(i, element); iterator.remove(); } assertFalse(iterator.hasNext()); assertTrue(myWeakList.toStrongList().isEmpty()); } @Test public void testRemoveLastViaIterator() { addElement(new Object()); addElement(new Object()); Iterator<Object> iterator = myWeakList.iterator(); iterator.next(); assertTrue(iterator.hasNext()); iterator.next(); assertFalse(iterator.hasNext()); iterator.remove(); } @Test public void testIteratorKeepsFirstElement() { addElement(new Object()); addElement(new Object()); Iterator<Object> iterator = myWeakList.iterator(); assertTrue(iterator.hasNext()); myHolder.clear(); gc(); assertNotNull(iterator.next()); assertFalse(iterator.hasNext()); } @Test public void testIteratorKeepsNextElement() { addElement(new Object()); addElement(new Object()); addElement(new Object()); Iterator<Object> iterator = myWeakList.iterator(); iterator.next(); assertTrue(iterator.hasNext()); myHolder.clear(); gc(); assertNotNull(iterator.next()); assertFalse(iterator.hasNext()); } @Test public void testIteratorRemoveEmpty() { Iterator<Object> iterator = myWeakList.iterator(); assertFalse(iterator.hasNext()); try { iterator.next(); fail("must not allow to next"); } catch (NoSuchElementException ignored) { } try { iterator.remove(); fail("must not allow to remove"); } catch (NoSuchElementException ignored) { } } @Test public void testElementGetsCollectedInTheMiddleAndListRebuildsItself() { int N = 200; fillWithObjects(N); String x = new String("xxx"); addElement(x); fillWithObjects(N); gc(); assertEquals(N + 1 + N, myWeakList.listSize()); myHolder.clear(); while (myWeakList.toStrongList().size() == N + 1 + N) { synchronized (myWeakList) { gc(); } } boolean removed = myWeakList.remove("zzz"); assertFalse(removed); assertEquals(1, myWeakList.listSize()); Object element = myWeakList.iterator().next(); assertSame(x, element); } @Test public void testIsEmpty() { assertTrue(myWeakList.isEmpty()); addElement(new Object()); assertFalse(myWeakList.isEmpty()); myHolder.clear(); gc(); assertEquals(1, myWeakList.listSize()); assertTrue(myWeakList.isEmpty()); } private void addElement(Object element) { myWeakList.add(element); myHolder.add(element); } private void fillWithObjects(int n) { for (int i = n - 1; i >= 0; i--) { addElement(new Object()); } } private void fillWithInts(int n) { for (int i = 0; i < n; i++) { addElement(i); } } private static void gc() { GCUtil.tryForceGC(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.utils; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; /** * PojoUtils. Travel object deeply, and convert complex type to simple type. * <p/> * Simple type below will be remained: * <ul> * <li> Primitive Type, also include <b>String</b>, <b>Number</b>(Integer, Long), <b>Date</b> * <li> Array of Primitive Type * <li> Collection, eg: List, Map, Set etc. * </ul> * <p/> * Other type will be covert to a map which contains the attributes and value pair of object. */ public class PojoUtils { private static final ConcurrentMap<String, Method> NAME_METHODS_CACHE = new ConcurrentHashMap<String, Method>(); private static final ConcurrentMap<Class<?>, ConcurrentMap<String, Field>> CLASS_FIELD_CACHE = new ConcurrentHashMap<Class<?>, ConcurrentMap<String, Field>>(); public static Object[] generalize(Object[] objs) { Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = generalize(objs[i]); } return dests; } public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } public static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes) { if (objs.length != types.length || objs.length != gtypes.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i], gtypes[i]); } return dests; } public static Object generalize(Object pojo) { return generalize(pojo, new IdentityHashMap<Object, Object>()); } @SuppressWarnings("unchecked") private static Object generalize(Object pojo, Map<Object, Object> history) { if (pojo == null) { return null; } if (pojo instanceof Enum<?>) { return ((Enum<?>) pojo).name(); } if (pojo.getClass().isArray() && Enum.class.isAssignableFrom(pojo.getClass().getComponentType())) { int len = Array.getLength(pojo); String[] values = new String[len]; for (int i = 0; i < len; i++) { values[i] = ((Enum<?>) Array.get(pojo, i)).name(); } return values; } if (ReflectUtils.isPrimitives(pojo.getClass())) { return pojo; } if (pojo instanceof Class) { return ((Class) pojo).getName(); } Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo); if (pojo.getClass().isArray()) { int len = Array.getLength(pojo); Object[] dest = new Object[len]; history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); dest[i] = generalize(obj, history); } return dest; } if (pojo instanceof Collection<?>) { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = (pojo instanceof List<?>) ? new ArrayList<Object>(len) : new HashSet<Object>(len); history.put(pojo, dest); for (Object obj : src) { dest.add(generalize(obj, history)); } return dest; } if (pojo instanceof Map<?, ?>) { Map<Object, Object> src = (Map<Object, Object>) pojo; Map<Object, Object> dest = createMap(src); history.put(pojo, dest); for (Map.Entry<Object, Object> obj : src.entrySet()) { dest.put(generalize(obj.getKey(), history), generalize(obj.getValue(), history)); } return dest; } Map<String, Object> map = new HashMap<String, Object>(); history.put(pojo, map); map.put("class", pojo.getClass().getName()); for (Method method : pojo.getClass().getMethods()) { if (ReflectUtils.isBeanPropertyReadMethod(method)) { try { map.put(ReflectUtils.getPropertyNameFromBeanReadMethod(method), generalize(method.invoke(pojo), history)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } // public field for (Field field : pojo.getClass().getFields()) { if (ReflectUtils.isPublicInstanceField(field)) { try { Object fieldValue = field.get(pojo); if (history.containsKey(pojo)) { Object pojoGenerilizedValue = history.get(pojo); if (pojoGenerilizedValue instanceof Map && ((Map) pojoGenerilizedValue).containsKey(field.getName())) { continue; } } if (fieldValue != null) { map.put(field.getName(), generalize(fieldValue, history)); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } return map; } public static Object realize(Object pojo, Class<?> type) { return realize0(pojo, type, null, new IdentityHashMap<Object, Object>()); } public static Object realize(Object pojo, Class<?> type, Type genericType) { return realize0(pojo, type, genericType, new IdentityHashMap<Object, Object>()); } private static class PojoInvocationHandler implements InvocationHandler { private Map<Object, Object> map; public PojoInvocationHandler(Map<Object, Object> map) { this.map = map; } @SuppressWarnings("unchecked") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(map, args); } String methodName = method.getName(); Object value = null; if (methodName.length() > 3 && methodName.startsWith("get")) { value = map.get(methodName.substring(3, 4).toLowerCase() + methodName.substring(4)); } else if (methodName.length() > 2 && methodName.startsWith("is")) { value = map.get(methodName.substring(2, 3).toLowerCase() + methodName.substring(3)); } else { value = map.get(methodName.substring(0, 1).toLowerCase() + methodName.substring(1)); } if (value instanceof Map<?, ?> && !Map.class.isAssignableFrom(method.getReturnType())) { value = realize0((Map<String, Object>) value, method.getReturnType(), null, new IdentityHashMap<Object, Object>()); } return value; } } @SuppressWarnings("unchecked") private static Collection<Object> createCollection(Class<?> type, int len) { if (type.isAssignableFrom(ArrayList.class)) { return new ArrayList<Object>(len); } if (type.isAssignableFrom(HashSet.class)) { return new HashSet<Object>(len); } if (!type.isInterface() && !Modifier.isAbstract(type.getModifiers())) { try { return (Collection<Object>) type.newInstance(); } catch (Exception e) { // ignore } } return new ArrayList<Object>(); } private static Map createMap(Map src) { Class<? extends Map> cl = src.getClass(); Map result = null; if (HashMap.class == cl) { result = new HashMap(); } else if (Hashtable.class == cl) { result = new Hashtable(); } else if (IdentityHashMap.class == cl) { result = new IdentityHashMap(); } else if (LinkedHashMap.class == cl) { result = new LinkedHashMap(); } else if (Properties.class == cl) { result = new Properties(); } else if (TreeMap.class == cl) { result = new TreeMap(); } else if (WeakHashMap.class == cl) { return new WeakHashMap(); } else if (ConcurrentHashMap.class == cl) { result = new ConcurrentHashMap(); } else if (ConcurrentSkipListMap.class == cl) { result = new ConcurrentSkipListMap(); } else { try { result = cl.newInstance(); } catch (Exception e) { /* ignore */ } if (result == null) { try { Constructor<?> constructor = cl.getConstructor(Map.class); result = (Map) constructor.newInstance(Collections.EMPTY_MAP); } catch (Exception e) { /* ignore */ } } } if (result == null) { result = new HashMap<Object, Object>(); } return result; } @SuppressWarnings({"unchecked", "rawtypes"}) private static Object realize0(Object pojo, Class<?> type, Type genericType, final Map<Object, Object> history) { if (pojo == null) { return null; } if (type != null && type.isEnum() && pojo.getClass() == String.class) { return Enum.valueOf((Class<Enum>) type, (String) pojo); } if (ReflectUtils.isPrimitives(pojo.getClass()) && !(type != null && type.isArray() && type.getComponentType().isEnum() && pojo.getClass() == String[].class)) { return CompatibleTypeUtils.compatibleTypeConvert(pojo, type); } Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo); if (pojo.getClass().isArray()) { if (Collection.class.isAssignableFrom(type)) { Class<?> ctype = pojo.getClass().getComponentType(); int len = Array.getLength(pojo); Collection dest = createCollection(type, len); history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); Object value = realize0(obj, ctype, null, history); dest.add(value); } return dest; } else { Class<?> ctype = (type != null && type.isArray() ? type.getComponentType() : pojo.getClass().getComponentType()); int len = Array.getLength(pojo); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); Object value = realize0(obj, ctype, null, history); Array.set(dest, i, value); } return dest; } } if (pojo instanceof Collection<?>) { if (type.isArray()) { Class<?> ctype = type.getComponentType(); Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); int i = 0; for (Object obj : src) { Object value = realize0(obj, ctype, null, history); Array.set(dest, i, value); i++; } return dest; } else { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = createCollection(type, len); history.put(pojo, dest); for (Object obj : src) { Type keyType = getGenericClassByIndex(genericType, 0); Class<?> keyClazz = obj.getClass(); if (keyType instanceof Class) { keyClazz = (Class<?>) keyType; } Object value = realize0(obj, keyClazz, keyType, history); dest.add(value); } return dest; } } if (pojo instanceof Map<?, ?> && type != null) { Object className = ((Map<Object, Object>) pojo).get("class"); if (className instanceof String) { try { type = ClassHelper.forName((String) className); } catch (ClassNotFoundException e) { // ignore } } // special logic for enum if (type.isEnum()) { Object name = ((Map<Object, Object>) pojo).get("name"); if (name != null) { return Enum.valueOf((Class<Enum>) type, name.toString()); } } Map<Object, Object> map; // when return type is not the subclass of return type from the signature and not an interface if (!type.isInterface() && !type.isAssignableFrom(pojo.getClass())) { try { map = (Map<Object, Object>) type.newInstance(); Map<Object, Object> mapPojo = (Map<Object, Object>) pojo; map.putAll(mapPojo); map.remove("class"); } catch (Exception e) { //ignore error map = (Map<Object, Object>) pojo; } } else { map = (Map<Object, Object>) pojo; } if (Map.class.isAssignableFrom(type) || type == Object.class) { final Map<Object, Object> result = createMap(map); history.put(pojo, result); for (Map.Entry<Object, Object> entry : map.entrySet()) { Type keyType = getGenericClassByIndex(genericType, 0); Type valueType = getGenericClassByIndex(genericType, 1); Class<?> keyClazz; if (keyType instanceof Class) { keyClazz = (Class<?>) keyType; } else if (keyType instanceof ParameterizedType) { keyClazz = (Class<?>) ((ParameterizedType) keyType).getRawType(); } else { keyClazz = entry.getKey() == null ? null : entry.getKey().getClass(); } Class<?> valueClazz; if (valueType instanceof Class) { valueClazz = (Class<?>) valueType; } else if (valueType instanceof ParameterizedType) { valueClazz = (Class<?>) ((ParameterizedType) valueType).getRawType(); } else { valueClazz = entry.getValue() == null ? null : entry.getValue().getClass(); } Object key = keyClazz == null ? entry.getKey() : realize0(entry.getKey(), keyClazz, keyType, history); Object value = valueClazz == null ? entry.getValue() : realize0(entry.getValue(), valueClazz, valueType, history); result.put(key, value); } return result; } else if (type.isInterface()) { Object dest = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{type}, new PojoInvocationHandler(map)); history.put(pojo, dest); return dest; } else { Object dest = newInstance(type); history.put(pojo, dest); for (Map.Entry<Object, Object> entry : map.entrySet()) { Object key = entry.getKey(); if (key instanceof String) { String name = (String) key; Object value = entry.getValue(); if (value != null) { Method method = getSetterMethod(dest.getClass(), name, value.getClass()); Field field = getField(dest.getClass(), name); if (method != null) { if (!method.isAccessible()) method.setAccessible(true); Type ptype = method.getGenericParameterTypes()[0]; value = realize0(value, method.getParameterTypes()[0], ptype, history); try { method.invoke(dest, value); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Failed to set pojo " + dest.getClass().getSimpleName() + " property " + name + " value " + value + "(" + value.getClass() + "), cause: " + e.getMessage(), e); } } else if (field != null) { value = realize0(value, field.getType(), field.getGenericType(), history); try { field.set(dest, value); } catch (IllegalAccessException e) { throw new RuntimeException("Failed to set filed " + name + " of pojo " + dest.getClass().getName() + " : " + e.getMessage(), e); } } } } } if (dest instanceof Throwable) { Object message = map.get("message"); if (message instanceof String) { try { Field filed = Throwable.class.getDeclaredField("detailMessage"); if (!filed.isAccessible()) { filed.setAccessible(true); } filed.set(dest, message); } catch (Exception e) { } } } return dest; } } return pojo; } /** * Get parameterized type * * @param genericType generic type * @param index index of the target parameterized type * @return Return Person.class for List<Person>, return Person.class for Map<String, Person> when index=0 */ private static Type getGenericClassByIndex(Type genericType, int index) { Type clazz = null; // find parameterized type if (genericType instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) genericType; Type[] types = t.getActualTypeArguments(); clazz = types[index]; } return clazz; } private static Object newInstance(Class<?> cls) { try { return cls.newInstance(); } catch (Throwable t) { try { Constructor<?>[] constructors = cls.getDeclaredConstructors(); if (constructors != null && constructors.length == 0) { throw new RuntimeException("Illegal constructor: " + cls.getName()); } Constructor<?> constructor = constructors[0]; if (constructor.getParameterTypes().length > 0) { for (Constructor<?> c : constructors) { if (c.getParameterTypes().length < constructor.getParameterTypes().length) { constructor = c; if (constructor.getParameterTypes().length == 0) { break; } } } } constructor.setAccessible(true); return constructor.newInstance(new Object[constructor.getParameterTypes().length]); } catch (InstantiationException e) { throw new RuntimeException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } } } private static Method getSetterMethod(Class<?> cls, String property, Class<?> valueCls) { String name = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); Method method = NAME_METHODS_CACHE.get(cls.getName() + "." + name + "(" + valueCls.getName() + ")"); if (method == null) { try { method = cls.getMethod(name, valueCls); } catch (NoSuchMethodException e) { for (Method m : cls.getMethods()) { if (ReflectUtils.isBeanPropertyWriteMethod(m) && m.getName().equals(name)) { method = m; } } } if (method != null) { NAME_METHODS_CACHE.put(cls.getName() + "." + name + "(" + valueCls.getName() + ")", method); } } return method; } private static Field getField(Class<?> cls, String fieldName) { Field result = null; if (CLASS_FIELD_CACHE.containsKey(cls) && CLASS_FIELD_CACHE.get(cls).containsKey(fieldName)) { return CLASS_FIELD_CACHE.get(cls).get(fieldName); } try { result = cls.getDeclaredField(fieldName); result.setAccessible(true); } catch (NoSuchFieldException e) { for (Field field : cls.getFields()) { if (fieldName.equals(field.getName()) && ReflectUtils.isPublicInstanceField(field)) { result = field; break; } } } if (result != null) { ConcurrentMap<String, Field> fields = CLASS_FIELD_CACHE.get(cls); if (fields == null) { fields = new ConcurrentHashMap<String, Field>(); CLASS_FIELD_CACHE.putIfAbsent(cls, fields); } fields = CLASS_FIELD_CACHE.get(cls); fields.putIfAbsent(fieldName, result); } return result; } public static boolean isPojo(Class<?> cls) { return !ReflectUtils.isPrimitives(cls) && !Collection.class.isAssignableFrom(cls) && !Map.class.isAssignableFrom(cls); } }
/** * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gamingmesh.jobs; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import com.gamingmesh.jobs.config.ConfigManager; import com.gamingmesh.jobs.container.Job; import com.gamingmesh.jobs.container.JobProgression; import com.gamingmesh.jobs.container.JobsPlayer; import com.gamingmesh.jobs.container.Title; import com.gamingmesh.jobs.dao.JobsDAO; import com.gamingmesh.jobs.i18n.Language; import com.gamingmesh.jobs.util.ChatColor; public class PlayerManager { private Map<String, JobsPlayer> players = Collections.synchronizedMap(new HashMap<String, JobsPlayer>()); /** * Handles join of new player * @param playername */ public void playerJoin(Player player) { synchronized (players) { JobsPlayer jPlayer = players.get(player.getName().toLowerCase()); if (jPlayer == null) { jPlayer = JobsPlayer.loadFromDao(Jobs.getJobsDAO(), player); players.put(player.getName().toLowerCase(), jPlayer); } jPlayer.onConnect(); jPlayer.reloadHonorific(); Jobs.getPermissionHandler().recalculatePermissions(jPlayer); } } /** * Handles player quit * @param playername */ public void playerQuit(Player player) { synchronized (players) { if (ConfigManager.getJobsConfiguration().saveOnDisconnect()) { JobsPlayer jPlayer = players.remove(player.getName().toLowerCase()); if (jPlayer != null) { jPlayer.save(Jobs.getJobsDAO()); jPlayer.onDisconnect(); } } else { JobsPlayer jPlayer = players.get(player.getName().toLowerCase()); if (jPlayer != null) { jPlayer.onDisconnect(); } } } } /** * Save all the information of all of the players in the game */ public void saveAll() { JobsDAO dao = Jobs.getJobsDAO(); /* * Saving is a three step process to minimize synchronization locks when called asynchronously. * * 1) Safely copy list for saving. * 2) Perform save on all players on copied list. * 3) Garbage collect the real list to remove any offline players with saved data */ ArrayList<JobsPlayer> list = null; synchronized (players) { list = new ArrayList<JobsPlayer>(players.values()); } for (JobsPlayer jPlayer : list) { jPlayer.save(dao); } synchronized (players) { Iterator<JobsPlayer> iter = players.values().iterator(); while (iter.hasNext()) { JobsPlayer jPlayer = iter.next(); synchronized (jPlayer.saveLock) { if (!jPlayer.isOnline() && jPlayer.isSaved()) { iter.remove(); } } } } } /** * Get the player job info for specific player * @param player - the player who's job you're getting * @return the player job info of the player */ public JobsPlayer getJobsPlayer(Player player) { return players.get(player.getName().toLowerCase()); } /** * Get the player job info for specific player * @param player - the player who's job you're getting * @return the player job info of the player */ public JobsPlayer getJobsPlayerOffline(OfflinePlayer offlinePlayer) { JobsPlayer jPlayer = players.get(offlinePlayer.getName().toLowerCase()); if (jPlayer != null) return jPlayer; return JobsPlayer.loadFromDao(Jobs.getJobsDAO(), offlinePlayer); } /** * Causes player to join their job * @param jPlayer * @param job */ public void joinJob(JobsPlayer jPlayer, Job job) { synchronized (jPlayer.saveLock) { if (jPlayer.isInJob(job)) return; // let the user join the job if (!jPlayer.joinJob(job)) return; Jobs.getJobsDAO().joinJob(jPlayer, job); Jobs.takeSlot(job); } } /** * Causes player to leave their job * @param jPlayer * @param job */ public void leaveJob(JobsPlayer jPlayer, Job job) { synchronized (jPlayer.saveLock) { if (!jPlayer.isInJob(job)) return; // let the user leave the job if (!jPlayer.leaveJob(job)) return; Jobs.getJobsDAO().quitJob(jPlayer, job); Jobs.leaveSlot(job); } } /** * Causes player to leave all their jobs * @param jPlayer */ public void leaveAllJobs(JobsPlayer jPlayer) { synchronized (jPlayer.saveLock) { for (JobProgression job : jPlayer.getJobProgression()) { Jobs.getJobsDAO().quitJob(jPlayer, job.getJob()); Jobs.leaveSlot(job.getJob()); } jPlayer.leaveAllJobs(); } } /** * Transfers player job * @param jPlayer * @param oldjob - the old job * @param newjob - the new job */ public void transferJob(JobsPlayer jPlayer, Job oldjob, Job newjob) { synchronized (jPlayer.saveLock) { if (!jPlayer.transferJob(oldjob, newjob)) return; JobsDAO dao = Jobs.getJobsDAO(); dao.quitJob(jPlayer, oldjob); dao.joinJob(jPlayer, newjob); jPlayer.save(dao); } } /** * Promotes player in their job * @param jPlayer * @param job - the job * @param levels - number of levels to promote */ public void promoteJob(JobsPlayer jPlayer, Job job, int levels) { synchronized (jPlayer.saveLock) { jPlayer.promoteJob(job, levels); jPlayer.save(Jobs.getJobsDAO()); } } /** * Demote player in their job * @param jPlayer * @param job - the job * @param levels - number of levels to demote */ public void demoteJob(JobsPlayer jPlayer, Job job, int levels) { synchronized (jPlayer.saveLock) { jPlayer.demoteJob(job, levels); jPlayer.save(Jobs.getJobsDAO()); } } /** * Adds experience to the player * @param jPlayer * @param job - the job * @param experience - experience gained */ public void addExperience(JobsPlayer jPlayer, Job job, double experience) { synchronized (jPlayer.saveLock) { JobProgression prog = jPlayer.getJobProgression(job); if (prog == null) return; int oldLevel = prog.getLevel(); if (prog.addExperience(experience)) performLevelUp(jPlayer, job, oldLevel); jPlayer.save(Jobs.getJobsDAO()); } } /** * Removes experience to the player * @param jPlayer * @param job - the job * @param experience - experience gained */ public void removeExperience(JobsPlayer jPlayer, Job job, double experience) { synchronized (jPlayer.saveLock) { JobProgression prog = jPlayer.getJobProgression(job); if (prog == null) return; prog.addExperience(-experience); jPlayer.save(Jobs.getJobsDAO()); } } /** * Broadcasts level up about a player * @param jPlayer * @param job * @param oldLevel */ public void performLevelUp(JobsPlayer jPlayer, Job job, int oldLevel) { Player player = Bukkit.getServer().getPlayer(jPlayer.getPlayerUUID()); JobProgression prog = jPlayer.getJobProgression(job); if (prog == null) return; String message; if (ConfigManager.getJobsConfiguration().isBroadcastingLevelups()) { message = Language.getMessage("message.levelup.broadcast"); } else { message = Language.getMessage("message.levelup.nobroadcast"); } message = message.replace("%jobname%", job.getChatColor() + job.getName() + ChatColor.WHITE); Title oldTitle = ConfigManager.getJobsConfiguration().getTitleForLevel(oldLevel); if (oldTitle != null) { message = message.replace("%titlename%", oldTitle.getChatColor() + oldTitle.getName() + ChatColor.WHITE); } if (player != null) { message = message.replace("%playername%", player.getDisplayName()); } else { message = message.replace("%playername%", jPlayer.getUserName()); } message = message.replace("%joblevel%", ""+prog.getLevel()); for (String line: message.split("\n")) { if (ConfigManager.getJobsConfiguration().isBroadcastingLevelups()) { Bukkit.getServer().broadcastMessage(line); } else if (player != null) { player.sendMessage(line); } } Title newTitle = ConfigManager.getJobsConfiguration().getTitleForLevel(prog.getLevel()); if (newTitle != null && !newTitle.equals(oldTitle)) { // user would skill up if (ConfigManager.getJobsConfiguration().isBroadcastingSkillups()) { message = Language.getMessage("message.skillup.broadcast"); } else { message = Language.getMessage("message.skillup.nobroadcast"); } if (player != null) { message = message.replace("%playername%", player.getDisplayName()); } else { message = message.replace("%playername%", jPlayer.getUserName()); } message = message.replace("%titlename%", newTitle.getChatColor() + newTitle.getName() + ChatColor.WHITE); message = message.replace("%jobname%", job.getChatColor() + job.getName() + ChatColor.WHITE); for (String line: message.split("\n")) { if (ConfigManager.getJobsConfiguration().isBroadcastingLevelups()) { Bukkit.getServer().broadcastMessage(line); } else if (player != null) { player.sendMessage(line); } } } jPlayer.reloadHonorific(); Jobs.getPermissionHandler().recalculatePermissions(jPlayer); } /** * Perform reload */ public void reload() { synchronized (players) { for (JobsPlayer jPlayer : players.values()) { for (JobProgression progression : jPlayer.getJobProgression()) { String jobName = progression.getJob().getName(); Job job = Jobs.getJob(jobName); if (job != null) { progression.setJob(job); } } if (jPlayer.isOnline()) { jPlayer.reloadHonorific(); Jobs.getPermissionHandler().recalculatePermissions(jPlayer); } } } } }
package com.lofland.housebot; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.PushbackInputStream; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; /** * A simple, tiny, nicely embeddable HTTP server in Java * <p/> * <p/> * NanoHTTPD * <p></p>Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias</p> * <p/> * <p/> * <b>Features + limitations: </b> * <ul> * <p/> * <li>Only one Java file</li> * <li>Java 5 compatible</li> * <li>Released as open source, Modified BSD licence</li> * <li>No fixed config files, logging, authorization etc. (Implement yourself if you need them.)</li> * <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)</li> * <li>Supports both dynamic content and file serving</li> * <li>Supports file upload (since version 1.2, 2010)</li> * <li>Supports partial content (streaming)</li> * <li>Supports ETags</li> * <li>Never caches anything</li> * <li>Doesn't limit bandwidth, request time or simultaneous connections</li> * <li>Default code serves files and shows all HTTP parameters and headers</li> * <li>File server supports directory listing, index.html and index.htm</li> * <li>File server supports partial content (streaming)</li> * <li>File server supports ETags</li> * <li>File server does the 301 redirection trick for directories without '/'</li> * <li>File server supports simple skipping for files (continue download)</li> * <li>File server serves also very long files without memory overhead</li> * <li>Contains a built-in list of most common mime types</li> * <li>All header names are converted lowercase so they don't vary between browsers/clients</li> * <p/> * </ul> * <p/> * <p/> * <b>How to use: </b> * <ul> * <p/> * <li>Subclass and implement serve() and embed to your own program</li> * <p/> * </ul> * <p/> * See the separate "LICENSE.md" file for the distribution license (Modified BSD licence) */ public abstract class NanoHTTPD { /** * Maximum time to wait on Socket.getInputStream().read() (in milliseconds) * This is required as the Keep-Alive HTTP connections would otherwise * block the socket reading thread forever (or as long the browser is open). */ public static final int SOCKET_READ_TIMEOUT = 5000; /** * Common mime type for dynamic content: plain text */ public static final String MIME_PLAINTEXT = "text/plain"; /** * Common mime type for dynamic content: html */ public static final String MIME_HTML = "text/html"; /** * Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing. */ private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING"; private final String hostname; private final int myPort; private ServerSocket myServerSocket; private Set<Socket> openConnections = new HashSet<Socket>(); private Thread myThread; /** * Pluggable strategy for asynchronously executing requests. */ private AsyncRunner asyncRunner; /** * Pluggable strategy for creating and cleaning up temporary files. */ private TempFileManagerFactory tempFileManagerFactory; /** * Constructs an HTTP server on given port. */ public NanoHTTPD(int port) { this(null, port); } /** * Constructs an HTTP server on given hostname and port. */ public NanoHTTPD(String hostname, int port) { this.hostname = hostname; this.myPort = port; setTempFileManagerFactory(new DefaultTempFileManagerFactory()); setAsyncRunner(new DefaultAsyncRunner()); } private static final void safeClose(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } private static final void safeClose(Socket closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } private static final void safeClose(ServerSocket closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { } } } /** * Start the server. * * @throws IOException if the socket is in use. */ public void start() throws IOException { myServerSocket = new ServerSocket(); myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); myThread = new Thread(new Runnable() { @Override public void run() { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); final InputStream inputStream = finalAccept.getInputStream(); asyncRunner.exec(new Runnable() { @Override public void run() { OutputStream outputStream = null; try { outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress()); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { e.printStackTrace(); } } finally { safeClose(outputStream); safeClose(inputStream); safeClose(finalAccept); unRegisterConnection(finalAccept); } } }); } catch (IOException e) { } } while (!myServerSocket.isClosed()); } }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); myThread.start(); } /** * Stop the server. */ public void stop() { try { safeClose(myServerSocket); closeAllConnections(); myThread.join(); } catch (Exception e) { e.printStackTrace(); } } /** * Registers that a new connection has been set up. * * @param socket * the {@link Socket} for the connection. */ public synchronized void registerConnection(Socket socket) { openConnections.add(socket); } /** * Registers that a connection has been closed * * @param socket * the {@link Socket} for the connection. */ public synchronized void unRegisterConnection(Socket socket) { openConnections.remove(socket); } /** * Forcibly closes all connections that are open. */ public synchronized void closeAllConnections() { for (Socket socket : openConnections) { safeClose(socket); } } public final int getListeningPort() { return myServerSocket == null ? -1 : myServerSocket.getLocalPort(); } public final boolean wasStarted() { return myServerSocket != null && myThread != null; } public final boolean isAlive() { return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive(); } /** * Override this to customize the server. * <p/> * <p/> * (By default, this delegates to serveFile() and allows directory listing.) * * @param uri Percent-decoded URI without parameters, for example "/index.cgi" * @param method "GET", "POST" etc. * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data. * @param headers Header entries, percent decoded * @return HTTP response, see class Response for details */ @Deprecated public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found"); } /** * Override this to customize the server. * <p/> * <p/> * (By default, this delegates to serveFile() and allows directory listing.) * * @param session The HTTP session * @return HTTP response, see class Response for details */ public Response serve(IHTTPSession session) { Map<String, String> files = new HashMap<String, String>(); Method method = session.getMethod(); if (Method.PUT.equals(method) || Method.POST.equals(method)) { try { session.parseBody(files); } catch (IOException ioe) { return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); } catch (ResponseException re) { return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); } } Map<String, String> parms = session.getParms(); parms.put(QUERY_STRING_PARAMETER, session.getQueryParameterString()); return serve(session.getUri(), method, session.getHeaders(), parms, files); } /** * Decode percent encoded <code>String</code> values. * * @param str the percent encoded <code>String</code> * @return expanded form of the input, for example "foo%20bar" becomes "foo bar" */ protected String decodePercent(String str) { String decoded = null; try { decoded = URLDecoder.decode(str, "UTF8"); } catch (UnsupportedEncodingException ignored) { } return decoded; } /** * Decode parameters from a URL, handing the case where a single parameter name might have been * supplied several times, by return lists of values. In general these lists will contain a single * element. * * @param parms original <b>NanoHttpd</b> parameters values, as passed to the <code>serve()</code> method. * @return a map of <code>String</code> (parameter name) to <code>List&lt;String&gt;</code> (a list of the values supplied). */ protected Map<String, List<String>> decodeParameters(Map<String, String> parms) { return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER)); } /** * Decode parameters from a URL, handing the case where a single parameter name might have been * supplied several times, by return lists of values. In general these lists will contain a single * element. * * @param queryString a query string pulled from the URL. * @return a map of <code>String</code> (parameter name) to <code>List&lt;String&gt;</code> (a list of the values supplied). */ protected Map<String, List<String>> decodeParameters(String queryString) { Map<String, List<String>> parms = new HashMap<String, List<String>>(); if (queryString != null) { StringTokenizer st = new StringTokenizer(queryString, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); if (!parms.containsKey(propertyName)) { parms.put(propertyName, new ArrayList<String>()); } String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null; if (propertyValue != null) { parms.get(propertyName).add(propertyValue); } } } return parms; } // ------------------------------------------------------------------------------- // // // Threading Strategy. // // ------------------------------------------------------------------------------- // /** * Pluggable strategy for asynchronously executing requests. * * @param asyncRunner new strategy for handling threads. */ public void setAsyncRunner(AsyncRunner asyncRunner) { this.asyncRunner = asyncRunner; } // ------------------------------------------------------------------------------- // // // Temp file handling strategy. // // ------------------------------------------------------------------------------- // /** * Pluggable strategy for creating and cleaning up temporary files. * * @param tempFileManagerFactory new strategy for handling temp files. */ public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) { this.tempFileManagerFactory = tempFileManagerFactory; } /** * HTTP Request methods, with the ability to decode a <code>String</code> back to its enum value. */ public enum Method { GET, PUT, POST, DELETE, HEAD, OPTIONS; static Method lookup(String method) { for (Method m : Method.values()) { if (m.toString().equalsIgnoreCase(method)) { return m; } } return null; } } /** * Pluggable strategy for asynchronously executing requests. */ public interface AsyncRunner { void exec(Runnable code); } /** * Factory to create temp file managers. */ public interface TempFileManagerFactory { TempFileManager create(); } // ------------------------------------------------------------------------------- // /** * Temp file manager. * <p/> * <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup * temporary files created as a result of handling the request.</p> */ public interface TempFileManager { TempFile createTempFile() throws Exception; void clear(); } /** * A temp file. * <p/> * <p>Temp files are responsible for managing the actual temporary storage and cleaning * themselves up when no longer needed.</p> */ public interface TempFile { OutputStream open() throws Exception; void delete() throws Exception; String getName(); } /** * Default threading strategy for NanoHttpd. * <p/> * <p>By default, the server spawns a new Thread for every incoming request. These are set * to <i>daemon</i> status, and named according to the request number. The name is * useful when profiling the application.</p> */ public static class DefaultAsyncRunner implements AsyncRunner { private long requestCount; @Override public void exec(Runnable code) { ++requestCount; Thread t = new Thread(code); t.setDaemon(true); t.setName("NanoHttpd Request Processor (#" + requestCount + ")"); t.start(); } } /** * Default strategy for creating and cleaning up temporary files. * <p/> * <p></p>This class stores its files in the standard location (that is, * wherever <code>java.io.tmpdir</code> points to). Files are added * to an internal list, and deleted when no longer needed (that is, * when <code>clear()</code> is invoked at the end of processing a * request).</p> */ public static class DefaultTempFileManager implements TempFileManager { private final String tmpdir; private final List<TempFile> tempFiles; public DefaultTempFileManager() { tmpdir = System.getProperty("java.io.tmpdir"); tempFiles = new ArrayList<TempFile>(); } @Override public TempFile createTempFile() throws Exception { DefaultTempFile tempFile = new DefaultTempFile(tmpdir); tempFiles.add(tempFile); return tempFile; } @Override public void clear() { for (TempFile file : tempFiles) { try { file.delete(); } catch (Exception ignored) { } } tempFiles.clear(); } } /** * Default strategy for creating and cleaning up temporary files. * <p/> * <p></p></[>By default, files are created by <code>File.createTempFile()</code> in * the directory specified.</p> */ public static class DefaultTempFile implements TempFile { private File file; private OutputStream fstream; public DefaultTempFile(String tempdir) throws IOException { file = File.createTempFile("NanoHTTPD-", "", new File(tempdir)); fstream = new FileOutputStream(file); } @Override public OutputStream open() throws Exception { return fstream; } @Override public void delete() throws Exception { safeClose(fstream); file.delete(); } @Override public String getName() { return file.getAbsolutePath(); } } /** * HTTP response. Return one of these from serve(). */ public static class Response { /** * HTTP status code after processing, e.g. "200 OK", HTTP_OK */ private IStatus status; /** * MIME type of content, e.g. "text/html" */ private String mimeType; /** * Data of the response, may be null. */ private InputStream data; /** * Headers for the HTTP response. Use addHeader() to add lines. */ private Map<String, String> header = new HashMap<String, String>(); /** * The request method that spawned this response. */ private Method requestMethod; /** * Use chunkedTransfer */ private boolean chunkedTransfer; /** * Default constructor: response = HTTP_OK, mime = MIME_HTML and your supplied message */ public Response(String msg) { this(Status.OK, MIME_HTML, msg); } /** * Basic constructor. */ public Response(IStatus status, String mimeType, InputStream data) { this.status = status; this.mimeType = mimeType; this.data = data; } /** * Convenience method that makes an InputStream out of given text. */ public Response(IStatus status, String mimeType, String txt) { this.status = status; this.mimeType = mimeType; try { this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null; } catch (java.io.UnsupportedEncodingException uee) { uee.printStackTrace(); } } /** * Adds given line to the header. */ public void addHeader(String name, String value) { header.put(name, value); } /** * Sends given response to the socket. */ protected void send(OutputStream outputStream) { String mime = mimeType; SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); try { if (status == null) { throw new Error("sendResponse(): Status can't be null."); } PrintWriter pw = new PrintWriter(outputStream); pw.print("HTTP/1.1 " + status.getDescription() + " \r\n"); if (mime != null) { pw.print("Content-Type: " + mime + "\r\n"); } if (header == null || header.get("Date") == null) { pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n"); } if (header != null) { for (String key : header.keySet()) { String value = header.get(key); pw.print(key + ": " + value + "\r\n"); } } sendConnectionHeaderIfNotAlreadyPresent(pw, header); if (requestMethod != Method.HEAD && chunkedTransfer) { sendAsChunked(outputStream, pw); } else { sendAsFixedLength(outputStream, pw); } outputStream.flush(); safeClose(data); } catch (IOException ioe) { // Couldn't write? No can do. } } protected void sendConnectionHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header) { boolean connectionAlreadySent = false; for (String headerName : header.keySet()) { connectionAlreadySent |= headerName.equalsIgnoreCase("connection"); } if (!connectionAlreadySent) { pw.print("Connection: keep-alive\r\n"); } } private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException { pw.print("Transfer-Encoding: chunked\r\n"); pw.print("\r\n"); pw.flush(); int BUFFER_SIZE = 16 * 1024; byte[] CRLF = "\r\n".getBytes(); byte[] buff = new byte[BUFFER_SIZE]; int read; while ((read = data.read(buff)) > 0) { outputStream.write(String.format("%x\r\n", read).getBytes()); outputStream.write(buff, 0, read); outputStream.write(CRLF); } outputStream.write(String.format("0\r\n\r\n").getBytes()); } private void sendAsFixedLength(OutputStream outputStream, PrintWriter pw) throws IOException { int pending = data != null ? data.available() : 0; // This is to support partial sends, see serveFile() pw.print("Content-Length: "+pending+"\r\n"); pw.print("\r\n"); pw.flush(); if (requestMethod != Method.HEAD && data != null) { int BUFFER_SIZE = 16 * 1024; byte[] buff = new byte[BUFFER_SIZE]; while (pending > 0) { int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending)); if (read <= 0) { break; } outputStream.write(buff, 0, read); pending -= read; } } } public IStatus getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public InputStream getData() { return data; } public void setData(InputStream data) { this.data = data; } public Method getRequestMethod() { return requestMethod; } public void setRequestMethod(Method requestMethod) { this.requestMethod = requestMethod; } public void setChunkedTransfer(boolean chunkedTransfer) { this.chunkedTransfer = chunkedTransfer; } public interface IStatus { int getRequestStatus(); String getDescription(); } /** * Some HTTP response status codes */ public enum Status implements IStatus { SWITCH_PROTOCOL(101, "Switching Protocols"), OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301, "Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error"); private final int requestStatus; private final String description; Status(int requestStatus, String description) { this.requestStatus = requestStatus; this.description = description; } @Override public int getRequestStatus() { return this.requestStatus; } @Override public String getDescription() { return "" + this.requestStatus + " " + description; } } } public static final class ResponseException extends Exception { private final Response.Status status; public ResponseException(Response.Status status, String message) { super(message); this.status = status; } public ResponseException(Response.Status status, String message, Exception e) { super(message, e); this.status = status; } public Response.Status getStatus() { return status; } } /** * Default strategy for creating and cleaning up temporary files. */ private class DefaultTempFileManagerFactory implements TempFileManagerFactory { @Override public TempFileManager create() { return new DefaultTempFileManager(); } } /** * Handles one session, i.e. parses the HTTP request and returns the response. */ public interface IHTTPSession { void execute() throws IOException; Map<String, String> getParms(); Map<String, String> getHeaders(); /** * @return the path part of the URL. */ String getUri(); String getQueryParameterString(); Method getMethod(); InputStream getInputStream(); CookieHandler getCookies(); /** * Adds the files in the request body to the files map. * @arg files - map to modify */ void parseBody(Map<String, String> files) throws IOException, ResponseException; } protected class HTTPSession implements IHTTPSession { public static final int BUFSIZE = 8192; private final TempFileManager tempFileManager; private final OutputStream outputStream; private PushbackInputStream inputStream; private int splitbyte; private int rlen; private String uri; private Method method; private Map<String, String> parms; private Map<String, String> headers; private CookieHandler cookies; private String queryParameterString; public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) { this.tempFileManager = tempFileManager; this.inputStream = new PushbackInputStream(inputStream, BUFSIZE); this.outputStream = outputStream; } public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) { this.tempFileManager = tempFileManager; this.inputStream = new PushbackInputStream(inputStream, BUFSIZE); this.outputStream = outputStream; String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString(); headers = new HashMap<String, String>(); headers.put("remote-addr", remoteIp); headers.put("http-client-ip", remoteIp); } @Override public void execute() throws IOException { try { // Read the first 8192 bytes. // The full header should fit in here. // Apache's default header limit is 8KB. // Do NOT assume that a single read will get the entire header at once! byte[] buf = new byte[BUFSIZE]; splitbyte = 0; rlen = 0; { int read = -1; try { read = inputStream.read(buf, 0, BUFSIZE); } catch (Exception e) { safeClose(inputStream); safeClose(outputStream); throw new SocketException("NanoHttpd Shutdown"); } if (read == -1) { // socket was been closed safeClose(inputStream); safeClose(outputStream); throw new SocketException("NanoHttpd Shutdown"); } while (read > 0) { rlen += read; splitbyte = findHeaderEnd(buf, rlen); if (splitbyte > 0) break; read = inputStream.read(buf, rlen, BUFSIZE - rlen); } } if (splitbyte < rlen) { inputStream.unread(buf, splitbyte, rlen - splitbyte); } parms = new HashMap<String, String>(); if(null == headers) { headers = new HashMap<String, String>(); } // Create a BufferedReader for parsing the header. BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen))); // Decode the header into parms and header java properties Map<String, String> pre = new HashMap<String, String>(); decodeHeader(hin, pre, parms, headers); method = Method.lookup(pre.get("method")); if (method == null) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error."); } uri = pre.get("uri"); cookies = new CookieHandler(headers); // Ok, now do the serve() Response r = serve(this); if (r == null) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response."); } else { cookies.unloadQueue(r); r.setRequestMethod(method); r.send(outputStream); } } catch (SocketException e) { // throw it out to close socket object (finalAccept) throw e; } catch (SocketTimeoutException ste) { throw ste; } catch (IOException ioe) { Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); r.send(outputStream); safeClose(outputStream); } catch (ResponseException re) { Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); r.send(outputStream); safeClose(outputStream); } finally { tempFileManager.clear(); } } @Override public void parseBody(Map<String, String> files) throws IOException, ResponseException { RandomAccessFile randomAccessFile = null; BufferedReader in = null; try { randomAccessFile = getTmpBucket(); long size; if (headers.containsKey("content-length")) { size = Integer.parseInt(headers.get("content-length")); } else if (splitbyte < rlen) { size = rlen - splitbyte; } else { size = 0; } // Now read all the body and write it to f byte[] buf = new byte[512]; while (rlen >= 0 && size > 0) { rlen = inputStream.read(buf, 0, (int)Math.min(size, 512)); size -= rlen; if (rlen > 0) { randomAccessFile.write(buf, 0, rlen); } } // Get the raw body as a byte [] ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length()); randomAccessFile.seek(0); // Create a BufferedReader for easily reading it as string. InputStream bin = new FileInputStream(randomAccessFile.getFD()); in = new BufferedReader(new InputStreamReader(bin)); // If the method is POST, there may be parameters // in data section, too, read it: if (Method.POST.equals(method)) { String contentType = ""; String contentTypeHeader = headers.get("content-type"); StringTokenizer st = null; if (contentTypeHeader != null) { st = new StringTokenizer(contentTypeHeader, ",; "); if (st.hasMoreTokens()) { contentType = st.nextToken(); } } if ("multipart/form-data".equalsIgnoreCase(contentType)) { // Handle multipart/form-data if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html"); } String boundaryStartString = "boundary="; int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length(); String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length()); if (boundary.startsWith("\"") && boundary.endsWith("\"")) { boundary = boundary.substring(1, boundary.length() - 1); } decodeMultipartData(boundary, fbuf, in, parms, files); } else { String postLine = ""; StringBuilder postLineBuffer = new StringBuilder(); char pbuf[] = new char[512]; int read = in.read(pbuf); while (read >= 0 && !postLine.endsWith("\r\n")) { postLine = String.valueOf(pbuf, 0, read); postLineBuffer.append(postLine); read = in.read(pbuf); } postLine = postLineBuffer.toString().trim(); // Handle application/x-www-form-urlencoded if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) { decodeParms(postLine, parms); } else if (postLine.length() != 0) { // Special case for raw POST data => create a special files entry "postData" with raw content data files.put("postData", postLine); } } } else if (Method.PUT.equals(method)) { files.put("content", saveTmpFile(fbuf, 0, fbuf.limit())); } } finally { safeClose(randomAccessFile); safeClose(in); } } /** * Decodes the sent headers and loads the data into Key/value pairs */ private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) throws ResponseException { try { // Read the request line String inLine = in.readLine(); if (inLine == null) { return; } StringTokenizer st = new StringTokenizer(inLine); if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html"); } pre.put("method", st.nextToken()); if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html"); } String uri = st.nextToken(); // Decode parameters from the URI int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } else { uri = decodePercent(uri); } // If there's another token, it's protocol version, // followed by HTTP headers. Ignore version but parse headers. // NOTE: this now forces header names lowercase since they are // case insensitive and vary by client. if (st.hasMoreTokens()) { String line = in.readLine(); while (line != null && line.trim().length() > 0) { int p = line.indexOf(':'); if (p >= 0) headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim()); line = in.readLine(); } } pre.put("uri", uri); } catch (IOException ioe) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); } } /** * Decodes the Multipart Body data and put it into Key/Value pairs. */ private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms, Map<String, String> files) throws ResponseException { try { int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes()); int boundarycount = 1; String mpline = in.readLine(); while (mpline != null) { if (!mpline.contains(boundary)) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html"); } boundarycount++; Map<String, String> item = new HashMap<String, String>(); mpline = in.readLine(); while (mpline != null && mpline.trim().length() > 0) { int p = mpline.indexOf(':'); if (p != -1) { item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim()); } mpline = in.readLine(); } if (mpline != null) { String contentDisposition = item.get("content-disposition"); if (contentDisposition == null) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html"); } StringTokenizer st = new StringTokenizer(contentDisposition, ";"); Map<String, String> disposition = new HashMap<String, String>(); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); int p = token.indexOf('='); if (p != -1) { disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim()); } } String pname = disposition.get("name"); pname = pname.substring(1, pname.length() - 1); String value = ""; if (item.get("content-type") == null) { while (mpline != null && !mpline.contains(boundary)) { mpline = in.readLine(); if (mpline != null) { int d = mpline.indexOf(boundary); if (d == -1) { value += mpline; } else { value += mpline.substring(0, d - 2); } } } } else { if (boundarycount > bpositions.length) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request"); } int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]); String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4); files.put(pname, path); value = disposition.get("filename"); value = value.substring(1, value.length() - 1); do { mpline = in.readLine(); } while (mpline != null && !mpline.contains(boundary)); } parms.put(pname, value); } } } catch (IOException ioe) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); } } /** * Find byte index separating header from body. It must be the last byte of the first two sequential new lines. */ private int findHeaderEnd(final byte[] buf, int rlen) { int splitbyte = 0; while (splitbyte + 3 < rlen) { if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') { return splitbyte + 4; } splitbyte++; } return 0; } /** * Find the byte positions where multipart boundaries start. */ private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) { int matchcount = 0; int matchbyte = -1; List<Integer> matchbytes = new ArrayList<Integer>(); for (int i = 0; i < b.limit(); i++) { if (b.get(i) == boundary[matchcount]) { if (matchcount == 0) matchbyte = i; matchcount++; if (matchcount == boundary.length) { matchbytes.add(matchbyte); matchcount = 0; matchbyte = -1; } } else { i -= matchcount; matchcount = 0; matchbyte = -1; } } int[] ret = new int[matchbytes.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = matchbytes.get(i); } return ret; } /** * Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned. */ private String saveTmpFile(ByteBuffer b, int offset, int len) { String path = ""; if (len > 0) { FileOutputStream fileOutputStream = null; try { TempFile tempFile = tempFileManager.createTempFile(); ByteBuffer src = b.duplicate(); fileOutputStream = new FileOutputStream(tempFile.getName()); FileChannel dest = fileOutputStream.getChannel(); src.position(offset).limit(offset + len); dest.write(src.slice()); path = tempFile.getName(); } catch (Exception e) { // Catch exception if any throw new Error(e); // we won't recover, so throw an error } finally { safeClose(fileOutputStream); } } return path; } private RandomAccessFile getTmpBucket() { try { TempFile tempFile = tempFileManager.createTempFile(); return new RandomAccessFile(tempFile.getName(), "rw"); } catch (Exception e) { throw new Error(e); // we won't recover, so throw an error } } /** * It returns the offset separating multipart file headers from the file's data. */ private int stripMultipartHeaders(ByteBuffer b, int offset) { int i; for (i = offset; i < b.limit(); i++) { if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') { break; } } return i + 1; } /** * Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and * adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map. */ private void decodeParms(String parms, Map<String, String> p) { if (parms == null) { queryParameterString = ""; return; } queryParameterString = parms; StringTokenizer st = new StringTokenizer(parms, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); if (sep >= 0) { p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1))); } else { p.put(decodePercent(e).trim(), ""); } } } @Override public final Map<String, String> getParms() { return parms; } public String getQueryParameterString() { return queryParameterString; } @Override public final Map<String, String> getHeaders() { return headers; } @Override public final String getUri() { return uri; } @Override public final Method getMethod() { return method; } @Override public final InputStream getInputStream() { return inputStream; } @Override public CookieHandler getCookies() { return cookies; } } public static class Cookie { private String n, v, e; public Cookie(String name, String value, String expires) { n = name; v = value; e = expires; } public Cookie(String name, String value) { this(name, value, 30); } public Cookie(String name, String value, int numDays) { n = name; v = value; e = getHTTPTime(numDays); } public String getHTTPHeader() { String fmt = "%s=%s; expires=%s"; return String.format(fmt, n, v, e); } public static String getHTTPTime(int days) { Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); calendar.add(Calendar.DAY_OF_MONTH, days); return dateFormat.format(calendar.getTime()); } } /** * Provides rudimentary support for cookies. * Doesn't support 'path', 'secure' nor 'httpOnly'. * Feel free to improve it and/or add unsupported features. * * @author LordFokas */ public class CookieHandler implements Iterable<String> { private HashMap<String, String> cookies = new HashMap<String, String>(); private ArrayList<Cookie> queue = new ArrayList<Cookie>(); public CookieHandler(Map<String, String> httpHeaders) { String raw = httpHeaders.get("cookie"); if (raw != null) { String[] tokens = raw.split(";"); for (String token : tokens) { String[] data = token.trim().split("="); if (data.length == 2) { cookies.put(data[0], data[1]); } } } } @Override public Iterator<String> iterator() { return cookies.keySet().iterator(); } /** * Read a cookie from the HTTP Headers. * * @param name The cookie's name. * @return The cookie's value if it exists, null otherwise. */ public String read(String name) { return cookies.get(name); } /** * Sets a cookie. * * @param name The cookie's name. * @param value The cookie's value. * @param expires How many days until the cookie expires. */ public void set(String name, String value, int expires) { queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires))); } public void set(Cookie cookie) { queue.add(cookie); } /** * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side. * * @param name The cookie name. */ public void delete(String name) { set(name, "-delete-", -30); } /** * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers. * * @param response The Response object to which headers the queued cookies will be added. */ public void unloadQueue(Response response) { for (Cookie cookie : queue) { response.addHeader("Set-Cookie", cookie.getHTTPHeader()); } } } }
package org.asciidoctor; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * * Directory walker that finds all files that match the given glob expression. * * Code is based on a class of wildcard project * (https://code.google.com/p/wildcard/). * * @author lordofthejars * */ public class GlobDirectoryWalker implements DirectoryWalker { private final File rootDirectory; private final File canonicalRootDir; private final List<File> matches = new ArrayList<File>(); private final String globExpression; public GlobDirectoryWalker(String rootDir, String globExpression) { rootDirectory = new File(rootDir); checkInput(rootDirectory); this.canonicalRootDir = getCanonicalPath(rootDirectory); this.globExpression = globExpression; } @Override public List<File> scan() { Pattern pattern = new Pattern(globExpression); scanDir(this.canonicalRootDir, Arrays.asList(pattern)); return this.matches; } private void checkInput(File rootDir) { if (!rootDir.exists()) { throw new IllegalArgumentException("Directory does not exist: " + rootDir); } if (!rootDir.isDirectory()) { throw new IllegalArgumentException("File must be a directory: " + rootDir); } } private File getCanonicalPath(File rootDir) { try { rootDir = rootDir.getCanonicalFile(); } catch (IOException ex) { throw new IllegalArgumentException( "Error determining canonical path: " + rootDir, ex); } return rootDir; } private void scanDir(File dir, List<Pattern> includes) { if (!dir.canRead()) return; if (isGlobalExpression(includes)) { findFilesThroughMatchingDirectories(dir, includes); } else { findFileInSpecificLocation(dir, includes); } } private void findFileInSpecificLocation(File dir, List<Pattern> includes) { List<Pattern> matchingIncludes = new ArrayList<Pattern>(1); for (Pattern include : includes) { if (matchingIncludes.isEmpty()) { matchingIncludes.add(include); } else { matchingIncludes.set(0, include); } process(dir, include.value, matchingIncludes); } } private void findFilesThroughMatchingDirectories(File dir, List<Pattern> includes) { for (String fileName : dir.list()) { List<Pattern> matchingIncludes = new ArrayList<Pattern>( includes.size()); for (Pattern include : includes) { if (include.matches(fileName)) { matchingIncludes.add(include); } } if (matchingIncludes.isEmpty()) { continue; } process(dir, fileName, matchingIncludes); } } private void process(File dir, String fileName, List<Pattern> matchingIncludes) { // Increment patterns that need to move to the next token. boolean isFinalMatch = false; List<Pattern> incrementedPatterns = new ArrayList<Pattern>(); for (Iterator<Pattern> iter = matchingIncludes.iterator(); iter .hasNext();) { Pattern include = iter.next(); if (include.incr(fileName)) { incrementedPatterns.add(include); if (include.isExhausted()) { iter.remove(); } } if (include.wasFinalMatch()) { isFinalMatch = true; } } File file = new File(dir, fileName); if (isFinalMatch) { int length = canonicalRootDir.getPath().length(); if (!canonicalRootDir.getPath().endsWith(File.separator)) { length++; // Lose starting slash. } matches.add(new File(this.rootDirectory, file.getPath().substring(length))); } if (!matchingIncludes.isEmpty() && file.isDirectory()) { scanDir(file, matchingIncludes); } // Decrement patterns. for (Pattern include : incrementedPatterns) { include.decr(); } } private boolean isGlobalExpression(List<Pattern> includes) { boolean scanAll = false; for (Pattern include : includes) { if (include.value.indexOf('*') != -1 || include.value.indexOf('?') != -1) { scanAll = true; break; } } return scanAll; } static class Pattern { String value; final String[] values; private int index; Pattern(String pattern) { pattern = pattern.replace('\\', '/'); pattern = pattern.replaceAll("\\*\\*[^/]", "**/*"); pattern = pattern.replaceAll("[^/]\\*\\*", "*/**"); values = pattern.split("/"); value = values[0]; } boolean matches(String fileName) { if (value.equals("**")) return true; // Shortcut if no wildcards. if (value.indexOf('*') == -1 && value.indexOf('?') == -1) { return fileName.equals(value); } int i = 0, j = 0; while (i < fileName.length() && j < value.length() && value.charAt(j) != '*') { if (value.charAt(j) != fileName.charAt(i) && value.charAt(j) != '?') { return false; } i++; j++; } // If reached end of pattern without finding a * wildcard, the match // has to fail if not same length. if (j == value.length()) { return fileName.length() == value.length(); } int cp = 0; int mp = 0; while (i < fileName.length()) { if (j < value.length() && value.charAt(j) == '*') { if (j++ >= value.length()) return true; mp = j; cp = i + 1; } else if (j < value.length() && (value.charAt(j) == fileName.charAt(i) || value .charAt(j) == '?')) { j++; i++; } else { j = mp; i = cp++; } } // Handle trailing asterisks. while (j < value.length() && value.charAt(j) == '*') { j++; } return j >= value.length(); } String nextValue() { if (index + 1 == values.length) { return null; } return values[index + 1]; } boolean incr(String fileName) { if (value.equals("**")) { if (index == values.length - 1) { return false; } incr(); if (matches(fileName)) { incr(); } else { decr(); return false; } } else { incr(); } return true; } void incr() { index++; if (index >= values.length) { value = null; } else { value = values[index]; } } void decr() { index--; if (index > 0 && values[index - 1].equals("**")) { index--; } value = values[index]; } void reset() { index = 0; value = values[0]; } boolean isExhausted() { return index >= values.length; } boolean isLast() { return index >= values.length - 1; } boolean wasFinalMatch() { return isExhausted() || (isLast() && value.equals("**")); } } }
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.model; import lombok.ToString; import org.hibernate.validator.constraints.Email; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.validation.constraints.Size; /** * The Class User maps the user that triggered the builds, and are linked to the BuildRecord * * @author avibelli */ @Entity @Table(name = "UserTable", uniqueConstraints = { @UniqueConstraint(name = "uk_user_email", columnNames = { "email" }), @UniqueConstraint(name = "uk_user_username", columnNames = { "username" }) }) public class User implements GenericEntity<Integer> { private static final long serialVersionUID = 8437525005838384722L; public static final String DEFAULT_SORTING_FIELD = "username"; public static final String SEQUENCE_NAME = "user_id_seq"; @Id @SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME, allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE_NAME) private Integer id; @Column(unique = true) @NotNull @Email @Size(max=255) private String email; @Size(max=50) private String firstName; @Size(max=50) private String lastName; /** * OAUTH token, used to pass around. Property is set once user is authenticated, * note that having a token doesn't necessary mean user is logged-in a token needs to be validated. */ @Transient private String loginToken; @Column(unique = true) @NotNull @Size(max=50) private String username; @OneToMany(mappedBy = "user") private List<BuildRecord> buildRecords; /** * Instantiates a new user. */ public User() { } /** * Gets the id. * * @return the id */ @Override public Integer getId() { return this.id; } /** * Sets the id. * * @param id the new id */ @Override public void setId(Integer id) { this.id = id; } /** * Gets the email. * * @return the email */ public String getEmail() { return this.email; } /** * Sets the email. * * @param email the new email */ public void setEmail(String email) { this.email = email; } /** * Gets the first name. * * @return the first name */ public String getFirstName() { return this.firstName; } /** * Sets the first name. * * @param firstName the new first name */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Gets the last name. * * @return the last name */ public String getLastName() { return this.lastName; } /** * Sets the last name. * * @param lastName the new last name */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Gets the username. * * @return the username */ public String getUsername() { return this.username; } /** * Sets the username. * * @param username the new username */ public void setUsername(String username) { this.username = username; } /** * Gets the project build record. * * @return the project build record */ public List<BuildRecord> getBuildRecords() { return buildRecords; } /** * Sets the project build record. * * @param buildRecords the new project build record */ public void setBuildRecords(List<BuildRecord> buildRecords) { this.buildRecords = buildRecords; } /** * Adds the project build record. * * @param buildRecord the project build record * @return the project build record */ public BuildRecord addBuildRecord(BuildRecord buildRecord) { getBuildRecords().add(buildRecord); buildRecord.setUser(this); return buildRecord; } /** * Removes the project build record. * * @param buildRecord the project build record * @return the project build record */ public BuildRecord removeBuildRecord(BuildRecord buildRecord) { getBuildRecords().remove(buildRecord); buildRecord.setUser(null); return buildRecord; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } User other = (User) obj; if (username == null) { if (other.username != null) { return false; } } else if (!username.equals(other.username)) { return false; } return true; } public String getLoginToken() { return loginToken; } public void setLoginToken(String loginToken) { this.loginToken = loginToken; } @Override public String toString() { return "User{" + "id=" + id + ", email='" + email + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", loginToken='" + loginToken + '\'' + ", username='" + username + '\'' + '}'; } public static class Builder { private Integer id; private String email; private String firstName; private String lastName; private String username; private List<BuildRecord> buildRecords; private Builder() { buildRecords = new ArrayList<>(); } public static Builder newBuilder() { return new Builder(); } public User build() { User user = new User(); user.setId(id); user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); user.setUsername(username); // Set the bi-directional mapping for (BuildRecord buildRecord : buildRecords) { buildRecord.setUser(user); } user.setBuildRecords(buildRecords); return user; } public Builder id(Integer id) { this.id = id; return this; } public Builder email(String email) { this.email = email; return this; } public Builder firstName(String firstName) { this.firstName = firstName; return this; } public Builder lastName(String lastName) { this.lastName = lastName; return this; } public Builder username(String username) { this.username = username; return this; } public Builder buildRecord(BuildRecord buildRecord) { this.buildRecords.add(buildRecord); return this; } public Builder buildRecords(List<BuildRecord> buildRecords) { this.buildRecords = buildRecords; return this; } } }
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * 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 io.netty.handler.codec; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.socket.ChannelInputShutdownEvent; import io.netty.util.internal.StringUtil; import java.util.List; /** * {@link ChannelInboundHandlerAdapter} which decodes bytes in a stream-like fashion from one {@link ByteBuf} to an * other Message type. * * For example here is an implementation which reads all readable bytes from * the input {@link ByteBuf} and create a new {@link ByteBuf}. * * <pre> * public class SquareDecoder extends {@link ByteToMessageDecoder} { * {@code @Override} * public void decode({@link ChannelHandlerContext} ctx, {@link ByteBuf} in, List&lt;Object&gt; out) * throws {@link Exception} { * out.add(in.readBytes(in.readableBytes())); * } * } * </pre> * * <h3>Frame detection</h3> * <p> * Generally frame detection should be handled earlier in the pipeline by adding a * {@link DelimiterBasedFrameDecoder}, {@link FixedLengthFrameDecoder}, {@link LengthFieldBasedFrameDecoder}, * or {@link LineBasedFrameDecoder}. * <p> * If a custom frame decoder is required, then one needs to be careful when implementing * one with {@link ByteToMessageDecoder}. Ensure there are enough bytes in the buffer for a * complete frame by checking {@link ByteBuf#readableBytes()}. If there are not enough bytes * for a complete frame, return without modifying the reader index to allow more bytes to arrive. * <p> * To check for complete frames without modifying the reader index, use methods like {@link ByteBuf#getInt(int)}. * One <strong>MUST</strong> use the reader index when using methods like {@link ByteBuf#getInt(int)}. * For example calling <tt>in.getInt(0)</tt> is assuming the frame starts at the beginning of the buffer, which * is not always the case. Use <tt>in.getInt(in.readerIndex())</tt> instead. * <h3>Pitfalls</h3> * <p> * Be aware that sub-classes of {@link ByteToMessageDecoder} <strong>MUST NOT</strong> * annotated with {@link @Sharable}. * <p> * Some methods such as {@link ByteBuf#readBytes(int)} will cause a memory leak if the returned buffer * is not released or added to the <tt>out</tt> {@link List}. Use derived buffers like {@link ByteBuf#readSlice(int)} * to avoid leaking memory. */ public abstract class ByteToMessageDecoder extends ChannelInboundHandlerAdapter { /** * Cumulate {@link ByteBuf}s by merge them into one {@link ByteBuf}'s, using memory copies. */ public static final Cumulator MERGE_CUMULATOR = new Cumulator() { @Override public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) { final ByteBuf buffer; if (cumulation.writerIndex() > cumulation.maxCapacity() - in.readableBytes() || cumulation.refCnt() > 1 || cumulation.isReadOnly()) { // Expand cumulation (by replace it) when either there is not more room in the buffer // or if the refCnt is greater then 1 which may happen when the user use slice().retain() or // duplicate().retain() or if its read-only. // // See: // - https://github.com/netty/netty/issues/2327 // - https://github.com/netty/netty/issues/1764 buffer = expandCumulation(alloc, cumulation, in.readableBytes()); } else { buffer = cumulation; } buffer.writeBytes(in); in.release(); return buffer; } }; /** * Cumulate {@link ByteBuf}s by add them to a {@link CompositeByteBuf} and so do no memory copy whenever possible. * Be aware that {@link CompositeByteBuf} use a more complex indexing implementation so depending on your use-case * and the decoder implementation this may be slower then just use the {@link #MERGE_CUMULATOR}. */ public static final Cumulator COMPOSITE_CUMULATOR = new Cumulator() { @Override public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) { ByteBuf buffer; if (cumulation.refCnt() > 1) { // Expand cumulation (by replace it) when the refCnt is greater then 1 which may happen when the user // use slice().retain() or duplicate().retain(). // // See: // - https://github.com/netty/netty/issues/2327 // - https://github.com/netty/netty/issues/1764 buffer = expandCumulation(alloc, cumulation, in.readableBytes()); buffer.writeBytes(in); in.release(); } else { CompositeByteBuf composite; if (cumulation instanceof CompositeByteBuf) { composite = (CompositeByteBuf) cumulation; } else { composite = alloc.compositeBuffer(Integer.MAX_VALUE); composite.addComponent(true, cumulation); } composite.addComponent(true, in); buffer = composite; } return buffer; } }; private static final byte STATE_INIT = 0; private static final byte STATE_CALLING_CHILD_DECODE = 1; private static final byte STATE_HANDLER_REMOVED_PENDING = 2; ByteBuf cumulation; private Cumulator cumulator = MERGE_CUMULATOR; private boolean singleDecode; private boolean decodeWasNull; private boolean first; /** * A bitmask where the bits are defined as * <ul> * <li>{@link #STATE_INIT}</li> * <li>{@link #STATE_CALLING_CHILD_DECODE}</li> * <li>{@link #STATE_HANDLER_REMOVED_PENDING}</li> * </ul> */ private byte decodeState = STATE_INIT; private int discardAfterReads = 16; private int numReads; protected ByteToMessageDecoder() { ensureNotSharable(); } /** * If set then only one message is decoded on each {@link #channelRead(ChannelHandlerContext, Object)} * call. This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up. * * Default is {@code false} as this has performance impacts. */ public void setSingleDecode(boolean singleDecode) { this.singleDecode = singleDecode; } /** * If {@code true} then only one message is decoded on each * {@link #channelRead(ChannelHandlerContext, Object)} call. * * Default is {@code false} as this has performance impacts. */ public boolean isSingleDecode() { return singleDecode; } /** * Set the {@link Cumulator} to use for cumulate the received {@link ByteBuf}s. */ public void setCumulator(Cumulator cumulator) { if (cumulator == null) { throw new NullPointerException("cumulator"); } this.cumulator = cumulator; } /** * Set the number of reads after which {@link ByteBuf#discardSomeReadBytes()} are called and so free up memory. * The default is {@code 16}. */ public void setDiscardAfterReads(int discardAfterReads) { if (discardAfterReads <= 0) { throw new IllegalArgumentException("discardAfterReads must be > 0"); } this.discardAfterReads = discardAfterReads; } /** * Returns the actual number of readable bytes in the internal cumulative * buffer of this decoder. You usually do not need to rely on this value * to write a decoder. Use it only when you must use it at your own risk. * This method is a shortcut to {@link #internalBuffer() internalBuffer().readableBytes()}. */ protected int actualReadableBytes() { return internalBuffer().readableBytes(); } /** * Returns the internal cumulative buffer of this decoder. You usually * do not need to access the internal buffer directly to write a decoder. * Use it only when you must use it at your own risk. */ protected ByteBuf internalBuffer() { if (cumulation != null) { return cumulation; } else { return Unpooled.EMPTY_BUFFER; } } @Override public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { if (decodeState == STATE_CALLING_CHILD_DECODE) { decodeState = STATE_HANDLER_REMOVED_PENDING; return; } ByteBuf buf = cumulation; if (buf != null) { // Directly set this to null so we are sure we not access it in any other method here anymore. cumulation = null; int readable = buf.readableBytes(); if (readable > 0) { ByteBuf bytes = buf.readBytes(readable); buf.release(); ctx.fireChannelRead(bytes); } else { buf.release(); } numReads = 0; ctx.fireChannelReadComplete(); } handlerRemoved0(ctx); } /** * Gets called after the {@link ByteToMessageDecoder} was removed from the actual context and it doesn't handle * events anymore. */ protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { CodecOutputList out = CodecOutputList.newInstance(); try { ByteBuf data = (ByteBuf) msg; first = cumulation == null; if (first) { cumulation = data; } else { cumulation = cumulator.cumulate(ctx.alloc(), cumulation, data); } callDecode(ctx, cumulation, out); } catch (DecoderException e) { throw e; } catch (Throwable t) { throw new DecoderException(t); } finally { if (cumulation != null && !cumulation.isReadable()) { numReads = 0; cumulation.release(); cumulation = null; } else if (++ numReads >= discardAfterReads) { // We did enough reads already try to discard some bytes so we not risk to see a OOME. // See https://github.com/netty/netty/issues/4275 numReads = 0; discardSomeReadBytes(); } int size = out.size(); decodeWasNull = !out.insertSinceRecycled(); fireChannelRead(ctx, out, size); out.recycle(); } } else { ctx.fireChannelRead(msg); } } /** * Get {@code numElements} out of the {@link List} and forward these through the pipeline. */ static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements) { if (msgs instanceof CodecOutputList) { fireChannelRead(ctx, (CodecOutputList) msgs, numElements); } else { for (int i = 0; i < numElements; i++) { ctx.fireChannelRead(msgs.get(i)); } } } /** * Get {@code numElements} out of the {@link CodecOutputList} and forward these through the pipeline. */ static void fireChannelRead(ChannelHandlerContext ctx, CodecOutputList msgs, int numElements) { for (int i = 0; i < numElements; i ++) { ctx.fireChannelRead(msgs.getUnsafe(i)); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { channelReadComplete(ctx, !decodeWasNull); } protected final void channelReadComplete(ChannelHandlerContext ctx, boolean readData) throws Exception { numReads = 0; discardSomeReadBytes(); decodeWasNull = false; if (readData) { ctx.fireChannelReadComplete(); } else if (!ctx.channel().config().isAutoRead()) { ctx.read(); } } protected final void discardSomeReadBytes() { if (cumulation != null && !first && cumulation.refCnt() == 1) { // discard some bytes if possible to make more room in the // buffer but only if the refCnt == 1 as otherwise the user may have // used slice().retain() or duplicate().retain(). // // See: // - https://github.com/netty/netty/issues/2327 // - https://github.com/netty/netty/issues/1764 cumulation.discardSomeReadBytes(); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channelInputClosed(ctx, true); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof ChannelInputShutdownEvent) { // The decodeLast method is invoked when a channelInactive event is encountered. // This method is responsible for ending requests in some situations and must be called // when the input has been shutdown. channelInputClosed(ctx, false); } super.userEventTriggered(ctx, evt); } private void channelInputClosed(ChannelHandlerContext ctx, boolean callChannelInactive) throws Exception { CodecOutputList out = CodecOutputList.newInstance(); try { channelInputClosed(ctx, out); } catch (DecoderException e) { throw e; } catch (Exception e) { throw new DecoderException(e); } finally { try { if (cumulation != null) { cumulation.release(); cumulation = null; } int size = out.size(); fireChannelRead(ctx, out, size); if (size > 0) { // Something was read, call fireChannelReadComplete() ctx.fireChannelReadComplete(); } if (callChannelInactive) { ctx.fireChannelInactive(); } } finally { // Recycle in all cases out.recycle(); } } } /** * Called when the input of the channel was closed which may be because it changed to inactive or because of * {@link ChannelInputShutdownEvent}. */ void channelInputClosed(ChannelHandlerContext ctx, List<Object> out) throws Exception { if (cumulation != null) { callDecode(ctx, cumulation, out); decodeLast(ctx, cumulation, out); } else { decodeLast(ctx, Unpooled.EMPTY_BUFFER, out); } } /** * Called once data should be decoded from the given {@link ByteBuf}. This method will call * {@link #decode(ChannelHandlerContext, ByteBuf, List)} as long as decoding should take place. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param in the {@link ByteBuf} from which to read data * @param out the {@link List} to which decoded messages should be added */ protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { try { while (in.isReadable()) { int outSize = out.size(); if (outSize > 0) { fireChannelRead(ctx, out, outSize); out.clear(); // Check if this handler was removed before continuing with decoding. // If it was removed, it is not safe to continue to operate on the buffer. // // See: // - https://github.com/netty/netty/issues/4635 if (ctx.isRemoved()) { break; } outSize = 0; } int oldInputLength = in.readableBytes(); decodeRemovalReentryProtection(ctx, in, out); // Check if this handler was removed before continuing the loop. // If it was removed, it is not safe to continue to operate on the buffer. // // See https://github.com/netty/netty/issues/1664 if (ctx.isRemoved()) { break; } if (outSize == out.size()) { if (oldInputLength == in.readableBytes()) { break; } else { continue; } } if (oldInputLength == in.readableBytes()) { throw new DecoderException( StringUtil.simpleClassName(getClass()) + ".decode() did not read anything but decoded a message."); } if (isSingleDecode()) { break; } } } catch (DecoderException e) { throw e; } catch (Throwable cause) { throw new DecoderException(cause); } } /** * Decode the from one {@link ByteBuf} to an other. This method will be called till either the input * {@link ByteBuf} has nothing to read when return from this method or till nothing was read from the input * {@link ByteBuf}. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param in the {@link ByteBuf} from which to read data * @param out the {@link List} to which decoded messages should be added * @throws Exception is thrown if an error occurs */ protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception; /** * Decode the from one {@link ByteBuf} to an other. This method will be called till either the input * {@link ByteBuf} has nothing to read when return from this method or till nothing was read from the input * {@link ByteBuf}. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param in the {@link ByteBuf} from which to read data * @param out the {@link List} to which decoded messages should be added * @throws Exception is thrown if an error occurs */ final void decodeRemovalReentryProtection(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { decodeState = STATE_CALLING_CHILD_DECODE; try { decode(ctx, in, out); } finally { boolean removePending = decodeState == STATE_HANDLER_REMOVED_PENDING; decodeState = STATE_INIT; if (removePending) { handlerRemoved(ctx); } } } /** * Is called one last time when the {@link ChannelHandlerContext} goes in-active. Which means the * {@link #channelInactive(ChannelHandlerContext)} was triggered. * * By default this will just call {@link #decode(ChannelHandlerContext, ByteBuf, List)} but sub-classes may * override this for some special cleanup operation. */ protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.isReadable()) { // Only call decode() if there is something left in the buffer to decode. // See https://github.com/netty/netty/issues/4386 decodeRemovalReentryProtection(ctx, in, out); } } static ByteBuf expandCumulation(ByteBufAllocator alloc, ByteBuf cumulation, int readable) { ByteBuf oldCumulation = cumulation; cumulation = alloc.buffer(oldCumulation.readableBytes() + readable); cumulation.writeBytes(oldCumulation); oldCumulation.release(); return cumulation; } /** * Cumulate {@link ByteBuf}s. */ public interface Cumulator { /** * Cumulate the given {@link ByteBuf}s and return the {@link ByteBuf} that holds the cumulated bytes. * The implementation is responsible to correctly handle the life-cycle of the given {@link ByteBuf}s and so * call {@link ByteBuf#release()} if a {@link ByteBuf} is fully consumed. */ ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in); } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.ui.update; import com.intellij.concurrency.JobScheduler; import com.intellij.openapi.application.ApplicationManager; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.UsefulTestCase; import com.intellij.util.Alarm; import com.intellij.util.ExceptionUtil; import com.intellij.util.TimeoutUtil; import com.intellij.util.WaitFor; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class MergingUpdateQueueTest extends UsefulTestCase { public void testOnShowNotify() { final MyUpdate first = new MyUpdate("first"); final MyUpdate second = new MyUpdate("second"); final MyQueue queue = new MyQueue(); queue.queue(first); queue.queue(second); assertFalse(first.isExecuted()); assertFalse(second.isExecuted()); queue.showNotify(); waitForExecution(queue); assertAfterProcessing(first, true, true); assertAfterProcessing(second, true, true); } public void testPriority() { final boolean[] attemps = new boolean[3]; final MyQueue queue = new MyQueue(); final MyUpdate first = new MyUpdate("addedFirstButRunLast") { // default priority is 999 @Override public void run() { super.run(); attemps[0] = true; assertTrue(attemps[1]); assertTrue(attemps[2]); } }; final MyUpdate second = new MyUpdate("addedSecondButRunFirst", Update.HIGH_PRIORITY) { @Override public void run() { super.run(); assertFalse(attemps[0]); attemps[1] = true; assertFalse(attemps[2]); } }; final MyUpdate third = new MyUpdate("addedThirdButRunSecond", 100) { @Override public void run() { super.run(); assertFalse(attemps[0]); assertTrue(attemps[1]); attemps[2] = true; } }; queue.queue(first); queue.queue(second); queue.queue(third); waitForExecution(queue); assertAfterProcessing(first, true, true); assertAfterProcessing(second, true, true); assertAfterProcessing(third, true, true); } public void testDoNoExecuteExpired() { final boolean[] expired = new boolean[1]; final MyUpdate first = new MyUpdate("first") { @Override public boolean isExpired() { return expired[0]; } }; final MyUpdate second = new MyUpdate("second"); final MyQueue queue = new MyQueue(); queue.queue(first); queue.queue(second); assertFalse(first.isExecuted()); assertFalse(second.isExecuted()); expired[0] = true; queue.showNotify(); waitForExecution(queue); assertAfterProcessing(first, false, true); assertAfterProcessing(second, true, true); } public void testOnShowNotifyMerging() { final MyUpdate twin1 = new MyUpdate("twin"); final MyUpdate twin2 = new MyUpdate("twin"); final MyQueue queue = new MyQueue(); queue.queue(twin1); queue.queue(twin2); assertFalse(twin1.isExecuted()); assertFalse(twin2.isExecuted()); queue.showNotify(); waitForExecution(queue); assertAfterProcessing(twin1, false, true); assertAfterProcessing(twin2, true, true); } public void testExecuteWhenActive() { final MyQueue queue = new MyQueue(); queue.showNotify(); final MyUpdate first = new MyUpdate("first"); final MyUpdate second = new MyUpdate("second"); queue.queue(first); queue.queue(second); waitForExecution(queue); assertAfterProcessing(first, true, true); assertAfterProcessing(second, true, true); } public void testMergeWhenActive() { final MyQueue queue = new MyQueue(); queue.showNotify(); final MyUpdate twin1 = new MyUpdate("twin"); final MyUpdate twin2 = new MyUpdate("twin"); queue.queue(twin1); queue.queue(twin2); waitForExecution(queue); assertAfterProcessing(twin1, false, true); assertAfterProcessing(twin2, true, true); } public void testEatByQueue() { executeEatingTest(false); } public void testEatUpdatesInQueue() { executeEatingTest(true); } private static void executeEatingTest(boolean foodFirst) { final MyQueue queue = new MyQueue(); queue.showNotify(); final MyUpdate food = new MyUpdate("food"); MyUpdate hungry = new MyUpdate("hungry") { @Override public boolean canEat(Update update) { return update == food; } }; if (foodFirst) { queue.queue(food); queue.queue(hungry); } else { queue.queue(hungry); queue.queue(food); } waitForExecution(queue); assertAfterProcessing(hungry, true, true); assertAfterProcessing(food, false, false); } public void testConcurrentFlushing() { final MyQueue queue = new MyQueue(); queue.showNotify(); queue.queue(new MyUpdate("update") { @Override public boolean isExpired() { queue.flush(); return false; } }); waitForExecution(queue); } public void testBlockingFlush() throws Exception { MyQueue queue = new MyQueue(); queue.showNotify(); AtomicReference<Object> executed = new AtomicReference<>(); ApplicationManager.getApplication().executeOnPooledThread(() -> { try { queue.queue(new MyUpdate("update")); queue.flush(); executed.set(queue.wasExecuted()); } catch (RuntimeException | Error th) { executed.set(th); } }); while (executed.get() == null) { PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue(); Thread.sleep(50); } Object result = executed.get(); if (result instanceof Throwable) { ExceptionUtil.rethrowUnchecked((Throwable)result); } assertTrue(Boolean.TRUE.equals(executed.get())); } public void testConcurrentQueueing() { final MyQueue queue = new MyQueue(); queue.showNotify(); queue.queue(new MyUpdate("update") { @Override public boolean isExpired() { queue.queue(new MyUpdate("update again")); return false; } }); waitForExecution(queue); } private static void assertAfterProcessing(MyUpdate update, boolean shouldBeExecuted, boolean shouldBeProcessed) { assertEquals(shouldBeExecuted, update.isExecuted()); assertEquals(shouldBeProcessed, update.wasProcessed()); } private static class MyUpdate extends Update { private boolean myExecuted; MyUpdate(String s) { super(s); } MyUpdate(Object identity, int priority) { super(identity, priority); } @Override public void run() { myExecuted = true; } private boolean isExecuted() { return myExecuted; } } private static final class MyQueue extends MergingUpdateQueue { private boolean myExecuted; private MyQueue() { this(400); } private MyQueue(int mergingTimeSpan) { super("Test", mergingTimeSpan, false, null); } @Override public void run() { } private void onTimer() { super.run(); } @Override protected void execute(final Update @NotNull [] update) { super.execute(update); myExecuted = true; } boolean wasExecuted() { return myExecuted; } @Override protected boolean isModalityStateCorrect() { return true; } } private static void waitForExecution(final MyQueue queue) { queue.onTimer(); new WaitFor(5000) { @Override protected boolean condition() { return queue.wasExecuted(); } }.assertCompleted(); } public void testReallyMergeEqualIdentityEqualPriority() { final MyQueue queue = new MyQueue(); final AtomicInteger count = new AtomicInteger(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { queue.queue(new Update("foo" + j) { @Override public void run() { count.incrementAndGet(); } }); } } queue.showNotify(); waitForExecution(queue); assertEquals(100, count.get()); } public void testMultiThreadedQueueing() throws ExecutionException, InterruptedException { final MyQueue queue = new MyQueue(20); queue.showNotify(); final AtomicInteger count = new AtomicInteger(); ScheduledExecutorService executor = JobScheduler.getScheduler(); List<Future> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { ScheduledFuture<?> future = executor.schedule(() -> { for (int j = 0; j < 100; j++) { TimeoutUtil.sleep(1); queue.queue(new Update(new Object()) { @Override public void run() { count.incrementAndGet(); } }); } }, 0, TimeUnit.MILLISECONDS); futures.add(future); } for (Future future : futures) { future.get(); } waitForExecution(queue); assertEquals(1000, count.get()); } public void testSamePriorityQueriesAreExecutedInAdditionOrder() { final MyQueue queue = new MyQueue(); StringBuilder expected = new StringBuilder(); final StringBuilder actual = new StringBuilder(); for (int i = 0; i < 20; i++) { expected.append(i); final int finalI = i; queue.queue(new Update(new Object()) { @Override public void run() { actual.append(finalI); } }); } queue.showNotify(); waitForExecution(queue); assertEquals(expected.toString(), actual.toString()); } public void testAddRequestsInPooledThreadDoNotExecuteConcurrently() throws InterruptedException { int delay = 10; MergingUpdateQueue queue = new MergingUpdateQueue("x", delay, true, null, getTestRootDisposable(), null, Alarm.ThreadToUse.POOLED_THREAD); CountDownLatch startedExecuting1 = new CountDownLatch(1); CountDownLatch canContinue = new CountDownLatch(1); queue.queue(new Update("1") { @Override public void run() { startedExecuting1.countDown(); try { canContinue.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }); assertTrue(startedExecuting1.await(10, TimeUnit.SECONDS)); CountDownLatch startedExecuting2 = new CountDownLatch(1); queue.queue(new Update("2") { @Override public void run() { startedExecuting2.countDown(); } }); TimeoutUtil.sleep(delay + 1000); canContinue.countDown(); assertTrue(startedExecuting2.await(10, TimeUnit.SECONDS)); } }
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.clustered.server.offheap; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.locks.ReentrantLock; import org.ehcache.clustered.common.internal.store.Chain; import org.ehcache.clustered.server.KeySegmentMapper; import org.ehcache.clustered.server.ServerStoreEventListener; import org.ehcache.clustered.server.store.ChainBuilder; import org.ehcache.clustered.server.store.ElementBuilder; import org.ehcache.clustered.common.internal.store.ServerStore; import org.ehcache.clustered.server.store.ServerStoreTest; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.terracotta.offheapstore.buffersource.OffHeapBufferSource; import org.terracotta.offheapstore.exceptions.OversizeMappingException; import org.terracotta.offheapstore.paging.UnlimitedPageSource; import org.terracotta.offheapstore.paging.UpfrontAllocatingPageSource; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.ehcache.clustered.ChainUtils.chainOf; import static org.ehcache.clustered.ChainUtils.createPayload; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.terracotta.offheapstore.util.MemoryUnit.GIGABYTES; import static org.terracotta.offheapstore.util.MemoryUnit.KILOBYTES; import static org.terracotta.offheapstore.util.MemoryUnit.MEGABYTES; public class OffHeapServerStoreTest extends ServerStoreTest { private static final KeySegmentMapper DEFAULT_MAPPER = new KeySegmentMapper(16); @SuppressWarnings("unchecked") private OffHeapChainMap<Object> getOffHeapChainMapMock() { return mock(OffHeapChainMap.class); } @SuppressWarnings("unchecked") private OffHeapChainMap<Long> getOffHeapChainMapLongMock() { return mock(OffHeapChainMap.class); } @SuppressWarnings("unchecked") private ChainStorageEngine<Long> getChainStorageEngineLongMock() { return mock(ChainStorageEngine.class); } @Override public ServerStore newStore() { return new OffHeapServerStore(new UnlimitedPageSource(new OffHeapBufferSource()), DEFAULT_MAPPER, false); } @Override public ChainBuilder newChainBuilder() { return elements -> { ByteBuffer[] buffers = new ByteBuffer[elements.length]; for (int i = 0; i < buffers.length; i++) { buffers[i] = elements[i].getPayload(); } return chainOf(buffers); }; } @Override public ElementBuilder newElementBuilder() { return payLoad -> () -> payLoad.asReadOnlyBuffer(); } @Test public void testGetMaxSize() { assertThat(OffHeapServerStore.getMaxSize(MEGABYTES.toBytes(2)), is(64L)); assertThat(OffHeapServerStore.getMaxSize(MEGABYTES.toBytes(4)), is(128L)); assertThat(OffHeapServerStore.getMaxSize(MEGABYTES.toBytes(16)), is(512L)); assertThat(OffHeapServerStore.getMaxSize(MEGABYTES.toBytes(64)), is(2048L)); assertThat(OffHeapServerStore.getMaxSize(MEGABYTES.toBytes(128)), is(4096L)); assertThat(OffHeapServerStore.getMaxSize(MEGABYTES.toBytes(256)), is(8192L)); assertThat(OffHeapServerStore.getMaxSize(MEGABYTES.toBytes(512)), is(8192L)); assertThat(OffHeapServerStore.getMaxSize(GIGABYTES.toBytes(2)), is(8192L)); } @Test public void put_worked_the_first_time_test() throws Exception { OffHeapChainMap<Long> offheapChainMap = getOffHeapChainMapLongMock(); ChainStorageEngine<Long> storageEngine = getChainStorageEngineLongMock(); when(offheapChainMap.getStorageEngine()).thenReturn(storageEngine); doNothing() .when(offheapChainMap).put(anyLong(), any(Chain.class)); OffHeapServerStore offHeapServerStore = new OffHeapServerStore(singletonList(offheapChainMap), mock(KeySegmentMapper.class)); offHeapServerStore.put(43L, mock(Chain.class)); } @Test(expected = OversizeMappingException.class) public void put_should_throw_when_underlying_put_always_throw_test() throws Exception { OffHeapChainMap<Long> offheapChainMap = getOffHeapChainMapLongMock(); ChainStorageEngine<Long> storageEngine = getChainStorageEngineLongMock(); when(offheapChainMap.getStorageEngine()).thenReturn(storageEngine); when(offheapChainMap.writeLock()).thenReturn(new ReentrantLock()); doThrow(new OversizeMappingException()) .when(offheapChainMap).put(anyLong(), any(Chain.class)); OffHeapServerStore offHeapServerStore = new OffHeapServerStore(singletonList(offheapChainMap), mock(KeySegmentMapper.class)); offHeapServerStore.put(43L, mock(Chain.class)); } @Test public void put_should_return_when_underlying_put_does_not_throw_test() throws Exception { OffHeapChainMap<Long> offheapChainMap = getOffHeapChainMapLongMock(); ChainStorageEngine<Long> storageEngine = getChainStorageEngineLongMock(); when(offheapChainMap.getStorageEngine()).thenReturn(storageEngine); when(offheapChainMap.writeLock()).thenReturn(new ReentrantLock()); // throw once, then ok doThrow(new OversizeMappingException()) .doNothing() .when(offheapChainMap).put(anyLong(), any(Chain.class)); OffHeapServerStore offHeapServerStore = new OffHeapServerStore(singletonList(offheapChainMap), mock(KeySegmentMapper.class)); offHeapServerStore.put(43L, mock(Chain.class)); } @Test public void put_should_return_when_underlying_put_does_not_throw_with_keymapper_test() throws Exception { long theKey = 43L; ChainStorageEngine<Long> storageEngine = getChainStorageEngineLongMock(); OffHeapChainMap<Long> offheapChainMap = getOffHeapChainMapLongMock(); OffHeapChainMap<Long> otherOffheapChainMap = getOffHeapChainMapLongMock(); when(offheapChainMap.shrink()).thenReturn(true); when(offheapChainMap.getStorageEngine()).thenReturn(storageEngine); when(offheapChainMap.writeLock()).thenReturn(new ReentrantLock()); when(otherOffheapChainMap.writeLock()).thenReturn(new ReentrantLock()); // throw twice, then OK doThrow(new OversizeMappingException()) .doThrow(new OversizeMappingException()) .doNothing() .when(otherOffheapChainMap).put(anyLong(), any(Chain.class)); KeySegmentMapper keySegmentMapper = mock(KeySegmentMapper.class); when(keySegmentMapper.getSegmentForKey(theKey)).thenReturn(1); OffHeapServerStore offHeapServerStore = new OffHeapServerStore(asList(offheapChainMap, otherOffheapChainMap), keySegmentMapper); offHeapServerStore.put(theKey, mock(Chain.class)); //getSegmentForKey was called 4 times : segmentFor, handleOversizeMappingException, segmentFor, segmentFor verify(keySegmentMapper, times(4)).getSegmentForKey(theKey); } @Test public void test_append_doesNotConsumeBuffer_evenWhenOversizeMappingException() throws Exception { OffHeapServerStore store = (OffHeapServerStore) spy(newStore()); final OffHeapChainMap<Object> offHeapChainMap = getOffHeapChainMapMock(); doThrow(OversizeMappingException.class).when(offHeapChainMap).append(any(Object.class), any(ByteBuffer.class)); when(store.segmentFor(anyLong())).then(new Answer<Object>() { int invocations = 0; @Override public Object answer(InvocationOnMock invocation) throws Throwable { if (invocations++ < 10) { return offHeapChainMap; } else { return invocation.callRealMethod(); } } }); when(store.tryShrinkOthers(anyLong())).thenReturn(true); ByteBuffer payload = createPayload(1L); store.append(1L, payload); assertThat(payload.remaining(), is(8)); } @Test public void test_getAndAppend_doesNotConsumeBuffer_evenWhenOversizeMappingException() throws Exception { OffHeapServerStore store = (OffHeapServerStore) spy(newStore()); final OffHeapChainMap<Object> offHeapChainMap = getOffHeapChainMapMock(); doThrow(OversizeMappingException.class).when(offHeapChainMap).getAndAppend(any(), any(ByteBuffer.class)); when(store.segmentFor(anyLong())).then(new Answer<Object>() { int invocations = 0; @Override public Object answer(InvocationOnMock invocation) throws Throwable { if (invocations++ < 10) { return offHeapChainMap; } else { return invocation.callRealMethod(); } } }); when(store.tryShrinkOthers(anyLong())).thenReturn(true); ByteBuffer payload = createPayload(1L); store.getAndAppend(1L, payload); assertThat(payload.remaining(), is(8)); Chain expected = newChainBuilder().build(newElementBuilder().build(payload), newElementBuilder().build(payload)); Chain update = newChainBuilder().build(newElementBuilder().build(payload)); store.replaceAtHead(1L, expected, update); assertThat(payload.remaining(), is(8)); } @Test public void test_replaceAtHead_doesNotConsumeBuffer_evenWhenOversizeMappingException() throws Exception { OffHeapServerStore store = (OffHeapServerStore) spy(newStore()); final OffHeapChainMap<Object> offHeapChainMap = getOffHeapChainMapMock(); doThrow(OversizeMappingException.class).when(offHeapChainMap).replaceAtHead(any(), any(Chain.class), any(Chain.class)); when(store.segmentFor(anyLong())).then(new Answer<Object>() { int invocations = 0; @Override public Object answer(InvocationOnMock invocation) throws Throwable { if (invocations++ < 10) { return offHeapChainMap; } else { return invocation.callRealMethod(); } } }); when(store.tryShrinkOthers(anyLong())).thenReturn(true); ByteBuffer payload = createPayload(1L); Chain expected = newChainBuilder().build(newElementBuilder().build(payload), newElementBuilder().build(payload)); Chain update = newChainBuilder().build(newElementBuilder().build(payload)); store.replaceAtHead(1L, expected, update); assertThat(payload.remaining(), is(8)); } @Test public void testCrossSegmentShrinking() { long seed = System.nanoTime(); Random random = new Random(seed); try { OffHeapServerStore store = new OffHeapServerStore(new UpfrontAllocatingPageSource(new OffHeapBufferSource(), MEGABYTES.toBytes(1L), MEGABYTES.toBytes(1)), DEFAULT_MAPPER, false); ByteBuffer smallValue = ByteBuffer.allocate(1024); for (int i = 0; i < 10000; i++) { try { store.getAndAppend(random.nextInt(500), smallValue.duplicate()); } catch (OversizeMappingException e) { //ignore } } ByteBuffer largeValue = ByteBuffer.allocate(100 * 1024); for (int i = 0; i < 10000; i++) { try { store.getAndAppend(random.nextInt(500), largeValue.duplicate()); } catch (OversizeMappingException e) { //ignore } } } catch (Throwable t) { throw (AssertionError) new AssertionError("Failed with seed " + seed).initCause(t); } } @Test public void testServerSideUsageStats() { long maxBytes = MEGABYTES.toBytes(1); OffHeapServerStore store = new OffHeapServerStore(new UpfrontAllocatingPageSource(new OffHeapBufferSource(), maxBytes, MEGABYTES.toBytes(1)), new KeySegmentMapper(16), false); int oneKb = 1024; long smallLoopCount = 5; ByteBuffer smallValue = ByteBuffer.allocate(oneKb); for (long i = 0; i < smallLoopCount; i++) { store.getAndAppend(i, smallValue.duplicate()); } assertThat(store.getAllocatedMemory(),lessThanOrEqualTo(maxBytes)); assertThat(store.getAllocatedMemory(),greaterThanOrEqualTo(smallLoopCount * oneKb)); assertThat(store.getAllocatedMemory(),greaterThanOrEqualTo(store.getOccupiedMemory())); //asserts above already guarantee that occupiedMemory <= maxBytes and that occupiedMemory <= allocatedMemory assertThat(store.getOccupiedMemory(),greaterThanOrEqualTo(smallLoopCount * oneKb)); assertThat(store.getSize(), is(smallLoopCount)); int multiplier = 100; long largeLoopCount = 5 + smallLoopCount; ByteBuffer largeValue = ByteBuffer.allocate(multiplier * oneKb); for (long i = smallLoopCount; i < largeLoopCount; i++) { store.getAndAppend(i, largeValue.duplicate()); } assertThat(store.getAllocatedMemory(),lessThanOrEqualTo(maxBytes)); assertThat(store.getAllocatedMemory(),greaterThanOrEqualTo( (smallLoopCount * oneKb) + ( (largeLoopCount - smallLoopCount) * oneKb * multiplier) )); assertThat(store.getAllocatedMemory(),greaterThanOrEqualTo(store.getOccupiedMemory())); //asserts above already guarantee that occupiedMemory <= maxBytes and that occupiedMemory <= allocatedMemory assertThat(store.getOccupiedMemory(),greaterThanOrEqualTo(smallLoopCount * oneKb)); assertThat(store.getSize(), is(smallLoopCount + (largeLoopCount - smallLoopCount))); } @Test public void testEvictionFiresEventsWithChainWhenEvictionIsEnabled() { OffHeapServerStore store = new OffHeapServerStore(new UpfrontAllocatingPageSource(new OffHeapBufferSource(), (long) MEGABYTES.toBytes(1), MEGABYTES.toBytes(1)), new KeySegmentMapper(16), false); AuditingServerStoreEventListener audit = new AuditingServerStoreEventListener(); store.setEventListener(audit); store.enableEvents(true); ByteBuffer buffer = ByteBuffer.allocate(KILOBYTES.toBytes(500)); store.append(1L, buffer.duplicate()); store.append(2L, buffer.duplicate()); store.append(3L, buffer.duplicate()); assertThat(store.getSize(), is(1L)); assertThat(audit.onEviction.size(), is(2)); assertThat(audit.onEviction.get(0).key, is(1L)); assertThat(audit.onEviction.get(0).evictedChain, is(notNullValue())); assertThat(audit.onEviction.get(1).key, is(2L)); assertThat(audit.onEviction.get(1).evictedChain, is(notNullValue())); } @Test public void testNoEventFiredWhenDisabled() { OffHeapServerStore store = new OffHeapServerStore(new UpfrontAllocatingPageSource(new OffHeapBufferSource(), (long) MEGABYTES.toBytes(1), MEGABYTES.toBytes(1)), new KeySegmentMapper(16), false); AuditingServerStoreEventListener audit = new AuditingServerStoreEventListener(); store.setEventListener(audit); store.append(1L, toBuffer(1)); store.getAndAppend(1L, toBuffer(2)); store.enableEvents(true); store.append(1L, toBuffer(3)); store.getAndAppend(1L, toBuffer(4)); store.enableEvents(false); store.append(1L, toBuffer(5)); store.getAndAppend(1L, toBuffer(6)); assertThat(audit.onAppend.size(), is(2)); assertThat(audit.onAppend.get(0).appended.asIntBuffer().get(), is(3)); assertThat(audit.onAppend.get(1).appended.asIntBuffer().get(), is(4)); } @Test public void testAppendFiresEvents() { OffHeapServerStore store = new OffHeapServerStore(new UpfrontAllocatingPageSource(new OffHeapBufferSource(), (long) MEGABYTES.toBytes(1), MEGABYTES.toBytes(1)), new KeySegmentMapper(16), false); AuditingServerStoreEventListener audit = new AuditingServerStoreEventListener(); store.setEventListener(audit); store.enableEvents(true); store.append(1L, toBuffer(1)); store.append(1L, toBuffer(2)); store.append(1L, toBuffer(3)); assertThat(audit.onAppend.size(), is(3)); assertThat(audit.onAppend.get(0).appended.asIntBuffer().get(), is(1)); assertThat(audit.onAppend.get(1).appended.asIntBuffer().get(), is(2)); assertThat(audit.onAppend.get(2).appended.asIntBuffer().get(), is(3)); } @Test public void testGetAndAppendFiresEvents() { OffHeapServerStore store = new OffHeapServerStore(new UpfrontAllocatingPageSource(new OffHeapBufferSource(), (long) MEGABYTES.toBytes(1), MEGABYTES.toBytes(1)), new KeySegmentMapper(16), false); AuditingServerStoreEventListener audit = new AuditingServerStoreEventListener(); store.setEventListener(audit); store.enableEvents(true); store.getAndAppend(1L, toBuffer(1)); store.getAndAppend(1L, toBuffer(2)); store.getAndAppend(1L, toBuffer(3)); assertThat(audit.onAppend.size(), is(3)); assertThat(audit.onAppend.get(0).appended.asIntBuffer().get(), is(1)); assertThat(audit.onAppend.get(1).appended.asIntBuffer().get(), is(2)); assertThat(audit.onAppend.get(2).appended.asIntBuffer().get(), is(3)); } private static class AuditingServerStoreEventListener implements ServerStoreEventListener { private final List<OnAppendArgs> onAppend = new ArrayList<>(); private final List<OnEvictionArgs> onEviction = new ArrayList<>(); @Override public void onEviction(long key, InternalChain evictedChain) { onEviction.add(new OnEvictionArgs(key, evictedChain)); } @Override public void onAppend(Chain beforeAppend, ByteBuffer appended) { onAppend.add(new OnAppendArgs(appended, beforeAppend)); } static class OnEvictionArgs { OnEvictionArgs(long key, InternalChain evictedChain) { this.key = key; this.evictedChain = evictedChain; } long key; InternalChain evictedChain; } static class OnAppendArgs { OnAppendArgs(ByteBuffer appended, Chain beforeAppend) { this.appended = appended; this.beforeAppend = beforeAppend; } ByteBuffer appended; Chain beforeAppend; } } private static ByteBuffer toBuffer(int i) { ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES); buffer.asIntBuffer().put(i); return buffer; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.provenance; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import org.apache.nifi.processor.DataUnit; import org.apache.nifi.provenance.search.SearchableField; import org.apache.nifi.util.FormatUtils; import org.apache.nifi.util.NiFiProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RepositoryConfiguration { private static final Logger logger = LoggerFactory.getLogger(RepositoryConfiguration.class); public static final String CONCURRENT_MERGE_THREADS = "nifi.provenance.repository.concurrent.merge.threads"; public static final String WARM_CACHE_FREQUENCY = "nifi.provenance.repository.warm.cache.frequency"; public static final String MAINTENACE_FREQUENCY = "nifi.provenance.repository.maintenance.frequency"; private final Map<String, File> storageDirectories = new LinkedHashMap<>(); private long recordLifeMillis = TimeUnit.MILLISECONDS.convert(24, TimeUnit.HOURS); private long storageCapacity = 1024L * 1024L * 1024L; // 1 GB private long eventFileMillis = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES); private long eventFileBytes = 1024L * 1024L * 5L; // 5 MB private int maxFileEvents = Integer.MAX_VALUE; private long desiredIndexBytes = 1024L * 1024L * 500L; // 500 MB private int journalCount = 16; private int compressionBlockBytes = 1024 * 1024; private int maxAttributeChars = 65536; private int debugFrequency = 1_000_000; private long maintenanceFrequencyMillis = TimeUnit.MINUTES.toMillis(1L); private List<SearchableField> searchableFields = new ArrayList<>(); private List<SearchableField> searchableAttributes = new ArrayList<>(); private boolean compress = true; private boolean alwaysSync = false; private int queryThreadPoolSize = 2; private int indexThreadPoolSize = 1; private boolean allowRollover = true; private int concurrentMergeThreads = 4; private Integer warmCacheFrequencyMinutes = null; public void setAllowRollover(final boolean allow) { this.allowRollover = allow; } public boolean isAllowRollover() { return allowRollover; } public int getCompressionBlockBytes() { return compressionBlockBytes; } public void setCompressionBlockBytes(int compressionBlockBytes) { this.compressionBlockBytes = compressionBlockBytes; } /** * Specifies where the repository will store data * * @return the directories where provenance files will be stored */ public Map<String, File> getStorageDirectories() { return Collections.unmodifiableMap(storageDirectories); } /** * Specifies where the repository should store data * * @param storageDirectory the directory to store provenance files */ public void addStorageDirectory(final String partitionName, final File storageDirectory) { this.storageDirectories.put(partitionName, storageDirectory); } public void addStorageDirectories(final Map<String, File> storageDirectories) { this.storageDirectories.putAll(storageDirectories); } /** * @param timeUnit the desired time unit * @return the max amount of time that a given record will stay in the repository */ public long getMaxRecordLife(final TimeUnit timeUnit) { return timeUnit.convert(recordLifeMillis, TimeUnit.MILLISECONDS); } /** * Specifies how long a record should stay in the repository * * @param maxRecordLife the max amount of time to keep a record in the repo * @param timeUnit the period of time used by maxRecordLife */ public void setMaxRecordLife(final long maxRecordLife, final TimeUnit timeUnit) { this.recordLifeMillis = TimeUnit.MILLISECONDS.convert(maxRecordLife, timeUnit); } /** * Returns the maximum amount of data to store in the repository (in bytes) * * @return the maximum amount of disk space to use for the prov repo */ public long getMaxStorageCapacity() { return storageCapacity; } /** * Sets the maximum amount of data to store in the repository (in bytes) * * @param maxStorageCapacity the maximum amount of disk space to use for the prov repo */ public void setMaxStorageCapacity(final long maxStorageCapacity) { this.storageCapacity = maxStorageCapacity; } /** * @param timeUnit the desired time unit for the returned value * @return the maximum amount of time that the repo will write to a single event file */ public long getMaxEventFileLife(final TimeUnit timeUnit) { return timeUnit.convert(eventFileMillis, TimeUnit.MILLISECONDS); } /** * @param maxEventFileTime the max amount of time to write to a single event file * @param timeUnit the units for the value supplied by maxEventFileTime */ public void setMaxEventFileLife(final long maxEventFileTime, final TimeUnit timeUnit) { this.eventFileMillis = TimeUnit.MILLISECONDS.convert(maxEventFileTime, timeUnit); } /** * @return the maximum number of bytes (pre-compression) that will be * written to a single event file before the file is rolled over */ public long getMaxEventFileCapacity() { return eventFileBytes; } /** * @param maxEventFileBytes the maximum number of bytes (pre-compression) that will be written * to a single event file before the file is rolled over */ public void setMaxEventFileCapacity(final long maxEventFileBytes) { this.eventFileBytes = maxEventFileBytes; } /** * @return the maximum number of events that should be written to a single event file before the file is rolled over */ public int getMaxEventFileCount() { return maxFileEvents; } /** * @param maxCount the maximum number of events that should be written to a single event file before the file is rolled over */ public void setMaxEventFileCount(final int maxCount) { this.maxFileEvents = maxCount; } /** * @return the fields that should be indexed */ public List<SearchableField> getSearchableFields() { return Collections.unmodifiableList(searchableFields); } /** * @param searchableFields the fields to index */ public void setSearchableFields(final List<SearchableField> searchableFields) { this.searchableFields = new ArrayList<>(searchableFields); } /** * @return the FlowFile attributes that should be indexed */ public List<SearchableField> getSearchableAttributes() { return Collections.unmodifiableList(searchableAttributes); } /** * @param searchableAttributes the FlowFile attributes to index */ public void setSearchableAttributes(final List<SearchableField> searchableAttributes) { this.searchableAttributes = new ArrayList<>(searchableAttributes); } /** * @return whether or not event files will be compressed when they are * rolled over */ public boolean isCompressOnRollover() { return compress; } /** * @param compress if true, the data will be compressed when rolled over */ public void setCompressOnRollover(final boolean compress) { this.compress = compress; } /** * @return the number of threads to use to query the repo */ public int getQueryThreadPoolSize() { return queryThreadPoolSize; } public void setQueryThreadPoolSize(final int queryThreadPoolSize) { if (queryThreadPoolSize < 1) { throw new IllegalArgumentException(); } this.queryThreadPoolSize = queryThreadPoolSize; } /** * @return the number of threads to use to index provenance events */ public int getIndexThreadPoolSize() { return indexThreadPoolSize; } public void setIndexThreadPoolSize(final int indexThreadPoolSize) { if (indexThreadPoolSize < 1) { throw new IllegalArgumentException(); } this.indexThreadPoolSize = indexThreadPoolSize; } public void setConcurrentMergeThreads(final int mergeThreads) { this.concurrentMergeThreads = mergeThreads; } public int getConcurrentMergeThreads() { return concurrentMergeThreads; } /** * <p> * Specifies the desired size of each Provenance Event index shard, in * bytes. We shard the index for a few reasons: * </p> * * <ol> * <li> * A very large index requires a significant amount of Java heap space to * search. As the size of the shard increases, the required Java heap space * also increases.</li> * <li> * By having multiple shards, we have the ability to use multiple concurrent * threads to search the individual shards, resulting in far less latency * when performing a search across millions or billions of records.</li> * <li> * We keep track of which time ranges each index shard spans. As a result, * we are able to determine which shards need to be searched if a search * provides a date range. This can greatly increase the speed of a search * and reduce resource utilization.</li> * </ol> * * @param bytes * the number of bytes to write to an index before beginning a * new shard */ public void setDesiredIndexSize(final long bytes) { this.desiredIndexBytes = bytes; } /** * @return the desired size of each index shard. See the * {@link #setDesiredIndexSize} method for an explanation of why we choose * to shard the index. */ public long getDesiredIndexSize() { return desiredIndexBytes; } /** * @param numJournals the number of Journal files to use when persisting records. */ public void setJournalCount(final int numJournals) { if (numJournals < 1) { throw new IllegalArgumentException(); } this.journalCount = numJournals; } /** * @return the number of Journal files that will be used when persisting records. */ public int getJournalCount() { return journalCount; } /** * @return <code>true</code> if the repository will perform an 'fsync' for all updates to disk */ public boolean isAlwaysSync() { return alwaysSync; } /** * Configures whether or not the Repository should sync all updates to disk. * Setting this value to true means that updates are guaranteed to be * persisted across restarted, even if there is a power failure or a sudden * Operating System crash, but it can be very expensive. * * @param alwaysSync whether or not to perform an 'fsync' for all updates to disk */ public void setAlwaysSync(boolean alwaysSync) { this.alwaysSync = alwaysSync; } /** * @return the maximum number of characters to include in any attribute. If an attribute in a Provenance * Event has more than this number of characters, it will be truncated when the event is retrieved. */ public int getMaxAttributeChars() { return maxAttributeChars; } /** * Sets the maximum number of characters to include in any attribute. If an attribute in a Provenance * Event has more than this number of characters, it will be truncated when it is retrieved. */ public void setMaxAttributeChars(int maxAttributeChars) { this.maxAttributeChars = maxAttributeChars; } public void setWarmCacheFrequencyMinutes(Integer frequencyMinutes) { this.warmCacheFrequencyMinutes = frequencyMinutes; } public Optional<Integer> getWarmCacheFrequencyMinutes() { return Optional.ofNullable(warmCacheFrequencyMinutes); } public int getDebugFrequency() { return debugFrequency; } public void setDebugFrequency(int debugFrequency) { this.debugFrequency = debugFrequency; } public long getMaintenanceFrequency(final TimeUnit timeUnit) { return timeUnit.convert(maintenanceFrequencyMillis, TimeUnit.MILLISECONDS); } public void setMaintenanceFrequency(final long period, final TimeUnit timeUnit) { this.maintenanceFrequencyMillis = timeUnit.toMillis(period); } public static RepositoryConfiguration create(final NiFiProperties nifiProperties) { final Map<String, Path> storageDirectories = nifiProperties.getProvenanceRepositoryPaths(); if (storageDirectories.isEmpty()) { storageDirectories.put("provenance_repository", Paths.get("provenance_repository")); } final String storageTime = nifiProperties.getProperty(NiFiProperties.PROVENANCE_MAX_STORAGE_TIME, "24 hours"); final String storageSize = nifiProperties.getProperty(NiFiProperties.PROVENANCE_MAX_STORAGE_SIZE, "1 GB"); final String rolloverTime = nifiProperties.getProperty(NiFiProperties.PROVENANCE_ROLLOVER_TIME, "5 mins"); final String rolloverSize = nifiProperties.getProperty(NiFiProperties.PROVENANCE_ROLLOVER_SIZE, "100 MB"); final int rolloverEventCount = nifiProperties.getIntegerProperty(NiFiProperties.PROVENANCE_ROLLOVER_EVENT_COUNT, Integer.MAX_VALUE); final String shardSize = nifiProperties.getProperty(NiFiProperties.PROVENANCE_INDEX_SHARD_SIZE, "500 MB"); final int queryThreads = nifiProperties.getIntegerProperty(NiFiProperties.PROVENANCE_QUERY_THREAD_POOL_SIZE, 2); final int indexThreads = nifiProperties.getIntegerProperty(NiFiProperties.PROVENANCE_INDEX_THREAD_POOL_SIZE, 2); final int journalCount = nifiProperties.getIntegerProperty(NiFiProperties.PROVENANCE_JOURNAL_COUNT, 16); final int concurrentMergeThreads = nifiProperties.getIntegerProperty(CONCURRENT_MERGE_THREADS, 2); final String warmCacheFrequency = nifiProperties.getProperty(WARM_CACHE_FREQUENCY); final String maintenanceFrequency = nifiProperties.getProperty(MAINTENACE_FREQUENCY); final long storageMillis = FormatUtils.getTimeDuration(storageTime, TimeUnit.MILLISECONDS); final long maxStorageBytes = DataUnit.parseDataSize(storageSize, DataUnit.B).longValue(); final long rolloverMillis = FormatUtils.getTimeDuration(rolloverTime, TimeUnit.MILLISECONDS); final long rolloverBytes = DataUnit.parseDataSize(rolloverSize, DataUnit.B).longValue(); final boolean compressOnRollover = Boolean.parseBoolean(nifiProperties.getProperty(NiFiProperties.PROVENANCE_COMPRESS_ON_ROLLOVER)); final String indexedFieldString = nifiProperties.getProperty(NiFiProperties.PROVENANCE_INDEXED_FIELDS); final String indexedAttrString = nifiProperties.getProperty(NiFiProperties.PROVENANCE_INDEXED_ATTRIBUTES); final Boolean alwaysSync = Boolean.parseBoolean(nifiProperties.getProperty("nifi.provenance.repository.always.sync", "false")); final int defaultMaxAttrChars = 65536; final String maxAttrLength = nifiProperties.getProperty("nifi.provenance.repository.max.attribute.length", String.valueOf(defaultMaxAttrChars)); int maxAttrChars; try { maxAttrChars = Integer.parseInt(maxAttrLength); // must be at least 36 characters because that's the length of the uuid attribute, // which must be kept intact if (maxAttrChars < 36) { maxAttrChars = 36; logger.warn("Found max attribute length property set to " + maxAttrLength + " but minimum length is 36; using 36 instead"); } } catch (final Exception e) { maxAttrChars = defaultMaxAttrChars; } final List<SearchableField> searchableFields = SearchableFieldParser.extractSearchableFields(indexedFieldString, true); final List<SearchableField> searchableAttributes = SearchableFieldParser.extractSearchableFields(indexedAttrString, false); // We always want to index the Event Time. if (!searchableFields.contains(SearchableFields.EventTime)) { searchableFields.add(SearchableFields.EventTime); } final RepositoryConfiguration config = new RepositoryConfiguration(); for (final Map.Entry<String, Path> entry : storageDirectories.entrySet()) { config.addStorageDirectory(entry.getKey(), entry.getValue().toFile()); } config.setCompressOnRollover(compressOnRollover); config.setSearchableFields(searchableFields); config.setSearchableAttributes(searchableAttributes); config.setMaxEventFileCapacity(rolloverBytes); config.setMaxEventFileCount(rolloverEventCount); config.setMaxEventFileLife(rolloverMillis, TimeUnit.MILLISECONDS); config.setMaxRecordLife(storageMillis, TimeUnit.MILLISECONDS); config.setMaxStorageCapacity(maxStorageBytes); config.setQueryThreadPoolSize(queryThreads); config.setIndexThreadPoolSize(indexThreads); config.setJournalCount(journalCount); config.setMaxAttributeChars(maxAttrChars); config.setConcurrentMergeThreads(concurrentMergeThreads); if (warmCacheFrequency != null && !warmCacheFrequency.trim().equals("")) { config.setWarmCacheFrequencyMinutes((int) FormatUtils.getTimeDuration(warmCacheFrequency, TimeUnit.MINUTES)); } if (shardSize != null) { config.setDesiredIndexSize(DataUnit.parseDataSize(shardSize, DataUnit.B).longValue()); } if (maintenanceFrequency != null && !maintenanceFrequency.trim().equals("")) { final long millis = FormatUtils.getTimeDuration(maintenanceFrequency.trim(), TimeUnit.MILLISECONDS); config.setMaintenanceFrequency(millis, TimeUnit.MILLISECONDS); } config.setAlwaysSync(alwaysSync); config.setDebugFrequency(nifiProperties.getIntegerProperty(NiFiProperties.PROVENANCE_REPO_DEBUG_FREQUENCY, config.getDebugFrequency())); return config; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.12.05 at 01:12:38 PM EST // package org.slc.sli.sample.entitiesR1; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * This entity represents a tool, instrument, process, or exhibition composed of a systematic sampling of behavior for measuring a student's competence, knowledge, skills or behavior. An assessment can be used to measure differences in individuals or groups and changes in performance from one occasion to the next. * * <p>Java class for Assessment complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Assessment"> * &lt;complexContent> * &lt;extension base="{http://ed-fi.org/0100}ComplexObjectType"> * &lt;sequence> * &lt;element name="AssessmentTitle" type="{http://ed-fi.org/0100}AssessmentTitle"/> * &lt;element name="AssessmentIdentificationCode" type="{http://ed-fi.org/0100}AssessmentIdentificationCode" maxOccurs="unbounded"/> * &lt;element name="AssessmentCategory" type="{http://ed-fi.org/0100}AssessmentCategoryType" minOccurs="0"/> * &lt;element name="AcademicSubject" type="{http://ed-fi.org/0100}AcademicSubjectType" minOccurs="0"/> * &lt;element name="GradeLevelAssessed" type="{http://ed-fi.org/0100}GradeLevelType" minOccurs="0"/> * &lt;element name="LowestGradeLevelAssessed" type="{http://ed-fi.org/0100}GradeLevelType" minOccurs="0"/> * &lt;element name="AssessmentPerformanceLevel" type="{http://ed-fi.org/0100}AssessmentPerformanceLevel" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="ContentStandard" type="{http://ed-fi.org/0100}ContentStandardType" minOccurs="0"/> * &lt;element name="AssessmentForm" type="{http://ed-fi.org/0100}AssessmentForm" minOccurs="0"/> * &lt;element name="Version" type="{http://ed-fi.org/0100}Version" minOccurs="0"/> * &lt;element name="RevisionDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/> * &lt;element name="MaxRawScore" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="Nomenclature" type="{http://ed-fi.org/0100}Nomenclature" minOccurs="0"/> * &lt;element name="AssessmentPeriod" type="{http://ed-fi.org/0100}AssessmentPeriodDescriptorType" minOccurs="0"/> * &lt;element name="AssessmentItemReference" type="{http://ed-fi.org/0100}ReferenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="ObjectiveAssessmentReference" type="{http://ed-fi.org/0100}ReferenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="AssessmentFamilyReference" type="{http://ed-fi.org/0100}AssessmentFamilyReferenceType" minOccurs="0"/> * &lt;element name="SectionReference" type="{http://ed-fi.org/0100}SectionReferenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Assessment", propOrder = { "assessmentTitle", "assessmentIdentificationCode", "assessmentCategory", "academicSubject", "gradeLevelAssessed", "lowestGradeLevelAssessed", "assessmentPerformanceLevel", "contentStandard", "assessmentForm", "version", "revisionDate", "maxRawScore", "nomenclature", "assessmentPeriod", "assessmentItemReference", "objectiveAssessmentReference", "assessmentFamilyReference", "sectionReference" }) public class Assessment extends ComplexObjectType { @XmlElement(name = "AssessmentTitle", required = true) protected String assessmentTitle; @XmlElement(name = "AssessmentIdentificationCode", required = true) protected List<AssessmentIdentificationCode> assessmentIdentificationCode; @XmlElement(name = "AssessmentCategory") protected AssessmentCategoryType assessmentCategory; @XmlElement(name = "AcademicSubject") protected AcademicSubjectType academicSubject; @XmlElement(name = "GradeLevelAssessed") protected GradeLevelType gradeLevelAssessed; @XmlElement(name = "LowestGradeLevelAssessed") protected GradeLevelType lowestGradeLevelAssessed; @XmlElement(name = "AssessmentPerformanceLevel") protected List<AssessmentPerformanceLevel> assessmentPerformanceLevel; @XmlElement(name = "ContentStandard") protected ContentStandardType contentStandard; @XmlElement(name = "AssessmentForm") protected String assessmentForm; @XmlElement(name = "Version") protected Integer version; @XmlElement(name = "RevisionDate") @XmlSchemaType(name = "date") protected XMLGregorianCalendar revisionDate; @XmlElement(name = "MaxRawScore") protected Integer maxRawScore; @XmlElement(name = "Nomenclature") protected String nomenclature; @XmlElement(name = "AssessmentPeriod") protected AssessmentPeriodDescriptorType assessmentPeriod; @XmlElement(name = "AssessmentItemReference") protected List<ReferenceType> assessmentItemReference; @XmlElement(name = "ObjectiveAssessmentReference") protected List<ReferenceType> objectiveAssessmentReference; @XmlElement(name = "AssessmentFamilyReference") protected AssessmentFamilyReferenceType assessmentFamilyReference; @XmlElement(name = "SectionReference") protected List<SectionReferenceType> sectionReference; /** * Gets the value of the assessmentTitle property. * * @return * possible object is * {@link String } * */ public String getAssessmentTitle() { return assessmentTitle; } /** * Sets the value of the assessmentTitle property. * * @param value * allowed object is * {@link String } * */ public void setAssessmentTitle(String value) { this.assessmentTitle = value; } /** * Gets the value of the assessmentIdentificationCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the assessmentIdentificationCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAssessmentIdentificationCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AssessmentIdentificationCode } * * */ public List<AssessmentIdentificationCode> getAssessmentIdentificationCode() { if (assessmentIdentificationCode == null) { assessmentIdentificationCode = new ArrayList<AssessmentIdentificationCode>(); } return this.assessmentIdentificationCode; } /** * Gets the value of the assessmentCategory property. * * @return * possible object is * {@link AssessmentCategoryType } * */ public AssessmentCategoryType getAssessmentCategory() { return assessmentCategory; } /** * Sets the value of the assessmentCategory property. * * @param value * allowed object is * {@link AssessmentCategoryType } * */ public void setAssessmentCategory(AssessmentCategoryType value) { this.assessmentCategory = value; } /** * Gets the value of the academicSubject property. * * @return * possible object is * {@link AcademicSubjectType } * */ public AcademicSubjectType getAcademicSubject() { return academicSubject; } /** * Sets the value of the academicSubject property. * * @param value * allowed object is * {@link AcademicSubjectType } * */ public void setAcademicSubject(AcademicSubjectType value) { this.academicSubject = value; } /** * Gets the value of the gradeLevelAssessed property. * * @return * possible object is * {@link GradeLevelType } * */ public GradeLevelType getGradeLevelAssessed() { return gradeLevelAssessed; } /** * Sets the value of the gradeLevelAssessed property. * * @param value * allowed object is * {@link GradeLevelType } * */ public void setGradeLevelAssessed(GradeLevelType value) { this.gradeLevelAssessed = value; } /** * Gets the value of the lowestGradeLevelAssessed property. * * @return * possible object is * {@link GradeLevelType } * */ public GradeLevelType getLowestGradeLevelAssessed() { return lowestGradeLevelAssessed; } /** * Sets the value of the lowestGradeLevelAssessed property. * * @param value * allowed object is * {@link GradeLevelType } * */ public void setLowestGradeLevelAssessed(GradeLevelType value) { this.lowestGradeLevelAssessed = value; } /** * Gets the value of the assessmentPerformanceLevel property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the assessmentPerformanceLevel property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAssessmentPerformanceLevel().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AssessmentPerformanceLevel } * * */ public List<AssessmentPerformanceLevel> getAssessmentPerformanceLevel() { if (assessmentPerformanceLevel == null) { assessmentPerformanceLevel = new ArrayList<AssessmentPerformanceLevel>(); } return this.assessmentPerformanceLevel; } /** * Gets the value of the contentStandard property. * * @return * possible object is * {@link ContentStandardType } * */ public ContentStandardType getContentStandard() { return contentStandard; } /** * Sets the value of the contentStandard property. * * @param value * allowed object is * {@link ContentStandardType } * */ public void setContentStandard(ContentStandardType value) { this.contentStandard = value; } /** * Gets the value of the assessmentForm property. * * @return * possible object is * {@link String } * */ public String getAssessmentForm() { return assessmentForm; } /** * Sets the value of the assessmentForm property. * * @param value * allowed object is * {@link String } * */ public void setAssessmentForm(String value) { this.assessmentForm = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link Integer } * */ public Integer getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link Integer } * */ public void setVersion(Integer value) { this.version = value; } /** * Gets the value of the revisionDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getRevisionDate() { return revisionDate; } /** * Sets the value of the revisionDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRevisionDate(XMLGregorianCalendar value) { this.revisionDate = value; } /** * Gets the value of the maxRawScore property. * * @return * possible object is * {@link Integer } * */ public Integer getMaxRawScore() { return maxRawScore; } /** * Sets the value of the maxRawScore property. * * @param value * allowed object is * {@link Integer } * */ public void setMaxRawScore(Integer value) { this.maxRawScore = value; } /** * Gets the value of the nomenclature property. * * @return * possible object is * {@link String } * */ public String getNomenclature() { return nomenclature; } /** * Sets the value of the nomenclature property. * * @param value * allowed object is * {@link String } * */ public void setNomenclature(String value) { this.nomenclature = value; } /** * Gets the value of the assessmentPeriod property. * * @return * possible object is * {@link AssessmentPeriodDescriptorType } * */ public AssessmentPeriodDescriptorType getAssessmentPeriod() { return assessmentPeriod; } /** * Sets the value of the assessmentPeriod property. * * @param value * allowed object is * {@link AssessmentPeriodDescriptorType } * */ public void setAssessmentPeriod(AssessmentPeriodDescriptorType value) { this.assessmentPeriod = value; } /** * Gets the value of the assessmentItemReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the assessmentItemReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAssessmentItemReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getAssessmentItemReference() { if (assessmentItemReference == null) { assessmentItemReference = new ArrayList<ReferenceType>(); } return this.assessmentItemReference; } /** * Gets the value of the objectiveAssessmentReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the objectiveAssessmentReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getObjectiveAssessmentReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getObjectiveAssessmentReference() { if (objectiveAssessmentReference == null) { objectiveAssessmentReference = new ArrayList<ReferenceType>(); } return this.objectiveAssessmentReference; } /** * Gets the value of the assessmentFamilyReference property. * * @return * possible object is * {@link AssessmentFamilyReferenceType } * */ public AssessmentFamilyReferenceType getAssessmentFamilyReference() { return assessmentFamilyReference; } /** * Sets the value of the assessmentFamilyReference property. * * @param value * allowed object is * {@link AssessmentFamilyReferenceType } * */ public void setAssessmentFamilyReference(AssessmentFamilyReferenceType value) { this.assessmentFamilyReference = value; } /** * Gets the value of the sectionReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the sectionReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSectionReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SectionReferenceType } * * */ public List<SectionReferenceType> getSectionReference() { if (sectionReference == null) { sectionReference = new ArrayList<SectionReferenceType>(); } return this.sectionReference; } }
package org.nd4j.linalg.jblas.complex; import org.nd4j.linalg.api.complex.IComplexDouble; import org.nd4j.linalg.api.complex.IComplexFloat; import org.nd4j.linalg.api.complex.IComplexNumber; import org.nd4j.linalg.factory.Nd4j; /** * Complex float * @author Adam Gibson */ public class ComplexFloat extends org.jblas.ComplexFloat implements IComplexFloat { public final static ComplexFloat UNIT = new ComplexFloat(1,0); public final static ComplexFloat NEG = new ComplexFloat(-1,0); public final static ComplexFloat ZERO = new ComplexFloat(0,0); public ComplexFloat(org.jblas.ComplexFloat c) { super(c.real(),c.imag()); } public ComplexFloat(float real, float imag) { super(real, imag); } public ComplexFloat(float real) { super(real); } @Override public IComplexNumber eqc(IComplexNumber num) { double val = num.realComponent().doubleValue(); double imag = num.imaginaryComponent().doubleValue(); double otherVal = num.realComponent().doubleValue(); double otherImag = num.imaginaryComponent().doubleValue(); if(val == otherVal) return Nd4j.createComplexNumber(1,0); else if(val != otherVal) return Nd4j.createComplexNumber(0,0); else if(imag == otherImag) return Nd4j.createComplexNumber(1,0); else return Nd4j.createComplexNumber(0,0); } @Override public IComplexNumber neqc(IComplexNumber num) { double val = num.realComponent().doubleValue(); double imag = num.imaginaryComponent().doubleValue(); double otherVal = num.realComponent().doubleValue(); double otherImag = num.imaginaryComponent().doubleValue(); if(val != otherVal) return Nd4j.createComplexNumber(1,0); else if(val == otherVal) return Nd4j.createComplexNumber(0,0); else if(imag != otherImag) return Nd4j.createComplexNumber(1,0); else return Nd4j.createComplexNumber(0,0); } @Override public IComplexNumber gt(IComplexNumber num) { double val = num.realComponent().doubleValue(); double imag = num.imaginaryComponent().doubleValue(); double otherVal = num.realComponent().doubleValue(); double otherImag = num.imaginaryComponent().doubleValue(); if(val > otherVal) return Nd4j.createComplexNumber(1,0); else if(val < otherVal) return Nd4j.createComplexNumber(0,0); else if(imag > otherImag) return Nd4j.createComplexNumber(1,0); else return Nd4j.createComplexNumber(0,0); } @Override public IComplexNumber lt(IComplexNumber num) { double val = num.realComponent().doubleValue(); double imag = num.imaginaryComponent().doubleValue(); double otherVal = num.realComponent().doubleValue(); double otherImag = num.imaginaryComponent().doubleValue(); if(val < otherVal) return Nd4j.createComplexNumber(1,0); else if(val > otherVal) return Nd4j.createComplexNumber(0,0); else if(imag < otherImag) return Nd4j.createComplexNumber(1,0); else return Nd4j.createComplexNumber(0,0); } /** * Returns the argument of a complex number. */ @Override public float arg() { return super.arg(); } /** * Return the absolute value */ @Override public float abs() { return super.abs(); } /** * Convert to a double * * @return this complex number as a double */ @Override public IComplexDouble asDouble() { return Nd4j.createDouble(realComponent(), imaginaryComponent()); } /** * Convert to a float * * @return this complex number as a float */ @Override public ComplexFloat asFloat() { return this; } @Override public ComplexFloat dup() { return new ComplexFloat(realComponent(), imaginaryComponent()); } @Override public ComplexFloat conji() { super.set(realComponent(), -imaginaryComponent()); return this; } @Override public ComplexFloat conj() { return dup().conji(); } @Override public IComplexNumber set(Number real, Number imag) { super.set(real.floatValue(),imag.floatValue()); return this; } @Override public IComplexNumber copy(IComplexNumber other) { return null; } /** * Add two complex numbers in-place * * @param c * @param result */ @Override public IComplexNumber addi(IComplexNumber c, IComplexNumber result) { if (this == result) { set(real() + c.realComponent().floatValue(),imag() + result.imaginaryComponent().floatValue()); } else { result.set(result.realComponent().floatValue() + c.realComponent().floatValue(),result.imaginaryComponent().floatValue() + c.imaginaryComponent().floatValue()); } return this; } /** * Add two complex numbers in-place storing the result in this. * * @param c */ @Override public IComplexNumber addi(IComplexNumber c) { return addi(c,this); } /** * Add two complex numbers. * * @param c */ @Override public IComplexNumber add(IComplexNumber c) { return dup().addi(c); } /** * Add a realComponent number to a complex number in-place. * * @param a * @param result */ @Override public IComplexNumber addi(Number a, IComplexNumber result) { if (this == result) { set(real() + a.floatValue(),imag() + a.floatValue()); } else { result.set(result.realComponent().floatValue() + a.floatValue(),imaginaryComponent() + a.floatValue()); } return result; } /** * Add a realComponent number to complex number in-place, storing the result in this. * * @param c */ @Override public IComplexNumber addi(Number c) { return addi(c,this); } /** * Add a realComponent number to a complex number. * * @param c */ @Override public IComplexNumber add(Number c) { return dup().addi(c); } /** * Subtract two complex numbers, in-place * * @param c * @param result */ @Override public IComplexNumber subi(IComplexNumber c, IComplexNumber result) { if (this == result) { set(real() - c.realComponent().floatValue(),imag() - result.imaginaryComponent().floatValue()); } else { result.set(result.realComponent().floatValue() - c.realComponent().floatValue(),result.imaginaryComponent().floatValue() - c.imaginaryComponent().floatValue()); } return this; } @Override public IComplexNumber subi(IComplexNumber c) { return subi(c,this); } /** * Subtract two complex numbers * * @param c */ @Override public IComplexNumber sub(IComplexNumber c) { return dup().subi(c); } @Override public IComplexNumber subi(Number a, IComplexNumber result) { if (this == result) { set(real() - a.floatValue(),imag() - a.floatValue()); } else { result.set(result.realComponent().floatValue() - a.floatValue(),imaginaryComponent().floatValue() - a.floatValue()); } return result; } @Override public IComplexNumber subi(Number a) { return subi(a,this); } @Override public IComplexNumber sub(Number r) { return dup().subi(r); } /** * Multiply two complex numbers, inplace * * @param c * @param result */ @Override public IComplexNumber muli(IComplexNumber c, IComplexNumber result) { float newR = real() * c.realComponent().floatValue() - imag() * c.imaginaryComponent().floatValue(); float newI = real() * c.imaginaryComponent().floatValue() + imag() * c.realComponent().floatValue(); result.set(newR,newI); return result; } @Override public IComplexNumber muli(IComplexNumber c) { return muli(c,this); } /** * Multiply two complex numbers * * @param c */ @Override public IComplexNumber mul(IComplexNumber c) { return dup().muli(c); } @Override public IComplexNumber mul(Number v) { return dup().muli(v); } @Override public IComplexNumber muli(Number v, IComplexNumber result) { if (this == result) { set(real() * v.floatValue(),imag() * v.floatValue()); } else { result.set(result.realComponent().floatValue() * v.floatValue(),imaginaryComponent().floatValue() * v.floatValue()); } return result; } @Override public IComplexNumber muli(Number v) { return muli(v,this); } /** * Divide two complex numbers * * @param c */ @Override public IComplexNumber div(IComplexNumber c) { return dup().divi(c); } /** * Divide two complex numbers, in-place * * @param c * @param result */ @Override public IComplexNumber divi(IComplexNumber c, IComplexNumber result) { float d = c.realComponent().floatValue() * c.realComponent().floatValue() + c.imaginaryComponent().floatValue() * c.imaginaryComponent().floatValue(); float newR = (real() * c.realComponent().floatValue() + imag() * c.imaginaryComponent().floatValue()) / d; float newI = (imag() * c.realComponent().floatValue() - real() * c.imaginaryComponent().floatValue()) / d; result.set(newR,newI); return result; } @Override public IComplexNumber divi(IComplexNumber c) { return divi(c,this); } @Override public IComplexNumber divi(Number v, IComplexNumber result) { if (this == result) { set(real() / v.floatValue(),imag()); } else { result.set(result.realComponent().floatValue() / v.floatValue(),imaginaryComponent()); } return result; } @Override public IComplexNumber divi(Number v) { return divi(v,this); } @Override public IComplexNumber div(Number v) { return dup().divi(v); } @Override public boolean eq(IComplexNumber c) { return false; } @Override public boolean ne(IComplexNumber c) { return false; } @Override public String toString() { return super.toString(); } @Override public org.jblas.ComplexFloat set(float real, float imag) { return super.set(real, imag); } @Override public float real() { return super.real(); } @Override public float imag() { return super.imag(); } @Override public Float realComponent() { return super.real(); } @Override public Float imaginaryComponent() { return super.imag(); } @Override public org.jblas.ComplexFloat copy(org.jblas.ComplexFloat other) { return super.copy(other); } /** * Add two complex numbers in-place * * @param c * @param result */ @Override public org.jblas.ComplexFloat addi(org.jblas.ComplexFloat c, org.jblas.ComplexFloat result) { return super.addi(c, result); } /** * Add two complex numbers in-place storing the result in this. * * @param c */ @Override public org.jblas.ComplexFloat addi(org.jblas.ComplexFloat c) { return super.addi(c); } /** * Add two complex numbers. * * @param c */ @Override public org.jblas.ComplexFloat add(org.jblas.ComplexFloat c) { return super.add(c); } /** * Add a realComponent number to a complex number in-place. * * @param a * @param result */ @Override public org.jblas.ComplexFloat addi(float a, org.jblas.ComplexFloat result) { return super.addi(a, result); } /** * Add a realComponent number to complex number in-place, storing the result in this. * * @param c */ @Override public org.jblas.ComplexFloat addi(float c) { return super.addi(c); } /** * Add a realComponent number to a complex number. * * @param c */ @Override public org.jblas.ComplexFloat add(float c) { return super.add(c); } /** * Subtract two complex numbers, in-place * * @param c * @param result */ @Override public org.jblas.ComplexFloat subi(org.jblas.ComplexFloat c, org.jblas.ComplexFloat result) { return super.subi(c, result); } @Override public org.jblas.ComplexFloat subi(org.jblas.ComplexFloat c) { return super.subi(c); } /** * Subtract two complex numbers * * @param c */ @Override public org.jblas.ComplexFloat sub(org.jblas.ComplexFloat c) { return super.sub(c); } @Override public org.jblas.ComplexFloat subi(float a, org.jblas.ComplexFloat result) { return super.subi(a, result); } @Override public org.jblas.ComplexFloat subi(float a) { return super.subi(a); } @Override public org.jblas.ComplexFloat sub(float r) { return super.sub(r); } /** * Multiply two complex numbers, inplace * * @param c * @param result */ @Override public org.jblas.ComplexFloat muli(org.jblas.ComplexFloat c, org.jblas.ComplexFloat result) { return super.muli(c, result); } @Override public org.jblas.ComplexFloat muli(org.jblas.ComplexFloat c) { return super.muli(c); } /** * Multiply two complex numbers * * @param c */ @Override public org.jblas.ComplexFloat mul(org.jblas.ComplexFloat c) { return super.mul(c); } @Override public org.jblas.ComplexFloat mul(float v) { return super.mul(v); } @Override public org.jblas.ComplexFloat muli(float v, org.jblas.ComplexFloat result) { return super.muli(v, result); } @Override public org.jblas.ComplexFloat muli(float v) { return super.muli(v); } /** * Divide two complex numbers * * @param c */ @Override public ComplexFloat div(org.jblas.ComplexFloat c) { return dup().divi(c); } /** * Divide two complex numbers, in-place * * @param c * @param result */ @Override public org.jblas.ComplexFloat divi(org.jblas.ComplexFloat c, org.jblas.ComplexFloat result) { return super.divi(c, result); } @Override public ComplexFloat divi(org.jblas.ComplexFloat c) { super.divi(c); return this; } @Override public ComplexFloat divi(float v, org.jblas.ComplexFloat result) { super.divi(v, result); return this; } @Override public ComplexFloat divi(float v) { super.divi(v); return this; } @Override public ComplexFloat div(float v) { super.div(v); return this; } /** * Return the absolute value */ @Override public Float absoluteValue() { return super.abs(); } /** * Returns the argument of a complex number. */ @Override public Float complexArgument() { return (float) Math.acos(realComponent()/ absoluteValue()); } @Override public ComplexFloat invi() { float d = realComponent() * realComponent() + imaginaryComponent() * imaginaryComponent(); set(realComponent() / d,-imaginaryComponent() / d); return this; } @Override public ComplexFloat inv() { return dup().invi(); } @Override public ComplexFloat neg() { return dup().negi(); } @Override public ComplexFloat negi() { set(-realComponent(),-imaginaryComponent()); return this; } @Override public ComplexFloat sqrt() { float a = absoluteValue(); float s2 = (float)Math.sqrt(2); float p = (float)Math.sqrt(a + realComponent())/s2; float q = (float)Math.sqrt(a - realComponent())/s2 * Math.signum(imaginaryComponent()); return new ComplexFloat(p, q); } /** * Comparing two floatComplex values. * * @param o */ @Override public boolean equals(Object o) { return super.equals(o); } @Override public boolean eq(org.jblas.ComplexFloat c) { return super.eq(c); } @Override public boolean ne(org.jblas.ComplexFloat c) { return super.ne(c); } @Override public boolean isZero() { return super.isZero(); } @Override public boolean isReal() { return imaginaryComponent() == 0.0; } @Override public boolean isImag() { return realComponent() == 0.0; } }
package org.drools.jpdl; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.drools.jpdl.core.JpdlConnection; import org.drools.jpdl.core.JpdlProcess; import org.drools.jpdl.core.node.Decision; import org.drools.jpdl.core.node.EndState; import org.drools.jpdl.core.node.Fork; import org.drools.jpdl.core.node.Join; import org.drools.jpdl.core.node.JpdlNode; import org.drools.jpdl.core.node.MailNode; import org.drools.jpdl.core.node.ProcessState; import org.drools.jpdl.core.node.StartState; import org.drools.jpdl.core.node.State; import org.drools.jpdl.core.node.TaskNode; import org.drools.process.core.ParameterDefinition; import org.drools.process.core.context.swimlane.Swimlane; import org.drools.process.core.context.swimlane.SwimlaneContext; import org.drools.process.core.datatype.impl.type.StringDataType; import org.drools.process.core.impl.ParameterDefinitionImpl; import org.drools.process.core.validation.ProcessValidationError; import org.drools.workflow.core.Node; import org.jbpm.graph.def.Event; import org.jbpm.graph.def.ExceptionHandler; import org.jbpm.graph.def.ProcessDefinition; import org.jbpm.taskmgmt.def.Task; public class JpdlParser { private static final Set<ParameterDefinition> EMAIL_PARAMETER_DEFINITIONS = new HashSet<ParameterDefinition>(); private static final Pattern MAIL_TEMPLATE_PATTERN = Pattern.compile("<template>(.*)</template>", Pattern.DOTALL); private static final Pattern MAIL_ACTORS_PATTERN = Pattern.compile("<actors>(.*)</actors>", Pattern.DOTALL); private static final Pattern MAIL_TO_PATTERN = Pattern.compile("<to>(.*)</to>", Pattern.DOTALL); private static final Pattern MAIL_SUBJECT_PATTERN = Pattern.compile("<subject>(.*)</subject>", Pattern.DOTALL); private static final Pattern MAIL_TEXT_PATTERN = Pattern.compile("<text>(.*)</text>", Pattern.DOTALL); static { EMAIL_PARAMETER_DEFINITIONS.add(new ParameterDefinitionImpl("From", new StringDataType())); EMAIL_PARAMETER_DEFINITIONS.add(new ParameterDefinitionImpl("To", new StringDataType())); EMAIL_PARAMETER_DEFINITIONS.add(new ParameterDefinitionImpl("Subject", new StringDataType())); EMAIL_PARAMETER_DEFINITIONS.add(new ParameterDefinitionImpl("Text", new StringDataType())); } private ProcessValidationError[] errors; public JpdlProcess loadJpdlProcess(String name) { org.jbpm.graph.def.ProcessDefinition processDefinition = org.jbpm.graph.def.ProcessDefinition.parseXmlResource(name); return loadJpdlProcess(processDefinition); } public JpdlProcess loadJpdlProcess(org.jbpm.graph.def.ProcessDefinition processDefinition) { JpdlProcess process = new JpdlProcess(); process.setId(processDefinition.getName()); process.setName(processDefinition.getName()); process.setPackageName("org.drools"); SwimlaneContext swimlaneContext = new SwimlaneContext(); process.addContext(swimlaneContext); process.setDefaultContext(swimlaneContext); org.jbpm.graph.def.Node startState = processDefinition.getStartState(); String startStateName = startState == null ? null : startState.getName(); List<org.jbpm.graph.def.Node> nodes = processDefinition.getNodes(); int nodeId = 0; Map<org.jbpm.graph.def.Node, Node> mapping = new HashMap<org.jbpm.graph.def.Node, Node>(); for (org.jbpm.graph.def.Node jPDLnode: nodes) { JpdlNode node = null; if (jPDLnode instanceof org.jbpm.graph.node.StartState) { node = new StartState(); } else if (jPDLnode instanceof org.jbpm.graph.node.EndState) { node = new EndState(); } else if (org.jbpm.graph.def.Node.class.equals(jPDLnode.getClass())) { JpdlNode newNode = new JpdlNode(); setDefaultNodeProperties(jPDLnode, newNode); node = newNode; } else if (jPDLnode instanceof org.jbpm.graph.node.Fork) { org.jbpm.graph.node.Fork jPDLfork = (org.jbpm.graph.node.Fork) jPDLnode; Fork newNode = new Fork(); newNode.setScript(jPDLfork.getScript()); node = newNode; } else if (jPDLnode instanceof org.jbpm.graph.node.Join) { org.jbpm.graph.node.Join jPDLjoin = (org.jbpm.graph.node.Join) jPDLnode; Join newNode = new Join(); newNode.setDiscriminator(jPDLjoin.isDiscriminator()); newNode.setTokenNames(jPDLjoin.getTokenNames()); newNode.setScript(jPDLjoin.getScript()); newNode.setNOutOfM(jPDLjoin.getNOutOfM()); node = newNode; } else if (jPDLnode instanceof org.jbpm.graph.node.MailNode) { String config = jPDLnode.getAction().getActionDelegation().getConfiguration(); MailNode newNode = new MailNode(); Matcher matcher = MAIL_TEMPLATE_PATTERN.matcher(config); if (matcher.find()) { newNode.setTemplate(matcher.group(1)); } matcher = MAIL_ACTORS_PATTERN.matcher(config); if (matcher.find()) { newNode.setActors(matcher.group(1)); } matcher = MAIL_TO_PATTERN.matcher(config); if (matcher.find()) { newNode.setTo(matcher.group(1)); } matcher = MAIL_SUBJECT_PATTERN.matcher(config); if (matcher.find()) { newNode.setSubject(matcher.group(1)); } matcher = MAIL_TEXT_PATTERN.matcher(config); if (matcher.find()) { newNode.setText(matcher.group(1)); } node = newNode; } else if (jPDLnode instanceof org.jbpm.graph.node.Decision) { org.jbpm.graph.node.Decision jPDLdecision = (org.jbpm.graph.node.Decision) jPDLnode; Decision newNode = new Decision(); newNode.setDecisionConditions(jPDLdecision.getDecisionConditions()); // TODO: unable to access decisionDelegation // TODO: unable to access decisionExpression node = newNode; } else if (jPDLnode instanceof org.jbpm.graph.node.ProcessState) { org.jbpm.graph.node.ProcessState jPDLprocessState = (org.jbpm.graph.node.ProcessState) jPDLnode; ProcessState newNode = new ProcessState(); ProcessDefinition subProcessDefinition = jPDLprocessState.getSubProcessDefinition(); if (subProcessDefinition != null) { newNode.setSubProcessName(subProcessDefinition.getName()); // TODO: parse sub process definition as well } // TODO: unable to access subProcessName // TODO: unable to access variableAccesses node = newNode; } else if (jPDLnode instanceof org.jbpm.graph.node.TaskNode) { org.jbpm.graph.node.TaskNode jPDLtaskNode = (org.jbpm.graph.node.TaskNode) jPDLnode; TaskNode newNode = new TaskNode(); Set<Task> tasks = jPDLtaskNode.getTasks(); newNode.setTasks(tasks); newNode.setSignal(jPDLtaskNode.getSignal()); newNode.setCreateTasks(jPDLtaskNode.getCreateTasks()); newNode.setEndTasks(jPDLtaskNode.isEndTasks()); for (Task task: tasks) { org.jbpm.taskmgmt.def.Swimlane jPDLswimlane = task.getSwimlane(); if (jPDLswimlane != null) { String swimlaneName = jPDLswimlane.getName(); if (swimlaneContext.getSwimlane(swimlaneName) == null) { Swimlane swimlane = new Swimlane(); swimlane.setName(swimlaneName); swimlane.setActorId(jPDLswimlane.getActorIdExpression()); // TODO support other types of actor expressions as well swimlaneContext.addSwimlane(swimlane); } } } node = newNode; } else if (jPDLnode instanceof org.jbpm.graph.node.State) { node = new State(); } if (node == null) { throw new IllegalArgumentException( "Unknown node type: " + jPDLnode.getClass().getName() + " " + jPDLnode); } setDefaultNodeProperties(jPDLnode, (JpdlNode) node); node.setId(++nodeId); mapping.put(jPDLnode, node); process.addNode(node); if (startStateName != null && startStateName.equals(node.getName())) { process.setStartState(node); } } for (Map.Entry<org.jbpm.graph.def.Node, Node> entry: mapping.entrySet()) { List<org.jbpm.graph.def.Transition> leavingTransitions = (List<org.jbpm.graph.def.Transition>) entry.getKey().getLeavingTransitions(); if (leavingTransitions != null) { for (org.jbpm.graph.def.Transition transition: leavingTransitions) { Node from = mapping.get(transition.getFrom()); Node to = mapping.get(transition.getTo()); String transitionName = transition.getName(); if (transitionName == null) { transitionName = Node.CONNECTION_DEFAULT_TYPE; } // TODO: transition condition, events and exception handlers JpdlConnection connection = new JpdlConnection(from, transitionName, to, Node.CONNECTION_DEFAULT_TYPE); Map<String, Event> events = transition.getEvents(); if (events != null) { for (Event event: events.values()) { connection.addEvent(event); } } List<ExceptionHandler> exceptionHandlers = transition.getExceptionHandlers(); if (exceptionHandlers != null) { for (ExceptionHandler exceptionHandler: exceptionHandlers) { connection.addExceptionHandler(exceptionHandler); } } connection.setCondition(transition.getCondition()); } } } errors = JpdlProcessValidator.getInstance().validateProcess(process); return process; } private void setDefaultNodeProperties(org.jbpm.graph.def.Node jPDLnode, JpdlNode newNode) { newNode.setName(jPDLnode.getName()); newNode.setAction(jPDLnode.getAction()); Map<String, Event> events = jPDLnode.getEvents(); if (events != null) { for (Event event: events.values()) { newNode.addEvent(event); // TODO: extract timer actions and replace by our timer framework } } List<ExceptionHandler> exceptionHandlers = jPDLnode.getExceptionHandlers(); if (exceptionHandlers != null) { for (ExceptionHandler exceptionHandler: exceptionHandlers) { newNode.addExceptionHandler(exceptionHandler); } } } public ProcessValidationError[] getErrors() { return this.errors; } }
/* * Java Portable Network Graphics Library * (C) Copyright 2013-2014 Tag Dynamics, LLC (http://tagdynamics.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tagdynamics.png.chunk.types.sBIT; import com.tagdynamics.png.api.IMutableChunk; import com.tagdynamics.png.chunk.AbstractChunk; import com.tagdynamics.png.chunk.types.IHDR.ColorType; public class sBITChunk extends AbstractChunk { private int significantGrayscaleBits; private int significantTruecolorIndexedColorRedBits; private int significantTruecolorIndexedColorGreenBits; private int significantTruecolorIndexedColorBlueBits; private int significantGrayscaleAlphaGrayscaleBits; private int significantGrayscaleAlphaAlphaBits; private int significantTruecolorAlphaRedBits; private int significantTruecolorAlphaGreenBits; private int significantTruecolorAlphaBlueBits; private int significantTruecolorAlphaAlphaBits; public sBITChunk(ColorType colorType, IMutableChunk chunk) { super(colorType, chunk); } @Override protected void processChunk() { switch (colorType) { case Grayscale: significantGrayscaleBits = chunk.getByte(0); break; case Truecolor: case IndexedColor: significantTruecolorIndexedColorRedBits = chunk.getByte(0); significantTruecolorIndexedColorGreenBits = chunk.getByte(1); significantTruecolorIndexedColorBlueBits = chunk.getByte(2); break; case GrayscaleAlpha: significantGrayscaleAlphaGrayscaleBits = chunk.getByte(0); significantGrayscaleAlphaAlphaBits = chunk.getByte(1); break; case TruecolorAlpha: significantTruecolorAlphaRedBits = chunk.getByte(0); significantTruecolorAlphaGreenBits = chunk.getByte(1); significantTruecolorAlphaBlueBits = chunk.getByte(2); significantTruecolorAlphaAlphaBits = chunk.getByte(3); break; } } public int getSignificantGrayscaleBits() { return significantGrayscaleBits; } public void setSignificantGrayscaleBits(int significantGrayscaleBits) { this.significantGrayscaleBits = significantGrayscaleBits; } public int getSignificantTruecolorIndexedColorRedBits() { return significantTruecolorIndexedColorRedBits; } public void setSignificantTruecolorIndexedColorRedBits(int significantTruecolorIndexedColorRedBits) { this.significantTruecolorIndexedColorRedBits = significantTruecolorIndexedColorRedBits; } public int getSignificantTruecolorIndexedColorGreenBits() { return significantTruecolorIndexedColorGreenBits; } public void setSignificantTruecolorIndexedColorGreenBits(int significantTruecolorIndexedColorGreenBits) { this.significantTruecolorIndexedColorGreenBits = significantTruecolorIndexedColorGreenBits; } public int getSignificantTruecolorIndexedColorBlueBits() { return significantTruecolorIndexedColorBlueBits; } public void setSignificantTruecolorIndexedColorBlueBits(int significantTruecolorIndexedColorBlueBits) { this.significantTruecolorIndexedColorBlueBits = significantTruecolorIndexedColorBlueBits; } public int getSignificantGrayscaleAlphaGrayscaleBits() { return significantGrayscaleAlphaGrayscaleBits; } public void setSignificantGrayscaleAlphaGrayscaleBits(int significantGrayscaleAlphaGrayscaleBits) { this.significantGrayscaleAlphaGrayscaleBits = significantGrayscaleAlphaGrayscaleBits; } public int getSignificantGrayscaleAlphaAlphaBits() { return significantGrayscaleAlphaAlphaBits; } public void setSignificantGrayscaleAlphaAlphaBits(int significantGrayscaleAlphaAlphaBits) { this.significantGrayscaleAlphaAlphaBits = significantGrayscaleAlphaAlphaBits; } public int getSignificantTruecolorAlphaRedBits() { return significantTruecolorAlphaRedBits; } public void setSignificantTruecolorAlphaRedBits(int significantTruecolorAlphaRedBits) { this.significantTruecolorAlphaRedBits = significantTruecolorAlphaRedBits; } public int getSignificantTruecolorAlphaGreenBits() { return significantTruecolorAlphaGreenBits; } public void setSignificantTruecolorAlphaGreenBits(int significantTruecolorAlphaGreenBits) { this.significantTruecolorAlphaGreenBits = significantTruecolorAlphaGreenBits; } public int getSignificantTruecolorAlphaBlueBits() { return significantTruecolorAlphaBlueBits; } public void setSignificantTruecolorAlphaBlueBits(int significantTruecolorAlphaBlueBits) { this.significantTruecolorAlphaBlueBits = significantTruecolorAlphaBlueBits; } public int getSignificantTruecolorAlphaAlphaBits() { return significantTruecolorAlphaAlphaBits; } public void setSignificantTruecolorAlphaAlphaBits(int significantTruecolorAlphaAlphaBits) { this.significantTruecolorAlphaAlphaBits = significantTruecolorAlphaAlphaBits; } @Override public String toString() { StringBuffer buf = new StringBuffer("sBITChunk{"); buf.append("colorType=" + colorType.toString()); switch (colorType) { case Grayscale: buf.append(", significantGrayscaleBits=").append(significantGrayscaleBits); significantGrayscaleBits = chunk.getByte(0); break; case Truecolor: case IndexedColor: buf.append(", significantTruecolorIndexedColorRedBits=").append(significantTruecolorIndexedColorRedBits); buf.append(", significantTruecolorIndexedColorGreenBits=").append(significantTruecolorIndexedColorGreenBits); buf.append(", significantTruecolorIndexedColorBlueBits=").append(significantTruecolorIndexedColorBlueBits); break; case GrayscaleAlpha: buf.append(", significantGrayscaleAlphaGrayscaleBits=").append(significantGrayscaleAlphaGrayscaleBits); buf.append(", significantGrayscaleAlphaAlphaBits=").append(significantGrayscaleAlphaAlphaBits); break; case TruecolorAlpha: buf.append(", significantTruecolorAlphaRedBits=").append(significantTruecolorAlphaRedBits); buf.append(", significantTruecolorAlphaGreenBits=").append(significantTruecolorAlphaGreenBits); buf.append(", significantTruecolorAlphaBlueBits=").append(significantTruecolorAlphaBlueBits); buf.append(", significantTruecolorAlphaAlphaBits=").append(significantTruecolorAlphaAlphaBits); break; } buf.append("}"); return buf.toString(); } }
/** * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.google.api.calendar; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.springframework.social.google.api.AbstractGoogleApiTest; import org.springframework.social.google.api.calendar.Event.DateTimeTimezone; import org.springframework.util.StreamUtils; /** * Tests to verify that the Event JSON is correctly updated through the Event class. * @author Martin Wink */ public class EventModificationTests extends AbstractGoogleApiTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); private File originalFile; private File newFile; private ObjectMapper mapper; private Event event; @Before public void createTestData() throws IOException { originalFile = jsonResource("pre_modification_event").getFile(); newFile = folder.newFile(); mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // kind etc not used in Event. mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // So output matches expected formatting. event = mapper.readValue(originalFile, Event.class); } @After public void cleanUp() { } private String loadFileToString(final File file) throws IOException { return StreamUtils.copyToString(new FileInputStream(file), Charset.defaultCharset()); } private String loadJsonResourceToString(final String name) throws IOException, JSONException { return normalizeJsonObjectLineFeeds(loadFileToString(jsonResource(name).getFile())); } @Test public void verify_unmodified() throws IOException, JSONException { mapper.writeValue(newFile, event); assertEquals(loadJsonResourceToString("post_unmodified_event"), normalizeJsonObjectLineFeeds(loadFileToString(newFile))); } @Test public void set_null_values() throws IOException, JSONException { event.setGuestsCanInviteOthers(null); assertEquals(null, event.isGuestsCanInviteOthers()); event.setGuestsCanSeeOtherGuests(null); assertEquals(null, event.isGuestsCanSeeOtherGuests()); event.setLocation(null); assertEquals(null, event.getLocation()); event.setStatus(null); assertEquals(null, event.getStatus()); event.setSummary(null); assertEquals(null, event.getSummary()); final DateTimeTimezone start = event.getStart(); start.setDate(null); assertNull(start.getDate()); start.setDateTime(null); assertNull(start.getDateTime()); start.setTimeZone(null); assertNull(start.getTimeZone()); final DateTimeTimezone end = event.getEnd(); end.setDate(null); assertNull(end.getDate()); end.setDateTime(null); assertNull(end.getDateTime()); end.setTimeZone(null); assertNull(end.getTimeZone()); event.setRecurrence(null); assertNull(event.getRecurrence()); mapper.writeValue(newFile, event); assertEquals(loadJsonResourceToString("post_null_values_event"), normalizeJsonObjectLineFeeds(loadFileToString(newFile))); } @Test public void set_non_null_values_1() throws IOException, JSONException { event.setGuestsCanInviteOthers(true); assertEquals(true, event.isGuestsCanInviteOthers()); event.setGuestsCanSeeOtherGuests(false); assertEquals(false, event.isGuestsCanSeeOtherGuests()); event.setLocation("Somewhere else"); assertEquals("Somewhere else", event.getLocation()); event.setStatus(EventStatus.CANCELLED); assertEquals(EventStatus.CANCELLED, event.getStatus()); event.setSummary("New summary"); assertEquals("New summary", event.getSummary()); final DateTimeTimezone start = event.getStart(); final Date date1 = DateUtils.makeDate(2014, 11, 27); start.setDate(date1); assertEquals(date1, start.getDate()); final Date date2 = DateUtils.makeDate(2014, 11, 28); start.setDateTime(date2); assertEquals(date2, start.getDateTime()); final TimeZone timeZone1 = TimeZone.getTimeZone("UTC"); start.setTimeZone(timeZone1); assertEquals(timeZone1, start.getTimeZone()); final DateTimeTimezone end = event.getEnd(); final Date date3 = DateUtils.makeDate(2014, 11, 29); end.setDate(date3); assertEquals(date3, end.getDate()); final Date date4 = DateUtils.makeDate(2014, 11, 30); end.setDateTime(date4); assertEquals(date4, end.getDateTime()); final TimeZone timeZone2 = TimeZone.getTimeZone("PST"); end.setTimeZone(timeZone2); assertEquals(timeZone2, end.getTimeZone()); event.setRecurrence(new ArrayList<>()); assertNotNull(event.getRecurrence()); assertEquals(0, event.getRecurrence().size()); mapper.writeValue(newFile, event); assertEquals(loadJsonResourceToString("post_non_null_values_1_event"), normalizeJsonObjectLineFeeds(loadFileToString(newFile))); } @Test public void set_non_null_values_2() throws IOException, JSONException { event.setGuestsCanInviteOthers(false); assertEquals(false, event.isGuestsCanInviteOthers()); event.setGuestsCanSeeOtherGuests(true); assertEquals(true, event.isGuestsCanSeeOtherGuests()); event.setLocation("Another place"); assertEquals("Another place", event.getLocation()); event.setStatus(EventStatus.TENTATIVE); assertEquals(EventStatus.TENTATIVE, event.getStatus()); event.setSummary("Another title"); assertEquals("Another title", event.getSummary()); final DateTimeTimezone start = event.getStart(); final Date date1 = DateUtils.makeDate(2013, 11, 27); start.setDate(date1); assertEquals(date1, start.getDate()); final Date date2 = DateUtils.makeDate(2013, 11, 28); start.setDateTime(date2); assertEquals(date2, start.getDateTime()); final TimeZone timeZone1 = TimeZone.getTimeZone("CET"); start.setTimeZone(timeZone1); assertEquals(timeZone1, start.getTimeZone()); final DateTimeTimezone end = event.getEnd(); final Date date3 = DateUtils.makeDate(2013, 11, 29); end.setDate(date3); assertEquals(date3, end.getDate()); final Date date4 = DateUtils.makeDate(2013, 11, 30); end.setDateTime(date4); assertEquals(date4, end.getDateTime()); final TimeZone timeZone2 = TimeZone.getTimeZone("MST"); end.setTimeZone(timeZone2); assertEquals(timeZone2, end.getTimeZone()); final ArrayList<String> list = new ArrayList<>(); list.add("RRULE:FREQ=MONTHLY;INTERVAL=1"); list.add("RRULE:FREQ=MONTHLY;INTERVAL=3"); event.setRecurrence(list); assertNotNull(event.getRecurrence()); assertEquals(2, event.getRecurrence().size()); mapper.writeValue(newFile, event); assertEquals(loadJsonResourceToString("post_non_null_values_2_event"), normalizeJsonObjectLineFeeds(loadFileToString(newFile))); } }
/* * Copyright 2013 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 kg.delletenebre.serialmanager.Preferences; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.Preference; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.util.AttributeSet; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import kg.delletenebre.serialmanager.R; /** * A preference that allows the user to choose an application or shortcut. */ public class AppChooserPreference extends Preference { private boolean mAllowUseDefault = false; private String value; public AppChooserPreference(Context context, AttributeSet attrs) { super(context, attrs); initAttrs(attrs, 0); } public AppChooserPreference(Context context) { super(context); initAttrs(null, 0); } public AppChooserPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initAttrs(attrs, defStyle); } private void initAttrs(AttributeSet attrs, int defStyle) { TypedArray a = getContext().getTheme().obtainStyledAttributes( attrs, R.styleable.AppChooserPreference, defStyle, defStyle); try { mAllowUseDefault = a.getBoolean(R.styleable.AppChooserPreference_allowUseDefault, true); } finally { a.recycle(); } } public void setIntentValue(Intent intent) { setValue(intent == null ? "" : intent.toUri(Intent.URI_INTENT_SCHEME)); } public void setValue(String value) { if (callChangeListener(value)) { this.value = value; persistString(value); notifyChanged(); } } public String getValue() { return value; } public static Intent getIntentValue(String value, Intent defaultIntent) { try { if (TextUtils.isEmpty(value)) { return defaultIntent; } return Intent.parseUri(value, Intent.URI_INTENT_SCHEME); } catch (URISyntaxException e) { return defaultIntent; } } public static CharSequence getDisplayValue(Context context, String value) { if (TextUtils.isEmpty(value)) { return context.getString(R.string.pref_shortcut_default); } Intent intent; try { intent = Intent.parseUri(value, Intent.URI_INTENT_SCHEME); } catch (URISyntaxException e) { return context.getString(R.string.pref_shortcut_default); } PackageManager pm = context.getPackageManager(); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); if (resolveInfos.isEmpty()) { return null; } StringBuilder label = new StringBuilder(); label.append(resolveInfos.get(0).loadLabel(pm)); if (intent.getData() != null && intent.getData().getScheme() != null && intent.getData().getScheme().startsWith("http")) { label.append(": ").append(intent.getDataString()); } return label; } @Override protected void onClick() { super.onClick(); AppChooserDialogFragment fragment = AppChooserDialogFragment.newInstance(); fragment.setPreference(this); Activity activity = (Activity) getContext(); activity.getFragmentManager().beginTransaction() .add(fragment, getFragmentTag()) .commit(); } @Override protected void onAttachedToActivity() { super.onAttachedToActivity(); Activity activity = (Activity) getContext(); AppChooserDialogFragment fragment = (AppChooserDialogFragment) activity .getFragmentManager().findFragmentByTag(getFragmentTag()); if (fragment != null) { // re-bind preference to fragment fragment.setPreference(this); } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getString(index); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedString("") : (String) defaultValue); } public String getFragmentTag() { return "app_chooser_" + getKey(); } public static class AppChooserDialogFragment extends DialogFragment { public static int REQUEST_CREATE_SHORTCUT = 1; private AppChooserPreference mPreference; private ActivityListAdapter mAppsAdapter; private ActivityListAdapter mShortcutsAdapter; private ListView mAppsList; private ListView mShortcutsList; public AppChooserDialogFragment() { } public static AppChooserDialogFragment newInstance() { return new AppChooserDialogFragment(); } public void setPreference(AppChooserPreference preference) { mPreference = preference; tryBindLists(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); tryBindLists(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Force Holo Light since ?android:actionBarXX would use dark action bar Context layoutContext = new ContextThemeWrapper(getActivity(), R.style.Theme_Dialog); LayoutInflater layoutInflater = LayoutInflater.from(layoutContext); View rootView = layoutInflater.inflate(R.layout.dialog_app_chooser, null); final ViewGroup tabWidget = (ViewGroup) rootView.findViewById(android.R.id.tabs); final ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager); pager.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics())); SimplePagedTabsHelper helper = new SimplePagedTabsHelper(layoutContext, tabWidget, pager); helper.addTab(R.string.title_apps, R.id.apps_list); helper.addTab(R.string.title_shortcuts, R.id.shortcuts_list); // Set up apps mAppsList = (ListView) rootView.findViewById(R.id.apps_list); mAppsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> listView, View view, int position, long itemId) { Intent intent = mAppsAdapter.getIntent(position); if (intent != null) { intent = Intent.makeMainActivity(intent.getComponent()); } mPreference.setIntentValue(intent); dismiss(); } }); // Set up shortcuts mShortcutsList = (ListView) rootView.findViewById(R.id.shortcuts_list); mShortcutsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> listView, View view, int position, long itemId) { startActivityForResult(mShortcutsAdapter.getIntent(position), REQUEST_CREATE_SHORTCUT); } }); tryBindLists(); return new AlertDialog.Builder(getActivity()) .setView(rootView) .create(); } private void tryBindLists() { if (mPreference == null) { return; } if (isAdded() && mAppsAdapter == null && mShortcutsAdapter == null) { mAppsAdapter = new ActivityListAdapter( new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER), mPreference.mAllowUseDefault); mShortcutsAdapter = new ActivityListAdapter( new Intent(Intent.ACTION_CREATE_SHORTCUT) .addCategory(Intent.CATEGORY_DEFAULT), false); } if (mAppsAdapter != null && mAppsList != null && mShortcutsAdapter != null && mShortcutsList != null) { mAppsList.setAdapter(mAppsAdapter); mShortcutsList.setAdapter(mShortcutsAdapter); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CREATE_SHORTCUT && resultCode == Activity.RESULT_OK) { mPreference.setIntentValue( (Intent) data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT)); dismiss(); } } static class ActivityInfo { CharSequence label; Drawable icon; ComponentName componentName; } private class ActivityListAdapter extends BaseAdapter { private Intent mQueryIntent; private PackageManager mPackageManager; private List<ActivityInfo> mInfos; private boolean mAllowUseDefault; private ActivityListAdapter(Intent queryIntent, boolean allowUseDefault) { mQueryIntent = queryIntent; mPackageManager = getActivity().getPackageManager(); mAllowUseDefault = allowUseDefault; mInfos = new ArrayList<>(); List<ResolveInfo> resolveInfos = mPackageManager.queryIntentActivities(queryIntent, 0); for (ResolveInfo ri : resolveInfos) { ActivityInfo ai = new ActivityInfo(); ai.icon = ri.loadIcon(mPackageManager); ai.label = ri.loadLabel(mPackageManager); ai.componentName = new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name); mInfos.add(ai); } Collections.sort(mInfos, new Comparator<ActivityInfo>() { @Override public int compare(ActivityInfo activityInfo, ActivityInfo activityInfo2) { return activityInfo.label.toString().compareTo( activityInfo2.label.toString()); } }); } @Override public int getCount() { return mInfos.size() + (mAllowUseDefault ? 1 : 0); } @Override public Object getItem(int position) { if (mAllowUseDefault && position == 0) { return null; } return mInfos.get(position - (mAllowUseDefault ? 1 : 0)); } public Intent getIntent(int position) { if (mAllowUseDefault && position == 0) { return null; } return new Intent(mQueryIntent) .setComponent(mInfos.get(position - (mAllowUseDefault ? 1 : 0)) .componentName); } @Override public long getItemId(int position) { if (mAllowUseDefault && position == 0) { return -1; } return mInfos.get(position - (mAllowUseDefault ? 1 : 0)).componentName.hashCode(); } @Override public View getView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = LayoutInflater.from(getActivity()) .inflate(R.layout.list_item_intent, container, false); } if (mAllowUseDefault && position == 0) { ((TextView) convertView.findViewById(android.R.id.text1)) .setText(getString(R.string.pref_shortcut_default)); ((ImageView) convertView.findViewById(android.R.id.icon)) .setImageDrawable(null); } else { ActivityInfo ai = mInfos.get(position - (mAllowUseDefault ? 1 : 0)); ((TextView) convertView.findViewById(android.R.id.text1)) .setText(ai.label); ((ImageView) convertView.findViewById(android.R.id.icon)) .setImageDrawable(ai.icon); } return convertView; } } } }
package jepperscore.scraper.callofduty; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.IOUtils; /** * This main class installs the scraper's dependencies. * * @author Chuck * */ public class InstallMain { /** * Specifies Call of Duty's install directory. */ private static final String COD_DIRECTORY_ARG = "d"; /** * Specifies the version of Call of Duty. */ private static final String COD_VERSION_ARG = "v"; /** * Specifies the mod to install for. */ private static final String MOD_ARG = "m"; /** * Specifies the .cfg file to output to. */ private static final String CONFIG_FILENAME_ARG = "o"; /** * The path of the config in the JAR. */ private static final String CONFIG_RES_PATH = "/stats.cfg"; /** * The main function. * * @param args * See option setup. * @throws ParseException * Exception throw from parsing problems. */ public static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption(COD_DIRECTORY_ARG, true, "Specifies Call of Duty's install directory."); options.addOption(COD_VERSION_ARG, true, "Specifies the version of Call of Duty. Values: " + CoDConstants.SUPPORTED_VERSIONS); options.addOption(MOD_ARG, true, "Specifies the mod to install for."); options.addOption(CONFIG_FILENAME_ARG, true, "Specifies the .cfg file to output to."); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (!cmd.hasOption(COD_DIRECTORY_ARG)) { throw new RuntimeException( "Incorrect arguments! Need -d [COD Install Directory] {-v [COD Version]} {-m [COD Mod]} {-o [Output Cfg Filename]}"); } File baseDirectory = new File(cmd.getOptionValue(COD_DIRECTORY_ARG)); if (!baseDirectory.exists()) { throw new RuntimeException("Directory does not exist: " + baseDirectory.getAbsolutePath()); } CodVersion version = CodVersion.Unknown; File windowsExecutable = null; File linuxExecutable = null; if (!cmd.hasOption(COD_VERSION_ARG)) { for (String file : baseDirectory.list()) { switch (file) { case "iw3mp.exe": version = CodVersion.COD4; windowsExecutable = new File(baseDirectory, file); break; case "cod4_lnxded": version = CodVersion.COD4; linuxExecutable = new File(baseDirectory, file); break; default: break; } if (version != CodVersion.Unknown) { break; } } } else { version = CodVersion.valueOf(cmd.getOptionValue(COD_VERSION_ARG)); } if (version == CodVersion.Unknown) { throw new RuntimeException( "Unable to detect Call of Duty version, supported versions are: " + CoDConstants.SUPPORTED_VERSIONS); } File configDirectory; if (!cmd.hasOption(MOD_ARG)) { configDirectory = new File(baseDirectory, "main"); } else { configDirectory = new File(baseDirectory, "Mods" + File.separator + cmd.getOptionValue(MOD_ARG)); } if (!configDirectory.exists()) { throw new RuntimeException( "Could not find configuration directory: " + configDirectory.getAbsolutePath()); } File configFile = new File(configDirectory, cmd.getOptionValue( CONFIG_FILENAME_ARG, "stats.cfg")); System.out.println("Installing Server Config (" + configFile.getAbsolutePath() + ")..."); InputStream configIn = null; FileOutputStream configOut = null; try { configIn = InstallMain.class.getResourceAsStream(CONFIG_RES_PATH); configOut = new FileOutputStream(configFile); IOUtils.copy(configIn, configOut); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(configOut); IOUtils.closeQuietly(configIn); } String defaultArgs; switch (version) { case COD4: defaultArgs = " +set g_gametype dm +map mp_showdown"; break; default: defaultArgs = ""; break; } if (windowsExecutable != null) { File batchScript = new File(baseDirectory, "start" + cmd.getOptionValue(MOD_ARG, "") + "ServerWithStats.bat"); if (batchScript.exists()) { System.out.println("Skipping creation of batch script (" + batchScript.getName() + "), file exists..."); } else { PrintStream scriptWriter = null; try { scriptWriter = new PrintStream(batchScript, "UTF-8"); scriptWriter.println("@echo off"); scriptWriter.println(windowsExecutable.getName() + " +exec stats.cfg +set dedicated 1" + defaultArgs + (cmd.hasOption(MOD_ARG) ? " +set fs_game Mods/" + cmd.getOptionValue(MOD_ARG) : "")); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(scriptWriter); } System.out.println("Wrote Windows server start up script: " + batchScript.getName()); } } if (linuxExecutable != null) { File shScript = new File(baseDirectory, "start" + cmd.getOptionValue(MOD_ARG, "") + "ServerWithStats.sh"); if (shScript.exists()) { System.out.println("Skipping creation of bash script (" + shScript.getName() + "), file exists..."); } else { PrintStream scriptWriter = null; try { scriptWriter = new PrintStream(shScript, "UTF-8"); scriptWriter.println("#!/bin/bash"); scriptWriter.println(linuxExecutable.getName() + " +exec stats.cfg +set dedicated 1" + defaultArgs + (cmd.hasOption(MOD_ARG) ? " +set fs_game Mods/" + cmd.getOptionValue(MOD_ARG) : "")); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(scriptWriter); } System.out.println("Wrote Linux server start up script: " + shScript.getName()); } } System.out.println("Done!"); } }
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.widget.NumberPicker; import android.widget.TextView; import java.util.ArrayList; import java.util.Calendar; import mynamespace.R; /** * AlertDialog.Builder for a TimePicker dialog that supports * a margin, minimum time and custom time increases */ public class CustomizableTimeMarginDialog extends AlertDialog.Builder implements NumberPicker.OnValueChangeListener{ /** * Separate custom view for AlertDialog title */ private View titleView; /** * NumberPickers for hour, minutes and margin */ private NumberPicker pickerHour, pickerMinutes, pickerMargin; /** * Values for all three NumberPickers */ private NumberPickerValues hours, minutes, margins; /** * Minimum possible time, saved separately as hour and minutes */ private int minHour, minMinutes; public CustomizableTimeMarginDialog(Context context) { super(context); } public CustomizableTimeMarginDialog(Context context, int theme) { super(context, theme); } /** * Create this dialog * @param min can be null * @param selected * @param margin * @param listener * @param hours * @param minutes * @param margins */ public void create(Calendar min, Calendar selected, int margin, final OnTimeMarginSetListener listener, NumberPickerValues hours, final NumberPickerValues minutes, NumberPickerValues margins) { //inflate layout LayoutInflater inflater = LayoutInflater.from(getContext()); View dialogLayout = inflater.inflate(R.layout.view_dialog_margintime, null); titleView = inflater.inflate(R.layout.view_title_margintime, null); pickerHour = (NumberPicker) dialogLayout.findViewById(R.id.picker_hour); pickerMinutes = (NumberPicker) dialogLayout.findViewById(R.id.picker_minutes); pickerMargin = (NumberPicker) dialogLayout.findViewById(R.id.picker_margin); this.hours = hours; this.minutes = minutes; this.margins = margins; //if no minimum time given, set it to 00:00 if(min == null){ min = Calendar.getInstance(); min.set(Calendar.HOUR_OF_DAY, 0); min.set(Calendar.MINUTE, 0); } //save minimum time minHour = min.get(Calendar.HOUR_OF_DAY); minMinutes = min.get(Calendar.MINUTE); //initialize NumberPicker values initPicker(pickerHour, this.hours, selected.get(Calendar.HOUR_OF_DAY)); initPicker(pickerMinutes, this.minutes, selected.get(Calendar.MINUTE)); initPicker(pickerMargin, this.margins, margin); pickerMargin.setWrapSelectorWheel(false); //initialize NumberPicker listeners pickerHour.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker numberPicker, int oldVal, int newVal) { int newMinMinutes = newVal == minHour ? minMinutes : minutes.min; pickerMinutes.setMinValue(minutes.getClosestIndex(newMinMinutes)); updateTitle(); } }); pickerMinutes.setOnValueChangedListener(this); pickerMargin.setOnValueChangedListener(this); //build dialog this.setView(dialogLayout) .setCustomTitle(titleView) .setPositiveButton( "Set", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); listener.OnTimeMarginSet(getHour(), getMinutes(), getMargin()); } }) .setNegativeButton( "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); this.create(); updateTitle(); } //use .show() afterwards to draw and use this dialog /** * Initialize NumberPicker with possible values and a selected one * @param picker * @param values * @param selected */ private void initPicker(NumberPicker picker, NumberPickerValues values, int selected) { if (values.min <= selected && selected <= values.max) { picker.setMinValue(values.getClosestIndex(values.min)); picker.setMaxValue(values.getClosestIndex(values.max)); picker.setDisplayedValues(values.valuesAsStrings); picker.setValue(values.getClosestIndex(selected)); } } /** * Update dialog title with selected time(s) */ private void updateTitle(){ if (titleView != null) { ((TextView) titleView.findViewById(R.id.textView)).setText(getTitle()); } } /** * Generate String for title from selected time(s) * @return String representation of time or timerange */ private String getTitle(){ Calendar start = Calendar.getInstance(); start.set(Calendar.HOUR_OF_DAY, getHour()); start.set(Calendar.MINUTE, getMinutes()); return CalendarUtil.getTimeRangeString(start, Calendar.MINUTE, getMargin()); } /** * Get selected hour * @return hour selected */ private int getHour(){ return hours.values.get(pickerHour.getValue()); } /** * Get selected minutes * @return minutes selected */ private int getMinutes(){ return minutes.values.get(pickerMinutes.getValue()); } /** * Get selected margin * @return margin selected */ private int getMargin(){ return margins.values.get(pickerMargin.getValue()); } /** * When a NumberPicker changes value, update title * @param numberPicker * @param oldVal * @param newVal */ @Override public void onValueChange(NumberPicker numberPicker, int oldVal, int newVal) { updateTitle(); } /*** Nested Classes ***/ /** * Custom listener fired when dialog's positive button is pushed */ public interface OnTimeMarginSetListener{ public void OnTimeMarginSet(int hour, int minutes, int margin); } /** * Wrapper around String[] of Integers, for NumberPicker DisplayedValues */ public static class NumberPickerValues{ /** * Numerical values */ private ArrayList<Integer> values; /** * Values as Strings */ private String[] valuesAsStrings; /** * Amount of values */ private int length; /** * Bounds for values */ private int min, max, step; public NumberPickerValues(int min, int max, int step){ this.min = min; this.max = max; this.step = step; //calculate length length = max - min; if (step > 0) length /= step; length++; //generate values values = new ArrayList<>(length); valuesAsStrings = new String[length]; for (int i = 0, val = min; i < length && val <= max; i++, val += step) { values.add(i, val); valuesAsStrings[i] = val + ""; } } /** * Get index for exact value or member of collection closest to value * @param value * @return index in collection */ private int getClosestIndex(int value){ return (value - min) / step; } } }
/* * Copyright (c) 2014 Villu Ruusmann */ package org.jpmml.model.filters; import org.dmg.pmml.Version; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLFilterImpl; abstract public class PMMLFilter extends XMLFilterImpl { private String sourceNamespaceURI = null; private Version source = null; private Version target = null; public PMMLFilter(Version target){ setTarget(target); } public PMMLFilter(XMLReader reader, Version target){ super(reader); setTarget(target); } abstract public String filterLocalName(String localName); abstract public Attributes filterAttributes(String localName, Attributes attributes); @Override public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { if(("").equals(prefix)){ updateSource(namespaceURI); super.startPrefixMapping("", getNamespaceURI()); return; } super.startPrefixMapping(prefix, namespaceURI); } @Override public void endPrefixMapping(String prefix) throws SAXException { super.endPrefixMapping(prefix); } @Override public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attributes) throws SAXException { if(isFilterable(namespaceURI)){ updateSource(namespaceURI); String filteredLocalName = filterLocalName(localName); String filteredQualifiedName = (("").equals(qualifiedName) ? "" : filteredLocalName); Attributes filteredAttributes = filterAttributes(localName, attributes); super.startElement(getNamespaceURI(), filteredLocalName, filteredQualifiedName, filteredAttributes); return; } super.startElement(namespaceURI, localName, qualifiedName, attributes); } @Override public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException { if(isFilterable(namespaceURI)){ String filteredLocalName = filterLocalName(localName); String filteredQualifiedName = (("").equals(qualifiedName) ? "" : filteredLocalName); super.endElement(getNamespaceURI(), filteredLocalName, filteredQualifiedName); return; } super.endElement(namespaceURI, localName, qualifiedName); } private boolean isFilterable(String namespaceURI){ if(("").equals(namespaceURI)){ return true; } // End if if(this.sourceNamespaceURI != null && (this.sourceNamespaceURI).equals(namespaceURI)){ return true; } return namespaceURI.startsWith("http://www.dmg.org/PMML-"); } private String getNamespaceURI(){ Version target = getTarget(); return target.getNamespaceURI(); } private void updateSource(String namespaceURI){ if(("").equals(namespaceURI)){ return; } // End if if(this.sourceNamespaceURI != null && (this.sourceNamespaceURI).equals(namespaceURI)){ return; } Version version = Version.forNamespaceURI(namespaceURI); Version source = getSource(); if(source != null && !(source).equals(version)){ throw new IllegalStateException(); } // Keep the String reference of the namespaceURI argument, as opposed to getting one using Version#getNamespaceURI(). // If the same String instance is reused, which is typical, // then String#equals(String) will be able to return quickly by performing an identity comparison this.sourceNamespaceURI = namespaceURI; setSource(version); } public Version getSource(){ return this.source; } private void setSource(Version source){ this.source = source; } public Version getTarget(){ return this.target; } private void setTarget(Version target){ if(target == null){ throw new NullPointerException(); } this.target = target; } static protected int compare(Version left, Version right){ if(left == null || right == null){ throw new IllegalStateException(); } return (left).compareTo(right); } static protected boolean hasAttribute(Attributes attributes, String localName){ int index = attributes.getIndex("", localName); return (index > -1); } static protected String getAttribute(Attributes attributes, String localName){ return attributes.getValue("", localName); } static protected Attributes setAttribute(Attributes attributes, String localName, String value){ int index = attributes.getIndex("", localName); AttributesImpl result = new AttributesImpl(attributes); if(index < 0){ result.addAttribute("", localName, "", "CDATA", value); // XXX } else { result.setValue(index, value); } return result; } static protected Attributes renameAttribute(Attributes attributes, String oldLocalName, String localName){ int index = attributes.getIndex("", oldLocalName); if(index < 0){ return attributes; } AttributesImpl result = new AttributesImpl(attributes); result.setLocalName(index, localName); result.setQName(index, localName); // XXX return result; } static protected Attributes removeAttribute(Attributes attributes, String localName){ int index = attributes.getIndex("", localName); if(index < 0){ return attributes; } AttributesImpl result = new AttributesImpl(attributes); result.removeAttribute(index); return result; } }
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.svn; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.NullableFunction; import junit.framework.Assert; import org.jetbrains.annotations.Nullable; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; /** * Created with IntelliJ IDEA. * User: Irina.Chernushina * Date: 2/28/13 * Time: 11:59 AM */ public class SvnCommitTest extends Svn17TestCase { private SvnVcs myVcs; private VcsDirtyScopeManager myDirtyScopeManager; private ChangeListManager myChangeListManager; @Override @Before public void setUp() throws Exception { super.setUp(); myVcs = SvnVcs.getInstance(myProject); myDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject); myChangeListManager = ChangeListManager.getInstance(myProject); } @Test public void testSimpleCommit() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); run2variants(new MyRunner() { private String myName = "a.txt"; @Override protected void run() throws Exception { final VirtualFile file = createFileInCommand(myWorkingCopyDir, myName, "123"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFile(file, FileStatus.ADDED); } @Override protected void cleanup() throws Exception { myName = "b.txt"; } }); } @Test public void testCommitRename() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); run2variants(new MyRunner() { private String myName = "a.txt"; private String myRenamedName = "aRenamed.txt"; @Override protected void run() throws Exception { final VirtualFile file = createFileInCommand(myWorkingCopyDir, myName, "123"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFile(file, FileStatus.ADDED); renameFileInCommand(file, myRenamedName); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFile(file, FileStatus.MODIFIED); } @Override protected void cleanup() throws Exception { myName = "b.txt"; myRenamedName = "bRenamed.txt"; } }); } @Test public void testRenameReplace() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); run2variants(new MyRunner() { private String myName = "a.txt"; private String myName2 = "aRenamed.txt"; @Override protected void run() throws Exception { final VirtualFile file = createFileInCommand(myWorkingCopyDir, myName, "123"); final VirtualFile file2 = createFileInCommand(myWorkingCopyDir, myName2, "1235"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(file, file2); renameFileInCommand(file, file.getName() + "7.txt"); renameFileInCommand(file2, myName); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(file, file2); } @Override protected void cleanup() throws Exception { myName = "b.txt"; myName2 = "bRenamed.txt"; } }); } @Test public void testRenameFolder() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); run2variants(new MyRunner() { private String folder = "f"; @Override protected void run() throws Exception { final VirtualFile dir = createDirInCommand(myWorkingCopyDir, folder); final VirtualFile file = createFileInCommand(dir, "a.txt", "123"); final VirtualFile file2 = createFileInCommand(dir, "b.txt", "1235"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(dir, file, file2); renameFileInCommand(dir, dir.getName() + "dd"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(dir, file, file2); } @Override protected void cleanup() throws Exception { folder = "f1"; } }); } @Test public void testCommitDeletion() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); run2variants(new MyRunner() { private String folder = "f"; @Override protected void run() throws Exception { final VirtualFile dir = createDirInCommand(myWorkingCopyDir, folder); final VirtualFile file = createFileInCommand(dir, "a.txt", "123"); final VirtualFile file2 = createFileInCommand(dir, "b.txt", "1235"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(dir, file, file2); final FilePath dirPath = new FilePathImpl(new File(dir.getPath()), true); deleteFileInCommand(dir); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinPaths(dirPath); } @Override protected void cleanup() throws Exception { folder = "f1"; } }); } @Test public void testSameRepoPlusInnerCopyCommitNative() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); prepareInnerCopy(false); final MyRunner runner = new MyRunner() { @Override protected void run() throws Exception { final File file1 = new File(myWorkingCopyDir.getPath(), "source/s1.txt"); final File fileInner = new File(myWorkingCopyDir.getPath(), "source/inner1/inner2/inner/t11.txt"); Assert.assertTrue(file1.exists()); Assert.assertTrue(fileInner.exists()); final VirtualFile vf1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file1); final VirtualFile vf2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(fileInner); Assert.assertNotNull(vf1); Assert.assertNotNull(vf2); editFileInCommand(vf1, "2317468732ghdwwe7y348rf"); editFileInCommand(vf2, "2317468732ghdwwe7y348rf csdjcjksw"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); final HashSet<String> strings = checkinFiles(vf1, vf2); System.out.println("" + StringUtil.join(strings, "\n")); Assert.assertEquals(1, strings.size()); } @Override protected void cleanup() throws Exception { } }; setNativeAcceleration(true); runner.run(); } @Test public void testSameRepoPlusInnerCopyCommitSvnkit() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); prepareInnerCopy(false); final MyRunner runner = new MyRunner() { @Override protected void run() throws Exception { final File file1 = new File(myWorkingCopyDir.getPath(), "source/s1.txt"); final File fileInner = new File(myWorkingCopyDir.getPath(), "source/inner1/inner2/inner/t11.txt"); Assert.assertTrue(file1.exists()); Assert.assertTrue(fileInner.exists()); final VirtualFile vf1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file1); final VirtualFile vf2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(fileInner); Assert.assertNotNull(vf1); Assert.assertNotNull(vf2); editFileInCommand(vf1, "2317468732ghdwwe7y348rf"); editFileInCommand(vf2, "2317468732ghdwwe7y348rf csdjcjksw"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); final HashSet<String> strings = checkinFiles(vf1, vf2); System.out.println("" + StringUtil.join(strings, "\n")); Assert.assertEquals(1, strings.size()); } @Override protected void cleanup() throws Exception { } }; setNativeAcceleration(true); runner.run(); } @Test public void testAnotherRepoPlusInnerCopyCommitNative() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); prepareInnerCopy(true); final MyRunner runner = new MyRunner() { @Override protected void run() throws Exception { final File file1 = new File(myWorkingCopyDir.getPath(), "source/s1.txt"); final File fileInner = new File(myWorkingCopyDir.getPath(), "source/inner1/inner2/inner/t11.txt"); Assert.assertTrue(file1.exists()); Assert.assertTrue(fileInner.exists()); final VirtualFile vf1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file1); final VirtualFile vf2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(fileInner); Assert.assertNotNull(vf1); Assert.assertNotNull(vf2); editFileInCommand(vf1, "2317468732ghdwwe7y348rf"); editFileInCommand(vf2, "2317468732ghdwwe7y348rf csdjcjksw"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(vf1, vf2); } @Override protected void cleanup() throws Exception { } }; setNativeAcceleration(true); runner.run(); } @Test public void testAnotherRepoPlusInnerCopyCommitSvnkit() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); prepareInnerCopy(true); final MyRunner runner = new MyRunner() { @Override protected void run() throws Exception { final File file1 = new File(myWorkingCopyDir.getPath(), "source/s1.txt"); final File fileInner = new File(myWorkingCopyDir.getPath(), "source/inner1/inner2/inner/t11.txt"); Assert.assertTrue(file1.exists()); Assert.assertTrue(fileInner.exists()); final VirtualFile vf1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file1); final VirtualFile vf2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(fileInner); Assert.assertNotNull(vf1); Assert.assertNotNull(vf2); editFileInCommand(vf1, "2317468732ghdwwe7y348rf"); editFileInCommand(vf2, "2317468732ghdwwe7y348rf csdjcjksw"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(vf1, vf2); } @Override protected void cleanup() throws Exception { } }; setNativeAcceleration(true); runner.run(); } @Test public void testPlusExternalCopyCommitNative() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); prepareExternal(); final MyRunner runner = new MyRunner() { @Override protected void run() throws Exception { final File file1 = new File(myWorkingCopyDir.getPath(), "source/s1.txt"); final File fileInner = new File(myWorkingCopyDir.getPath(), "source/external/t11.txt"); Assert.assertTrue(file1.exists()); Assert.assertTrue(fileInner.exists()); final VirtualFile vf1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file1); final VirtualFile vf2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(fileInner); Assert.assertNotNull(vf1); Assert.assertNotNull(vf2); editFileInCommand(vf1, "2317468732ghdwwe7y348rf"); editFileInCommand(vf2, "2317468732ghdwwe7y348rf csdjcjksw"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(vf1, vf2); } @Override protected void cleanup() throws Exception { } }; setNativeAcceleration(true); runner.run(); } @Test public void testPlusExternalCopyCommitSvnkit() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); prepareExternal(); final MyRunner runner = new MyRunner() { @Override protected void run() throws Exception { final File file1 = new File(myWorkingCopyDir.getPath(), "source/s1.txt"); final File fileInner = new File(myWorkingCopyDir.getPath(), "source/external/t11.txt"); Assert.assertTrue(file1.exists()); Assert.assertTrue(fileInner.exists()); final VirtualFile vf1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file1); final VirtualFile vf2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(fileInner); Assert.assertNotNull(vf1); Assert.assertNotNull(vf2); editFileInCommand(vf1, "2317468732ghdwwe7y348rf"); editFileInCommand(vf2, "2317468732ghdwwe7y348rf csdjcjksw"); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); checkinFiles(vf1, vf2); } @Override protected void cleanup() throws Exception { } }; setNativeAcceleration(false); runner.run(); } private void checkinPaths(FilePath... files) { final List<Change> changes = new ArrayList<Change>(); for (FilePath file : files) { final Change change = myChangeListManager.getChange(file); Assert.assertNotNull(change); changes.add(change); } final List<VcsException> exceptions = myVcs.getCheckinEnvironment().commit(changes, "test comment list"); Assert.assertTrue(exceptions == null || exceptions.isEmpty()); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); for (FilePath file : files) { final Change changeA = myChangeListManager.getChange(file); Assert.assertNull(changeA); } } private HashSet<String> checkinFiles(VirtualFile... files) { final List<Change> changes = new ArrayList<Change>(); for (VirtualFile file : files) { final Change change = myChangeListManager.getChange(file); Assert.assertNotNull(change); changes.add(change); } final HashSet<String> feedback = new HashSet<String>(); final List<VcsException> exceptions = myVcs.getCheckinEnvironment().commit(changes, "test comment list", new NullableFunction<Object, Object>() { @Nullable @Override public Object fun(Object o) { return null; } }, feedback); if (exceptions !=null && ! exceptions.isEmpty()) { exceptions.get(0).printStackTrace(); } Assert.assertTrue(exceptions == null || exceptions.isEmpty()); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); for (VirtualFile file : files) { final Change changeA = myChangeListManager.getChange(file); Assert.assertNull(changeA); } return feedback; } private void checkinFile(VirtualFile file, FileStatus status) { final Change change = myChangeListManager.getChange(file); Assert.assertNotNull(change); Assert.assertEquals(status, change.getFileStatus()); final List<VcsException> exceptions = myVcs.getCheckinEnvironment().commit(Collections.singletonList(change), "test comment"); Assert.assertTrue(exceptions == null || exceptions.isEmpty()); myDirtyScopeManager.markEverythingDirty(); myChangeListManager.ensureUpToDate(false); final Change changeA = myChangeListManager.getChange(file); Assert.assertNull(changeA); } protected void run2variants(final MyRunner runner) throws Exception { setNativeAcceleration(false); runner.run(); runner.cleanup(); setNativeAcceleration(true); runner.run(); } private static abstract class MyRunner { protected abstract void run() throws Exception; protected abstract void cleanup() throws Exception; } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.intellij.packaging.impl.artifacts; import com.intellij.compiler.CompilerConfiguration; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.CompilerProjectExtension; import com.intellij.openapi.roots.ModuleRootModel; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Trinity; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.artifacts.ArtifactManager; import com.intellij.packaging.artifacts.ArtifactProperties; import com.intellij.packaging.artifacts.ArtifactType; import com.intellij.packaging.elements.*; import com.intellij.packaging.impl.elements.*; import com.intellij.util.Processor; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author nik */ public class ArtifactUtil { private ArtifactUtil() { } public static CompositePackagingElement<?> copyFromRoot(@NotNull CompositePackagingElement<?> oldRoot, @NotNull Project project) { final CompositePackagingElement<?> newRoot = (CompositePackagingElement<?>)copyElement(oldRoot, project); copyChildren(oldRoot, newRoot, project); return newRoot; } public static void copyChildren(CompositePackagingElement<?> oldParent, CompositePackagingElement<?> newParent, @NotNull Project project) { for (PackagingElement<?> child : oldParent.getChildren()) { newParent.addOrFindChild(copyWithChildren(child, project)); } } @NotNull public static <S> PackagingElement<S> copyWithChildren(@NotNull PackagingElement<S> element, @NotNull Project project) { final PackagingElement<S> copy = copyElement(element, project); if (element instanceof CompositePackagingElement<?>) { copyChildren((CompositePackagingElement<?>)element, (CompositePackagingElement<?>)copy, project); } return copy; } @NotNull private static <S> PackagingElement<S> copyElement(@NotNull PackagingElement<S> element, @NotNull Project project) { //noinspection unchecked final PackagingElement<S> copy = (PackagingElement<S>)element.getType().createEmpty(project); copy.loadState(element.getState()); return copy; } public static <E extends PackagingElement<?>> boolean processPackagingElements(@NotNull Artifact artifact, @Nullable PackagingElementType<E> type, @NotNull final Processor<? super E> processor, final @NotNull PackagingElementResolvingContext resolvingContext, final boolean processSubstitutions) { return processPackagingElements(artifact, type, new PackagingElementProcessor<E>() { @Override public boolean process(@NotNull E e, @NotNull PackagingElementPath path) { return processor.process(e); } }, resolvingContext, processSubstitutions); } public static <E extends PackagingElement<?>> boolean processPackagingElements(@NotNull Artifact artifact, @Nullable PackagingElementType<E> type, @NotNull PackagingElementProcessor<? super E> processor, final @NotNull PackagingElementResolvingContext resolvingContext, final boolean processSubstitutions) { return processPackagingElements(artifact.getRootElement(), type, processor, resolvingContext, processSubstitutions, artifact.getArtifactType()); } public static <E extends PackagingElement<?>> boolean processPackagingElements(final PackagingElement<?> rootElement, @Nullable PackagingElementType<E> type, @NotNull PackagingElementProcessor<? super E> processor, final @NotNull PackagingElementResolvingContext resolvingContext, final boolean processSubstitutions, final ArtifactType artifactType) { return processElementRecursively(rootElement, type, processor, resolvingContext, processSubstitutions, artifactType, PackagingElementPath.EMPTY, new HashSet<PackagingElement<?>>()); } private static <E extends PackagingElement<?>> boolean processElementsRecursively(final List<? extends PackagingElement<?>> elements, @Nullable PackagingElementType<E> type, @NotNull PackagingElementProcessor<? super E> processor, final @NotNull PackagingElementResolvingContext resolvingContext, final boolean processSubstitutions, ArtifactType artifactType, @NotNull PackagingElementPath path, Set<PackagingElement<?>> processed) { for (PackagingElement<?> element : elements) { if (!processElementRecursively(element, type, processor, resolvingContext, processSubstitutions, artifactType, path, processed)) { return false; } } return true; } private static <E extends PackagingElement<?>> boolean processElementRecursively(@NotNull PackagingElement<?> element, @Nullable PackagingElementType<E> type, @NotNull PackagingElementProcessor<? super E> processor, @NotNull PackagingElementResolvingContext resolvingContext, final boolean processSubstitutions, ArtifactType artifactType, @NotNull PackagingElementPath path, Set<PackagingElement<?>> processed) { if (!processor.shouldProcess(element) || !processed.add(element)) { return true; } if (type == null || element.getType().equals(type)) { if (!processor.process((E)element, path)) { return false; } } if (element instanceof CompositePackagingElement<?>) { final CompositePackagingElement<?> composite = (CompositePackagingElement<?>)element; return processElementsRecursively(composite.getChildren(), type, processor, resolvingContext, processSubstitutions, artifactType, path.appendComposite(composite), processed); } else if (element instanceof ComplexPackagingElement<?> && processSubstitutions) { final ComplexPackagingElement<?> complexElement = (ComplexPackagingElement<?>)element; if (processor.shouldProcessSubstitution(complexElement)) { final List<? extends PackagingElement<?>> substitution = complexElement.getSubstitution(resolvingContext, artifactType); if (substitution != null) { return processElementsRecursively(substitution, type, processor, resolvingContext, processSubstitutions, artifactType, path.appendComplex(complexElement), processed); } } } return true; } public static void removeDuplicates(@NotNull CompositePackagingElement<?> parent) { List<PackagingElement<?>> prevChildren = new ArrayList<PackagingElement<?>>(); List<PackagingElement<?>> toRemove = new ArrayList<PackagingElement<?>>(); for (PackagingElement<?> child : parent.getChildren()) { if (child instanceof CompositePackagingElement<?>) { removeDuplicates((CompositePackagingElement<?>)child); } boolean merged = false; for (PackagingElement<?> prevChild : prevChildren) { if (child.isEqualTo(prevChild)) { if (child instanceof CompositePackagingElement<?>) { for (PackagingElement<?> childElement : ((CompositePackagingElement<?>)child).getChildren()) { ((CompositePackagingElement<?>)prevChild).addOrFindChild(childElement); } } merged = true; break; } } if (merged) { toRemove.add(child); } else { prevChildren.add(child); } } for (PackagingElement<?> child : toRemove) { parent.removeChild(child); } } public static <S> void copyProperties(ArtifactProperties<?> from, ArtifactProperties<S> to) { //noinspection unchecked to.loadState((S)from.getState()); } @Nullable public static String getDefaultArtifactOutputPath(@NotNull String artifactName, final @NotNull Project project) { final CompilerProjectExtension extension = CompilerProjectExtension.getInstance(project); if (extension == null) return null; String outputUrl = extension.getCompilerOutputUrl(); if (outputUrl == null || outputUrl.length() == 0) { final VirtualFile baseDir = project.getBaseDir(); if (baseDir == null) return null; outputUrl = baseDir.getUrl() + "/out"; } return VfsUtil.urlToPath(outputUrl) + "/artifacts/" + FileUtil.sanitizeFileName(artifactName); } public static <E extends PackagingElement<?>> boolean processElementsWithSubstitutions(@NotNull List<? extends PackagingElement<?>> elements, @NotNull PackagingElementResolvingContext context, @NotNull ArtifactType artifactType, @NotNull PackagingElementPath parentPath, @NotNull PackagingElementProcessor<E> processor) { return processElementsWithSubstitutions(elements, context, artifactType, parentPath, processor, new HashSet<PackagingElement<?>>()); } private static <E extends PackagingElement<?>> boolean processElementsWithSubstitutions(@NotNull List<? extends PackagingElement<?>> elements, @NotNull PackagingElementResolvingContext context, @NotNull ArtifactType artifactType, @NotNull PackagingElementPath parentPath, @NotNull PackagingElementProcessor<E> processor, final Set<PackagingElement<?>> processed) { for (PackagingElement<?> element : elements) { if (!processed.add(element)) { continue; } if (element instanceof ComplexPackagingElement<?> && processor.shouldProcessSubstitution((ComplexPackagingElement)element)) { final ComplexPackagingElement<?> complexElement = (ComplexPackagingElement<?>)element; final List<? extends PackagingElement<?>> substitution = complexElement.getSubstitution(context, artifactType); if (substitution != null && !processElementsWithSubstitutions(substitution, context, artifactType, parentPath.appendComplex(complexElement), processor, processed)) { return false; } } else if (!processor.process((E)element, parentPath)) { return false; } } return true; } public static List<PackagingElement<?>> findByRelativePath(@NotNull CompositePackagingElement<?> parent, @NotNull String relativePath, @NotNull PackagingElementResolvingContext context, @NotNull ArtifactType artifactType) { final List<PackagingElement<?>> result = new ArrayList<PackagingElement<?>>(); processElementsByRelativePath(parent, relativePath, context, artifactType, PackagingElementPath.EMPTY, new PackagingElementProcessor<PackagingElement<?>>() { @Override public boolean process(@NotNull PackagingElement<?> packagingElement, @NotNull PackagingElementPath path) { result.add(packagingElement); return true; } }); return result; } public static boolean processElementsByRelativePath(@NotNull final CompositePackagingElement<?> parent, @NotNull String relativePath, @NotNull final PackagingElementResolvingContext context, @NotNull final ArtifactType artifactType, @NotNull PackagingElementPath parentPath, @NotNull final PackagingElementProcessor<PackagingElement<?>> processor) { relativePath = StringUtil.trimStart(relativePath, "/"); if (relativePath.length() == 0) { return true; } int i = relativePath.indexOf('/'); final String firstName = i != -1 ? relativePath.substring(0, i) : relativePath; final String tail = i != -1 ? relativePath.substring(i+1) : ""; return processElementsWithSubstitutions(parent.getChildren(), context, artifactType, parentPath.appendComposite(parent), new PackagingElementProcessor<PackagingElement<?>>() { @Override public boolean process(@NotNull PackagingElement<?> element, @NotNull PackagingElementPath path) { boolean process = false; if (element instanceof CompositePackagingElement && firstName.equals(((CompositePackagingElement<?>)element).getName())) { process = true; } else if (element instanceof FileCopyPackagingElement) { final FileCopyPackagingElement fileCopy = (FileCopyPackagingElement)element; if (firstName.equals(fileCopy.getOutputFileName())) { process = true; } } if (process) { if (tail.length() == 0) { if (!processor.process(element, path)) return false; } else if (element instanceof CompositePackagingElement<?>) { return processElementsByRelativePath((CompositePackagingElement)element, tail, context, artifactType, path, processor); } } return true; } }); } public static boolean processDirectoryChildren(@NotNull CompositePackagingElement<?> parent, @NotNull PackagingElementPath pathToParent, @NotNull String relativePath, @NotNull final PackagingElementResolvingContext context, @NotNull final ArtifactType artifactType, @NotNull final PackagingElementProcessor<PackagingElement<?>> processor) { return processElementsByRelativePath(parent, relativePath, context, artifactType, pathToParent, new PackagingElementProcessor<PackagingElement<?>>() { @Override public boolean process(@NotNull PackagingElement<?> element, @NotNull PackagingElementPath path) { if (element instanceof DirectoryPackagingElement) { final List<PackagingElement<?>> children = ((DirectoryPackagingElement)element).getChildren(); if (!processElementsWithSubstitutions(children, context, artifactType, path.appendComposite((DirectoryPackagingElement)element), processor)) { return false; } } return true; } }); } public static void processFileOrDirectoryCopyElements(Artifact artifact, PackagingElementProcessor<FileOrDirectoryCopyPackagingElement<?>> processor, PackagingElementResolvingContext context, boolean processSubstitutions) { processPackagingElements(artifact, PackagingElementFactoryImpl.FILE_COPY_ELEMENT_TYPE, processor, context, processSubstitutions); processPackagingElements(artifact, PackagingElementFactoryImpl.DIRECTORY_COPY_ELEMENT_TYPE, processor, context, processSubstitutions); processPackagingElements(artifact, PackagingElementFactoryImpl.EXTRACTED_DIRECTORY_ELEMENT_TYPE, processor, context, processSubstitutions); } public static Collection<Trinity<Artifact, PackagingElementPath, String>> findContainingArtifactsWithOutputPaths(@NotNull final VirtualFile file, @NotNull Project project) { final boolean isResourceFile = CompilerConfiguration.getInstance(project).isResourceFile(file); final List<Trinity<Artifact, PackagingElementPath, String>> artifacts = new ArrayList<Trinity<Artifact, PackagingElementPath, String>>(); final PackagingElementResolvingContext context = ArtifactManager.getInstance(project).getResolvingContext(); for (final Artifact artifact : ArtifactManager.getInstance(project).getArtifacts()) { processPackagingElements(artifact, null, new PackagingElementProcessor<PackagingElement<?>>() { @Override public boolean process(@NotNull PackagingElement<?> element, @NotNull PackagingElementPath path) { if (element instanceof FileOrDirectoryCopyPackagingElement<?>) { final VirtualFile root = ((FileOrDirectoryCopyPackagingElement)element).findFile(); if (root != null && VfsUtil.isAncestor(root, file, false)) { final String relativePath; if (root.equals(file) && element instanceof FileCopyPackagingElement) { relativePath = ((FileCopyPackagingElement)element).getOutputFileName(); } else { relativePath = VfsUtil.getRelativePath(file, root, '/'); } artifacts.add(Trinity.create(artifact, path, relativePath)); return false; } } else if (isResourceFile && element instanceof ModuleOutputPackagingElement) { final String relativePath = getRelativePathInSources(file, (ModuleOutputPackagingElement)element, context); if (relativePath != null) { artifacts.add(Trinity.create(artifact, path, relativePath)); return false; } } return true; } }, context, true); } return artifacts; } @Nullable private static String getRelativePathInSources(@NotNull VirtualFile file, final @NotNull ModuleOutputPackagingElement moduleElement, @NotNull PackagingElementResolvingContext context) { final Module module = moduleElement.findModule(context); if (module != null) { final ModuleRootModel rootModel = context.getModulesProvider().getRootModel(module); for (VirtualFile sourceRoot : rootModel.getSourceRoots(false)) { if (VfsUtil.isAncestor(sourceRoot, file, true)) { return VfsUtil.getRelativePath(file, sourceRoot, '/'); } } } return null; } @Nullable public static VirtualFile findSourceFileByOutputPath(Artifact artifact, String outputPath, PackagingElementResolvingContext context) { final List<VirtualFile> files = findSourceFilesByOutputPath(artifact.getRootElement(), outputPath, context, artifact.getArtifactType()); return files.isEmpty() ? null : files.get(0); } @Nullable public static VirtualFile findSourceFileByOutputPath(CompositePackagingElement<?> parent, String outputPath, PackagingElementResolvingContext context, ArtifactType artifactType) { final List<VirtualFile> files = findSourceFilesByOutputPath(parent, outputPath, context, artifactType); return files.isEmpty() ? null : files.get(0); } public static List<VirtualFile> findSourceFilesByOutputPath(CompositePackagingElement<?> parent, final String outputPath, final PackagingElementResolvingContext context, final ArtifactType artifactType) { final String path = StringUtil.trimStart(outputPath, "/"); if (path.length() == 0) { return Collections.emptyList(); } int i = path.indexOf('/'); final String firstName = i != -1 ? path.substring(0, i) : path; final String tail = i != -1 ? path.substring(i+1) : ""; final List<VirtualFile> result = new SmartList<VirtualFile>(); processElementsWithSubstitutions(parent.getChildren(), context, artifactType, PackagingElementPath.EMPTY, new PackagingElementProcessor<PackagingElement<?>>() { @Override public boolean process(@NotNull PackagingElement<?> element, @NotNull PackagingElementPath elementPath) { //todo[nik] replace by method findSourceFile() in PackagingElement if (element instanceof CompositePackagingElement) { final CompositePackagingElement<?> compositeElement = (CompositePackagingElement<?>)element; if (firstName.equals(compositeElement.getName())) { result.addAll(findSourceFilesByOutputPath(compositeElement, tail, context, artifactType)); } } else if (element instanceof FileCopyPackagingElement) { final FileCopyPackagingElement fileCopyElement = (FileCopyPackagingElement)element; if (firstName.equals(fileCopyElement.getOutputFileName()) && tail.length() == 0) { ContainerUtil.addIfNotNull(fileCopyElement.findFile(), result); } } else if (element instanceof DirectoryCopyPackagingElement || element instanceof ExtractedDirectoryPackagingElement) { final VirtualFile sourceRoot = ((FileOrDirectoryCopyPackagingElement<?>)element).findFile(); if (sourceRoot != null) { ContainerUtil.addIfNotNull(sourceRoot.findFileByRelativePath(path), result); } } else if (element instanceof ModuleOutputPackagingElement) { final Module module = ((ModuleOutputPackagingElement)element).findModule(context); if (module != null) { final CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(context.getProject()); final ModuleRootModel rootModel = context.getModulesProvider().getRootModel(module); for (VirtualFile sourceRoot : rootModel.getSourceRoots(false)) { final VirtualFile sourceFile = sourceRoot.findFileByRelativePath(path); if (sourceFile != null && compilerConfiguration.isResourceFile(sourceFile)) { result.add(sourceFile); } } } } return true; } }); return result; } public static boolean processParents(@NotNull Artifact artifact, @NotNull PackagingElementResolvingContext context, @NotNull ParentElementProcessor processor, int maxLevel) { return processParents(artifact, context, processor, FList.<Pair<Artifact, CompositePackagingElement<?>>>emptyList(), maxLevel, new HashSet<Artifact>()); } private static boolean processParents(@NotNull final Artifact artifact, @NotNull final PackagingElementResolvingContext context, @NotNull final ParentElementProcessor processor, FList<Pair<Artifact, CompositePackagingElement<?>>> pathToElement, final int maxLevel, final Set<Artifact> processed) { if (!processed.add(artifact)) return true; final FList<Pair<Artifact, CompositePackagingElement<?>>> pathFromRoot; final CompositePackagingElement<?> rootElement = artifact.getRootElement(); if (rootElement instanceof ArtifactRootElement<?>) { pathFromRoot = pathToElement; } else { if (!processor.process(rootElement, pathToElement, artifact)) { return false; } pathFromRoot = pathToElement.prepend(new Pair<Artifact, CompositePackagingElement<?>>(artifact, rootElement)); } if (pathFromRoot.size() > maxLevel) return true; for (final Artifact anArtifact : context.getArtifactModel().getArtifacts()) { if (processed.contains(anArtifact)) continue; final PackagingElementProcessor<ArtifactPackagingElement> elementProcessor = new PackagingElementProcessor<ArtifactPackagingElement>() { @Override public boolean shouldProcessSubstitution(ComplexPackagingElement<?> element) { return !(element instanceof ArtifactPackagingElement); } @Override public boolean process(@NotNull ArtifactPackagingElement element, @NotNull PackagingElementPath path) { if (artifact.getName().equals(element.getArtifactName())) { FList<Pair<Artifact, CompositePackagingElement<?>>> currentPath = pathFromRoot; final List<CompositePackagingElement<?>> parents = path.getParents(); for (int i = 0, parentsSize = parents.size(); i < parentsSize - 1; i++) { CompositePackagingElement<?> parent = parents.get(i); if (!processor.process(parent, currentPath, anArtifact)) { return false; } currentPath = currentPath.prepend(new Pair<Artifact, CompositePackagingElement<?>>(anArtifact, parent)); if (currentPath.size() > maxLevel) { return true; } } if (!parents.isEmpty()) { CompositePackagingElement<?> lastParent = parents.get(parents.size() - 1); if (lastParent instanceof ArtifactRootElement<?> && !processor.process(lastParent, currentPath, anArtifact)) { return false; } } return processParents(anArtifact, context, processor, currentPath, maxLevel, processed); } return true; } }; if (!processPackagingElements(anArtifact, ArtifactElementType.ARTIFACT_ELEMENT_TYPE, elementProcessor, context, true)) { return false; } } return true; } public static boolean isArchiveName(String name) { return name.length() >= 4 && name.charAt(name.length() - 4) == '.' && StringUtil.endsWithIgnoreCase(name, "ar"); } public static void removeChildrenRecursively(@NotNull CompositePackagingElement<?> element, @NotNull Condition<PackagingElement<?>> condition) { List<PackagingElement<?>> toRemove = new ArrayList<PackagingElement<?>>(); for (PackagingElement<?> child : element.getChildren()) { if (child instanceof CompositePackagingElement<?>) { final CompositePackagingElement<?> compositeChild = (CompositePackagingElement<?>)child; removeChildrenRecursively(compositeChild, condition); if (compositeChild.getChildren().isEmpty()) { toRemove.add(child); } } else if (condition.value(child)) { toRemove.add(child); } } element.removeChildren(toRemove); } public static boolean shouldClearArtifactOutputBeforeRebuild(Artifact artifact) { final String outputPath = artifact.getOutputPath(); return !StringUtil.isEmpty(outputPath) && artifact.getRootElement() instanceof ArtifactRootElement<?>; } public static Set<Module> getModulesIncludedInArtifacts(final @NotNull Collection<? extends Artifact> artifacts, final @NotNull Project project) { final Set<Module> modules = new HashSet<Module>(); final PackagingElementResolvingContext resolvingContext = ArtifactManager.getInstance(project).getResolvingContext(); for (Artifact artifact : artifacts) { processPackagingElements(artifact, null, new Processor<PackagingElement<?>>() { @Override public boolean process(PackagingElement<?> element) { if (element instanceof ModuleOutputPackagingElement) { ContainerUtil.addIfNotNull(modules, ((ModuleOutputPackagingElement)element).findModule(resolvingContext)); } return true; } }, resolvingContext, true); } return modules; } }
/* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ui; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.TestBean; import org.springframework.test.AssertThrows; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * @author Rick Evans * @author Juergen Hoeller */ public final class ModelMapTests extends TestCase { public void testNoArgCtorYieldsEmptyModel() throws Exception { assertEquals(0, new ModelMap().size()); } /* * SPR-2185 - Null model assertion causes backwards compatibility issue */ public void testAddNullObjectWithExplicitKey() throws Exception { ModelMap model = new ModelMap(); model.addObject("foo", null); assertTrue(model.containsKey("foo")); assertNull(model.get("foo")); } /* * SPR-2185 - Null model assertion causes backwards compatibility issue */ public void testAddNullObjectViaCtorWithExplicitKey() throws Exception { ModelMap model = new ModelMap("foo", null); assertTrue(model.containsKey("foo")); assertNull(model.get("foo")); } public void testNamedObjectCtor() throws Exception { ModelMap model = new ModelMap("foo", "bing"); assertEquals(1, model.size()); String bing = (String) model.get("foo"); assertNotNull(bing); assertEquals("bing", bing); } public void testUnnamedCtorScalar() throws Exception { ModelMap model = new ModelMap("foo", "bing"); assertEquals(1, model.size()); String bing = (String) model.get("foo"); assertNotNull(bing); assertEquals("bing", bing); } public void testOneArgCtorWithScalar() throws Exception { ModelMap model = new ModelMap("bing"); assertEquals(1, model.size()); String string = (String) model.get("string"); assertNotNull(string); assertEquals("bing", string); } public void testOneArgCtorWithNull() throws Exception { new AssertThrows(IllegalArgumentException.class, "Null model arguments added without a name being explicitly supplied are not allowed.") { public void test() throws Exception { new ModelMap(null); } }.runTest(); } public void testOneArgCtorWithCollection() throws Exception { ModelMap model = new ModelMap(new String[]{"foo", "boing"}); assertEquals(1, model.size()); String[] strings = (String[]) model.get("stringList"); assertNotNull(strings); assertEquals(2, strings.length); assertEquals("foo", strings[0]); assertEquals("boing", strings[1]); } public void testOneArgCtorWithEmptyCollection() throws Exception { ModelMap model = new ModelMap(new HashSet()); // must not add if collection is empty... assertEquals(0, model.size()); } public void testAddObjectWithNull() throws Exception { new AssertThrows(IllegalArgumentException.class, "Null model arguments added without a name being explicitly supplied are not allowed.") { public void test() throws Exception { ModelMap model = new ModelMap(); model.addObject(null); } }.runTest(); } public void testAddObjectWithEmptyArray() throws Exception { ModelMap model = new ModelMap(new int[]{}); assertEquals(1, model.size()); int[] ints = (int[]) model.get("intList"); assertNotNull(ints); assertEquals(0, ints.length); } public void testAddAllObjectsWithNullMap() throws Exception { ModelMap model = new ModelMap(); model.addAllObjects((Map) null); assertEquals(0, model.size()); } public void testAddAllObjectsWithNullCollection() throws Exception { ModelMap model = new ModelMap(); model.addAllObjects((Collection) null); assertEquals(0, model.size()); } public void testAddAllObjectsWithSparseArrayList() throws Exception { new AssertThrows(IllegalArgumentException.class, "Null model arguments added without a name being explicitly supplied are not allowed.") { public void test() throws Exception { ModelMap model = new ModelMap(); ArrayList list = new ArrayList(); list.add("bing"); list.add(null); model.addAllObjects(list); } }.runTest(); } public void testAddMap() throws Exception { Map map = new HashMap(); map.put("one", "one-value"); map.put("two", "two-value"); ModelMap model = new ModelMap(); model.addObject(map); assertEquals(1, model.size()); String key = StringUtils.uncapitalize(ClassUtils.getShortName(map.getClass())); assertTrue(model.containsKey(key)); } public void testAddObjectNoKeyOfSameTypeOverrides() throws Exception { ModelMap model = new ModelMap(); model.addObject("foo"); model.addObject("bar"); assertEquals(1, model.size()); String bar = (String) model.get("string"); assertEquals("bar", bar); } public void testAddListOfTheSameObjects() throws Exception { List beans = new ArrayList(); beans.add(new TestBean("one")); beans.add(new TestBean("two")); beans.add(new TestBean("three")); ModelMap model = new ModelMap(); model.addAllObjects(beans); assertEquals(1, model.size()); } public void testInnerClass() throws Exception { ModelMap map = new ModelMap(); SomeInnerClass inner = new SomeInnerClass(); map.addObject(inner); assertSame(inner, map.get("someInnerClass")); } public void testInnerClassWithTwoUpperCaseLetters() throws Exception { ModelMap map = new ModelMap(); UKInnerClass inner = new UKInnerClass(); map.addObject(inner); assertSame(inner, map.get("UKInnerClass")); } public void testAopCglibProxy() throws Exception { ModelMap map = new ModelMap(); ProxyFactory factory = new ProxyFactory(); Date date = new Date(); factory.setTarget(date); factory.setProxyTargetClass(true); map.addObject(factory.getProxy()); assertTrue(map.containsKey("date")); assertEquals(date, map.get("date")); } public void testAopJdkProxy() throws Exception { ModelMap map = new ModelMap(); ProxyFactory factory = new ProxyFactory(); Map target = new HashMap(); factory.setTarget(target); factory.addInterface(Map.class); Object proxy = factory.getProxy(); map.addObject(proxy); assertSame(proxy, map.get("map")); } public void testAopJdkProxyWithMultipleInterfaces() throws Exception { ModelMap map = new ModelMap(); Map target = new HashMap(); ProxyFactory factory = new ProxyFactory(); factory.setTarget(target); factory.addInterface(Serializable.class); factory.addInterface(Cloneable.class); factory.addInterface(Comparable.class); factory.addInterface(Map.class); Object proxy = factory.getProxy(); map.addObject(proxy); assertSame(proxy, map.get("map")); } public void testAopJdkProxyWithDetectedInterfaces() throws Exception { ModelMap map = new ModelMap(); Map target = new HashMap(); ProxyFactory factory = new ProxyFactory(target); Object proxy = factory.getProxy(); map.addObject(proxy); assertSame(proxy, map.get("map")); } public void testRawJdkProxy() throws Exception { ModelMap map = new ModelMap(); Object proxy = Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {Map.class}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { return "proxy"; } }); map.addObject(proxy); assertSame(proxy, map.get("map")); } private static class SomeInnerClass { } private static class UKInnerClass { } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.sources.v2; import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.spark.annotation.Evolving; /** * An immutable string-to-string map in which keys are case-insensitive. This is used to represent * data source options. * * Each data source implementation can define its own options and teach its users how to set them. * Spark doesn't have any restrictions about what options a data source should or should not have. * Instead Spark defines some standard options that data sources can optionally adopt. It's possible * that some options are very common and many data sources use them. However different data * sources may define the common options(key and meaning) differently, which is quite confusing to * end users. * * The standard options defined by Spark: * <table summary="standard data source options"> * <tr> * <th><b>Option key</b></th> * <th><b>Option value</b></th> * </tr> * <tr> * <td>path</td> * <td>A path string of the data files/directories, like * <code>path1</code>, <code>/absolute/file2</code>, <code>path3/*</code>. The path can * either be relative or absolute, points to either file or directory, and can contain * wildcards. This option is commonly used by file-based data sources.</td> * </tr> * <tr> * <td>paths</td> * <td>A JSON array style paths string of the data files/directories, like * <code>["path1", "/absolute/file2"]</code>. The format of each path is same as the * <code>path</code> option, plus it should follow JSON string literal format, e.g. quotes * should be escaped, <code>pa\"th</code> means pa"th. * </td> * </tr> * <tr> * <td>table</td> * <td>A table name string representing the table name directly without any interpretation. * For example, <code>db.tbl</code> means a table called db.tbl, not a table called tbl * inside database db. <code>`t*b.l`</code> means a table called `t*b.l`, not t*b.l.</td> * </tr> * <tr> * <td>database</td> * <td>A database name string representing the database name directly without any * interpretation, which is very similar to the table name option.</td> * </tr> * </table> */ @Evolving public class DataSourceOptions { private final Map<String, String> keyLowerCasedMap; private String toLowerCase(String key) { return key.toLowerCase(Locale.ROOT); } public static DataSourceOptions empty() { return new DataSourceOptions(new HashMap<>()); } public DataSourceOptions(Map<String, String> originalMap) { keyLowerCasedMap = new HashMap<>(originalMap.size()); for (Map.Entry<String, String> entry : originalMap.entrySet()) { keyLowerCasedMap.put(toLowerCase(entry.getKey()), entry.getValue()); } } public Map<String, String> asMap() { return new HashMap<>(keyLowerCasedMap); } /** * Returns the option value to which the specified key is mapped, case-insensitively. */ public Optional<String> get(String key) { return Optional.ofNullable(keyLowerCasedMap.get(toLowerCase(key))); } /** * Returns the boolean value to which the specified key is mapped, * or defaultValue if there is no mapping for the key. The key match is case-insensitive */ public boolean getBoolean(String key, boolean defaultValue) { String lcaseKey = toLowerCase(key); return keyLowerCasedMap.containsKey(lcaseKey) ? Boolean.parseBoolean(keyLowerCasedMap.get(lcaseKey)) : defaultValue; } /** * Returns the integer value to which the specified key is mapped, * or defaultValue if there is no mapping for the key. The key match is case-insensitive */ public int getInt(String key, int defaultValue) { String lcaseKey = toLowerCase(key); return keyLowerCasedMap.containsKey(lcaseKey) ? Integer.parseInt(keyLowerCasedMap.get(lcaseKey)) : defaultValue; } /** * Returns the long value to which the specified key is mapped, * or defaultValue if there is no mapping for the key. The key match is case-insensitive */ public long getLong(String key, long defaultValue) { String lcaseKey = toLowerCase(key); return keyLowerCasedMap.containsKey(lcaseKey) ? Long.parseLong(keyLowerCasedMap.get(lcaseKey)) : defaultValue; } /** * Returns the double value to which the specified key is mapped, * or defaultValue if there is no mapping for the key. The key match is case-insensitive */ public double getDouble(String key, double defaultValue) { String lcaseKey = toLowerCase(key); return keyLowerCasedMap.containsKey(lcaseKey) ? Double.parseDouble(keyLowerCasedMap.get(lcaseKey)) : defaultValue; } /** * The option key for singular path. */ public static final String PATH_KEY = "path"; /** * The option key for multiple paths. */ public static final String PATHS_KEY = "paths"; /** * The option key for table name. */ public static final String TABLE_KEY = "table"; /** * The option key for database name. */ public static final String DATABASE_KEY = "database"; /** * The option key for whether to check existence of files for a table. */ public static final String CHECK_FILES_EXIST_KEY = "check_files_exist"; /** * Returns all the paths specified by both the singular path option and the multiple * paths option. */ public String[] paths() { String[] singularPath = get(PATH_KEY).map(s -> new String[]{s}).orElseGet(() -> new String[0]); Optional<String> pathsStr = get(PATHS_KEY); if (pathsStr.isPresent()) { ObjectMapper objectMapper = new ObjectMapper(); try { String[] paths = objectMapper.readValue(pathsStr.get(), String[].class); return Stream.of(singularPath, paths).flatMap(Stream::of).toArray(String[]::new); } catch (IOException e) { return singularPath; } } else { return singularPath; } } /** * Returns the value of the table name option. */ public Optional<String> tableName() { return get(TABLE_KEY); } /** * Returns the value of the database name option. */ public Optional<String> databaseName() { return get(DATABASE_KEY); } public Boolean checkFilesExist() { Optional<String> result = get(CHECK_FILES_EXIST_KEY); return result.isPresent() && result.get().equals("true"); } }
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.pixmob.httpclient; import static org.pixmob.httpclient.Constants.HTTP_DELETE; import static org.pixmob.httpclient.Constants.HTTP_GET; import static org.pixmob.httpclient.Constants.HTTP_HEAD; import static org.pixmob.httpclient.Constants.HTTP_POST; import static org.pixmob.httpclient.Constants.HTTP_PUT; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import android.content.Context; import android.os.Build; /** * This class is used to prepare and execute an Http request. * @author Pixmob */ public final class HttpRequestBuilder { private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private static final String CONTENT_CHARSET = "UTF-8"; private static final Map<String, List<String>> NO_HEADERS = new HashMap<String, List<String>>(0); private static TrustManager[] trustManagers; private final byte[] buffer = new byte[1024]; private final HttpClient hc; private final List<HttpRequestHandler> reqHandlers = new ArrayList<HttpRequestHandler>(2); private String uri; private String method; private Set<Integer> expectedStatusCodes = new HashSet<Integer>(2); private Map<String, String> cookies; private Map<String, List<String>> headers; private Map<String, String> parameters; private byte[] content; private boolean contentSet; private String contentType; private HttpResponseHandler handler; HttpRequestBuilder(final HttpClient hc, final String uri, final String method) { this.hc = hc; this.uri = uri; this.method = method; } public HttpRequestBuilder with(HttpRequestHandler handler) { if (handler != null) { reqHandlers.add(handler); } return this; } public HttpRequestBuilder expect(int... statusCodes) { if (statusCodes != null) { for (final int statusCode : statusCodes) { if (statusCode < 1) { throw new IllegalArgumentException("Invalid status code: " + statusCode); } expectedStatusCodes.add(statusCode); } } return this; } public HttpRequestBuilder content(byte[] content, String contentType) { this.content = content; this.contentType = contentType; if (content != null) { contentSet = true; } return this; } public HttpRequestBuilder cookies(Map<String, String> cookies) { this.cookies = cookies; return this; } public HttpRequestBuilder headers(Map<String, List<String>> headers) { this.headers = headers; return this; } public HttpRequestBuilder header(String name, String value) { if (name == null) { throw new IllegalArgumentException("Header name cannot be null"); } if (value == null) { throw new IllegalArgumentException("Header value cannot be null"); } if (headers == null) { headers = new HashMap<String, List<String>>(2); } List<String> values = headers.get(name); if (values == null) { values = new ArrayList<String>(1); headers.put(name, values); } values.add(value); return this; } public HttpRequestBuilder params(Map<String, String> parameters) { this.parameters = parameters; return this; } public HttpRequestBuilder param(String name, String value) { if (name == null) { throw new IllegalArgumentException("Parameter name cannot be null"); } if (value == null) { throw new IllegalArgumentException("Parameter value cannot be null"); } if (parameters == null) { parameters = new HashMap<String, String>(4); } parameters.put(name, value); return this; } public HttpRequestBuilder cookie(String name, String value) { if (name == null) { throw new IllegalArgumentException("Cookie name cannot be null"); } if (value == null) { throw new IllegalArgumentException("Cookie value cannot be null"); } if (cookies == null) { cookies = new HashMap<String, String>(2); } cookies.put(name, value); return this; } public HttpRequestBuilder to(HttpResponseHandler handler) { this.handler = handler; return this; } public HttpRequestBuilder to(File file) throws IOException { to(new WriteToOutputStreamHandler(new FileOutputStream(file))); return this; } public HttpRequestBuilder to(OutputStream output) { to(new WriteToOutputStreamHandler(output)); return this; } public HttpResponse execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try { if (parameters != null && !parameters.isEmpty()) { final StringBuilder buf = new StringBuilder(256); if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) { buf.append('?'); } int paramIdx = 0; for (final Map.Entry<String, String> e : parameters.entrySet()) { if (paramIdx != 0) { buf.append("&"); } final String name = e.getKey(); final String value = e.getValue(); buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=") .append(URLEncoder.encode(value, CONTENT_CHARSET)); ++paramIdx; } if (!contentSet && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) { try { content = buf.toString().getBytes(CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { // Unlikely to happen. throw new HttpClientException("Encoding error", e); } } else { uri += buf; } } conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setConnectTimeout(hc.getConnectTimeout()); conn.setReadTimeout(hc.getReadTimeout()); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setDoInput(true); if (headers != null && !headers.isEmpty()) { for (final Map.Entry<String, List<String>> e : headers.entrySet()) { final List<String> values = e.getValue(); if (values != null) { final String name = e.getKey(); for (final String value : values) { conn.addRequestProperty(name, value); } } } } if (cookies != null && !cookies.isEmpty() || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) { final StringBuilder cookieHeaderValue = new StringBuilder(256); prepareCookieHeader(cookies, cookieHeaderValue); prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue); conn.setRequestProperty("Cookie", cookieHeaderValue.toString()); } final String userAgent = hc.getUserAgent(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Location", uri); conn.setRequestProperty("Referrer", uri); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET); if (conn instanceof HttpsURLConnection) { setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn); } if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) { if (content != null) { conn.setDoOutput(true); if (!contentSet) { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET); } else if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } conn.setFixedLengthStreamingMode(content.length); final OutputStream out = conn.getOutputStream(); out.write(content); out.flush(); } else { conn.setFixedLengthStreamingMode(0); } } for (final HttpRequestHandler connHandler : reqHandlers) { try { connHandler.onRequest(conn); } catch (HttpClientException e) { throw e; } catch (Exception e) { throw new HttpClientException("Failed to prepare request to " + uri, e); } } conn.connect(); final int statusCode = conn.getResponseCode(); if (statusCode == -1) { throw new HttpClientException("Invalid response from " + uri); } if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) { throw new HttpClientException("Expected status code " + expectedStatusCodes + ", got " + statusCode); } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) { throw new HttpClientException("Expected status code 2xx, got " + statusCode); } final Map<String, List<String>> headerFields = conn.getHeaderFields(); final Map<String, String> inMemoryCookies = hc.getInMemoryCookies(); if (headerFields != null) { final List<String> newCookies = headerFields.get("Set-Cookie"); if (newCookies != null) { for (final String newCookie : newCookies) { final String rawCookie = newCookie.split(";", 2)[0]; final int i = rawCookie.indexOf('='); final String name = rawCookie.substring(0, i); final String value = rawCookie.substring(i + 1); inMemoryCookies.put(name, value); } } } if (isStatusCodeError(statusCode)) { // Got an error: cannot read input. payloadStream = new UncloseableInputStream(getErrorStream(conn)); } else { payloadStream = new UncloseableInputStream(getInputStream(conn)); } final HttpResponse resp = new HttpResponse(statusCode, payloadStream, headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies); if (handler != null) { try { handler.onResponse(resp); } catch (HttpClientException e) { throw e; } catch (Exception e) { throw new HttpClientException("Error in response handler", e); } } else { final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir()); resp.preload(temp); temp.delete(); } return resp; } catch (SocketTimeoutException e) { if (handler != null) { try { handler.onTimeout(); return null; } catch (HttpClientException e2) { throw e2; } catch (Exception e2) { throw new HttpClientException("Error in response handler", e2); } } else { throw new HttpClientException("Response timeout from " + uri, e); } } catch (IOException e) { throw new HttpClientException("Connection failed to " + uri, e); } finally { if (conn != null) { if (payloadStream != null) { // Fully read Http response: // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html try { while (payloadStream.read(buffer) != -1) { ; } } catch (IOException ignore) { } payloadStream.forceClose(); } conn.disconnect(); } } } private static boolean isStatusCodeError(int sc) { final int i = sc / 100; return i == 4 || i == 5; } private static void prepareCookieHeader(Map<String, String> cookies, StringBuilder headerValue) { if (cookies != null) { for (final Map.Entry<String, String> e : cookies.entrySet()) { if (headerValue.length() != 0) { headerValue.append("; "); } headerValue.append(e.getKey()).append("=").append(e.getValue()); } } } /** * Open the {@link InputStream} of an Http response. This method supports * GZIP and DEFLATE responses. */ private static InputStream getInputStream(HttpURLConnection conn) throws IOException { final List<String> contentEncodingValues = conn.getHeaderFields().get("Content-Encoding"); if (contentEncodingValues != null) { for (final String contentEncoding : contentEncodingValues) { if (contentEncoding != null) { if (contentEncoding.contains("gzip")) { return new GZIPInputStream(conn.getInputStream()); } if (contentEncoding.contains("deflate")) { return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); } } } } return conn.getInputStream(); } /** * Open the error {@link InputStream} of an Http response. This method * supports GZIP and DEFLATE responses. */ private static InputStream getErrorStream(HttpURLConnection conn) throws IOException { final List<String> contentEncodingValues = conn.getHeaderFields().get("Content-Encoding"); if (contentEncodingValues != null) { for (final String contentEncoding : contentEncodingValues) { if (contentEncoding != null) { if (contentEncoding.contains("gzip")) { return new GZIPInputStream(conn.getErrorStream()); } if (contentEncoding.contains("deflate")) { return new InflaterInputStream(conn.getErrorStream(), new Inflater(true)); } } } } return conn.getErrorStream(); } private static KeyStore loadCertificates(Context context) throws IOException { try { final KeyStore localTrustStore = KeyStore.getInstance("BKS"); final InputStream in = context.getResources().openRawResource(R.raw.hc_keystore); try { localTrustStore.load(in, null); } finally { in.close(); } return localTrustStore; } catch (Exception e) { final IOException ioe = new IOException("Failed to load SSL certificates"); ioe.initCause(e); throw ioe; } } /** * Setup SSL connection. */ private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException { final SSLContext sslContext; try { // SSL certificates are provided by the Guardian Project: // https://github.com/guardianproject/cacert if (trustManagers == null) { // Load SSL certificates: // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html // Earlier Android versions do not have updated root CA // certificates, resulting in connection errors. final KeyStore keyStore = loadCertificates(context); final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore); trustManagers = new TrustManager[] { customTrustManager }; } // Init SSL connection with custom certificates. // The same SecureRandom instance is used for every connection to // speed up initialization. sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, SECURE_RANDOM); } catch (GeneralSecurityException e) { final IOException ioe = new IOException("Failed to initialize SSL engine"); ioe.initCause(e); throw ioe; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // Fix slow read: // http://code.google.com/p/android/issues/detail?id=13117 // Prior to ICS, the host name is still resolved even if we already // know its IP address, for each connection. final SSLSocketFactory delegate = sslContext.getSocketFactory(); final SSLSocketFactory socketFactory = new SSLSocketFactory() { @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { InetAddress addr = InetAddress.getByName(host); injectHostname(addr, host); return delegate.createSocket(addr, port); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { return delegate.createSocket(host, port, localHost, localPort); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); } private void injectHostname(InetAddress address, String host) { try { Field field = InetAddress.class.getDeclaredField("hostName"); field.setAccessible(true); field.set(address, host); } catch (Exception ignored) { } } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { injectHostname(s.getInetAddress(), host); return delegate.createSocket(s, host, port, autoClose); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } }; conn.setSSLSocketFactory(socketFactory); } else { conn.setSSLSocketFactory(sslContext.getSocketFactory()); } conn.setHostnameVerifier(new BrowserCompatHostnameVerifier()); } }
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.recents; import android.app.ActivityManager; import android.app.UiModeManager; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Point; import android.graphics.Rect; import android.hardware.display.DisplayManager; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.os.SystemProperties; import android.os.UserHandle; import android.provider.Settings; import android.util.EventLog; import android.util.Log; import android.view.Display; import android.widget.Toast; import com.android.internal.logging.MetricsLogger; import com.android.internal.logging.MetricsProto.MetricsEvent; import com.android.systemui.EventLogConstants; import com.android.systemui.EventLogTags; import com.android.systemui.R; import com.android.systemui.RecentsComponent; import com.android.systemui.SystemUI; import com.android.systemui.recents.events.EventBus; import com.android.systemui.recents.events.activity.ConfigurationChangedEvent; import com.android.systemui.recents.events.activity.DockedTopTaskEvent; import com.android.systemui.recents.events.activity.RecentsActivityStartingEvent; import com.android.systemui.recents.events.component.RecentsVisibilityChangedEvent; import com.android.systemui.recents.events.component.ScreenPinningRequestEvent; import com.android.systemui.recents.events.ui.RecentsDrawnEvent; import com.android.systemui.recents.misc.SystemServicesProxy; import com.android.systemui.recents.model.RecentsTaskLoader; import com.android.systemui.recents.tv.RecentsTvImpl; import com.android.systemui.stackdivider.Divider; import java.util.ArrayList; /** * An implementation of the SystemUI recents component, which supports both system and secondary * users. */ public class Recents extends SystemUI implements RecentsComponent { private final static String TAG = "Recents"; private final static boolean DEBUG = false; public final static int EVENT_BUS_PRIORITY = 1; public final static int BIND_TO_SYSTEM_USER_RETRY_DELAY = 5000; public final static int RECENTS_GROW_TARGET_INVALID = -1; // Purely for experimentation private final static String RECENTS_OVERRIDE_SYSPROP_KEY = "persist.recents_override_pkg"; private final static String ACTION_SHOW_RECENTS = "com.android.systemui.recents.ACTION_SHOW"; private final static String ACTION_HIDE_RECENTS = "com.android.systemui.recents.ACTION_HIDE"; private final static String ACTION_TOGGLE_RECENTS = "com.android.systemui.recents.ACTION_TOGGLE"; private static final String COUNTER_WINDOW_SUPPORTED = "window_enter_supported"; private static final String COUNTER_WINDOW_UNSUPPORTED = "window_enter_unsupported"; private static final String COUNTER_WINDOW_INCOMPATIBLE = "window_enter_incompatible"; private static SystemServicesProxy sSystemServicesProxy; private static RecentsDebugFlags sDebugFlags; private static RecentsTaskLoader sTaskLoader; private static RecentsConfiguration sConfiguration; // For experiments only, allows another package to handle recents if it is defined in the system // properties. This is limited to show/toggle/hide, and does not tie into the ActivityManager, // and does not reside in the home stack. private String mOverrideRecentsPackageName; private Handler mHandler; private RecentsImpl mImpl; private int mDraggingInRecentsCurrentUser; // Only For system user, this is the callbacks instance we return to each secondary user private RecentsSystemUser mSystemToUserCallbacks; // Only for secondary users, this is the callbacks instance provided by the system user to make // calls back private IRecentsSystemUserCallbacks mUserToSystemCallbacks; // The set of runnables to run after binding to the system user's service. private final ArrayList<Runnable> mOnConnectRunnables = new ArrayList<>(); // Only for secondary users, this is the death handler for the binder from the system user private final IBinder.DeathRecipient mUserToSystemCallbacksDeathRcpt = new IBinder.DeathRecipient() { @Override public void binderDied() { mUserToSystemCallbacks = null; EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION, EventLogConstants.SYSUI_RECENTS_CONNECTION_USER_SYSTEM_UNBOUND, sSystemServicesProxy.getProcessUser()); // Retry after a fixed duration mHandler.postDelayed(new Runnable() { @Override public void run() { registerWithSystemUser(); } }, BIND_TO_SYSTEM_USER_RETRY_DELAY); } }; // Only for secondary users, this is the service connection we use to connect to the system user private final ServiceConnection mUserToSystemServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { if (service != null) { mUserToSystemCallbacks = IRecentsSystemUserCallbacks.Stub.asInterface( service); EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION, EventLogConstants.SYSUI_RECENTS_CONNECTION_USER_SYSTEM_BOUND, sSystemServicesProxy.getProcessUser()); // Listen for system user's death, so that we can reconnect later try { service.linkToDeath(mUserToSystemCallbacksDeathRcpt, 0); } catch (RemoteException e) { Log.e(TAG, "Lost connection to (System) SystemUI", e); } // Run each of the queued runnables runAndFlushOnConnectRunnables(); } // Unbind ourselves now that we've registered our callbacks. The // binder to the system user are still valid at this point. mContext.unbindService(this); } @Override public void onServiceDisconnected(ComponentName name) { // Do nothing } }; /** * Returns the callbacks interface that non-system users can call. */ public IBinder getSystemUserCallbacks() { return mSystemToUserCallbacks; } public static RecentsTaskLoader getTaskLoader() { return sTaskLoader; } public static SystemServicesProxy getSystemServices() { return sSystemServicesProxy; } public static RecentsConfiguration getConfiguration() { return sConfiguration; } public static RecentsDebugFlags getDebugFlags() { return sDebugFlags; } @Override public void start() { sDebugFlags = new RecentsDebugFlags(mContext); sSystemServicesProxy = SystemServicesProxy.getInstance(mContext); sTaskLoader = new RecentsTaskLoader(mContext); sConfiguration = new RecentsConfiguration(mContext); mHandler = new Handler(); UiModeManager uiModeManager = (UiModeManager) mContext. getSystemService(Context.UI_MODE_SERVICE); if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) { mImpl = new RecentsTvImpl(mContext); } else { mImpl = new RecentsImpl(mContext); } // Check if there is a recents override package if ("userdebug".equals(Build.TYPE) || "eng".equals(Build.TYPE)) { String cnStr = SystemProperties.get(RECENTS_OVERRIDE_SYSPROP_KEY); if (!cnStr.isEmpty()) { mOverrideRecentsPackageName = cnStr; } } // Register with the event bus EventBus.getDefault().register(this, EVENT_BUS_PRIORITY); EventBus.getDefault().register(sSystemServicesProxy, EVENT_BUS_PRIORITY); EventBus.getDefault().register(sTaskLoader, EVENT_BUS_PRIORITY); // Due to the fact that RecentsActivity is per-user, we need to establish and interface for // the system user's Recents component to pass events (like show/hide/toggleRecents) to the // secondary user, and vice versa (like visibility change, screen pinning). final int processUser = sSystemServicesProxy.getProcessUser(); if (sSystemServicesProxy.isSystemUser(processUser)) { // For the system user, initialize an instance of the interface that we can pass to the // secondary user mSystemToUserCallbacks = new RecentsSystemUser(mContext, mImpl); } else { // For the secondary user, bind to the primary user's service to get a persistent // interface to register its implementation and to later update its state registerWithSystemUser(); } putComponent(Recents.class, this); } @Override public void onBootCompleted() { mImpl.onBootCompleted(); } /** * Shows the Recents. */ @Override public void showRecents(boolean triggeredFromAltTab, boolean fromHome) { // Ensure the device has been provisioned before allowing the user to interact with // recents if (!isUserSetup()) { return; } if (proxyToOverridePackage(ACTION_SHOW_RECENTS)) { return; } int recentsGrowTarget = getComponent(Divider.class).getView().growsRecents(); int currentUser = sSystemServicesProxy.getCurrentUser(); if (sSystemServicesProxy.isSystemUser(currentUser)) { mImpl.showRecents(triggeredFromAltTab, false /* draggingInRecents */, true /* animate */, false /* reloadTasks */, fromHome, recentsGrowTarget); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser); if (callbacks != null) { try { callbacks.showRecents(triggeredFromAltTab, false /* draggingInRecents */, true /* animate */, false /* reloadTasks */, fromHome, recentsGrowTarget); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser); } } } } /** * Hides the Recents. */ @Override public void hideRecents(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) { // Ensure the device has been provisioned before allowing the user to interact with // recents if (!isUserSetup()) { return; } if (proxyToOverridePackage(ACTION_HIDE_RECENTS)) { return; } int currentUser = sSystemServicesProxy.getCurrentUser(); if (sSystemServicesProxy.isSystemUser(currentUser)) { mImpl.hideRecents(triggeredFromAltTab, triggeredFromHomeKey); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser); if (callbacks != null) { try { callbacks.hideRecents(triggeredFromAltTab, triggeredFromHomeKey); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser); } } } } /** * Toggles the Recents activity. */ @Override public void toggleRecents(Display display) { // Ensure the device has been provisioned before allowing the user to interact with // recents if (!isUserSetup()) { return; } if (proxyToOverridePackage(ACTION_TOGGLE_RECENTS)) { return; } int growTarget = getComponent(Divider.class).getView().growsRecents(); int currentUser = sSystemServicesProxy.getCurrentUser(); if (sSystemServicesProxy.isSystemUser(currentUser)) { mImpl.toggleRecents(growTarget); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser); if (callbacks != null) { try { callbacks.toggleRecents(growTarget); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser); } } } } /** * Preloads info for the Recents activity. */ @Override public void preloadRecents() { // Ensure the device has been provisioned before allowing the user to interact with // recents if (!isUserSetup()) { return; } int currentUser = sSystemServicesProxy.getCurrentUser(); if (sSystemServicesProxy.isSystemUser(currentUser)) { mImpl.preloadRecents(); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser); if (callbacks != null) { try { callbacks.preloadRecents(); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser); } } } } @Override public void cancelPreloadingRecents() { // Ensure the device has been provisioned before allowing the user to interact with // recents if (!isUserSetup()) { return; } int currentUser = sSystemServicesProxy.getCurrentUser(); if (sSystemServicesProxy.isSystemUser(currentUser)) { mImpl.cancelPreloadingRecents(); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser); if (callbacks != null) { try { callbacks.cancelPreloadingRecents(); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser); } } } } @Override public boolean dockTopTask(int dragMode, int stackCreateMode, Rect initialBounds, int metricsDockAction) { // Ensure the device has been provisioned before allowing the user to interact with // recents if (!isUserSetup()) { return false; } Point realSize = new Point(); if (initialBounds == null) { mContext.getSystemService(DisplayManager.class).getDisplay(Display.DEFAULT_DISPLAY) .getRealSize(realSize); initialBounds = new Rect(0, 0, realSize.x, realSize.y); } int currentUser = sSystemServicesProxy.getCurrentUser(); SystemServicesProxy ssp = Recents.getSystemServices(); ActivityManager.RunningTaskInfo runningTask = ssp.getRunningTask(); boolean screenPinningActive = ssp.isScreenPinningActive(); boolean isRunningTaskInHomeStack = runningTask != null && SystemServicesProxy.isHomeStack(runningTask.stackId); if (runningTask != null && !isRunningTaskInHomeStack && !screenPinningActive) { logDockAttempt(mContext, runningTask.topActivity, runningTask.resizeMode); if (runningTask.isDockable) { if (metricsDockAction != -1) { MetricsLogger.action(mContext, metricsDockAction, runningTask.topActivity.flattenToShortString()); } if (sSystemServicesProxy.isSystemUser(currentUser)) { mImpl.dockTopTask(runningTask.id, dragMode, stackCreateMode, initialBounds); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser); if (callbacks != null) { try { callbacks.dockTopTask(runningTask.id, dragMode, stackCreateMode, initialBounds); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser); } } } mDraggingInRecentsCurrentUser = currentUser; return true; } else { Toast.makeText(mContext, R.string.recents_incompatible_app_message, Toast.LENGTH_SHORT).show(); return false; } } else { return false; } } public static void logDockAttempt(Context ctx, ComponentName activity, int resizeMode) { if (resizeMode == ActivityInfo.RESIZE_MODE_UNRESIZEABLE) { MetricsLogger.action(ctx, MetricsEvent.ACTION_WINDOW_DOCK_UNRESIZABLE, activity.flattenToShortString()); } MetricsLogger.count(ctx, getMetricsCounterForResizeMode(resizeMode), 1); } private static String getMetricsCounterForResizeMode(int resizeMode) { switch (resizeMode) { case ActivityInfo.RESIZE_MODE_FORCE_RESIZEABLE: return COUNTER_WINDOW_UNSUPPORTED; case ActivityInfo.RESIZE_MODE_RESIZEABLE: case ActivityInfo.RESIZE_MODE_RESIZEABLE_AND_PIPABLE: return COUNTER_WINDOW_SUPPORTED; default: return COUNTER_WINDOW_INCOMPATIBLE; } } @Override public void onDraggingInRecents(float distanceFromTop) { if (sSystemServicesProxy.isSystemUser(mDraggingInRecentsCurrentUser)) { mImpl.onDraggingInRecents(distanceFromTop); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser( mDraggingInRecentsCurrentUser); if (callbacks != null) { try { callbacks.onDraggingInRecents(distanceFromTop); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + mDraggingInRecentsCurrentUser); } } } } @Override public void onDraggingInRecentsEnded(float velocity) { if (sSystemServicesProxy.isSystemUser(mDraggingInRecentsCurrentUser)) { mImpl.onDraggingInRecentsEnded(velocity); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser( mDraggingInRecentsCurrentUser); if (callbacks != null) { try { callbacks.onDraggingInRecentsEnded(velocity); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + mDraggingInRecentsCurrentUser); } } } } @Override public void showNextAffiliatedTask() { // Ensure the device has been provisioned before allowing the user to interact with // recents if (!isUserSetup()) { return; } mImpl.showNextAffiliatedTask(); } @Override public void showPrevAffiliatedTask() { // Ensure the device has been provisioned before allowing the user to interact with // recents if (!isUserSetup()) { return; } mImpl.showPrevAffiliatedTask(); } /** * Updates on configuration change. */ public void onConfigurationChanged(Configuration newConfig) { int currentUser = sSystemServicesProxy.getCurrentUser(); if (sSystemServicesProxy.isSystemUser(currentUser)) { mImpl.onConfigurationChanged(); } else { if (mSystemToUserCallbacks != null) { IRecentsNonSystemUserCallbacks callbacks = mSystemToUserCallbacks.getNonSystemUserRecentsForUser(currentUser); if (callbacks != null) { try { callbacks.onConfigurationChanged(); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } else { Log.e(TAG, "No SystemUI callbacks found for user: " + currentUser); } } } } /** * Handle Recents activity visibility changed. */ public final void onBusEvent(final RecentsVisibilityChangedEvent event) { SystemServicesProxy ssp = Recents.getSystemServices(); int processUser = ssp.getProcessUser(); if (ssp.isSystemUser(processUser)) { mImpl.onVisibilityChanged(event.applicationContext, event.visible); } else { postToSystemUser(new Runnable() { @Override public void run() { try { mUserToSystemCallbacks.updateRecentsVisibility(event.visible); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } }); } } /** * Handle screen pinning request. */ public final void onBusEvent(final ScreenPinningRequestEvent event) { int processUser = sSystemServicesProxy.getProcessUser(); if (sSystemServicesProxy.isSystemUser(processUser)) { mImpl.onStartScreenPinning(event.applicationContext, event.taskId); } else { postToSystemUser(new Runnable() { @Override public void run() { try { mUserToSystemCallbacks.startScreenPinning(event.taskId); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } }); } } public final void onBusEvent(final RecentsDrawnEvent event) { int processUser = sSystemServicesProxy.getProcessUser(); if (!sSystemServicesProxy.isSystemUser(processUser)) { postToSystemUser(new Runnable() { @Override public void run() { try { mUserToSystemCallbacks.sendRecentsDrawnEvent(); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } }); } } public final void onBusEvent(final DockedTopTaskEvent event) { int processUser = sSystemServicesProxy.getProcessUser(); if (!sSystemServicesProxy.isSystemUser(processUser)) { postToSystemUser(new Runnable() { @Override public void run() { try { mUserToSystemCallbacks.sendDockingTopTaskEvent(event.dragMode, event.initialRect); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } }); } } public final void onBusEvent(final RecentsActivityStartingEvent event) { int processUser = sSystemServicesProxy.getProcessUser(); if (!sSystemServicesProxy.isSystemUser(processUser)) { postToSystemUser(new Runnable() { @Override public void run() { try { mUserToSystemCallbacks.sendLaunchRecentsEvent(); } catch (RemoteException e) { Log.e(TAG, "Callback failed", e); } } }); } } public final void onBusEvent(ConfigurationChangedEvent event) { // Update the configuration for the Recents component when the activity configuration // changes as well mImpl.onConfigurationChanged(); } /** * Attempts to register with the system user. */ private void registerWithSystemUser() { final int processUser = sSystemServicesProxy.getProcessUser(); postToSystemUser(new Runnable() { @Override public void run() { try { mUserToSystemCallbacks.registerNonSystemUserCallbacks( new RecentsImplProxy(mImpl), processUser); } catch (RemoteException e) { Log.e(TAG, "Failed to register", e); } } }); } /** * Runs the runnable in the system user's Recents context, connecting to the service if * necessary. */ private void postToSystemUser(final Runnable onConnectRunnable) { mOnConnectRunnables.add(onConnectRunnable); if (mUserToSystemCallbacks == null) { Intent systemUserServiceIntent = new Intent(); systemUserServiceIntent.setClass(mContext, RecentsSystemUserService.class); boolean bound = mContext.bindServiceAsUser(systemUserServiceIntent, mUserToSystemServiceConnection, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM); EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION, EventLogConstants.SYSUI_RECENTS_CONNECTION_USER_BIND_SERVICE, sSystemServicesProxy.getProcessUser()); if (!bound) { // Retry after a fixed duration mHandler.postDelayed(new Runnable() { @Override public void run() { registerWithSystemUser(); } }, BIND_TO_SYSTEM_USER_RETRY_DELAY); } } else { runAndFlushOnConnectRunnables(); } } /** * Runs all the queued runnables after a service connection is made. */ private void runAndFlushOnConnectRunnables() { for (Runnable r : mOnConnectRunnables) { r.run(); } mOnConnectRunnables.clear(); } /** * @return whether this device is provisioned and the current user is set up. */ private boolean isUserSetup() { ContentResolver cr = mContext.getContentResolver(); return (Settings.Global.getInt(cr, Settings.Global.DEVICE_PROVISIONED, 0) != 0) && (Settings.Secure.getInt(cr, Settings.Secure.USER_SETUP_COMPLETE, 0) != 0); } /** * Attempts to proxy the following action to the override recents package. * @return whether the proxying was successful */ private boolean proxyToOverridePackage(String action) { if (mOverrideRecentsPackageName != null) { Intent intent = new Intent(action); intent.setPackage(mOverrideRecentsPackageName); intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); mContext.sendBroadcast(intent); return true; } return false; } }
package com.codahale.metrics; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import com.codahale.metrics.WeightedSnapshot.WeightedSample; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.offset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; public class WeightedSnapshotTest { static public ArrayList<WeightedSample> WeightedArray(long[] values, double[] weights) { if (values.length != weights.length) { throw new IllegalArgumentException("Mismatched lengths: " + values.length + " vs " + weights.length); } final ArrayList<WeightedSample> samples = new ArrayList<WeightedSnapshot.WeightedSample>(); for (int i = 0; i < values.length; i++) { samples.add(new WeightedSnapshot.WeightedSample(values[i], weights[i])); } return samples; } private final Snapshot snapshot = new WeightedSnapshot( WeightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2}) ); @Test public void smallQuantilesAreTheFirstValue() throws Exception { assertThat(snapshot.getValue(0.0)) .isEqualTo(1.0, offset(0.1)); } @Test public void bigQuantilesAreTheLastValue() throws Exception { assertThat(snapshot.getValue(1.0)) .isEqualTo(5.0, offset(0.1)); } @Test(expected = IllegalArgumentException.class) public void disallowsNotANumberQuantile() { snapshot.getValue( Double.NaN ); } @Test(expected = IllegalArgumentException.class) public void disallowsNegativeQuantile() { snapshot.getValue( -0.5 ); } @Test(expected = IllegalArgumentException.class) public void disallowsQuantileOverOne() { snapshot.getValue( 1.5 ); } @Test public void hasAMedian() throws Exception { assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); } @Test public void hasAp75() throws Exception { assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); } @Test public void hasAp95() throws Exception { assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test public void hasAp98() throws Exception { assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test public void hasAp99() throws Exception { assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test public void hasAp999() throws Exception { assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test public void hasValues() throws Exception { assertThat(snapshot.getValues()) .containsOnly(1, 2, 3, 4, 5); } @Test public void hasASize() throws Exception { assertThat(snapshot.size()) .isEqualTo(5); } @Test public void worksWithUnderestimatedCollections() throws Exception { final List<WeightedSample> items = spy(WeightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2})); when(items.size()).thenReturn(4, 5); final Snapshot other = new WeightedSnapshot(items); assertThat(other.getValues()) .containsOnly(1, 2, 3, 4, 5); } @Test public void worksWithOverestimatedCollections() throws Exception { final List<WeightedSample> items = spy(WeightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2})); when(items.size()).thenReturn(6, 5); final Snapshot other = new WeightedSnapshot(items); assertThat(other.getValues()) .containsOnly(1, 2, 3, 4, 5); } @Test public void dumpsToAStream() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); snapshot.dump(output); assertThat(output.toString()) .isEqualTo(String.format("1%n2%n3%n4%n5%n")); } @Test public void calculatesTheMinimumValue() throws Exception { assertThat(snapshot.getMin()) .isEqualTo(1); } @Test public void calculatesTheMaximumValue() throws Exception { assertThat(snapshot.getMax()) .isEqualTo(5); } @Test public void calculatesTheMeanValue() throws Exception { assertThat(snapshot.getMean()) .isEqualTo(2.7); } @Test public void calculatesTheStdDev() throws Exception { assertThat(snapshot.getStdDev()) .isEqualTo(1.2688, offset(0.0001)); } @Test public void calculatesAMinOfZeroForAnEmptySnapshot() throws Exception { final Snapshot emptySnapshot = new WeightedSnapshot( WeightedArray(new long[]{}, new double[]{}) ); assertThat(emptySnapshot.getMin()) .isZero(); } @Test public void calculatesAMaxOfZeroForAnEmptySnapshot() throws Exception { final Snapshot emptySnapshot = new WeightedSnapshot( WeightedArray(new long[]{}, new double[]{}) ); assertThat(emptySnapshot.getMax()) .isZero(); } @Test public void calculatesAMeanOfZeroForAnEmptySnapshot() throws Exception { final Snapshot emptySnapshot = new WeightedSnapshot( WeightedArray(new long[]{}, new double[]{}) ); assertThat(emptySnapshot.getMean()) .isZero(); } @Test public void calculatesAStdDevOfZeroForAnEmptySnapshot() throws Exception { final Snapshot emptySnapshot = new WeightedSnapshot( WeightedArray(new long[]{}, new double[]{}) ); assertThat(emptySnapshot.getStdDev()) .isZero(); } @Test public void calculatesAStdDevOfZeroForASingletonSnapshot() throws Exception { final Snapshot singleItemSnapshot = new WeightedSnapshot( WeightedArray(new long[]{ 1 }, new double[]{ 1.0 }) ); assertThat(singleItemSnapshot.getStdDev()) .isZero(); } @Test public void expectNoOverflowForLowWeights() throws Exception { final Snapshot scatteredSnapshot = new WeightedSnapshot( WeightedArray( new long[]{ 1, 2, 3 }, new double[]{ Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE } ) ); assertThat(scatteredSnapshot.getMean()) .isEqualTo(2); } }
package br.com.delogic.jnerator.impl; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import br.com.delogic.jfunk.Each; import br.com.delogic.jfunk.ForEach; import br.com.delogic.jnerator.AttributeConfiguration; import br.com.delogic.jnerator.AttributeConfigurationFactory; import br.com.delogic.jnerator.AttributeConfigurationImpl; import br.com.delogic.jnerator.AttributeGenerator; import br.com.delogic.jnerator.AttributeGeneratorFactory; import br.com.delogic.jnerator.InstanceGenerator; import br.com.delogic.jnerator.JNerator; import br.com.delogic.jnerator.RelationshipConfiguration; import br.com.delogic.jnerator.RelationshipConfigurationFactory; import br.com.delogic.jnerator.exception.JNeratorException; import br.com.delogic.jnerator.util.ReflectionUtils; public class SimpleInstanceGenerator<T> implements InstanceGenerator<T> { private final Map<String, AttributeConfigurationImpl<T>> attributesConfiguration; private final Map<String, AttributeGenerator> attributesGenerator; private final Class<T> type; private List<T> cachedInstances; private final JNerator jNerator; private final RelationshipConfigurationFactory relationshipConfigurationFactory; private final AttributeGeneratorFactory attributeGeneratorFactory; private final Set<String> ignoredAttributes; public SimpleInstanceGenerator(Class<T> type, AttributeConfigurationFactory attributeConfigurationFactory, AttributeGeneratorFactory attributeGeneratorFactory, RelationshipConfigurationFactory relationshipConfigurationFactory, JNerator jNerator) { this.type = type; this.jNerator = jNerator; this.relationshipConfigurationFactory = relationshipConfigurationFactory; this.attributeGeneratorFactory = attributeGeneratorFactory; this.attributesConfiguration = asMap(attributeConfigurationFactory.create(type, this)); this.attributesGenerator = new LinkedHashMap<String, AttributeGenerator>(); this.ignoredAttributes = new HashSet<String>(); for (Entry<String, AttributeConfigurationImpl<T>> attributeConfiguration : attributesConfiguration.entrySet()) { AttributeGenerator generator = attributeGeneratorFactory.create(attributeConfiguration.getValue().getField(), this); attributesGenerator.put(attributeConfiguration.getValue().getName(), generator); } } private Map<String, AttributeConfigurationImpl<T>> asMap(List<AttributeConfigurationImpl<T>> create) { Map<String, AttributeConfigurationImpl<T>> attrs = new LinkedHashMap<String, AttributeConfigurationImpl<T>>(); for (AttributeConfigurationImpl<T> ac : create) { attrs.put(ac.getName(), ac); } return attrs; } public List<T> generate(int amount) { List<T> instances = new ArrayList<T>(); removeIgnoredAttributes(); int displayedExecution = 0; int currentAmount = 0; if (amount > 1000) System.out.println(type); for (int index = 0; index < amount; index++) { T instance = (T) ReflectionUtils.instantiate(type); populateInstance(instance, index); instances.add(instance); if (amount > 1000 && (currentAmount = (int) (((float) index / amount) * 100)) > displayedExecution) { String line = "" + currentAmount + "%\r"; System.out.print(line); displayedExecution = currentAmount; } } cachedInstances = Collections.unmodifiableList(instances); return instances; } private void removeIgnoredAttributes() { ForEach.element(ignoredAttributes, new Each<String>() { public void each(String element, int arg1) { attributesConfiguration.remove(element); attributesGenerator.remove(element); } }); } void populateInstance(T instance, int index) { for (String attributeName : attributesGenerator.keySet()) { AttributeGenerator generator = attributesGenerator.get(attributeName); AttributeConfiguration<T> config = attributesConfiguration.get(attributeName); Object value = generator.generate(index, config, instance); Field field = config.getField(); setFieldValue(field, instance, value); } } void setFieldValue(Field field, T instance, Object value) { try { if (!field.isAccessible()) { field.setAccessible(true); } field.set(instance, value); } catch (Exception e) { throw new JNeratorException("Error trying to set field value for field:" + field + " and value: " + value, e); } } public List<T> getCachedInstances() { return cachedInstances; } public <E> InstanceGenerator<T> setAttributeGenerator(String attributeName, AttributeGenerator attributeGenerator) { attributesGenerator.remove(attributeName); // always put new generators at the end to obey order of generation attributesGenerator.put(attributeName, attributeGenerator); return this; } @SuppressWarnings("unchecked") public <R> InstanceGenerator<R> forRelationship(String attributeName, Class<? extends R> relationshipType) { AttributeConfiguration<T> config = attributesConfiguration.get(attributeName); RelationshipConfiguration relationshipConfiguration = relationshipConfigurationFactory.create(config.getField()); InstanceGenerator<R> instanceGenerator = (InstanceGenerator<R>) jNerator.prepare(relationshipType); AttributeGenerator attributeGenerator = attributeGeneratorFactory.create(config.getField(), instanceGenerator, relationshipConfiguration); this.attributesGenerator.put(attributeName, attributeGenerator); return instanceGenerator; } public InstanceGenerator<T> doNotGenerateAttribute(String... attributeNames) { for (String atr : attributeNames) { ignoredAttributes.add(atr); } return this; } public AttributeConfiguration<T> forAttr(String attributeName) { return (AttributeConfiguration<T>) attributesConfiguration.get(attributeName); } @SuppressWarnings("unchecked") public <E> InstanceGenerator<E> forRelationship(String attributeName, List<Class<? extends E>> types) { AttributeConfiguration<T> config = attributesConfiguration.get(attributeName); RelationshipConfiguration relationshipConfiguration = relationshipConfigurationFactory.create(config.getField()); final List<InstanceGenerator<E>> allTypesGenerators = new ArrayList<InstanceGenerator<E>>(); for (Class<? extends E> relType : types) { allTypesGenerators.add((InstanceGenerator<E>) jNerator.prepare(relType)); } InstanceGenerator<E> proxyMultiGenerators = new InstanceGenerator<E>() { public List<E> generate(int amount) { List<E> ts = new ArrayList<E>(); for (InstanceGenerator<E> ig : allTypesGenerators) { ts.addAll(ig.generate(amount)); } // let's shufle to avoid same results Collections.shuffle(ts); return ts; } public List<E> getCachedInstances() { List<E> ts = new ArrayList<E>(); for (InstanceGenerator<E> ig : allTypesGenerators) { ts.addAll(ig.getCachedInstances()); } return ts; } public <I> InstanceGenerator<E> setAttributeGenerator(String attributeName, AttributeGenerator attributeGenerator) { for (InstanceGenerator<E> ig : allTypesGenerators) { ig.setAttributeGenerator(attributeName, attributeGenerator); } return this; } public <EE> InstanceGenerator<EE> forRelationship(String attributeName, Class<? extends EE> type) { throw new UnsupportedOperationException( "Multi types relationship attribute generators cannot set other attribute generators"); } public InstanceGenerator<E> doNotGenerateAttribute(String... attributeNames) { throw new UnsupportedOperationException( "Multi types relationship attribute generators cannot set this parameter"); } public AttributeConfiguration<E> forAttr(String attributeName) { throw new UnsupportedOperationException( "Multi types relationship attribute generators cannot set this parameter"); } public <R> InstanceGenerator<R> forRelationship(String attributeName, List<Class<? extends R>> types) { throw new UnsupportedOperationException( "Multi types relationship attribute generators cannot set this parameter"); } }; AttributeGenerator attributeGenerator = attributeGeneratorFactory.create(config.getField(), proxyMultiGenerators, relationshipConfiguration); this.attributesGenerator.put(attributeName, attributeGenerator); return proxyMultiGenerators; } }
// ======================================================================== // Copyright (c) 2006-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.deploy; import java.io.File; import java.io.FilenameFilter; import java.util.HashMap; import java.util.Map; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.util.AttributesMap; import org.eclipse.jetty.util.Scanner; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.xml.XmlConfiguration; /** * Legacy Context Deployer. * * <p> * Note: The WebAppDeployer is being phased out of Jetty in favor of the {@link DeploymentManager} and * {@link org.eclipse.jetty.deploy.providers.ContextProvider} implementation. * * <p> * This deployer scans a designated directory by {@link #setConfigurationDir(String)} for the appearance/disappearance * or changes to xml configuration files. The scan is performed at startup and at an optional hot deployment frequency * specified by {@link #setScanInterval(int)}. By default, the scanning is NOT recursive, but can be made so by * {@link #setRecursive(boolean)}. * * <p> * Each configuration file is in {@link XmlConfiguration} format and represents the configuration of a instance of * {@link ContextHandler} (or a subclass specified by the XML <code>Configure</code> element). * * <p> * The xml should configure the context and the instance is deployed to the {@link ContextHandlerCollection} specified * by {@link Server#setHandler(org.eclipse.jetty.server.Handler)}. * * <p> * Similarly, when one of these existing files is removed, the corresponding context is undeployed; when one of these * files is changed, the corresponding context is undeployed, the (changed) xml config file reapplied to it, and then * (re)deployed. * * <p> * Note that the context itself is NOT copied into the hot deploy directory. The webapp directory or war file can exist * anywhere. It is the xml config file that points to it's location and deploys it from there. * * <p> * It means, for example, that you can keep a "read-only" copy of your webapp somewhere, and apply different * configurations to it simply by dropping different xml configuration files into the configuration directory. * * @see DeploymentManager * @see MonitoredDirAppProvider * * @org.apache.xbean.XBean element="hotDeployer" description="Creates a hot deployer to watch a directory for changes at * a configurable interval." */ @SuppressWarnings("unchecked") @Deprecated public class ContextDeployer extends AbstractLifeCycle { private int _scanInterval=10; private Scanner _scanner; private ScannerListener _scannerListener; private Resource _contextsDir; private Map _currentDeployments = new HashMap(); private ContextHandlerCollection _contexts; private ConfigurationManager _configMgr; private boolean _recursive = false; private AttributesMap _contextAttributes = new AttributesMap(); /* ------------------------------------------------------------ */ protected class ScannerListener implements Scanner.DiscreteListener { /** * Handle a new deployment * * @see org.eclipse.jetty.util.Scanner.DiscreteListener#fileAdded(java.lang.String) */ public void fileAdded(String filename) throws Exception { deploy(filename); } /** * Handle a change to an existing deployment. Undeploy then redeploy. * * @see org.eclipse.jetty.util.Scanner.DiscreteListener#fileChanged(java.lang.String) */ public void fileChanged(String filename) throws Exception { redeploy(filename); } /** * Handle an undeploy. * * @see org.eclipse.jetty.util.Scanner.DiscreteListener#fileRemoved(java.lang.String) */ public void fileRemoved(String filename) throws Exception { undeploy(filename); } @Override public String toString() { return "ContextDeployer$Scanner"; } } /** * Constructor */ public ContextDeployer() { Log.warn("ContextDeployer is deprecated. Use ContextProvider"); _scanner=new Scanner(); } /* ------------------------------------------------------------ */ /** * @return the ContextHandlerColletion to which to deploy the contexts */ public ContextHandlerCollection getContexts() { return _contexts; } /* ------------------------------------------------------------ */ /** * Associate with a {@link ContextHandlerCollection}. * * @param contexts * the ContextHandlerColletion to which to deploy the contexts */ public void setContexts(ContextHandlerCollection contexts) { if (isStarted()||isStarting()) throw new IllegalStateException("Cannot set Contexts after deployer start"); _contexts=contexts; } /* ------------------------------------------------------------ */ /** * @param seconds * The period in second between scans for changed configuration * files. A zero or negative interval disables hot deployment */ public void setScanInterval(int seconds) { if (isStarted()||isStarting()) throw new IllegalStateException("Cannot change scan interval after deployer start"); _scanInterval=seconds; } /* ------------------------------------------------------------ */ public int getScanInterval() { return _scanInterval; } /* ------------------------------------------------------------ */ /** * @param dir Directory to scan for context descriptors */ public void setContextsDir(String dir) { try { _contextsDir=Resource.newResource(dir); } catch(Exception e) { throw new IllegalArgumentException(e); } } /* ------------------------------------------------------------ */ public String getContextsDir() { return _contextsDir==null?null:_contextsDir.toString(); } /* ------------------------------------------------------------ */ /** * @param dir * @throws Exception * @deprecated use {@link #setContextsDir(String)} */ @Deprecated public void setConfigurationDir(String dir) throws Exception { setConfigurationDir(Resource.newResource(dir)); } /* ------------------------------------------------------------ */ /** * @param file * @throws Exception * @deprecated use {@link #setContextsDir(String)} */ @Deprecated public void setConfigurationDir(File file) throws Exception { setConfigurationDir(Resource.newResource(file.toURL())); } /* ------------------------------------------------------------ */ /** * @param resource * @deprecated use {@link #setContextsDir(String)} */ @Deprecated public void setConfigurationDir(Resource resource) { if (isStarted()||isStarting()) throw new IllegalStateException("Cannot change hot deploy dir after deployer start"); _contextsDir=resource; } /* ------------------------------------------------------------ */ /** * @param directory * @deprecated use {@link #setContextsDir(String)} */ @Deprecated public void setDirectory(String directory) throws Exception { setConfigurationDir(directory); } /* ------------------------------------------------------------ */ /** * @return the directory * @deprecated use {@link #setContextsDir(String)} */ @Deprecated public String getDirectory() { return getConfigurationDir().getName(); } /* ------------------------------------------------------------ */ /** * @return the configuration directory * @deprecated use {@link #setContextsDir(String)} */ @Deprecated public Resource getConfigurationDir() { return _contextsDir; } /* ------------------------------------------------------------ */ /** * @param configMgr */ public void setConfigurationManager(ConfigurationManager configMgr) { _configMgr=configMgr; } /* ------------------------------------------------------------ */ /** * @return the configuration manager */ public ConfigurationManager getConfigurationManager() { return _configMgr; } /* ------------------------------------------------------------ */ public void setRecursive (boolean recursive) { _recursive=recursive; } /* ------------------------------------------------------------ */ public boolean getRecursive () { return _recursive; } /* ------------------------------------------------------------ */ public boolean isRecursive() { return _recursive; } /* ------------------------------------------------------------ */ /** * Set a contextAttribute that will be set for every Context deployed by this deployer. * @param name * @param value */ public void setAttribute (String name, Object value) { _contextAttributes.setAttribute(name,value); } /* ------------------------------------------------------------ */ /** * Get a contextAttribute that will be set for every Context deployed by this deployer. * @param name * @return the attribute value */ public Object getAttribute (String name) { return _contextAttributes.getAttribute(name); } /* ------------------------------------------------------------ */ /** * Remove a contextAttribute that will be set for every Context deployed by this deployer. * @param name */ public void removeAttribute(String name) { _contextAttributes.removeAttribute(name); } /* ------------------------------------------------------------ */ private void deploy(String filename) throws Exception { ContextHandler context=createContext(filename); Log.info("Deploy "+filename+" -> "+ context); _contexts.addHandler(context); _currentDeployments.put(filename,context); if (_contexts.isStarted()) context.start(); } /* ------------------------------------------------------------ */ private void undeploy(String filename) throws Exception { ContextHandler context=(ContextHandler)_currentDeployments.get(filename); Log.info("Undeploy "+filename+" -> "+context); if (context==null) return; context.stop(); _contexts.removeHandler(context); _currentDeployments.remove(filename); } /* ------------------------------------------------------------ */ private void redeploy(String filename) throws Exception { undeploy(filename); deploy(filename); } /* ------------------------------------------------------------ */ /** * Start the hot deployer looking for webapps to deploy/undeploy * * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() */ @SuppressWarnings("deprecation") @Override protected void doStart() throws Exception { if (_contextsDir==null) throw new IllegalStateException("No configuration dir specified"); if (_contexts==null) throw new IllegalStateException("No context handler collection specified for deployer"); _scanner.setScanDir(_contextsDir.getFile()); _scanner.setScanInterval(getScanInterval()); _scanner.setRecursive(_recursive); //only look in the top level for deployment files? // Accept changes only in files that could be a deployment descriptor _scanner.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { try { if (name.endsWith(".xml")) return true; return false; } catch (Exception e) { Log.warn(e); return false; } } }); _scannerListener=new ScannerListener(); _scanner.addListener(_scannerListener); _scanner.scan(); _scanner.start(); _contexts.getServer().getContainer().addBean(_scanner); } /* ------------------------------------------------------------ */ /** * Stop the hot deployer. * * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStop() */ @Override protected void doStop() throws Exception { _scanner.removeListener(_scannerListener); _scanner.stop(); } /* ------------------------------------------------------------ */ /** * Create a WebAppContext for the webapp being hot deployed, then apply the * xml config file to it to configure it. * * @param filename * the config file found in the hot deploy directory * @return * @throws Exception */ private ContextHandler createContext(String filename) throws Exception { // The config file can call any method on WebAppContext to configure // the webapp being deployed. Resource resource = Resource.newResource(filename); if (!resource.exists()) return null; XmlConfiguration xmlConfiguration=new XmlConfiguration(resource.getURL()); HashMap properties = new HashMap(); properties.put("Server", _contexts.getServer()); if (_configMgr!=null) properties.putAll(_configMgr.getProperties()); xmlConfiguration.setProperties(properties); ContextHandler context=(ContextHandler)xmlConfiguration.configure(); // merge attributes if (_contextAttributes!=null && _contextAttributes.size()>0) { AttributesMap attributes = new AttributesMap(_contextAttributes); attributes.addAll(context.getAttributes()); context.setAttributes(attributes); } return context; } }
package com.fissionworks.restalm.model.entity.testlab; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.testng.Assert; import org.testng.annotations.Test; import com.fissionworks.restalm.constants.field.TestInstanceField; import com.fissionworks.restalm.model.entity.base.Field; import com.fissionworks.restalm.model.entity.base.GenericEntity; import com.fissionworks.restalm.model.entity.defects.Defect; import com.fissionworks.restalm.model.entity.testplan.AlmTest; import com.fissionworks.restalm.model.entity.testplan.TestConfig; public class TestInstanceTest { private static final ThreadLocal<DateFormat> DATE_FORMATTER = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); } }; private final Calendar cal = Calendar.getInstance(); @Test public void createEntity_shouldCreateEnityWithAllFields() { final TestInstance sourceTestInstance = createFullTestInstance(); final GenericEntity createdEntity = sourceTestInstance.createEntity(); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.ID.getName()), Arrays.asList(String.valueOf(sourceTestInstance.getId()))); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.LAST_MODIFIED.getName()), Arrays.asList(sourceTestInstance.getLastModified())); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.PLANNED_HOST.getName()), Arrays.asList(sourceTestInstance.getPlannedHost())); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.RESPONSIBLE_TESTER.getName()), Arrays.asList(sourceTestInstance.getResponsibleTester())); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.STATUS.getName()), Arrays.asList(sourceTestInstance.getStatus())); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.TEST_CONFIG_ID.getName()), Arrays.asList(String.valueOf(sourceTestInstance.getTestConfigId()))); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.TEST_ID.getName()), Arrays.asList(String.valueOf(sourceTestInstance.getTestId()))); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.TEST_INSTANCE_NUMBER.getName()), Arrays.asList(String.valueOf(sourceTestInstance.getTestInstanceNumber()))); Assert.assertEquals(createdEntity.getFieldValues(TestInstanceField.TEST_SET_ID.getName()), Arrays.asList(String.valueOf(sourceTestInstance.getTestSetId()))); } @Test public void createEntity_withTestSetHavingDefaultValues__shouldCreateEntityWithoutInvalidValues() { final TestInstance sourceTestInstance = new TestInstance(); final GenericEntity createdEntity = sourceTestInstance.createEntity(); Assert.assertFalse(createdEntity.hasFieldValue(TestInstanceField.ID.getName())); Assert.assertFalse(createdEntity.hasFieldValue(TestInstanceField.TEST_CONFIG_ID.getName())); Assert.assertFalse(createdEntity.hasFieldValue(TestInstanceField.TEST_ID.getName())); Assert.assertFalse(createdEntity.hasFieldValue(TestInstanceField.TEST_INSTANCE_NUMBER.getName())); Assert.assertFalse(createdEntity.hasFieldValue(TestInstanceField.TEST_SET_ID.getName())); } @Test public void equals_comparingTestInstanceToAnEqualObject_shouldReturnTrue() { final TestInstance testInstanceOne = createFullTestInstance(); Assert.assertTrue(testInstanceOne.equals(createFullTestInstance())); } @Test public void equals_comparingTestInstanceToAnotherObjectType_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); Assert.assertFalse(testInstanceOne.equals(new Object())); } @Test public void equals_comparingTestInstanceToItself_shouldReturnTrue() { final TestInstance testInstanceOne = createFullTestInstance(); Assert.assertTrue(testInstanceOne.equals(testInstanceOne)); } @Test public void equals_comparingTestInstanceToNull_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); Assert.assertFalse(testInstanceOne.equals(null)); } @Test public void equals_comparingTestInstanceToTestInstanceWithDifferentId_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setId(1234); Assert.assertFalse(testInstanceOne.equals(testInstanceTwo)); } @Test public void equals_comparingTestInstanceToTestInstanceWithDifferentTestConfigId_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setTestConfigId(9999); Assert.assertFalse(testInstanceOne.equals(testInstanceTwo)); } @Test public void equals_comparingTestInstanceToTestInstanceWithDifferentTestSetId_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setTestSetId(9999); Assert.assertFalse(testInstanceOne.equals(testInstanceTwo)); } @Test public void equals_comparingTestInstanceToTestWithDifferentParentId_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstaceTwo = createFullTestInstance(); testInstaceTwo.setTestId(123456); Assert.assertFalse(testInstanceOne.equals(testInstaceTwo)); } @Test public void getAssociatedTest_withAssociatedTestSet_shouldReturnAssociatedTest() { final TestInstance instance = new TestInstance(); final AlmTest associatedTest = new AlmTest(); associatedTest.setName("parent name"); instance.setAssociatedTest(associatedTest); Assert.assertEquals(instance.getAssociatedTest(), associatedTest); } @Test public void getAssociatedTest_withNoAssociatedTestSet_shouldReturnDefaultTest() { Assert.assertEquals(new TestInstance().getAssociatedTest(), new AlmTest()); } @Test public void getAssociatedTestConfig_withAssociatedTestConfigSet_shouldReturnAssociatedTestConfig() { final TestInstance instance = new TestInstance(); final TestConfig associatedTestConfig = new TestConfig(); associatedTestConfig.setName("parent name"); instance.setAssociatedTestConfig(associatedTestConfig); Assert.assertEquals(instance.getAssociatedTestConfig(), associatedTestConfig); } @Test public void getAssociatedTestConfig_withNoAssociatedTestConfigSet_shouldReturnDefaultTest() { Assert.assertEquals(new TestInstance().getAssociatedTestConfig(), new TestConfig()); } @Test public void getEntityCollectionType_shouldReturnCollectionType() { Assert.assertEquals(new TestInstance().getEntityCollectionType(), "test-instances"); } @Test public void getEntityType_shouldReturnType() { Assert.assertEquals(new TestInstance().getEntityType(), "test-instance"); } @Test public void getParentTestSet_withNoParentTestSetSet_shouldReturnDefaultTestSet() { Assert.assertEquals(new TestInstance().getParentTestSet(), new TestSet()); } @Test public void getParentTestSet_withparentTestSetSet_shouldReturnParentTestSet() { final TestInstance instance = new TestInstance(); final TestSet parentTestSet = new TestSet(); parentTestSet.setName("parent name"); instance.setParentTestSet(parentTestSet); Assert.assertEquals(instance.getParentTestSet(), parentTestSet); } @Test public void hashCode_forEqualTestInstances_shouldBeEqual() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); Assert.assertEquals(testInstanceOne.hashCode(), testInstanceTwo.hashCode()); } @Test public void hashCode_forUnEqualTestInstances_shouldNotBeEqual() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceOne.setId(1234); Assert.assertNotEquals(testInstanceOne.hashCode(), testInstanceTwo.hashCode()); } @Test public void instantiate_withDefaultConstructor_shouldSetLastModifiedToLongMinValue() { cal.setTimeInMillis(Long.MIN_VALUE); final TestInstance testInstance = new TestInstance(); Assert.assertEquals(testInstance.getLastModified(), DATE_FORMATTER.get().format(cal.getTime())); } @Test public void isExactMatch_comparingTestInstanceToExactlyMatchingTestInstanceWithNoAssociatedEntities_shouldReturnTrue() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); Assert.assertTrue(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToExactlyMatchingTestWithAssociatedTest_shouldReturnTrue() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceOne.setAssociatedTest(new AlmTest()); testInstanceTwo.setAssociatedTest(new AlmTest()); Assert.assertTrue(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToExactlyMatchingTestWithAssociatedTestConfig_shouldReturnTrue() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceOne.setAssociatedTestConfig(new TestConfig()); testInstanceTwo.setAssociatedTestConfig(new TestConfig()); Assert.assertTrue(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToExactlyMatchingTestWithParentTestSet_shouldReturnTrue() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceOne.setParentTestSet(new TestSet()); testInstanceTwo.setParentTestSet(new TestSet()); Assert.assertTrue(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToItself_shouldReturnTrue() { final TestInstance testInstanceOne = createFullTestInstance(); Assert.assertTrue(testInstanceOne.isExactMatch(testInstanceOne)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceThatDoesNotSatisyEquals_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setTestId(123456); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentAssociatedTest_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); final AlmTest test = new AlmTest(); test.setName("theName"); testInstanceOne.setAssociatedTest(new AlmTest()); testInstanceTwo.setAssociatedTest(test); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentAssociatedTestConfig_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); final TestConfig testConfig = new TestConfig(); testConfig.setName("theName"); testInstanceOne.setAssociatedTestConfig(new TestConfig()); testInstanceTwo.setAssociatedTestConfig(testConfig); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentLastModifiedDate_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setLastModified("1776-07-06 11:12:13"); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentParentTestSet_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); final TestSet testSet = new TestSet(); testSet.setName("theName"); testInstanceOne.setParentTestSet(new TestSet()); testInstanceTwo.setParentTestSet(testSet); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentPlannedHost_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setPlannedHost("win7.64.ie"); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentResponsibleTester_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setResponsibleTester("differentTester"); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentStatus_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setStatus("different"); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentSubType_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setSubtype("different"); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentTestInstanceNumber_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setTestInstanceNumber(123456789); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceToTestInstanceWithDifferentTestOrder_shouldReturnFalse() { final TestInstance testInstanceOne = createFullTestInstance(); final TestInstance testInstanceTwo = createFullTestInstance(); testInstanceTwo.setTestOrder(9999999); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceWithNullAssociatedTestConfigToTestInstanceWithAssociatedTestConfig_shouldReturnFalse() { final TestInstance testInstanceOne = new TestInstance(); final TestInstance testInstanceTwo = new TestInstance(); testInstanceTwo.setAssociatedTestConfig(new TestConfig()); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceWithNullAssociatedTestToTestWithAssociatedTest_shouldReturnFalse() { final TestInstance testInstanceOne = new TestInstance(); final TestInstance testInstanceTwo = new TestInstance(); testInstanceTwo.setAssociatedTest(new AlmTest()); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void isExactMatch_comparingTestInstanceWithNullParentTestSetToTestInstanceWithParentTestSet_shouldReturnFalse() { final TestInstance testInstanceOne = new TestInstance(); final TestInstance testInstanceTwo = new TestInstance(); testInstanceTwo.setParentTestSet(new TestSet()); Assert.assertFalse(testInstanceOne.isExactMatch(testInstanceTwo)); } @Test public void populateFields_withEmptyEntity_shouldSetAllFieldsAsDefault() { final TestInstance testInstance = new TestInstance(); cal.setTimeInMillis(Long.MIN_VALUE); testInstance.populateFields( new GenericEntity("test-set", Arrays.asList(new Field("dummy", new ArrayList<String>())))); Assert.assertEquals(testInstance.getId(), Integer.MIN_VALUE); Assert.assertEquals(testInstance.getLastModified(), DATE_FORMATTER.get().format(cal.getTime())); Assert.assertEquals(testInstance.getPlannedHost(), ""); Assert.assertEquals(testInstance.getResponsibleTester(), ""); Assert.assertEquals(testInstance.getStatus(), ""); Assert.assertEquals(testInstance.getSubtype(), ""); Assert.assertEquals(testInstance.getTestConfigId(), Integer.MIN_VALUE); Assert.assertEquals(testInstance.getTestId(), Integer.MIN_VALUE); Assert.assertEquals(testInstance.getTestOrder(), Integer.MIN_VALUE); Assert.assertEquals(testInstance.getTestInstanceNumber(), Integer.MIN_VALUE); Assert.assertEquals(testInstance.getTestSetId(), Integer.MIN_VALUE); } @Test public void populateFields_withEntityHavingAllTestInstanceFieldsPopulated_shouldSetAllTestInstanceFields() { final TestInstance testInstance = new TestInstance(); final GenericEntity sourceEntity = createFullyPopulatedEntity(); testInstance.populateFields(sourceEntity); Assert.assertTrue(testInstance.getId() == Integer .valueOf(sourceEntity.getFieldValues(TestInstanceField.ID.getName()).get(0))); Assert.assertEquals(testInstance.getLastModified(), sourceEntity.getFieldValues(TestInstanceField.LAST_MODIFIED.getName()).get(0)); Assert.assertEquals(testInstance.getPlannedHost(), sourceEntity.getFieldValues(TestInstanceField.PLANNED_HOST.getName()).get(0)); Assert.assertEquals(testInstance.getResponsibleTester(), sourceEntity.getFieldValues(TestInstanceField.RESPONSIBLE_TESTER.getName()).get(0)); Assert.assertEquals(testInstance.getStatus(), sourceEntity.getFieldValues(TestInstanceField.STATUS.getName()).get(0)); Assert.assertEquals(testInstance.getSubtype(), sourceEntity.getFieldValues(TestInstanceField.SUBTYPE.getName()).get(0)); Assert.assertTrue(testInstance.getTestConfigId() == Integer .valueOf(sourceEntity.getFieldValues(TestInstanceField.TEST_CONFIG_ID.getName()).get(0))); Assert.assertTrue(testInstance.getTestId() == Integer .valueOf(sourceEntity.getFieldValues(TestInstanceField.TEST_ID.getName()).get(0))); Assert.assertTrue(testInstance.getTestInstanceNumber() == Integer .valueOf(sourceEntity.getFieldValues(TestInstanceField.TEST_INSTANCE_NUMBER.getName()).get(0))); Assert.assertTrue(testInstance.getTestOrder() == Integer .valueOf(sourceEntity.getFieldValues(TestInstanceField.TEST_ORDER.getName()).get(0))); Assert.assertTrue(testInstance.getTestSetId() == Integer .valueOf(sourceEntity.getFieldValues(TestInstanceField.TEST_SET_ID.getName()).get(0))); } @Test public void populateFields_withEntityHavingAssociatedTestConfigSet_shouldSetNewAssociatedTest() { final TestInstance testInstance = new TestInstance(); testInstance.setAssociatedTestConfig(new TestConfig()); final TestConfig associatedTestConfig = new TestConfig(); associatedTestConfig.setName("parent name"); final GenericEntity sourceEntity = new GenericEntity("test-set", Arrays.asList(new Field("dummy", new ArrayList<String>()))); sourceEntity.addRelatedEntity(associatedTestConfig.createEntity()); testInstance.populateFields(sourceEntity); Assert.assertEquals(testInstance.getAssociatedTestConfig(), associatedTestConfig); } @Test public void populateFields_withEntityHavingAssociatedTestSet_shouldSetNewAssociatedTest() { final TestInstance testInstance = new TestInstance(); testInstance.setAssociatedTest(new AlmTest()); final AlmTest associatedTest = new AlmTest(); associatedTest.setName("parent name"); final GenericEntity sourceEntity = new GenericEntity("test-set", Arrays.asList(new Field("dummy", new ArrayList<String>()))); sourceEntity.addRelatedEntity(associatedTest.createEntity()); testInstance.populateFields(sourceEntity); Assert.assertEquals(testInstance.getAssociatedTest(), associatedTest); } @Test public void populateFields_withEntityHavingNoAssociatedTestConfigSet_shouldSetNewAssociatedTest() { final TestInstance testInstance = new TestInstance(); final TestConfig associatedTestConfig = new TestConfig(); associatedTestConfig.setName("parent name"); final GenericEntity sourceEntity = new GenericEntity("test-set", Arrays.asList(new Field("dummy", new ArrayList<String>()))); sourceEntity.addRelatedEntity(associatedTestConfig.createEntity()); testInstance.populateFields(sourceEntity); Assert.assertEquals(testInstance.getAssociatedTestConfig(), associatedTestConfig); } @Test public void populateFields_withEntityHavingNoAssociatedTestSet_shouldSetNewAssociatedTest() { final TestInstance testInstance = new TestInstance(); final AlmTest associatedTest = new AlmTest(); associatedTest.setName("parent name"); final GenericEntity sourceEntity = new GenericEntity("test-set", Arrays.asList(new Field("dummy", new ArrayList<String>()))); sourceEntity.addRelatedEntity(associatedTest.createEntity()); testInstance.populateFields(sourceEntity); Assert.assertEquals(testInstance.getAssociatedTest(), associatedTest); } @Test public void populateFields_withEntityHavingNoParentTestSetSet_shouldSetNewParentTestSet() { final TestInstance testInstance = new TestInstance(); final TestSet parentTestSet = new TestSet(); parentTestSet.setName("parent name"); final GenericEntity sourceEntity = new GenericEntity("test-set", Arrays.asList(new Field("dummy", new ArrayList<String>()))); sourceEntity.addRelatedEntity(parentTestSet.createEntity()); testInstance.populateFields(sourceEntity); Assert.assertEquals(testInstance.getParentTestSet(), parentTestSet); } @Test public void populateFields_withEntityHavingParentTestSetSet_shouldSetNewParentTestSet() { final TestInstance testInstance = new TestInstance(); testInstance.setParentTestSet(new TestSet()); final TestSet parentTestSet = new TestSet(); parentTestSet.setName("parent name"); final GenericEntity sourceEntity = new GenericEntity("test-set", Arrays.asList(new Field("dummy", new ArrayList<String>()))); sourceEntity.addRelatedEntity(parentTestSet.createEntity()); testInstance.populateFields(sourceEntity); Assert.assertEquals(testInstance.getParentTestSet(), parentTestSet); } @Test public void populateFields_withGenericEntityHavingUnrelatedEntity_shouldIgnoreUnrelatedEntity() { final TestInstance testInstance = new TestInstance(); final GenericEntity sourceEntity = new GenericEntity("test-set", Arrays.asList(new Field("dummy", new ArrayList<String>()))); sourceEntity.addRelatedEntity(new Defect().createEntity()); testInstance.populateFields(sourceEntity); Assert.assertEquals(testInstance.getAssociatedTest(), new AlmTest()); Assert.assertEquals(testInstance.getAssociatedTestConfig(), new TestConfig()); Assert.assertEquals(testInstance.getParentTestSet(), new TestSet()); } @Test(expectedExceptions = IllegalArgumentException.class) public void setLastModifiedDate_withIncorrectDateFormat_shouldThrowException() { final TestInstance testInstanceOne = createFullTestInstance(); testInstanceOne.setLastModified("June 23, 1967"); } @Test public void toString_withAssociatedTest_shouldReturnNonDefaultStringWithAssociatedTestInfo() { final TestInstance testInstanceOne = createFullTestInstance(); testInstanceOne.setAssociatedTest(new AlmTest()); Assert.assertTrue(StringUtils.contains(testInstanceOne.toString(), "<TestInstance>")); Assert.assertTrue(StringUtils.contains(testInstanceOne.toString(), "<AlmTest>")); } @Test public void toString_withAssociatedTestConfig_shouldReturnNonDefaultStringWithAssociatedTestConfigInfo() { final TestInstance testInstanceOne = createFullTestInstance(); testInstanceOne.setAssociatedTestConfig(new TestConfig()); Assert.assertTrue(StringUtils.contains(testInstanceOne.toString(), "<TestInstance>")); Assert.assertTrue(StringUtils.contains(testInstanceOne.toString(), "<TestConfig>")); } @Test public void toString_withNoParentTestFolder_shouldReturnNonDefaultStringWithNoParentFolderInfo() { final TestInstance testInstanceOne = createFullTestInstance(); Assert.assertTrue(StringUtils.contains(testInstanceOne.toString(), "<TestInstance>")); Assert.assertTrue(StringUtils.contains(testInstanceOne.toString(), "Not Set")); Assert.assertFalse(StringUtils.contains(testInstanceOne.toString(), "<TestSet>")); Assert.assertFalse(StringUtils.contains(testInstanceOne.toString(), "<AlmTest>")); Assert.assertFalse(StringUtils.contains(testInstanceOne.toString(), "<TestConfig>")); } @Test public void toString_withParentTestSet_shouldReturnNonDefaultStringWithParentTestSetInfo() { final TestInstance testInstanceOne = createFullTestInstance(); testInstanceOne.setParentTestSet(new TestSet()); Assert.assertTrue(StringUtils.contains(testInstanceOne.toString(), "<TestInstance>")); Assert.assertTrue(StringUtils.contains(testInstanceOne.toString(), "<TestSet>")); } private TestInstance createFullTestInstance() { final TestInstance testInstance = new TestInstance(); testInstance.setId(1337); testInstance.setLastModified("1776-07-04 11:12:13"); testInstance.setPlannedHost("win7.64.ff"); testInstance.setResponsibleTester("tnugent"); testInstance.setStatus("No Run"); testInstance.setTestConfigId(1776); testInstance.setTestId(2001); testInstance.setTestInstanceNumber(42); testInstance.setTestSetId(101); testInstance.setTestOrder(42); testInstance.setSubtype("hp.qc.test-instance.FUNCTIONAL"); return testInstance; } private GenericEntity createFullyPopulatedEntity() { final List<Field> fields = new ArrayList<>(); fields.add(new Field(TestInstanceField.LAST_MODIFIED.getName(), Arrays.asList(DATE_FORMATTER.get().format(cal.getTime())))); fields.add(new Field(TestInstanceField.ID.getName(), Arrays.asList("1337"))); fields.add(new Field(TestInstanceField.PLANNED_HOST.getName(), Arrays.asList("theHost"))); fields.add(new Field(TestInstanceField.RESPONSIBLE_TESTER.getName(), Arrays.asList("sclegane"))); fields.add(new Field(TestInstanceField.STATUS.getName(), Arrays.asList("theStatus"))); fields.add(new Field(TestInstanceField.SUBTYPE.getName(), Arrays.asList("theSubtype"))); fields.add(new Field(TestInstanceField.TEST_CONFIG_ID.getName(), Arrays.asList("1776"))); fields.add(new Field(TestInstanceField.TEST_ID.getName(), Arrays.asList("2014"))); fields.add(new Field(TestInstanceField.TEST_INSTANCE_NUMBER.getName(), Arrays.asList("42"))); fields.add(new Field(TestInstanceField.TEST_SET_ID.getName(), Arrays.asList("1492"))); fields.add(new Field(TestInstanceField.TEST_ORDER.getName(), Arrays.asList("7"))); return new GenericEntity("test-instance", fields); } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.management.mbean; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.management.AttributeValueExp; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.Query; import javax.management.QueryExp; import javax.management.StringValueExp; import org.w3c.dom.Document; import org.apache.camel.CamelContext; import org.apache.camel.ManagementStatisticsLevel; import org.apache.camel.Route; import org.apache.camel.ServiceStatus; import org.apache.camel.TimerListener; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.api.management.mbean.ManagedProcessorMBean; import org.apache.camel.api.management.mbean.ManagedRouteMBean; import org.apache.camel.model.ModelCamelContext; import org.apache.camel.model.ModelHelper; import org.apache.camel.model.RouteDefinition; import org.apache.camel.spi.InflightRepository; import org.apache.camel.spi.ManagementStrategy; import org.apache.camel.spi.RouteError; import org.apache.camel.spi.RoutePolicy; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.XmlLineNumberParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ManagedResource(description = "Managed Route") public class ManagedRoute extends ManagedPerformanceCounter implements TimerListener, ManagedRouteMBean { public static final String VALUE_UNKNOWN = "Unknown"; private static final Logger LOG = LoggerFactory.getLogger(ManagedRoute.class); protected final Route route; protected final String description; protected final ModelCamelContext context; private final LoadTriplet load = new LoadTriplet(); private final String jmxDomain; public ManagedRoute(ModelCamelContext context, Route route) { this.route = route; this.context = context; this.description = route.getDescription(); this.jmxDomain = context.getManagementStrategy().getManagementAgent().getMBeanObjectDomainName(); } @Override public void init(ManagementStrategy strategy) { super.init(strategy); boolean enabled = context.getManagementStrategy().getManagementAgent().getStatisticsLevel() != ManagementStatisticsLevel.Off; setStatisticsEnabled(enabled); } public Route getRoute() { return route; } public CamelContext getContext() { return context; } public String getRouteId() { String id = route.getId(); if (id == null) { id = VALUE_UNKNOWN; } return id; } public String getDescription() { return description; } @Override public String getEndpointUri() { if (route.getEndpoint() != null) { return route.getEndpoint().getEndpointUri(); } return VALUE_UNKNOWN; } public String getState() { // must use String type to be sure remote JMX can read the attribute without requiring Camel classes. ServiceStatus status = context.getRouteStatus(route.getId()); // if no status exists then its stopped if (status == null) { status = ServiceStatus.Stopped; } return status.name(); } public String getUptime() { return route.getUptime(); } public long getUptimeMillis() { return route.getUptimeMillis(); } public Integer getInflightExchanges() { return (int) super.getExchangesInflight(); } public String getCamelId() { return context.getName(); } public String getCamelManagementName() { return context.getManagementName(); } public Boolean getTracing() { return route.getRouteContext().isTracing(); } public void setTracing(Boolean tracing) { route.getRouteContext().setTracing(tracing); } public Boolean getMessageHistory() { return route.getRouteContext().isMessageHistory(); } public Boolean getLogMask() { return route.getRouteContext().isLogMask(); } public String getRoutePolicyList() { List<RoutePolicy> policyList = route.getRouteContext().getRoutePolicyList(); if (policyList == null || policyList.isEmpty()) { // return an empty string to have it displayed nicely in JMX consoles return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < policyList.size(); i++) { RoutePolicy policy = policyList.get(i); sb.append(policy.getClass().getSimpleName()); sb.append("(").append(ObjectHelper.getIdentityHashCode(policy)).append(")"); if (i < policyList.size() - 1) { sb.append(", "); } } return sb.toString(); } public String getLoad01() { double load1 = load.getLoad1(); if (Double.isNaN(load1)) { // empty string if load statistics is disabled return ""; } else { return String.format("%.2f", load1); } } public String getLoad05() { double load5 = load.getLoad5(); if (Double.isNaN(load5)) { // empty string if load statistics is disabled return ""; } else { return String.format("%.2f", load5); } } public String getLoad15() { double load15 = load.getLoad15(); if (Double.isNaN(load15)) { // empty string if load statistics is disabled return ""; } else { return String.format("%.2f", load15); } } @Override public void onTimer() { load.update(getInflightExchanges()); } public void start() throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } context.getRouteController().startRoute(getRouteId()); } public void stop() throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } context.getRouteController().stopRoute(getRouteId()); } public void stop(long timeout) throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } context.getRouteController().stopRoute(getRouteId(), timeout, TimeUnit.SECONDS); } public boolean stop(Long timeout, Boolean abortAfterTimeout) throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } return context.getRouteController().stopRoute(getRouteId(), timeout, TimeUnit.SECONDS, abortAfterTimeout); } public void shutdown() throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } String routeId = getRouteId(); context.stopRoute(routeId); context.removeRoute(routeId); } public void shutdown(long timeout) throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } String routeId = getRouteId(); context.stopRoute(routeId, timeout, TimeUnit.SECONDS); context.removeRoute(routeId); } public boolean remove() throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } return context.removeRoute(getRouteId()); } public String dumpRouteAsXml() throws Exception { return dumpRouteAsXml(false); } @Override public String dumpRouteAsXml(boolean resolvePlaceholders) throws Exception { String id = route.getId(); RouteDefinition def = context.getRouteDefinition(id); if (def != null) { String xml = ModelHelper.dumpModelAsXml(context, def); // if resolving placeholders we parse the xml, and resolve the property placeholders during parsing if (resolvePlaceholders) { final AtomicBoolean changed = new AtomicBoolean(); InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8")); Document dom = XmlLineNumberParser.parseXml(is, new XmlLineNumberParser.XmlTextTransformer() { @Override public String transform(String text) { try { String after = getContext().resolvePropertyPlaceholders(text); if (!changed.get()) { changed.set(!text.equals(after)); } return after; } catch (Exception e) { // ignore return text; } } }); // okay there were some property placeholder replaced so re-create the model if (changed.get()) { xml = context.getTypeConverter().mandatoryConvertTo(String.class, dom); RouteDefinition copy = ModelHelper.createModelFromXml(context, xml, RouteDefinition.class); xml = ModelHelper.dumpModelAsXml(context, copy); } } return xml; } return null; } public void updateRouteFromXml(String xml) throws Exception { // convert to model from xml RouteDefinition def = ModelHelper.createModelFromXml(context, xml, RouteDefinition.class); if (def == null) { return; } // if the xml does not contain the route-id then we fix this by adding the actual route id // this may be needed if the route-id was auto-generated, as the intend is to update this route // and not add a new route, adding a new route, use the MBean operation on ManagedCamelContext instead. if (ObjectHelper.isEmpty(def.getId())) { def.setId(getRouteId()); } else if (!def.getId().equals(getRouteId())) { throw new IllegalArgumentException("Cannot update route from XML as routeIds does not match. routeId: " + getRouteId() + ", routeId from XML: " + def.getId()); } LOG.debug("Updating route: {} from xml: {}", def.getId(), xml); try { // add will remove existing route first context.addRouteDefinition(def); } catch (Exception e) { // log the error as warn as the management api may be invoked remotely over JMX which does not propagate such exception String msg = "Error updating route: " + def.getId() + " from xml: " + xml + " due: " + e.getMessage(); LOG.warn(msg, e); throw e; } } public String dumpRouteStatsAsXml(boolean fullStats, boolean includeProcessors) throws Exception { // in this logic we need to calculate the accumulated processing time for the processor in the route // and hence why the logic is a bit more complicated to do this, as we need to calculate that from // the bottom -> top of the route but this information is valuable for profiling routes StringBuilder sb = new StringBuilder(); // need to calculate this value first, as we need that value for the route stat Long processorAccumulatedTime = 0L; // gather all the processors for this route, which requires JMX if (includeProcessors) { sb.append(" <processorStats>\n"); MBeanServer server = getContext().getManagementStrategy().getManagementAgent().getMBeanServer(); if (server != null) { // get all the processor mbeans and sort them accordingly to their index String prefix = getContext().getManagementStrategy().getManagementAgent().getIncludeHostName() ? "*/" : ""; ObjectName query = ObjectName.getInstance(jmxDomain + ":context=" + prefix + getContext().getManagementName() + ",type=processors,*"); Set<ObjectName> names = server.queryNames(query, null); List<ManagedProcessorMBean> mps = new ArrayList<ManagedProcessorMBean>(); for (ObjectName on : names) { ManagedProcessorMBean processor = context.getManagementStrategy().getManagementAgent().newProxyClient(on, ManagedProcessorMBean.class); // the processor must belong to this route if (getRouteId().equals(processor.getRouteId())) { mps.add(processor); } } mps.sort(new OrderProcessorMBeans()); // walk the processors in reverse order, and calculate the accumulated total time Map<String, Long> accumulatedTimes = new HashMap<String, Long>(); Collections.reverse(mps); for (ManagedProcessorMBean processor : mps) { processorAccumulatedTime += processor.getTotalProcessingTime(); accumulatedTimes.put(processor.getProcessorId(), processorAccumulatedTime); } // and reverse back again Collections.reverse(mps); // and now add the sorted list of processors to the xml output for (ManagedProcessorMBean processor : mps) { sb.append(" <processorStat").append(String.format(" id=\"%s\" index=\"%s\" state=\"%s\"", processor.getProcessorId(), processor.getIndex(), processor.getState())); // do we have an accumulated time then append that Long accTime = accumulatedTimes.get(processor.getProcessorId()); if (accTime != null) { sb.append(" accumulatedProcessingTime=\"").append(accTime).append("\""); } // use substring as we only want the attributes sb.append(" ").append(processor.dumpStatsAsXml(fullStats).substring(7)).append("\n"); } } sb.append(" </processorStats>\n"); } // route self time is route total - processor accumulated total) long routeSelfTime = getTotalProcessingTime() - processorAccumulatedTime; if (routeSelfTime < 0) { // ensure we don't calculate that as negative routeSelfTime = 0; } StringBuilder answer = new StringBuilder(); answer.append("<routeStat").append(String.format(" id=\"%s\"", route.getId())).append(String.format(" state=\"%s\"", getState())); // use substring as we only want the attributes String stat = dumpStatsAsXml(fullStats); answer.append(" exchangesInflight=\"").append(getInflightExchanges()).append("\""); answer.append(" selfProcessingTime=\"").append(routeSelfTime).append("\""); InflightRepository.InflightExchange oldest = getOldestInflightEntry(); if (oldest == null) { answer.append(" oldestInflightExchangeId=\"\""); answer.append(" oldestInflightDuration=\"\""); } else { answer.append(" oldestInflightExchangeId=\"").append(oldest.getExchange().getExchangeId()).append("\""); answer.append(" oldestInflightDuration=\"").append(oldest.getDuration()).append("\""); } answer.append(" ").append(stat.substring(7, stat.length() - 2)).append(">\n"); if (includeProcessors) { answer.append(sb); } answer.append("</routeStat>"); return answer.toString(); } public void reset(boolean includeProcessors) throws Exception { reset(); // and now reset all processors for this route if (includeProcessors) { MBeanServer server = getContext().getManagementStrategy().getManagementAgent().getMBeanServer(); if (server != null) { // get all the processor mbeans and sort them accordingly to their index String prefix = getContext().getManagementStrategy().getManagementAgent().getIncludeHostName() ? "*/" : ""; ObjectName query = ObjectName.getInstance(jmxDomain + ":context=" + prefix + getContext().getManagementName() + ",type=processors,*"); QueryExp queryExp = Query.match(new AttributeValueExp("RouteId"), new StringValueExp(getRouteId())); Set<ObjectName> names = server.queryNames(query, queryExp); for (ObjectName name : names) { server.invoke(name, "reset", null, null); } } } } public String createRouteStaticEndpointJson() { return getContext().createRouteStaticEndpointJson(getRouteId()); } @Override public String createRouteStaticEndpointJson(boolean includeDynamic) { return getContext().createRouteStaticEndpointJson(getRouteId(), includeDynamic); } @Override public boolean equals(Object o) { return this == o || (o != null && getClass() == o.getClass() && route.equals(((ManagedRoute) o).route)); } @Override public int hashCode() { return route.hashCode(); } private InflightRepository.InflightExchange getOldestInflightEntry() { return getContext().getInflightRepository().oldest(getRouteId()); } public Long getOldestInflightDuration() { InflightRepository.InflightExchange oldest = getOldestInflightEntry(); if (oldest == null) { return null; } else { return oldest.getDuration(); } } public String getOldestInflightExchangeId() { InflightRepository.InflightExchange oldest = getOldestInflightEntry(); if (oldest == null) { return null; } else { return oldest.getExchange().getExchangeId(); } } @Override public Boolean getHasRouteController() { return route.getRouteContext().getRouteController() != null; } @Override public RouteError getLastError() { return route.getRouteContext().getLastError(); } /** * Used for sorting the processor mbeans accordingly to their index. */ private static final class OrderProcessorMBeans implements Comparator<ManagedProcessorMBean> { @Override public int compare(ManagedProcessorMBean o1, ManagedProcessorMBean o2) { return o1.getIndex().compareTo(o2.getIndex()); } } }
package com.mapswithme.maps.bookmarks; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.cocosw.bottomsheet.BottomSheet; import com.mapswithme.maps.Framework; import com.mapswithme.maps.MwmActivity; import com.mapswithme.maps.R; import com.mapswithme.maps.base.BaseMwmListFragment; import com.mapswithme.maps.bookmarks.data.Bookmark; import com.mapswithme.maps.bookmarks.data.BookmarkCategory; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.Track; import com.mapswithme.maps.widget.placepage.EditBookmarkFragment; import com.mapswithme.util.BottomSheetHelper; import com.mapswithme.util.sharing.ShareOption; import com.mapswithme.util.sharing.SharingHelper; public class BookmarksListFragment extends BaseMwmListFragment implements AdapterView.OnItemLongClickListener, MenuItem.OnMenuItemClickListener { public static final String TAG = BookmarksListFragment.class.getSimpleName(); private BookmarkCategory mCategory; private int mCategoryIndex; private int mSelectedPosition; private BookmarkListAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCategoryIndex = getArguments().getInt(ChooseBookmarkCategoryFragment.CATEGORY_ID, -1); mCategory = BookmarkManager.INSTANCE.getCategoryById(mCategoryIndex); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.simple_list, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initList(); setHasOptionsMenu(true); ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(mCategory.getName()); } @Override public void onResume() { super.onResume(); mAdapter.startLocationUpdate(); mAdapter.notifyDataSetChanged(); } @Override public void onPause() { super.onPause(); mAdapter.stopLocationUpdate(); } private void initList() { mAdapter = new BookmarkListAdapter(getActivity(), mCategory); mAdapter.startLocationUpdate(); setListAdapter(mAdapter); getListView().setOnItemLongClickListener(this); } @Override public void onListItemClick(ListView l, View v, int position, long id) { switch (mAdapter.getItemViewType(position)) { case BookmarkListAdapter.TYPE_SECTION: return; case BookmarkListAdapter.TYPE_BOOKMARK: final Bookmark bookmark = (Bookmark) mAdapter.getItem(position); BookmarkManager.INSTANCE.showBookmarkOnMap(mCategoryIndex, bookmark.getBookmarkId()); break; case BookmarkListAdapter.TYPE_TRACK: final Track track = (Track) mAdapter.getItem(position); Framework.nativeShowTrackRect(track.getCategoryId(), track.getTrackId()); break; } final Intent i = new Intent(getActivity(), MwmActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { mSelectedPosition = position; final Object item = mAdapter.getItem(mSelectedPosition); int type = mAdapter.getItemViewType(mSelectedPosition); switch (type) { case BookmarkListAdapter.TYPE_SECTION: // Do nothing here? break; case BookmarkListAdapter.TYPE_BOOKMARK: BottomSheet bs = BottomSheetHelper.create(getActivity()) .title(((Bookmark) item).getName()) .sheet(R.menu.menu_bookmarks) .listener(this) .build(); if (!ShareOption.SMS.isSupported(getActivity())) bs.getMenu().removeItem(R.id.share_message); if (!ShareOption.EMAIL.isSupported(getActivity())) bs.getMenu().removeItem(R.id.share_email); bs.show(); break; case BookmarkListAdapter.TYPE_TRACK: BottomSheetHelper.create(getActivity()) .title(((Track) item).getName()) .sheet(Menu.NONE, R.drawable.ic_delete, R.string.delete) .listener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { BookmarkManager.INSTANCE.deleteTrack((Track) item); mAdapter.notifyDataSetChanged(); } }).show(); break; } return true; } @Override public boolean onMenuItemClick(MenuItem menuItem) { Bookmark item = (Bookmark) mAdapter.getItem(mSelectedPosition); switch (menuItem.getItemId()) { case R.id.share_message: ShareOption.SMS.shareMapObject(getActivity(), item); break; case R.id.share_email: ShareOption.EMAIL.shareMapObject(getActivity(), item); break; case R.id.share: ShareOption.ANY.shareMapObject(getActivity(), item); break; case R.id.edit: editBookmark(mCategory.getId(), item.getBookmarkId()); break; case R.id.delete: BookmarkManager.INSTANCE.deleteBookmark(item); mAdapter.notifyDataSetChanged(); break; } return false; } private void editBookmark(int cat, int bmk) { final Bundle args = new Bundle(); args.putInt(EditBookmarkFragment.EXTRA_CATEGORY_ID, cat); args.putInt(EditBookmarkFragment.EXTRA_BOOKMARK_ID, bmk); final EditBookmarkFragment fragment = (EditBookmarkFragment) Fragment.instantiate(getActivity(), EditBookmarkFragment.class.getName(), args); fragment.setArguments(args); fragment.show(getChildFragmentManager(), null); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.option_menu_bookmarks, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.set_share) { SharingHelper.shareBookmarksCategory(getActivity(), mCategory.getId()); return true; } return super.onOptionsItemSelected(item); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datafactory.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.datafactory.fluent.models.ValidationActivityTypeProperties; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import java.util.List; /** This activity verifies that an external resource exists. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeName("Validation") @Fluent public final class ValidationActivity extends ControlActivity { @JsonIgnore private final ClientLogger logger = new ClientLogger(ValidationActivity.class); /* * Validation activity properties. */ @JsonProperty(value = "typeProperties", required = true) private ValidationActivityTypeProperties innerTypeProperties = new ValidationActivityTypeProperties(); /** * Get the innerTypeProperties property: Validation activity properties. * * @return the innerTypeProperties value. */ private ValidationActivityTypeProperties innerTypeProperties() { return this.innerTypeProperties; } /** {@inheritDoc} */ @Override public ValidationActivity withName(String name) { super.withName(name); return this; } /** {@inheritDoc} */ @Override public ValidationActivity withDescription(String description) { super.withDescription(description); return this; } /** {@inheritDoc} */ @Override public ValidationActivity withDependsOn(List<ActivityDependency> dependsOn) { super.withDependsOn(dependsOn); return this; } /** {@inheritDoc} */ @Override public ValidationActivity withUserProperties(List<UserProperty> userProperties) { super.withUserProperties(userProperties); return this; } /** * Get the timeout property: Specifies the timeout for the activity to run. If there is no value specified, it takes * the value of TimeSpan.FromDays(7) which is 1 week as default. Type: string (or Expression with resultType * string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). * * @return the timeout value. */ public Object timeout() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().timeout(); } /** * Set the timeout property: Specifies the timeout for the activity to run. If there is no value specified, it takes * the value of TimeSpan.FromDays(7) which is 1 week as default. Type: string (or Expression with resultType * string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). * * @param timeout the timeout value to set. * @return the ValidationActivity object itself. */ public ValidationActivity withTimeout(Object timeout) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new ValidationActivityTypeProperties(); } this.innerTypeProperties().withTimeout(timeout); return this; } /** * Get the sleep property: A delay in seconds between validation attempts. If no value is specified, 10 seconds will * be used as the default. Type: integer (or Expression with resultType integer). * * @return the sleep value. */ public Object sleep() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().sleep(); } /** * Set the sleep property: A delay in seconds between validation attempts. If no value is specified, 10 seconds will * be used as the default. Type: integer (or Expression with resultType integer). * * @param sleep the sleep value to set. * @return the ValidationActivity object itself. */ public ValidationActivity withSleep(Object sleep) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new ValidationActivityTypeProperties(); } this.innerTypeProperties().withSleep(sleep); return this; } /** * Get the minimumSize property: Can be used if dataset points to a file. The file must be greater than or equal in * size to the value specified. Type: integer (or Expression with resultType integer). * * @return the minimumSize value. */ public Object minimumSize() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().minimumSize(); } /** * Set the minimumSize property: Can be used if dataset points to a file. The file must be greater than or equal in * size to the value specified. Type: integer (or Expression with resultType integer). * * @param minimumSize the minimumSize value to set. * @return the ValidationActivity object itself. */ public ValidationActivity withMinimumSize(Object minimumSize) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new ValidationActivityTypeProperties(); } this.innerTypeProperties().withMinimumSize(minimumSize); return this; } /** * Get the childItems property: Can be used if dataset points to a folder. If set to true, the folder must have at * least one file. If set to false, the folder must be empty. Type: boolean (or Expression with resultType boolean). * * @return the childItems value. */ public Object childItems() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().childItems(); } /** * Set the childItems property: Can be used if dataset points to a folder. If set to true, the folder must have at * least one file. If set to false, the folder must be empty. Type: boolean (or Expression with resultType boolean). * * @param childItems the childItems value to set. * @return the ValidationActivity object itself. */ public ValidationActivity withChildItems(Object childItems) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new ValidationActivityTypeProperties(); } this.innerTypeProperties().withChildItems(childItems); return this; } /** * Get the dataset property: Validation activity dataset reference. * * @return the dataset value. */ public DatasetReference dataset() { return this.innerTypeProperties() == null ? null : this.innerTypeProperties().dataset(); } /** * Set the dataset property: Validation activity dataset reference. * * @param dataset the dataset value to set. * @return the ValidationActivity object itself. */ public ValidationActivity withDataset(DatasetReference dataset) { if (this.innerTypeProperties() == null) { this.innerTypeProperties = new ValidationActivityTypeProperties(); } this.innerTypeProperties().withDataset(dataset); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (innerTypeProperties() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property innerTypeProperties in model ValidationActivity")); } else { innerTypeProperties().validate(); } } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.cluster.ack; import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteResponse; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesResponse; import org.elasticsearch.action.admin.indices.close.CloseIndexResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse; import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.AliasMetaData; import org.elasticsearch.cluster.metadata.AliasOrIndex; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.IndexMetaData.State; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.discovery.DiscoverySettings; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import java.util.concurrent.TimeUnit; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.common.settings.Settings.settingsBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; @ClusterScope(minNumDataNodes = 2) public class AckIT extends ESIntegTestCase { @Override protected Settings nodeSettings(int nodeOrdinal) { //to test that the acknowledgement mechanism is working we better disable the wait for publish //otherwise the operation is most likely acknowledged even if it doesn't support ack return Settings.builder().put(super.nodeSettings(nodeOrdinal)) .put(DiscoverySettings.PUBLISH_TIMEOUT_SETTING.getKey(), 0).build(); } public void testUpdateSettingsAcknowledgement() { createIndex("test"); assertAcked(client().admin().indices().prepareUpdateSettings("test") .setSettings(Settings.builder().put("refresh_interval", 9999, TimeUnit.MILLISECONDS))); for (Client client : clients()) { String refreshInterval = getLocalClusterState(client).metaData().index("test").getSettings().get("index.refresh_interval"); assertThat(refreshInterval, equalTo("9999ms")); } } public void testUpdateSettingsNoAcknowledgement() { createIndex("test"); UpdateSettingsResponse updateSettingsResponse = client().admin().indices().prepareUpdateSettings("test").setTimeout("0s") .setSettings(Settings.builder().put("refresh_interval", 9999, TimeUnit.MILLISECONDS)).get(); assertThat(updateSettingsResponse.isAcknowledged(), equalTo(false)); } public void testClusterRerouteAcknowledgement() throws InterruptedException { assertAcked(prepareCreate("test").setSettings(Settings.builder() .put(indexSettings()) .put(SETTING_NUMBER_OF_SHARDS, between(cluster().numDataNodes(), DEFAULT_MAX_NUM_SHARDS)) .put(SETTING_NUMBER_OF_REPLICAS, 0) )); ensureGreen(); MoveAllocationCommand moveAllocationCommand = getAllocationCommand(); final Index index = client().admin().cluster().prepareState().get().getState().metaData().index("test").getIndex(); final ShardId commandShard = new ShardId(index, moveAllocationCommand.shardId()); assertAcked(client().admin().cluster().prepareReroute().add(moveAllocationCommand)); for (Client client : clients()) { ClusterState clusterState = getLocalClusterState(client); for (ShardRouting shardRouting : clusterState.getRoutingNodes().routingNodeIter(moveAllocationCommand.fromNode())) { //if the shard that we wanted to move is still on the same node, it must be relocating if (shardRouting.shardId().equals(commandShard)) { assertThat(shardRouting.relocating(), equalTo(true)); } } boolean found = false; for (ShardRouting shardRouting : clusterState.getRoutingNodes().routingNodeIter(moveAllocationCommand.toNode())) { if (shardRouting.shardId().equals(commandShard)) { assertThat(shardRouting.state(), anyOf(equalTo(ShardRoutingState.INITIALIZING), equalTo(ShardRoutingState.STARTED))); found = true; break; } } assertThat(found, equalTo(true)); } } public void testClusterRerouteNoAcknowledgement() throws InterruptedException { client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder() .put(SETTING_NUMBER_OF_SHARDS, between(cluster().numDataNodes(), DEFAULT_MAX_NUM_SHARDS)) .put(SETTING_NUMBER_OF_REPLICAS, 0)).get(); ensureGreen(); MoveAllocationCommand moveAllocationCommand = getAllocationCommand(); ClusterRerouteResponse clusterRerouteResponse = client().admin().cluster().prepareReroute().setTimeout("0s").add(moveAllocationCommand).get(); assertThat(clusterRerouteResponse.isAcknowledged(), equalTo(false)); } public void testClusterRerouteAcknowledgementDryRun() throws InterruptedException { client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder() .put(SETTING_NUMBER_OF_SHARDS, between(cluster().numDataNodes(), DEFAULT_MAX_NUM_SHARDS)) .put(SETTING_NUMBER_OF_REPLICAS, 0)).get(); ensureGreen(); MoveAllocationCommand moveAllocationCommand = getAllocationCommand(); final Index index = client().admin().cluster().prepareState().get().getState().metaData().index("test").getIndex(); final ShardId commandShard = new ShardId(index, moveAllocationCommand.shardId()); assertAcked(client().admin().cluster().prepareReroute().setDryRun(true).add(moveAllocationCommand)); //testing only on master with the latest cluster state as we didn't make any change thus we cannot guarantee that //all nodes hold the same cluster state version. We only know there was no need to change anything, thus no need for ack on this update. ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().get(); boolean found = false; for (ShardRouting shardRouting : clusterStateResponse.getState().getRoutingNodes().routingNodeIter(moveAllocationCommand.fromNode())) { //the shard that we wanted to move is still on the same node, as we had dryRun flag if (shardRouting.shardId().equals(commandShard)) { assertThat(shardRouting.started(), equalTo(true)); found = true; break; } } assertThat(found, equalTo(true)); for (ShardRouting shardRouting : clusterStateResponse.getState().getRoutingNodes().routingNodeIter(moveAllocationCommand.toNode())) { if (shardRouting.shardId().equals(commandShard)) { fail("shard [" + shardRouting + "] shouldn't be on node [" + moveAllocationCommand.toString() + "]"); } } } public void testClusterRerouteNoAcknowledgementDryRun() throws InterruptedException { client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder() .put(SETTING_NUMBER_OF_SHARDS, between(cluster().numDataNodes(), DEFAULT_MAX_NUM_SHARDS)) .put(SETTING_NUMBER_OF_REPLICAS, 0)).get(); ensureGreen(); MoveAllocationCommand moveAllocationCommand = getAllocationCommand(); ClusterRerouteResponse clusterRerouteResponse = client().admin().cluster().prepareReroute().setTimeout("0s").setDryRun(true).add(moveAllocationCommand).get(); //acknowledged anyway as no changes were made assertThat(clusterRerouteResponse.isAcknowledged(), equalTo(true)); } private MoveAllocationCommand getAllocationCommand() { String fromNodeId = null; String toNodeId = null; ShardRouting shardToBeMoved = null; ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().get(); for (RoutingNode routingNode : clusterStateResponse.getState().getRoutingNodes()) { if (routingNode.node().isDataNode()) { if (fromNodeId == null && routingNode.numberOfOwningShards() > 0) { fromNodeId = routingNode.nodeId(); shardToBeMoved = routingNode.get(randomInt(routingNode.size() - 1)); } else { toNodeId = routingNode.nodeId(); } if (toNodeId != null && fromNodeId != null) { break; } } } assertNotNull(fromNodeId); assertNotNull(toNodeId); assertNotNull(shardToBeMoved); logger.info("==> going to move shard [{}] from [{}] to [{}]", shardToBeMoved, fromNodeId, toNodeId); return new MoveAllocationCommand(shardToBeMoved.getIndexName(), shardToBeMoved.id(), fromNodeId, toNodeId); } public void testIndicesAliasesAcknowledgement() { createIndex("test"); //testing acknowledgement when trying to submit an existing alias too //in that case it would not make any change, but we are sure about the cluster state //as the previous operation was acknowledged for (int i = 0; i < 2; i++) { assertAcked(client().admin().indices().prepareAliases().addAlias("test", "alias")); for (Client client : clients()) { AliasMetaData aliasMetaData = ((AliasOrIndex.Alias) getLocalClusterState(client).metaData().getAliasAndIndexLookup().get("alias")).getFirstAliasMetaData(); assertThat(aliasMetaData.alias(), equalTo("alias")); } } } public void testIndicesAliasesNoAcknowledgement() { createIndex("test"); IndicesAliasesResponse indicesAliasesResponse = client().admin().indices().prepareAliases().addAlias("test", "alias").setTimeout("0s").get(); assertThat(indicesAliasesResponse.isAcknowledged(), equalTo(false)); } public void testCloseIndexAcknowledgement() { createIndex("test"); ensureGreen(); assertAcked(client().admin().indices().prepareClose("test")); for (Client client : clients()) { IndexMetaData indexMetaData = getLocalClusterState(client).metaData().indices().get("test"); assertThat(indexMetaData.getState(), equalTo(State.CLOSE)); } } public void testCloseIndexNoAcknowledgement() { createIndex("test"); ensureGreen(); CloseIndexResponse closeIndexResponse = client().admin().indices().prepareClose("test").setTimeout("0s").get(); assertThat(closeIndexResponse.isAcknowledged(), equalTo(false)); } public void testOpenIndexAcknowledgement() { createIndex("test"); ensureGreen(); assertAcked(client().admin().indices().prepareClose("test")); assertAcked(client().admin().indices().prepareOpen("test")); for (Client client : clients()) { IndexMetaData indexMetaData = getLocalClusterState(client).metaData().indices().get("test"); assertThat(indexMetaData.getState(), equalTo(State.OPEN)); } } public void testPutMappingAcknowledgement() { createIndex("test"); ensureGreen(); assertAcked(client().admin().indices().preparePutMapping("test").setType("test").setSource("field", "type=string,index=not_analyzed")); for (Client client : clients()) { assertThat(getLocalClusterState(client).metaData().indices().get("test").mapping("test"), notNullValue()); } } public void testPutMappingNoAcknowledgement() { createIndex("test"); ensureGreen(); PutMappingResponse putMappingResponse = client().admin().indices().preparePutMapping("test").setType("test").setSource("field", "type=string,index=not_analyzed").setTimeout("0s").get(); assertThat(putMappingResponse.isAcknowledged(), equalTo(false)); } public void testCreateIndexAcknowledgement() { createIndex("test"); for (Client client : clients()) { assertThat(getLocalClusterState(client).metaData().indices().containsKey("test"), equalTo(true)); } //let's wait for green, otherwise there can be issues with after test checks (mock directory wrapper etc.) //but we do want to check that the new index is on all nodes cluster state even before green ensureGreen(); } public void testCreateIndexNoAcknowledgement() { CreateIndexResponse createIndexResponse = client().admin().indices().prepareCreate("test").setTimeout("0s").get(); assertThat(createIndexResponse.isAcknowledged(), equalTo(false)); //let's wait for green, otherwise there can be issues with after test checks (mock directory wrapper etc.) ensureGreen(); } private static ClusterState getLocalClusterState(Client client) { return client.admin().cluster().prepareState().setLocal(true).get().getState(); } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.storagegateway.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * A JSON object containing one or more of the following fields: * </p> * <ul> * <li> * <p> * <a>UpdateSnapshotScheduleInput$Description</a> * </p> * </li> * <li> * <p> * <a>UpdateSnapshotScheduleInput$RecurrenceInHours</a> * </p> * </li> * <li> * <p> * <a>UpdateSnapshotScheduleInput$StartAt</a> * </p> * </li> * <li> * <p> * <a>UpdateSnapshotScheduleInput$VolumeARN</a> * </p> * </li> * </ul> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/storagegateway-2013-06-30/UpdateSnapshotSchedule" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateSnapshotScheduleRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) of the volume. Use the <a>ListVolumes</a> operation to return a list of gateway * volumes. * </p> */ private String volumeARN; /** * <p> * The hour of the day at which the snapshot schedule begins represented as <i>hh</i>, where <i>hh</i> is the hour * (0 to 23). The hour of the day is in the time zone of the gateway. * </p> */ private Integer startAt; /** * <p> * Frequency of snapshots. Specify the number of hours between snapshots. * </p> */ private Integer recurrenceInHours; /** * <p> * Optional description of the snapshot that overwrites the existing description. * </p> */ private String description; /** * <p> * A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair. * </p> * <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the * maximum length for a tag's value is 256. * </p> * </note> */ private com.amazonaws.internal.SdkInternalList<Tag> tags; /** * <p> * The Amazon Resource Name (ARN) of the volume. Use the <a>ListVolumes</a> operation to return a list of gateway * volumes. * </p> * * @param volumeARN * The Amazon Resource Name (ARN) of the volume. Use the <a>ListVolumes</a> operation to return a list of * gateway volumes. */ public void setVolumeARN(String volumeARN) { this.volumeARN = volumeARN; } /** * <p> * The Amazon Resource Name (ARN) of the volume. Use the <a>ListVolumes</a> operation to return a list of gateway * volumes. * </p> * * @return The Amazon Resource Name (ARN) of the volume. Use the <a>ListVolumes</a> operation to return a list of * gateway volumes. */ public String getVolumeARN() { return this.volumeARN; } /** * <p> * The Amazon Resource Name (ARN) of the volume. Use the <a>ListVolumes</a> operation to return a list of gateway * volumes. * </p> * * @param volumeARN * The Amazon Resource Name (ARN) of the volume. Use the <a>ListVolumes</a> operation to return a list of * gateway volumes. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateSnapshotScheduleRequest withVolumeARN(String volumeARN) { setVolumeARN(volumeARN); return this; } /** * <p> * The hour of the day at which the snapshot schedule begins represented as <i>hh</i>, where <i>hh</i> is the hour * (0 to 23). The hour of the day is in the time zone of the gateway. * </p> * * @param startAt * The hour of the day at which the snapshot schedule begins represented as <i>hh</i>, where <i>hh</i> is the * hour (0 to 23). The hour of the day is in the time zone of the gateway. */ public void setStartAt(Integer startAt) { this.startAt = startAt; } /** * <p> * The hour of the day at which the snapshot schedule begins represented as <i>hh</i>, where <i>hh</i> is the hour * (0 to 23). The hour of the day is in the time zone of the gateway. * </p> * * @return The hour of the day at which the snapshot schedule begins represented as <i>hh</i>, where <i>hh</i> is * the hour (0 to 23). The hour of the day is in the time zone of the gateway. */ public Integer getStartAt() { return this.startAt; } /** * <p> * The hour of the day at which the snapshot schedule begins represented as <i>hh</i>, where <i>hh</i> is the hour * (0 to 23). The hour of the day is in the time zone of the gateway. * </p> * * @param startAt * The hour of the day at which the snapshot schedule begins represented as <i>hh</i>, where <i>hh</i> is the * hour (0 to 23). The hour of the day is in the time zone of the gateway. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateSnapshotScheduleRequest withStartAt(Integer startAt) { setStartAt(startAt); return this; } /** * <p> * Frequency of snapshots. Specify the number of hours between snapshots. * </p> * * @param recurrenceInHours * Frequency of snapshots. Specify the number of hours between snapshots. */ public void setRecurrenceInHours(Integer recurrenceInHours) { this.recurrenceInHours = recurrenceInHours; } /** * <p> * Frequency of snapshots. Specify the number of hours between snapshots. * </p> * * @return Frequency of snapshots. Specify the number of hours between snapshots. */ public Integer getRecurrenceInHours() { return this.recurrenceInHours; } /** * <p> * Frequency of snapshots. Specify the number of hours between snapshots. * </p> * * @param recurrenceInHours * Frequency of snapshots. Specify the number of hours between snapshots. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateSnapshotScheduleRequest withRecurrenceInHours(Integer recurrenceInHours) { setRecurrenceInHours(recurrenceInHours); return this; } /** * <p> * Optional description of the snapshot that overwrites the existing description. * </p> * * @param description * Optional description of the snapshot that overwrites the existing description. */ public void setDescription(String description) { this.description = description; } /** * <p> * Optional description of the snapshot that overwrites the existing description. * </p> * * @return Optional description of the snapshot that overwrites the existing description. */ public String getDescription() { return this.description; } /** * <p> * Optional description of the snapshot that overwrites the existing description. * </p> * * @param description * Optional description of the snapshot that overwrites the existing description. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateSnapshotScheduleRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair. * </p> * <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the * maximum length for a tag's value is 256. * </p> * </note> * * @return A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair.</p> <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and * the following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, * and the maximum length for a tag's value is 256. * </p> */ public java.util.List<Tag> getTags() { if (tags == null) { tags = new com.amazonaws.internal.SdkInternalList<Tag>(); } return tags; } /** * <p> * A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair. * </p> * <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the * maximum length for a tag's value is 256. * </p> * </note> * * @param tags * A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair.</p> <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and * the maximum length for a tag's value is 256. * </p> */ public void setTags(java.util.Collection<Tag> tags) { if (tags == null) { this.tags = null; return; } this.tags = new com.amazonaws.internal.SdkInternalList<Tag>(tags); } /** * <p> * A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair. * </p> * <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the * maximum length for a tag's value is 256. * </p> * </note> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair.</p> <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and * the maximum length for a tag's value is 256. * </p> * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateSnapshotScheduleRequest withTags(Tag... tags) { if (this.tags == null) { setTags(new com.amazonaws.internal.SdkInternalList<Tag>(tags.length)); } for (Tag ele : tags) { this.tags.add(ele); } return this; } /** * <p> * A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair. * </p> * <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and the * maximum length for a tag's value is 256. * </p> * </note> * * @param tags * A list of up to 50 tags that can be assigned to a snapshot. Each tag is a key-value pair.</p> <note> * <p> * Valid characters for key and value are letters, spaces, and numbers representable in UTF-8 format, and the * following special characters: + - = . _ : / @. The maximum length of a tag's key is 128 characters, and * the maximum length for a tag's value is 256. * </p> * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateSnapshotScheduleRequest withTags(java.util.Collection<Tag> tags) { setTags(tags); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getVolumeARN() != null) sb.append("VolumeARN: ").append(getVolumeARN()).append(","); if (getStartAt() != null) sb.append("StartAt: ").append(getStartAt()).append(","); if (getRecurrenceInHours() != null) sb.append("RecurrenceInHours: ").append(getRecurrenceInHours()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateSnapshotScheduleRequest == false) return false; UpdateSnapshotScheduleRequest other = (UpdateSnapshotScheduleRequest) obj; if (other.getVolumeARN() == null ^ this.getVolumeARN() == null) return false; if (other.getVolumeARN() != null && other.getVolumeARN().equals(this.getVolumeARN()) == false) return false; if (other.getStartAt() == null ^ this.getStartAt() == null) return false; if (other.getStartAt() != null && other.getStartAt().equals(this.getStartAt()) == false) return false; if (other.getRecurrenceInHours() == null ^ this.getRecurrenceInHours() == null) return false; if (other.getRecurrenceInHours() != null && other.getRecurrenceInHours().equals(this.getRecurrenceInHours()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getVolumeARN() == null) ? 0 : getVolumeARN().hashCode()); hashCode = prime * hashCode + ((getStartAt() == null) ? 0 : getStartAt().hashCode()); hashCode = prime * hashCode + ((getRecurrenceInHours() == null) ? 0 : getRecurrenceInHours().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public UpdateSnapshotScheduleRequest clone() { return (UpdateSnapshotScheduleRequest) super.clone(); } }
package com.ambrosoft.exercises; /* 11/15/2017 Problem: You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1 Analysis/brainstorming: (I typically create such written analyses for tougher problems, with drawings. Final form should be edited to remove ideas rejected) Assuming that nodes hold values and that value equality is a necessary condition if nodes are to match (but not sufficient -- children may not match) (There can be a more difficult variant of this problem if T2 was to match nodes and edges of T1 but where nodes corresponding to T2's leaves could have children in T1. But in this case we will assume that T2's leaves will correspond to T1's leaves.) The matching of the leaves is an important observation; a corollary is that the height of T2 constrains possibly matching roots of T1's subtrees to be high enough in T1 One can always attack this problem with a brute force approach: 1) define a recursive function isEqual(Node n1, Node n2) in the obvious way: compare value, require equality of children if present 2) traverse T1 in some order and for every node of T1 test isEqual(n, root-of-T2) While matching nodes from T1 and T2, we compare values stored in the nodes; this comparison is an operation (OP) OP can itself be expensive. We would ideally try to reduce the number of OPs We may be presented with mischievous input where T1 and T2 are both balanced and containing the same values except the rightmost leaf; there would be A LOT of node testing before T2 is found in T1 as last subtree. The time complexity of brute force solution would be big A more effective algorithm would need to prune the number of OPs Since T2 is smaller perhaps we can precompute some data structure from T2 ("signature") such that searching for this structure in T1 is simpler than the recursive "isEqual" That data structure can be eg. a serialization of T2 into an array or string, or some form of "hash function". We would then scan T1, incrementally updating an analogous serialization and/or hash, searching for a match In general, the problem of performance optimization here is very hard w/o any simplifying assumptions We don't know any statistics on T1, such as heights of nodes, and can only explore the tree by following links to children In the worst case, as mentioned above, T2's root node's value may occur *multiple* times in T1 making filtering on that value ineffective, leading to a lot of node matching (OPs) For example, if T2's node n holds value V, and we are looking at a node in T1 that also holds the value V, and it has 2 non-empty children both holding V as well, then we can have a match at n or at any of the children (we don't know the heights of these nodes) As we noticed above, T2 as a smaller tree can more readily be preprocessed to eg. a hash or a serialized form, but *if we need to search T1 repeatedly* we would benefit from preprocessing/"indexing"/augmenting T1 as well, for example caching node heights and subtree node counts Additional ideas: 1) try using node height information in recursive matching 2) add subtree height information to serialization 3) parallelize */ import java.util.concurrent.ThreadLocalRandom; public class SubtreeTest { static final int RANDOM_TREE_VALUE_BOUND = 1000; // making the solution more general interface Datum { boolean equals(final Datum other); // sb will be modified void serialize(final StringBuilder sb); Datum copy(); } static final class IntegerDatum implements Datum { private final int value; IntegerDatum(int value) { this.value = value; } @Override public int hashCode() { return value; } @Override public String toString() { return Integer.toString(value); } @Override public boolean equals(final Datum other) { return other instanceof IntegerDatum && ((IntegerDatum) other).value == value; } @Override public void serialize(final StringBuilder sb) { sb.append(value); } public IntegerDatum copy() { return new IntegerDatum(value); } } static class BinaryTreeNode { final Datum datum; BinaryTreeNode lft; BinaryTreeNode rgt; BinaryTreeNode(Datum datum) { this.datum = datum; } // this function to be called with non-null argument boolean equals(final BinaryTreeNode other) { if (!datum.equals(other.datum)) { return false; } else if (lft == null) { return other.lft == null; } else if (rgt == null) { return other.rgt == null; } else { // other.child != null tests performed here as they are cheap and can help avoid function calls // plus they guarantee non-nullness of this function's arg return other.lft != null && other.rgt != null && lft.equals(other.lft) && rgt.equals(other.rgt); } } int height() { return Math.max(lft != null ? lft.height() : -1, rgt != null ? rgt.height() : -1) + 1; } private static void serializeChild(final StringBuilder sb, final BinaryTreeNode child) { if (child != null) { child.serialize(sb.append(' ')); // prepend space as separator before serializing value } else { sb.append('n'); // 'n' for null } } void serialize(final StringBuilder sb) { datum.serialize(sb); serializeChild(sb, lft); serializeChild(sb, rgt); } BinaryTreeNode copy() { final BinaryTreeNode result = new BinaryTreeNode(datum.copy()); if (lft != null) { result.lft = lft.copy(); } if (rgt != null) { result.rgt = rgt.copy(); } return result; } BinaryTreeNode pickRandomNodeAtLevel(int level) { if (level < 0) { throw new IllegalArgumentException("level cannot be negative"); } if (level == 0) { return this; } else { final boolean goLeft = ThreadLocalRandom.current().nextBoolean(); if (goLeft) { return lft != null ? lft.pickRandomNodeAtLevel(level - 1) : null; } else { return rgt != null ? rgt.pickRandomNodeAtLevel(level - 1) : null; } } } } static class BinaryTree { final BinaryTreeNode root; BinaryTree(BinaryTreeNode root) { this.root = root; } boolean isEmpty() { return root == null; } boolean containsViaSerialization(final BinaryTree subtree) { if (subtree.isEmpty()) { return true; } else if (isEmpty()) { return false; } else { final StringBuilder sb = new StringBuilder(); serialize(sb); return sb.indexOf(subtree.serializeToString()) >= 0; } } boolean containsRecursive(final BinaryTree subtree) { return subtree.isEmpty() || !isEmpty() && containsRecursiveAux(root, subtree.root); } private boolean containsRecursiveAux(BinaryTreeNode t1node, BinaryTreeNode t2root) { return t2root.equals(t1node) || t1node.lft != null && containsRecursiveAux(t1node.lft, t2root) || t1node.rgt != null && containsRecursiveAux(t1node.rgt, t2root); } int height() { if (isEmpty()) { throw new IllegalStateException("height of empty tree undefined"); } return root.height(); } void serialize(final StringBuilder sb) { root.serialize(sb); } String serializeToString() { final StringBuilder sb = new StringBuilder(); serialize(sb); return sb.toString(); } BinaryTree copy() { return new BinaryTree(root != null ? root.copy() : null); } static BinaryTree createRandomSubtree(final int height) { if (height < 0) { throw new IllegalArgumentException("need non negative tree height"); } return new BinaryTree(createRandomSubtree(height, ThreadLocalRandom.current())); } BinaryTree pickRandomSubtreeAtLevel(final int level) { if (level < 0) { throw new IllegalArgumentException("level cannot be negative"); } if (root == null) { return new BinaryTree(null); } else { return new BinaryTree(root.pickRandomNodeAtLevel(level)); } } private static BinaryTreeNode createRandomSubtree(int height, ThreadLocalRandom random) { if (height >= 0) { final BinaryTreeNode node = new BinaryTreeNode(new IntegerDatum(random.nextInt(RANDOM_TREE_VALUE_BOUND))); node.lft = createRandomSubtree(height - 1, random); node.rgt = createRandomSubtree(height - 1, random); return node; } else { return null; } } } public static void main(String[] args) { BinaryTree tree = BinaryTree.createRandomSubtree(5); BinaryTree subtree = tree.pickRandomSubtreeAtLevel(2).copy(); System.out.println(tree.serializeToString()); System.out.println(subtree.serializeToString()); boolean contains1 = tree.containsViaSerialization(subtree); System.out.println("contains1 = " + contains1); boolean contains2 = tree.containsRecursive(subtree); System.out.println("contains basic recursive = " + contains2); System.out.println("cont3 = " + subtree.containsRecursive(subtree)); } }
/* * 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.facebook.presto.server.remotetask; import com.facebook.presto.OutputBuffers; import com.facebook.presto.client.NodeVersion; import com.facebook.presto.execution.NodeTaskMap; import com.facebook.presto.execution.QueryManagerConfig; import com.facebook.presto.execution.RemoteTask; import com.facebook.presto.execution.TaskId; import com.facebook.presto.execution.TaskInfo; import com.facebook.presto.execution.TaskManagerConfig; import com.facebook.presto.execution.TaskState; import com.facebook.presto.execution.TaskStatus; import com.facebook.presto.execution.TaskTestUtils; import com.facebook.presto.execution.TestSqlTaskManager; import com.facebook.presto.metadata.HandleJsonModule; import com.facebook.presto.metadata.HandleResolver; import com.facebook.presto.metadata.PrestoNode; import com.facebook.presto.server.HttpRemoteTaskFactory; import com.facebook.presto.server.TaskUpdateRequest; import com.facebook.presto.spi.ErrorCode; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeManager; import com.facebook.presto.testing.TestingHandleResolver; import com.facebook.presto.type.TypeDeserializer; import com.facebook.presto.type.TypeRegistry; import com.google.common.collect.ImmutableMultimap; import com.google.inject.Binder; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.Scopes; import io.airlift.bootstrap.Bootstrap; import io.airlift.http.client.testing.TestingHttpClient; import io.airlift.jaxrs.JsonMapper; import io.airlift.jaxrs.testing.JaxrsTestingHttpProcessor; import io.airlift.json.JsonCodec; import io.airlift.json.JsonModule; import io.airlift.units.Duration; import org.testng.annotations.Test; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import static com.facebook.presto.OutputBuffers.createInitialEmptyOutputBuffers; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE; import static com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_WAIT; import static com.facebook.presto.spi.StandardErrorCode.REMOTE_TASK_ERROR; import static com.facebook.presto.spi.StandardErrorCode.REMOTE_TASK_MISMATCH; import static com.facebook.presto.testing.assertions.Assert.assertEquals; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.inject.multibindings.Multibinder.newSetBinder; import static io.airlift.json.JsonBinder.jsonBinder; import static io.airlift.json.JsonCodecBinder.jsonCodecBinder; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.Assert.assertTrue; public class TestHttpRemoteTask { // This 30 sec per-test timeout should never be reached because the test should fail and do proper cleanup after 20 sec. private static final Duration IDLE_TIMEOUT = new Duration(3, SECONDS); private static final Duration FAIL_TIMEOUT = new Duration(20, SECONDS); private static final TaskManagerConfig TASK_MANAGER_CONFIG = new TaskManagerConfig() // Shorten status refresh wait and info update interval so that we can have a shorter test timeout .setStatusRefreshMaxWait(new Duration(IDLE_TIMEOUT.roundTo(MILLISECONDS) / 100, MILLISECONDS)) .setInfoUpdateInterval(new Duration(IDLE_TIMEOUT.roundTo(MILLISECONDS) / 10, MILLISECONDS)); private static final boolean TRACE_HTTP = false; @Test(timeOut = 30000) public void testRemoteTaskMismatch() throws Exception { runTest(TestCase.TASK_MISMATCH); } @Test(timeOut = 30000) public void testRejectedExecutionWhenVersionIsHigh() throws Exception { runTest(TestCase.TASK_MISMATCH_WHEN_VERSION_IS_HIGH); } @Test(timeOut = 30000) public void testRejectedExecution() throws Exception { runTest(TestCase.REJECTED_EXECUTION); } private void runTest(TestCase testCase) throws Exception { AtomicLong lastActivityNanos = new AtomicLong(System.nanoTime()); TestingTaskResource testingTaskResource = new TestingTaskResource(lastActivityNanos, testCase); HttpRemoteTaskFactory httpRemoteTaskFactory = createHttpRemoteTaskFactory(testingTaskResource); RemoteTask remoteTask = httpRemoteTaskFactory.createRemoteTask( TEST_SESSION, new TaskId("test", 1, 2), new PrestoNode("node-id", URI.create("http://fake.invalid/"), new NodeVersion("version"), false), TaskTestUtils.PLAN_FRAGMENT, ImmutableMultimap.of(), createInitialEmptyOutputBuffers(OutputBuffers.BufferType.BROADCAST), new NodeTaskMap.PartitionedSplitCountTracker(i -> { }), true); testingTaskResource.setInitialTaskInfo(remoteTask.getTaskInfo()); remoteTask.start(); CompletableFuture<Void> testComplete = new CompletableFuture<>(); asyncRun( IDLE_TIMEOUT.roundTo(MILLISECONDS), FAIL_TIMEOUT.roundTo(MILLISECONDS), lastActivityNanos, () -> testComplete.complete(null), (message, cause) -> testComplete.completeExceptionally(new AssertionError(message, cause))); testComplete.get(); httpRemoteTaskFactory.stop(); assertTrue(remoteTask.getTaskStatus().getState().isDone(), format("TaskStatus is not in a done state: %s", remoteTask.getTaskStatus())); assertTrue(remoteTask.getTaskInfo().getTaskStatus().getState().isDone(), format("TaskInfo is not in a done state: %s", remoteTask.getTaskInfo())); ErrorCode actualErrorCode = getOnlyElement(remoteTask.getTaskStatus().getFailures()).getErrorCode(); switch (testCase) { case TASK_MISMATCH: case TASK_MISMATCH_WHEN_VERSION_IS_HIGH: assertEquals(actualErrorCode, REMOTE_TASK_MISMATCH.toErrorCode()); break; case REJECTED_EXECUTION: assertEquals(actualErrorCode, REMOTE_TASK_ERROR.toErrorCode()); break; default: throw new UnsupportedOperationException(); } } private static HttpRemoteTaskFactory createHttpRemoteTaskFactory(TestingTaskResource testingTaskResource) throws Exception { Bootstrap app = new Bootstrap( new JsonModule(), new HandleJsonModule(), new Module() { @Override public void configure(Binder binder) { binder.bind(JsonMapper.class); binder.bind(TypeRegistry.class).in(Scopes.SINGLETON); binder.bind(TypeManager.class).to(TypeRegistry.class).in(Scopes.SINGLETON); jsonBinder(binder).addDeserializerBinding(Type.class).to(TypeDeserializer.class); newSetBinder(binder, Type.class); jsonCodecBinder(binder).bindJsonCodec(TaskStatus.class); jsonCodecBinder(binder).bindJsonCodec(TaskInfo.class); jsonCodecBinder(binder).bindJsonCodec(TaskUpdateRequest.class); } @Provides private HttpRemoteTaskFactory createHttpRemoteTaskFactory( JsonMapper jsonMapper, JsonCodec<TaskStatus> taskStatusCodec, JsonCodec<TaskInfo> taskInfoCodec, JsonCodec<TaskUpdateRequest> taskUpdateRequestCodec) { JaxrsTestingHttpProcessor jaxrsTestingHttpProcessor = new JaxrsTestingHttpProcessor(URI.create("http://fake.invalid/"), testingTaskResource, jsonMapper); TestingHttpClient testingHttpClient = new TestingHttpClient(jaxrsTestingHttpProcessor.setTrace(TRACE_HTTP)); return new HttpRemoteTaskFactory( new QueryManagerConfig(), TASK_MANAGER_CONFIG, testingHttpClient, new TestSqlTaskManager.MockLocationFactory(), taskStatusCodec, taskInfoCodec, taskUpdateRequestCodec, new RemoteTaskStats()); } } ); Injector injector = app .strictConfig() .doNotInitializeLogging() .initialize(); HandleResolver handleResolver = injector.getInstance(HandleResolver.class); handleResolver.addConnectorName("test", new TestingHandleResolver()); return injector.getInstance(HttpRemoteTaskFactory.class); } private static void asyncRun(long idleTimeoutMillis, long failTimeoutMillis, AtomicLong lastActivityNanos, Runnable runAfterIdle, BiConsumer<String, Throwable> runAfterFail) { new Thread(() -> { long startTimeNanos = System.nanoTime(); try { while (true) { long millisSinceLastActivity = (System.nanoTime() - lastActivityNanos.get()) / 1_000_000L; long millisSinceStart = (System.nanoTime() - startTimeNanos) / 1_000_000L; long millisToIdleTarget = idleTimeoutMillis - millisSinceLastActivity; long millisToFailTarget = failTimeoutMillis - millisSinceStart; if (millisToFailTarget < millisToIdleTarget) { runAfterFail.accept(format("Activity doesn't stop after %sms", failTimeoutMillis), null); return; } if (millisToIdleTarget < 0) { runAfterIdle.run(); return; } Thread.sleep(millisToIdleTarget); } } catch (InterruptedException e) { runAfterFail.accept("Idle/fail timeout monitor thread interrupted", e); } }).start(); } private enum TestCase { TASK_MISMATCH, TASK_MISMATCH_WHEN_VERSION_IS_HIGH, REJECTED_EXECUTION } @Path("/task/{nodeId}") public static class TestingTaskResource { private static final String INITIAL_TASK_INSTANCE_ID = "task-instance-id"; private static final String NEW_TASK_INSTANCE_ID = "task-instance-id-x"; private final AtomicLong lastActivityNanos; private final TestCase testCase; private TaskInfo initialTaskInfo; private TaskStatus initialTaskStatus; private long version; private TaskState taskState; private String taskInstanceId = INITIAL_TASK_INSTANCE_ID; private long statusFetchCounter; public TestingTaskResource(AtomicLong lastActivityNanos, TestCase testCase) { this.lastActivityNanos = requireNonNull(lastActivityNanos, "lastActivityNanos is null"); this.testCase = requireNonNull(testCase, "testCase is null"); } @GET @Path("{taskId}") @Produces(MediaType.APPLICATION_JSON) public synchronized TaskInfo getTaskInfo( @PathParam("taskId") final TaskId taskId, @HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState, @HeaderParam(PRESTO_MAX_WAIT) Duration maxWait, @Context UriInfo uriInfo) { lastActivityNanos.set(System.nanoTime()); return buildTaskInfo(); } @POST @Path("{taskId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public synchronized TaskInfo createOrUpdateTask( @PathParam("taskId") TaskId taskId, TaskUpdateRequest taskUpdateRequest, @Context UriInfo uriInfo) { lastActivityNanos.set(System.nanoTime()); return buildTaskInfo(); } @GET @Path("{taskId}/status") @Produces(MediaType.APPLICATION_JSON) public synchronized TaskStatus getTaskStatus( @PathParam("taskId") TaskId taskId, @HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState, @HeaderParam(PRESTO_MAX_WAIT) Duration maxWait, @Context UriInfo uriInfo) throws InterruptedException { lastActivityNanos.set(System.nanoTime()); wait(maxWait.roundTo(MILLISECONDS)); return buildTaskStatus(); } @DELETE @Path("{taskId}") @Produces(MediaType.APPLICATION_JSON) public synchronized TaskInfo deleteTask( @PathParam("taskId") TaskId taskId, @QueryParam("abort") @DefaultValue("true") boolean abort, @Context UriInfo uriInfo) { lastActivityNanos.set(System.nanoTime()); taskState = abort ? TaskState.ABORTED : TaskState.CANCELED; return buildTaskInfo(); } public void setInitialTaskInfo(TaskInfo initialTaskInfo) { this.initialTaskInfo = initialTaskInfo; this.initialTaskStatus = initialTaskInfo.getTaskStatus(); this.taskState = initialTaskStatus.getState(); this.version = initialTaskStatus.getVersion(); switch (testCase) { case TASK_MISMATCH_WHEN_VERSION_IS_HIGH: // Make the initial version large enough. // This way, the version number can't be reached if it is reset to 0. version = 1_000_000; break; case TASK_MISMATCH: case REJECTED_EXECUTION: break; // do nothing default: throw new UnsupportedOperationException(); } } private TaskInfo buildTaskInfo() { return new TaskInfo( buildTaskStatus(), initialTaskInfo.getLastHeartbeat(), initialTaskInfo.getOutputBuffers(), initialTaskInfo.getNoMoreSplits(), initialTaskInfo.getStats(), initialTaskInfo.isNeedsPlan(), initialTaskInfo.isComplete()); } private TaskStatus buildTaskStatus() { statusFetchCounter++; // Change the task instance id after 10th fetch to simulate worker restart switch (testCase) { case TASK_MISMATCH: case TASK_MISMATCH_WHEN_VERSION_IS_HIGH: if (statusFetchCounter == 10) { taskInstanceId = NEW_TASK_INSTANCE_ID; version = 0; } break; case REJECTED_EXECUTION: if (statusFetchCounter >= 10) { throw new RejectedExecutionException(); } break; default: throw new UnsupportedOperationException(); } return new TaskStatus( initialTaskStatus.getTaskId(), taskInstanceId, ++version, taskState, initialTaskStatus.getSelf(), initialTaskStatus.getFailures(), initialTaskStatus.getQueuedPartitionedDrivers(), initialTaskStatus.getRunningPartitionedDrivers(), initialTaskStatus.getMemoryReservation()); } } }
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.examples; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.bitcoinj.core.*; import org.bitcoinj.kits.WalletAppKit; import org.bitcoinj.params.RegTestParams; import org.bitcoinj.protocols.channels.PaymentChannelClient; import org.bitcoinj.protocols.channels.PaymentChannelClientConnection; import org.bitcoinj.protocols.channels.StoredPaymentChannelClientStates; import org.bitcoinj.protocols.channels.ValueOutOfRangeException; import org.bitcoinj.utils.BriefLogFormatter; import org.bitcoinj.utils.Threading; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.Uninterruptibles; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import static org.bitcoinj.core.Coin.CENT; /** * Simple client that connects to the given host, opens a channel, and pays one cent. */ public class ExamplePaymentChannelClient { private static final org.slf4j.Logger log = LoggerFactory.getLogger(ExamplePaymentChannelClient.class); private WalletAppKit appKit; private final Coin channelSize; private final ECKey myKey; private final NetworkParameters params; public static void main(String[] args) throws Exception { BriefLogFormatter.init(); OptionParser parser = new OptionParser(); OptionSpec<NetworkEnum> net = parser.accepts("net", "The network to run the examples on").withRequiredArg().ofType(NetworkEnum.class).defaultsTo(NetworkEnum.TEST); OptionSpec<Integer> version = parser.accepts("version", "The payment channel protocol to use").withRequiredArg().ofType(Integer.class); parser.accepts("help", "Displays program options"); OptionSet opts = parser.parse(args); if (opts.has("help") || !opts.has(net) || opts.nonOptionArguments().size() != 1) { System.err.println("usage: ExamplePaymentChannelClient --net=MAIN/TEST/REGTEST --version=1/2 host"); parser.printHelpOn(System.err); return; } PaymentChannelClient.VersionSelector versionSelector = PaymentChannelClient.VersionSelector.VERSION_1; if (opts.has("version")) { switch (version.value(opts)) { case 1: versionSelector = PaymentChannelClient.VersionSelector.VERSION_1; break; case 2: versionSelector = PaymentChannelClient.VersionSelector.VERSION_2; break; default: System.err.println("Invalid version - valid versions are 1, 2"); return; } } NetworkParameters params = net.value(opts).get(); new ExamplePaymentChannelClient().run(opts.nonOptionArguments().get(0), versionSelector, params); } public ExamplePaymentChannelClient() { channelSize = CENT; myKey = new ECKey(); params = RegTestParams.get(); } public void run(final String host, PaymentChannelClient.VersionSelector versionSelector, final NetworkParameters params) throws Exception { // Bring up all the objects we need, create/load a wallet, sync the chain, etc. We override WalletAppKit so we // can customize it by adding the extension objects - we have to do this before the wallet file is loaded so // the plugin that knows how to parse all the additional data is present during the load. appKit = new WalletAppKit(params, new File("."), "payment_channel_example_client") { @Override protected List<WalletExtension> provideWalletExtensions() { // The StoredPaymentChannelClientStates object is responsible for, amongst other things, broadcasting // the refund transaction if its lock time has expired. It also persists channels so we can resume them // after a restart. // We should not send a PeerGroup in the StoredPaymentChannelClientStates constructor // since WalletAppKit will find it for us. return ImmutableList.<WalletExtension>of(new StoredPaymentChannelClientStates(null)); } }; // Broadcasting can take a bit of time so we up the timeout for "real" networks final int timeoutSeconds = params.getId().equals(NetworkParameters.ID_REGTEST) ? 15 : 150; if (params == RegTestParams.get()) { appKit.connectToLocalHost(); } appKit.startAsync(); appKit.awaitRunning(); // We now have active network connections and a fully synced wallet. // Add a new key which will be used for the multisig contract. appKit.wallet().importKey(myKey); appKit.wallet().allowSpendingUnconfirmedTransactions(); System.out.println(appKit.wallet()); // Create the object which manages the payment channels protocol, client side. Tell it where the server to // connect to is, along with some reasonable network timeouts, the wallet and our temporary key. We also have // to pick an amount of value to lock up for the duration of the channel. // // Note that this may or may not actually construct a new channel. If an existing unclosed channel is found in // the wallet, then it'll re-use that one instead. final InetSocketAddress server = new InetSocketAddress(host, 4242); waitForSufficientBalance(channelSize); final String channelID = host; // Do this twice as each one sends 1/10th of a bitcent 5 times, so to send a bitcent, we do it twice. This // demonstrates resuming a channel that wasn't closed yet. It should close automatically once we run out // of money on the channel. log.info("Round one ..."); openAndSend(timeoutSeconds, server, channelID, 5, versionSelector); log.info("Round two ..."); log.info(appKit.wallet().toString()); openAndSend(timeoutSeconds, server, channelID, 4, versionSelector); // 4 times because the opening of the channel made a payment. log.info("Stopping ..."); appKit.stopAsync(); appKit.awaitTerminated(); } private void openAndSend(int timeoutSecs, InetSocketAddress server, String channelID, final int times, PaymentChannelClient.VersionSelector versionSelector) throws IOException, ValueOutOfRangeException, InterruptedException { // Use protocol version 1 for simplicity PaymentChannelClientConnection client = new PaymentChannelClientConnection( server, timeoutSecs, appKit.wallet(), myKey, channelSize, channelID, versionSelector); // Opening the channel requires talking to the server, so it's asynchronous. final CountDownLatch latch = new CountDownLatch(1); Futures.addCallback(client.getChannelOpenFuture(), new FutureCallback<PaymentChannelClientConnection>() { @Override public void onSuccess(PaymentChannelClientConnection client) { // By the time we get here, if the channel is new then we already made a micropayment! The reason is, // we are not allowed to have payment channels that pay nothing at all. log.info("Success! Trying to make {} micropayments. Already paid {} satoshis on this channel", times, client.state().getValueSpent()); final Coin MICROPAYMENT_SIZE = CENT.divide(10); for (int i = 0; i < times; i++) { try { // Wait because the act of making a micropayment is async, and we're not allowed to overlap. // This callback is running on the user thread (see the last lines in openAndSend) so it's safe // for us to block here: if we didn't select the right thread, we'd end up blocking the payment // channels thread and would deadlock. Uninterruptibles.getUninterruptibly(client.incrementPayment(MICROPAYMENT_SIZE)); } catch (ValueOutOfRangeException e) { log.error("Failed to increment payment by a CENT, remaining value is {}", client.state().getValueRefunded()); throw new RuntimeException(e); } catch (ExecutionException e) { log.error("Failed to increment payment", e); throw new RuntimeException(e); } log.info("Successfully sent payment of one CENT, total remaining on channel is now {}", client.state().getValueRefunded()); } if (client.state().getValueRefunded().compareTo(MICROPAYMENT_SIZE) < 0) { // Now tell the server we're done so they should broadcast the final transaction and refund us what's // left. If we never do this then eventually the server will time out and do it anyway and if the // server goes away for longer, then eventually WE will time out and the refund tx will get broadcast // by ourselves. log.info("Settling channel for good"); client.settle(); } else { // Just unplug from the server but leave the channel open so it can resume later. client.disconnectWithoutSettlement(); } latch.countDown(); } @Override public void onFailure(Throwable throwable) { log.error("Failed to open connection", throwable); latch.countDown(); } }, Threading.USER_THREAD); latch.await(); } private void waitForSufficientBalance(Coin amount) { // Not enough money in the wallet. Coin amountPlusFee = amount.add(Wallet.SendRequest.DEFAULT_FEE_PER_KB); // ESTIMATED because we don't really need to wait for confirmation. ListenableFuture<Coin> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee, Wallet.BalanceType.ESTIMATED); if (!balanceFuture.isDone()) { System.out.println("Please send " + amountPlusFee.toFriendlyString() + " to " + myKey.toAddress(params)); Futures.getUnchecked(balanceFuture); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/services/ad_group_criterion_label_service.proto package com.google.ads.googleads.v8.services; /** * <pre> * The result for an ad group criterion label mutate. * </pre> * * Protobuf type {@code google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult} */ public final class MutateAdGroupCriterionLabelResult extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult) MutateAdGroupCriterionLabelResultOrBuilder { private static final long serialVersionUID = 0L; // Use MutateAdGroupCriterionLabelResult.newBuilder() to construct. private MutateAdGroupCriterionLabelResult(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateAdGroupCriterionLabelResult() { resourceName_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateAdGroupCriterionLabelResult(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MutateAdGroupCriterionLabelResult( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); resourceName_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v8.services.AdGroupCriterionLabelServiceProto.internal_static_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelResult_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v8.services.AdGroupCriterionLabelServiceProto.internal_static_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelResult_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult.class, com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult.Builder.class); } public static final int RESOURCE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object resourceName_; /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult)) { return super.equals(obj); } com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult other = (com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * The result for an ad group criterion label mutate. * </pre> * * Protobuf type {@code google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult) com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResultOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v8.services.AdGroupCriterionLabelServiceProto.internal_static_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelResult_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v8.services.AdGroupCriterionLabelServiceProto.internal_static_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelResult_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult.class, com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult.Builder.class); } // Construct using com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); resourceName_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v8.services.AdGroupCriterionLabelServiceProto.internal_static_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelResult_descriptor; } @java.lang.Override public com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult getDefaultInstanceForType() { return com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult build() { com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult buildPartial() { com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult result = new com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult(this); result.resourceName_ = resourceName_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult) { return mergeFrom((com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult other) { if (other == com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object resourceName_ = ""; /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; onChanged(); return this; } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); onChanged(); return this; } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1;</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult) private static final com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult(); } public static com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateAdGroupCriterionLabelResult> PARSER = new com.google.protobuf.AbstractParser<MutateAdGroupCriterionLabelResult>() { @java.lang.Override public MutateAdGroupCriterionLabelResult parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MutateAdGroupCriterionLabelResult(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MutateAdGroupCriterionLabelResult> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateAdGroupCriterionLabelResult> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v8.services.MutateAdGroupCriterionLabelResult getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.bgp.controller.impl; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Service; import org.onosproject.bgp.controller.BgpCfg; import org.onosproject.bgp.controller.BgpController; import org.onosproject.bgp.controller.BgpId; import org.onosproject.bgp.controller.BgpLocalRib; import org.onosproject.bgp.controller.BgpPeer; import org.onosproject.bgp.controller.BgpNodeListener; import org.onosproject.bgp.controller.BgpPeerManager; import org.onosproject.bgpio.exceptions.BgpParseException; import org.onosproject.bgpio.protocol.BgpMessage; import org.onosproject.bgpio.protocol.BgpUpdateMsg; import org.onosproject.bgpio.types.BgpValueType; import org.onosproject.bgpio.types.MpReachNlri; import org.onosproject.bgpio.types.MpUnReachNlri; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component(immediate = true) @Service public class BgpControllerImpl implements BgpController { private static final Logger log = LoggerFactory.getLogger(BgpControllerImpl.class); protected ConcurrentHashMap<BgpId, BgpPeer> connectedPeers = new ConcurrentHashMap<BgpId, BgpPeer>(); protected BgpPeerManagerImpl peerManager = new BgpPeerManagerImpl(); private BgpLocalRib bgplocalRIB = new BgpLocalRibImpl(this); private BgpLocalRib bgplocalRIBVpn = new BgpLocalRibImpl(this); protected Set<BgpNodeListener> bgpNodeListener = new CopyOnWriteArraySet<>(); final Controller ctrl = new Controller(this); private BgpConfig bgpconfig = new BgpConfig(this); @Activate public void activate() { this.ctrl.start(); log.info("Started"); } @Deactivate public void deactivate() { // Close all connected peers closeConnectedPeers(); this.ctrl.stop(); log.info("Stopped"); } @Override public Iterable<BgpPeer> getPeers() { return this.connectedPeers.values(); } @Override public BgpPeer getPeer(BgpId bgpId) { return this.connectedPeers.get(bgpId); } @Override public void addListener(BgpNodeListener listener) { this.bgpNodeListener.add(listener); } @Override public void removeListener(BgpNodeListener listener) { this.bgpNodeListener.remove(listener); } @Override public Set<BgpNodeListener> listener() { return bgpNodeListener; } @Override public void writeMsg(BgpId bgpId, BgpMessage msg) { this.getPeer(bgpId).sendMessage(msg); } @Override public void processBGPPacket(BgpId bgpId, BgpMessage msg) throws BgpParseException { BgpPeer peer = getPeer(bgpId); switch (msg.getType()) { case OPEN: // TODO: Process Open message break; case KEEP_ALIVE: // TODO: Process keepalive message break; case NOTIFICATION: // TODO: Process notificatoin message break; case UPDATE: BgpUpdateMsg updateMsg = (BgpUpdateMsg) msg; List<BgpValueType> pathAttr = updateMsg.bgpPathAttributes().pathAttributes(); if (pathAttr == null) { log.debug("llPathAttr is null, cannot process update message"); break; } Iterator<BgpValueType> listIterator = pathAttr.iterator(); boolean isLinkstate = false; while (listIterator.hasNext()) { BgpValueType attr = listIterator.next(); if ((attr instanceof MpReachNlri) || (attr instanceof MpUnReachNlri)) { isLinkstate = true; } } if (isLinkstate) { peer.buildAdjRibIn(pathAttr); } break; default: // TODO: Process other message break; } } @Override public void closeConnectedPeers() { BgpPeer bgpPeer; for (BgpId id : this.connectedPeers.keySet()) { bgpPeer = getPeer(id); bgpPeer.disconnectPeer(); } } /** * Implementation of an BGP Peer which is responsible for keeping track of connected peers and the state in which * they are. */ public class BgpPeerManagerImpl implements BgpPeerManager { private final Logger log = LoggerFactory.getLogger(BgpPeerManagerImpl.class); private final Lock peerLock = new ReentrantLock(); @Override public boolean addConnectedPeer(BgpId bgpId, BgpPeer bgpPeer) { if (connectedPeers.get(bgpId) != null) { this.log.error("Trying to add connectedPeer but found previous " + "value for bgp ip: {}", bgpId.toString()); return false; } else { this.log.debug("Added Peer {}", bgpId.toString()); connectedPeers.put(bgpId, bgpPeer); return true; } } @Override public boolean isPeerConnected(BgpId bgpId) { if (connectedPeers.get(bgpId) == null) { this.log.error("Is peer connected: bgpIp {}.", bgpId.toString()); return false; } return true; } @Override public void removeConnectedPeer(BgpId bgpId) { connectedPeers.remove(bgpId); } @Override public BgpPeer getPeer(BgpId bgpId) { return connectedPeers.get(bgpId); } /** * Gets bgp peer instance. * * @param bgpController controller instance. * @param sessionInfo bgp session info. * @param pktStats packet statistics. * @return BGPPeer peer instance. */ public BgpPeer getBgpPeerInstance(BgpController bgpController, BgpSessionInfoImpl sessionInfo, BgpPacketStatsImpl pktStats) { BgpPeer bgpPeer = new BgpPeerImpl(bgpController, sessionInfo, pktStats); return bgpPeer; } } /** * Returns controller. * * @return controller */ public Controller controller() { return this.ctrl; } @Override public ConcurrentHashMap<BgpId, BgpPeer> connectedPeers() { return connectedPeers; } @Override public BgpPeerManagerImpl peerManager() { return peerManager; } @Override public BgpCfg getConfig() { return this.bgpconfig; } @Override public int connectedPeerCount() { return connectedPeers.size(); } /** * Gets the BGP local RIB. * * @return bgplocalRIB BGP local RIB. */ @Override public BgpLocalRib bgpLocalRib() { return bgplocalRIB; } /** * Gets the BGP local RIB with VPN. * * @return bgplocalRIBVpn BGP VPN local RIB . */ @Override public BgpLocalRib bgpLocalRibVpn() { return bgplocalRIBVpn; } }
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.siddhi.core.query.ratelimit; import junit.framework.Assert; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.wso2.siddhi.core.ExecutionPlanRuntime; import org.wso2.siddhi.core.SiddhiManager; import org.wso2.siddhi.core.event.Event; import org.wso2.siddhi.core.query.output.callback.QueryCallback; import org.wso2.siddhi.core.stream.input.InputHandler; import org.wso2.siddhi.core.util.EventPrinter; public class EventOutputRateLimitTestCase { static final Logger log = Logger.getLogger(EventOutputRateLimitTestCase.class); private volatile int count; private volatile boolean eventArrived; @Before public void init() { count = 0; eventArrived = false; } @Test public void testEventOutputRateLimitQuery1() throws InterruptedException { log.info("EventOutputRateLimit test1"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest1') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "output all every 2 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 4, count); executionPlanRuntime.shutdown(); } @Test public void testEventOutputRateLimitQuery2() throws InterruptedException { log.info("EventOutputRateLimit test2"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest2') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "output every 2 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 4, count); executionPlanRuntime.shutdown(); } @Test public void testEventOutputRateLimitQuery3() throws InterruptedException { log.info("EventOutputRateLimit test3"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest3') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "output every 5 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.30"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 5, count); executionPlanRuntime.shutdown(); } @Test public void testEventOutputRateLimitQuery4() throws InterruptedException { log.info("EventOutputRateLimit test4"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest4') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "output first every 2 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; Assert.assertTrue("192.10.1.5".equals(inEvents[0].getData(0)) || "192.10.1.9".equals(inEvents[0].getData(0)) || "192.10.1.3".equals(inEvents[0].getData(0))); } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 3, count); executionPlanRuntime.shutdown(); } @Test public void testEventOutputRateLimitQuery5() throws InterruptedException { log.info("EventOutputRateLimit test5"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest5') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "output first every 3 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; Assert.assertTrue("192.10.1.5".equals(inEvents[0].getData(0)) || "192.10.1.4".equals(inEvents[0].getData(0))); } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 2, count); executionPlanRuntime.shutdown(); } @Test public void testEventOutputRateLimitQuery6() throws InterruptedException { log.info("EventOutputRateLimit test6"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest6') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "output last every 2 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; Assert.assertTrue("192.10.1.5".equals(inEvents[0].getData(0)) || "192.10.1.4".equals(inEvents[0].getData(0))); } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 2, count); executionPlanRuntime.shutdown(); } @Test public void testEventOutputRateLimitQuery7() throws InterruptedException { log.info("EventOutputRateLimit test7"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest7') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "output last every 4 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; Assert.assertTrue("192.10.1.4".equals(inEvents[0].getData(0))); } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 1, count); executionPlanRuntime.shutdown(); } @Test public void testEventOutputRateLimitQuery8() throws InterruptedException { log.info("EventOutputRateLimit test8"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest8') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "group by ip " + "output first every 5 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.30"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 6, count); executionPlanRuntime.shutdown(); } @Test public void testEventOutputRateLimitQuery9() throws InterruptedException { log.info("EventOutputRateLimit test9"); SiddhiManager siddhiManager = new SiddhiManager(); String executionPlan = "" + "@Plan:name('EventOutputRateLimitTest9') " + "" + "define stream LoginEvents (timeStamp long, ip string);" + "" + "@info(name = 'query1') " + "from LoginEvents " + "select ip " + "group by ip " + "output last every 5 events " + "insert into uniqueIps ;"; ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(executionPlan); log.info("Running : " + executionPlanRuntime.getName()); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); if (inEvents != null) { count += inEvents.length; } else { Assert.fail("Remove events emitted"); } eventArrived = true; } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("LoginEvents"); executionPlanRuntime.start(); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.5"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.3"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.9"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.4"}); inputHandler.send(new Object[]{System.currentTimeMillis(), "192.10.1.30"}); Thread.sleep(1000); Assert.assertEquals("Event arrived", true, eventArrived); Assert.assertEquals("Number of output event value", 4, count); executionPlanRuntime.shutdown(); } }
package android.os; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * 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. * #L% */ @com.francetelecom.rd.stubs.annotation.ClassDone(0) public abstract class BatteryStats implements Parcelable { // Classes public abstract static class Counter { // Constructors public Counter(){ } // Methods public abstract int getCountLocked(int arg1); public abstract void logState(android.util.Printer arg1, java.lang.String arg2); } public abstract static class Timer { // Constructors public Timer(){ } // Methods public abstract int getCountLocked(int arg1); public abstract void logState(android.util.Printer arg1, java.lang.String arg2); public abstract long getTotalTimeLocked(long arg1, int arg2); } public abstract static class Uid { // Classes public abstract static class Wakelock { // Constructors public Wakelock(){ } // Methods public abstract BatteryStats.Timer getWakeTime(int arg1); } public abstract static class Sensor { // Fields public static final int GPS = -10000; // Constructors public Sensor(){ } // Methods public abstract int getHandle(); public abstract BatteryStats.Timer getSensorTime(); } public class Pid { // Fields public long mWakeSum; public long mWakeStart; // Constructors public Pid(){ } } public abstract static class Proc { // Classes public static class ExcessivePower { // Fields public static final int TYPE_WAKE = 1; public static final int TYPE_CPU = 2; public int type; public long overTime; public long usedTime; // Constructors public ExcessivePower(){ } } // Constructors public Proc(){ } // Methods public abstract int getStarts(int arg1); public abstract long getUserTime(int arg1); public abstract long getSystemTime(int arg1); public abstract long getForegroundTime(int arg1); public abstract long getTimeAtCpuSpeedStep(int arg1, int arg2); public abstract int countExcessivePowers(); public abstract BatteryStats.Uid.Proc.ExcessivePower getExcessivePower(int arg1); } public abstract static class Pkg { // Classes public abstract class Serv { // Fields // Constructors public Serv(){ } // Methods public abstract long getStartTime(long arg1, int arg2); public abstract int getStarts(int arg1); public abstract int getLaunches(int arg1); } // Constructors public Pkg(){ } // Methods public abstract java.util.Map<java.lang.String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats(); public abstract int getWakeups(int arg1); } // Fields public static final int NUM_USER_ACTIVITY_TYPES = 7; // Constructors public Uid(){ } // Methods public abstract int getUid(); public abstract void noteUserActivityLocked(int arg1); public abstract void noteWifiRunningLocked(); public abstract void noteWifiStoppedLocked(); public abstract void noteFullWifiLockAcquiredLocked(); public abstract void noteFullWifiLockReleasedLocked(); public abstract void noteScanWifiLockAcquiredLocked(); public abstract void noteScanWifiLockReleasedLocked(); public abstract void noteWifiMulticastEnabledLocked(); public abstract void noteWifiMulticastDisabledLocked(); public abstract java.util.Map<java.lang.String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats(); public abstract java.util.Map<java.lang.Integer, ? extends BatteryStats.Uid.Sensor> getSensorStats(); public abstract android.util.SparseArray<? extends BatteryStats.Uid.Pid> getPidStats(); public abstract java.util.Map<java.lang.String, ? extends BatteryStats.Uid.Proc> getProcessStats(); public abstract java.util.Map<java.lang.String, ? extends BatteryStats.Uid.Pkg> getPackageStats(); public abstract long getTcpBytesReceived(int arg1); public abstract long getTcpBytesSent(int arg1); public abstract void noteAudioTurnedOnLocked(); public abstract void noteAudioTurnedOffLocked(); public abstract void noteVideoTurnedOnLocked(); public abstract void noteVideoTurnedOffLocked(); public abstract long getWifiRunningTime(long arg1, int arg2); public abstract long getFullWifiLockTime(long arg1, int arg2); public abstract long getScanWifiLockTime(long arg1, int arg2); public abstract long getWifiMulticastTime(long arg1, int arg2); public abstract long getAudioTurnedOnTime(long arg1, int arg2); public abstract long getVideoTurnedOnTime(long arg1, int arg2); public abstract boolean hasUserActivity(); public abstract int getUserActivityCount(int arg1, int arg2); } public static final class HistoryItem implements Parcelable { // Fields public BatteryStats.HistoryItem next; public long time; public static final byte CMD_NULL = 0; public static final byte CMD_UPDATE = 1; public static final byte CMD_START = 2; public static final byte CMD_OVERFLOW = 3; public byte cmd; public byte batteryLevel; public byte batteryStatus; public byte batteryHealth; public byte batteryPlugType; public char batteryTemperature; public char batteryVoltage; public static final int STATE_BRIGHTNESS_MASK = 15; public static final int STATE_BRIGHTNESS_SHIFT = 0; public static final int STATE_SIGNAL_STRENGTH_MASK = 240; public static final int STATE_SIGNAL_STRENGTH_SHIFT = 4; public static final int STATE_PHONE_STATE_MASK = 3840; public static final int STATE_PHONE_STATE_SHIFT = 8; public static final int STATE_DATA_CONNECTION_MASK = 61440; public static final int STATE_DATA_CONNECTION_SHIFT = 12; public static final int STATE_WAKE_LOCK_FLAG = 1073741824; public static final int STATE_SENSOR_ON_FLAG = 536870912; public static final int STATE_GPS_ON_FLAG = 268435456; public static final int STATE_PHONE_SCANNING_FLAG = 134217728; public static final int STATE_WIFI_RUNNING_FLAG = 67108864; public static final int STATE_WIFI_FULL_LOCK_FLAG = 33554432; public static final int STATE_WIFI_SCAN_LOCK_FLAG = 16777216; public static final int STATE_WIFI_MULTICAST_ON_FLAG = 8388608; public static final int STATE_AUDIO_ON_FLAG = 4194304; public static final int STATE_VIDEO_ON_FLAG = 2097152; public static final int STATE_SCREEN_ON_FLAG = 1048576; public static final int STATE_BATTERY_PLUGGED_FLAG = 524288; public static final int STATE_PHONE_IN_CALL_FLAG = 262144; public static final int STATE_WIFI_ON_FLAG = 131072; public static final int STATE_BLUETOOTH_ON_FLAG = 65536; public static final int MOST_INTERESTING_STATES = 270270464; public int states; // Constructors public HistoryItem(){ } public HistoryItem(long arg1, Parcel arg2){ } // Methods public void clear(){ } public void writeToParcel(Parcel arg1, int arg2){ } public int describeContents(){ return 0; } public void setTo(BatteryStats.HistoryItem arg1){ } public void setTo(long arg1, byte arg2, BatteryStats.HistoryItem arg3){ } public void writeDelta(Parcel arg1, BatteryStats.HistoryItem arg2){ } public void readDelta(Parcel arg1){ } public boolean same(BatteryStats.HistoryItem arg1){ return false; } } public static final class BitDescription { // Fields public final int mask = 0; public final int shift = 0; public final java.lang.String name = (java.lang.String) null; public final java.lang.String [] values = (java.lang.String []) null; // Constructors public BitDescription(int arg1, java.lang.String arg2){ } public BitDescription(int arg1, int arg2, java.lang.String arg3, java.lang.String [] arg4){ } } public static class HistoryPrinter { // Constructors public HistoryPrinter(){ } // Methods public void printNextItem(java.io.PrintWriter arg1, BatteryStats.HistoryItem arg2, long arg3){ } } // Fields public static final int WAKE_TYPE_PARTIAL = 0; public static final int WAKE_TYPE_FULL = 1; public static final int WAKE_TYPE_WINDOW = 2; public static final int SENSOR = 3; public static final int WIFI_RUNNING = 4; public static final int FULL_WIFI_LOCK = 5; public static final int SCAN_WIFI_LOCK = 6; public static final int WIFI_MULTICAST_ENABLED = 7; public static final int AUDIO_TURNED_ON = 7; public static final int VIDEO_TURNED_ON = 8; public static final int STATS_SINCE_CHARGED = 0; public static final int STATS_LAST = 1; public static final int STATS_CURRENT = 2; public static final int STATS_SINCE_UNPLUGGED = 3; public static final int SCREEN_BRIGHTNESS_DARK = 0; public static final int SCREEN_BRIGHTNESS_DIM = 1; public static final int SCREEN_BRIGHTNESS_MEDIUM = 2; public static final int SCREEN_BRIGHTNESS_LIGHT = 3; public static final int SCREEN_BRIGHTNESS_BRIGHT = 4; public static final int NUM_SCREEN_BRIGHTNESS_BINS = 5; public static final int DATA_CONNECTION_NONE = 0; public static final int DATA_CONNECTION_GPRS = 1; public static final int DATA_CONNECTION_EDGE = 2; public static final int DATA_CONNECTION_UMTS = 3; public static final int DATA_CONNECTION_CDMA = 4; public static final int DATA_CONNECTION_EVDO_0 = 5; public static final int DATA_CONNECTION_EVDO_A = 6; public static final int DATA_CONNECTION_1xRTT = 7; public static final int DATA_CONNECTION_HSDPA = 8; public static final int DATA_CONNECTION_HSUPA = 9; public static final int DATA_CONNECTION_HSPA = 10; public static final int DATA_CONNECTION_IDEN = 11; public static final int DATA_CONNECTION_EVDO_B = 12; public static final int DATA_CONNECTION_LTE = 13; public static final int DATA_CONNECTION_EHRPD = 14; public static final int DATA_CONNECTION_OTHER = 15; public static final int NUM_DATA_CONNECTION_TYPES = 16; public static final BatteryStats.BitDescription [] HISTORY_STATE_DESCRIPTIONS = null; // Constructors public BatteryStats(){ } // Methods public final void dumpLocked(java.io.PrintWriter arg1, java.lang.String arg2, int arg3, int arg4){ } public void dumpLocked(java.io.PrintWriter arg1){ } public final void dumpCheckinLocked(java.io.PrintWriter arg1, int arg2, int arg3){ } public void dumpCheckinLocked(java.io.PrintWriter arg1, java.lang.String [] arg2, java.util.List<android.content.pm.ApplicationInfo> arg3){ } public abstract boolean startIteratingHistoryLocked(); public abstract boolean getNextHistoryLocked(BatteryStats.HistoryItem arg1); public abstract void finishIteratingHistoryLocked(); public abstract boolean startIteratingOldHistoryLocked(); public abstract boolean getNextOldHistoryLocked(BatteryStats.HistoryItem arg1); public abstract void finishIteratingOldHistoryLocked(); public abstract long getHistoryBaseTime(); public abstract int getStartCount(); public abstract long getScreenOnTime(long arg1, int arg2); public abstract long getScreenBrightnessTime(int arg1, long arg2, int arg3); public abstract int getInputEventCount(int arg1); public abstract long getPhoneOnTime(long arg1, int arg2); public abstract long getPhoneSignalStrengthTime(int arg1, long arg2, int arg3); public abstract long getPhoneSignalScanningTime(long arg1, int arg2); public abstract int getPhoneSignalStrengthCount(int arg1, int arg2); public abstract long getPhoneDataConnectionTime(int arg1, long arg2, int arg3); public abstract int getPhoneDataConnectionCount(int arg1, int arg2); public abstract long getWifiOnTime(long arg1, int arg2); public abstract long getGlobalWifiRunningTime(long arg1, int arg2); public abstract long getBluetoothOnTime(long arg1, int arg2); public abstract boolean getIsOnBattery(); public abstract android.util.SparseArray<? extends BatteryStats.Uid> getUidStats(); public abstract long getBatteryUptime(long arg1); public long getRadioDataUptimeMs(){ return 0l; } public abstract long getRadioDataUptime(); public abstract long getBatteryRealtime(long arg1); public abstract int getDischargeStartLevel(); public abstract int getDischargeCurrentLevel(); public abstract int getLowDischargeAmountSinceCharge(); public abstract int getHighDischargeAmountSinceCharge(); public abstract int getDischargeAmountScreenOn(); public abstract int getDischargeAmountScreenOnSinceCharge(); public abstract int getDischargeAmountScreenOff(); public abstract int getDischargeAmountScreenOffSinceCharge(); public abstract long computeBatteryUptime(long arg1, int arg2); public abstract long computeBatteryRealtime(long arg1, int arg2); public abstract long computeUptime(long arg1, int arg2); public abstract long computeRealtime(long arg1, int arg2); public abstract java.util.Map<java.lang.String, ? extends BatteryStats.Timer> getKernelWakelockStats(); public abstract int getCpuSpeedSteps(); public void prepareForDumpLocked(){ } }
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aurora.scheduler.http; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; import javax.servlet.http.HttpServletRequest; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.net.HostAndPort; import org.apache.aurora.common.testing.easymock.EasyMockTest; import org.apache.aurora.common.thrift.Endpoint; import org.apache.aurora.common.thrift.ServiceInstance; import org.apache.aurora.scheduler.app.ServiceGroupMonitor; import org.apache.aurora.scheduler.app.ServiceGroupMonitor.MonitorException; import org.junit.Before; import org.junit.Test; import static org.apache.aurora.scheduler.http.LeaderRedirect.LeaderStatus; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.junit.Assert.assertEquals; public class LeaderRedirectTest extends EasyMockTest { private static final int HTTP_PORT = 500; private static final Function<HostAndPort, ServiceInstance> CREATE_INSTANCE = endpoint -> new ServiceInstance() .setServiceEndpoint(new Endpoint(endpoint.getHostText(), endpoint.getPort())); private AtomicReference<ImmutableSet<ServiceInstance>> schedulers; private ServiceGroupMonitor serviceGroupMonitor; private LeaderRedirect leaderRedirector; @Before public void setUp() throws MonitorException { schedulers = new AtomicReference<>(ImmutableSet.of()); serviceGroupMonitor = createMock(ServiceGroupMonitor.class); HttpService http = createMock(HttpService.class); expect(http.getAddress()).andStubReturn(HostAndPort.fromParts("localhost", HTTP_PORT)); leaderRedirector = new LeaderRedirect(http, serviceGroupMonitor); } private void replayAndMonitor(int expectedGetCalls) throws Exception { serviceGroupMonitor.start(); expectLastCall(); expect(serviceGroupMonitor.get()).andAnswer(() -> schedulers.get()).times(expectedGetCalls); control.replay(); leaderRedirector.monitor(); } @Test public void testLeader() throws Exception { replayAndMonitor(3); publishSchedulers(localPort(HTTP_PORT)); assertEquals(Optional.absent(), leaderRedirector.getRedirect()); // NB: LEADING takes 2 tests of the server group membership to calculate; thus we expect 3 // server group get calls, 1 for the getRedirect() above and 2 here. assertEquals(LeaderStatus.LEADING, leaderRedirector.getLeaderStatus()); } @Test public void testNotLeader() throws Exception { replayAndMonitor(3); HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT); publishSchedulers(remote); assertEquals(Optional.of(remote), leaderRedirector.getRedirect()); // NB: NOT_LEADING takes 2 tests of the server group membership to calculate; thus we expect 3 // server group get calls, 1 for the getRedirect() above and 2 here. assertEquals(LeaderStatus.NOT_LEADING, leaderRedirector.getLeaderStatus()); } @Test public void testLeaderOnSameHost() throws Exception { replayAndMonitor(3); HostAndPort local = localPort(555); publishSchedulers(local); assertEquals(Optional.of(local), leaderRedirector.getRedirect()); // NB: NOT_LEADING takes 2 tests of the server group membership to calculate; thus we expect 3 // server group get calls, 1 for the getRedirect() above and 2 here. assertEquals(LeaderStatus.NOT_LEADING, leaderRedirector.getLeaderStatus()); } @Test public void testNoLeaders() throws Exception { replayAndMonitor(2); assertEquals(Optional.absent(), leaderRedirector.getRedirect()); assertEquals(LeaderStatus.NO_LEADER, leaderRedirector.getLeaderStatus()); } @Test public void testMultipleLeaders() throws Exception { replayAndMonitor(2); publishSchedulers(HostAndPort.fromParts("foobar", 500), HostAndPort.fromParts("baz", 800)); assertEquals(Optional.absent(), leaderRedirector.getRedirect()); assertEquals(LeaderStatus.NO_LEADER, leaderRedirector.getLeaderStatus()); } @Test public void testBadServiceInstance() throws Exception { replayAndMonitor(2); publishSchedulers(ImmutableSet.of(new ServiceInstance())); assertEquals(Optional.absent(), leaderRedirector.getRedirect()); assertEquals(LeaderStatus.NO_LEADER, leaderRedirector.getLeaderStatus()); } private HttpServletRequest mockRequest(String attributeValue, String queryString) { HttpServletRequest mockRequest = createMock(HttpServletRequest.class); expect(mockRequest.getScheme()).andReturn("http"); expect(mockRequest.getAttribute(JettyServerModule.ORIGINAL_PATH_ATTRIBUTE_NAME)) .andReturn(attributeValue); expect(mockRequest.getRequestURI()).andReturn("/some/path"); expect(mockRequest.getQueryString()).andReturn(queryString); return mockRequest; } @Test public void testRedirectTargetNoAttribute() throws Exception { HttpServletRequest mockRequest = mockRequest(null, null); replayAndMonitor(1); HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT); publishSchedulers(remote); assertEquals( Optional.of("http://foobar:500/some/path"), leaderRedirector.getRedirectTarget(mockRequest)); } @Test public void testRedirectTargetWithAttribute() throws Exception { HttpServletRequest mockRequest = mockRequest("/the/original/path", null); replayAndMonitor(1); HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT); publishSchedulers(remote); assertEquals( Optional.of("http://foobar:500/the/original/path"), leaderRedirector.getRedirectTarget(mockRequest)); } @Test public void testRedirectTargetQueryString() throws Exception { HttpServletRequest mockRequest = mockRequest(null, "bar=baz"); replayAndMonitor(1); HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT); publishSchedulers(remote); assertEquals( Optional.of("http://foobar:500/some/path?bar=baz"), leaderRedirector.getRedirectTarget(mockRequest)); } private void publishSchedulers(HostAndPort... schedulerHttpEndpoints) { publishSchedulers(ImmutableSet.copyOf(Iterables.transform(Arrays.asList(schedulerHttpEndpoints), CREATE_INSTANCE))); } private void publishSchedulers(ImmutableSet<ServiceInstance> instances) { schedulers.set(instances); } private static HostAndPort localPort(int port) { return HostAndPort.fromParts("localhost", port); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ambari.server.state; import java.io.File; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlTransient; import org.apache.ambari.server.api.services.AmbariMetaInfo; import org.apache.ambari.server.stack.Validable; import org.apache.ambari.server.state.stack.MetricDefinition; import org.apache.ambari.server.state.stack.StackRoleCommandOrder; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.annotate.JsonFilter; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; @XmlAccessorType(XmlAccessType.FIELD) @JsonFilter("propertiesfilter") public class ServiceInfo implements Validable{ public static final AbstractMap.SimpleEntry<String, String> DEFAULT_SERVICE_INSTALLABLE_PROPERTY = new AbstractMap.SimpleEntry<>("installable", "true"); public static final AbstractMap.SimpleEntry<String, String> DEFAULT_SERVICE_MANAGED_PROPERTY = new AbstractMap.SimpleEntry<>("managed", "true"); public static final AbstractMap.SimpleEntry<String, String> DEFAULT_SERVICE_MONITORED_PROPERTY = new AbstractMap.SimpleEntry<>("monitored", "true"); /** * Format version. Added at schema ver 2 */ @XmlTransient private String schemaVersion; private String name; private String displayName; private String version; private String comment; private String serviceType; private Selection selection; /** * Default to Python if not specified. */ @XmlEnum public enum ServiceAdvisorType { @XmlEnumValue("PYTHON") PYTHON, @XmlEnumValue("JAVA") JAVA } @XmlElement(name="service_advisor_type") private ServiceAdvisorType serviceAdvisorType = null; @XmlTransient private List<PropertyInfo> properties; @XmlElementWrapper(name="components") @XmlElements(@XmlElement(name="component")) private List<ComponentInfo> components; @XmlElement(name="deleted") private boolean isDeleted = false; @XmlElement(name="supportDeleteViaUI") private Boolean supportDeleteViaUIField; private boolean supportDeleteViaUIInternal = true; @JsonIgnore @XmlTransient private volatile Map<String, Set<String>> configLayout = null; @XmlElementWrapper(name="configuration-dependencies") @XmlElement(name="config-type") private List<String> configDependencies; @XmlElementWrapper(name="excluded-config-types") @XmlElement(name="config-type") private Set<String> excludedConfigTypes = new HashSet<>(); @XmlTransient private Map<String, Map<String, Map<String, String>>> configTypes; @JsonIgnore private Boolean monitoringService; @JsonIgnore @XmlElement(name = "restartRequiredAfterChange") private Boolean restartRequiredAfterChange; @JsonIgnore @XmlElement(name = "restartRequiredAfterRackChange") private Boolean restartRequiredAfterRackChange; @XmlElement(name = "extends") private String parent; @XmlElement(name = "widgetsFileName") private String widgetsFileName = AmbariMetaInfo.WIDGETS_DESCRIPTOR_FILE_NAME; @XmlElement(name = "metricsFileName") private String metricsFileName = AmbariMetaInfo.SERVICE_METRIC_FILE_NAME; @XmlTransient private volatile Map<String, PropertyInfo> requiredProperties; /** * Credential store information */ @XmlElements(@XmlElement(name = "credential-store")) private CredentialStoreInfo credentialStoreInfo; public Boolean isRestartRequiredAfterChange() { return restartRequiredAfterChange; } public void setRestartRequiredAfterChange(Boolean restartRequiredAfterChange) { this.restartRequiredAfterChange = restartRequiredAfterChange; } @XmlTransient private File metricsFile = null; @XmlTransient private Map<String, Map<String, List<MetricDefinition>>> metrics = null; @XmlTransient private File advisorFile = null; @XmlTransient private String advisorName = null; @XmlTransient private File alertsFile = null; @XmlTransient private File kerberosDescriptorFile = null; @XmlTransient private File widgetsDescriptorFile = null; private StackRoleCommandOrder roleCommandOrder; @XmlTransient private boolean valid = true; @XmlElementWrapper(name = "properties") @XmlElement(name="property") private List<ServicePropertyInfo> servicePropertyList = Lists.newArrayList(); @XmlTransient private Map<String, String> servicePropertyMap = ImmutableMap.copyOf(ensureMandatoryServiceProperties(Maps.newHashMap())); /** * * @return valid xml flag */ @Override public boolean isValid() { return valid; } /** * * @param valid set validity flag */ @Override public void setValid(boolean valid) { this.valid = valid; } @XmlTransient private Set<String> errorSet = new HashSet<>(); @Override public void addError(String error) { errorSet.add(error); } @Override public Collection<String> getErrors() { return errorSet; } @Override public void addErrors(Collection<String> errors) { this.errorSet.addAll(errors); } /** * Internal list of os-specific details (loaded from xml). Added at schema ver 2 */ @JsonIgnore @XmlElementWrapper(name="osSpecifics") @XmlElements(@XmlElement(name="osSpecific")) private List<ServiceOsSpecific> serviceOsSpecifics; @JsonIgnore @XmlElement(name="configuration-dir") private String configDir = AmbariMetaInfo.SERVICE_CONFIG_FOLDER_NAME; @JsonIgnore @XmlElement(name = "themes-dir") private String themesDir = AmbariMetaInfo.SERVICE_THEMES_FOLDER_NAME; @JsonIgnore @XmlElementWrapper(name = "themes") @XmlElements(@XmlElement(name = "theme")) private List<ThemeInfo> themes; @XmlTransient private volatile Map<String, ThemeInfo> themesMap; @JsonIgnore @XmlElement(name = "quickLinksConfigurations-dir") private String quickLinksConfigurationsDir = AmbariMetaInfo.SERVICE_QUICKLINKS_CONFIGURATIONS_FOLDER_NAME; @JsonIgnore @XmlElementWrapper(name = "quickLinksConfigurations") @XmlElements(@XmlElement(name = "quickLinksConfiguration")) private List<QuickLinksConfigurationInfo> quickLinksConfigurations; @XmlTransient private volatile Map<String, QuickLinksConfigurationInfo> quickLinksConfigurationsMap; /** * Map of of os-specific details that is exposed (and initialised from list) * at getter. * Added at schema ver 2 */ private volatile Map<String, ServiceOsSpecific> serviceOsSpecificsMap; /** * This is used to add service check actions for services. * Added at schema ver 2 */ private CommandScriptDefinition commandScript; /** * Added at schema ver 2 */ @XmlElementWrapper(name="customCommands") @XmlElements(@XmlElement(name="customCommand")) private List<CustomCommandDefinition> customCommands; @XmlElementWrapper(name="requiredServices") @XmlElement(name="service") private List<String> requiredServices = new ArrayList<>(); /** * Meaning: stores subpath from stack root to exact directory, that contains * service scripts and templates. Since schema ver 2, * we may have multiple service metadata inside folder. * Added at schema ver 2 */ @XmlTransient private String servicePackageFolder; /** * Stores the path to the upgrades folder which contains the upgrade xmls for the given service. */ @XmlTransient private File serviceUpgradesFolder; /** * Stores the path to the checks folder which contains prereq check jars for the given service. */ @XmlTransient private File checksFolder; public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean deleted) { isDeleted = deleted; } public Boolean getSupportDeleteViaUIField(){ return supportDeleteViaUIField; } public void setSupportDeleteViaUIField(Boolean supportDeleteViaUIField) { this.supportDeleteViaUIField = supportDeleteViaUIField; } public boolean isSupportDeleteViaUI() { if (null != supportDeleteViaUIField) { return supportDeleteViaUIField.booleanValue(); } // If set to null and has a parent, then the value would have already been resolved and set. // Otherwise, return the default value (true). return this.supportDeleteViaUIInternal; } public void setSupportDeleteViaUI(boolean supportDeleteViaUI){ this.supportDeleteViaUIInternal = supportDeleteViaUI; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public void setServiceAdvisorType(ServiceAdvisorType type) { this.serviceAdvisorType = type; } public ServiceAdvisorType getServiceAdvisorType() { return serviceAdvisorType; } public String getServiceType() { return serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public Selection getSelection() { if (selection == null) { return Selection.DEFAULT; } return selection; } public void setSelection(Selection selection) { this.selection = selection; } /** * Check if selection was presented in xml. We need this for proper stack inheritance, because {@link ServiceInfo#getSelection} * by default returns {@link Selection#DEFAULT}, even if no value found in metainfo.xml. * @return true, if selection not defined in metainfo.xml */ public boolean isSelectionEmpty() { return selection == null; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public List<String> getRequiredServices() { return requiredServices; } public String getWidgetsFileName() { return widgetsFileName; } public void setWidgetsFileName(String widgetsFileName) { this.widgetsFileName = widgetsFileName; } public String getMetricsFileName() { return metricsFileName; } public void setMetricsFileName(String metricsFileName) { this.metricsFileName = metricsFileName; } public void setRequiredServices(List<String> requiredServices) { this.requiredServices = requiredServices; } public List<PropertyInfo> getProperties() { if (properties == null) properties = new ArrayList<>(); return properties; } public void setProperties(List properties) { this.properties = properties; } public List<ComponentInfo> getComponents() { if (components == null) components = new ArrayList<>(); return components; } /** * Finds ComponentInfo by component name * @param componentName name of the component * @return ComponentInfo componentName or null */ public ComponentInfo getComponentByName(String componentName){ for(ComponentInfo componentInfo : getComponents()) { if(componentInfo.getName().equals(componentName)){ return componentInfo; } } return null; } public boolean isClientOnlyService() { if (components == null || components.isEmpty()) { return false; } for (ComponentInfo compInfo : components) { if (!compInfo.isClient()) { return false; } } return true; } public ComponentInfo getClientComponent() { ComponentInfo client = null; if (components != null) { for (ComponentInfo compInfo : components) { if (compInfo.isClient()) { client = compInfo; break; } } } return client; } public File getAdvisorFile() { return advisorFile; } public void setAdvisorFile(File advisorFile) { this.advisorFile = advisorFile; } public String getAdvisorName() { return advisorName; } public void setAdvisorName(String advisorName) { this.advisorName = advisorName; } /** * Indicates if this service supports credential store. * False, it was not specified. * * @return true or false */ public boolean isCredentialStoreSupported() { if (credentialStoreInfo != null) { if (credentialStoreInfo.isSupported() != null) { return credentialStoreInfo.isSupported(); } } return false; } /** * Set a value indicating if this service supports credential store. * @param credentialStoreSupported */ public void setCredentialStoreSupported(boolean credentialStoreSupported) { if (credentialStoreInfo == null) { credentialStoreInfo = new CredentialStoreInfo(); } credentialStoreInfo.setSupported(credentialStoreSupported); } /** * Indicates if this service is requires credential store. * False if it was not specified. * * @return true or false */ public boolean isCredentialStoreRequired() { if (credentialStoreInfo != null) { if (credentialStoreInfo.isRequired() != null) { return credentialStoreInfo.isRequired(); } } return false; } /** * Set a value indicating if this service requires credential store. * @param credentialStoreRequired */ public void setCredentialStoreRequired(boolean credentialStoreRequired) { if (credentialStoreInfo == null) { credentialStoreInfo = new CredentialStoreInfo(); } credentialStoreInfo.setRequired(credentialStoreRequired); } /** * Indicates if this service is enabled for credential store use. * False if it was not specified. * * @return true or false */ public boolean isCredentialStoreEnabled() { if (credentialStoreInfo != null) { if (credentialStoreInfo.isEnabled() != null) { return credentialStoreInfo.isEnabled(); } } return false; } /** * Set a value indicating if this service is enabled for credential store use. * @param credentialStoreEnabled */ public void setCredentialStoreEnabled(boolean credentialStoreEnabled) { if (credentialStoreInfo == null) { credentialStoreInfo = new CredentialStoreInfo(); } credentialStoreInfo.setEnabled(credentialStoreEnabled); } /** * Get the credential store information object. * * @return */ public CredentialStoreInfo getCredentialStoreInfo() { return credentialStoreInfo; } /** * Set a new value for the credential store information. * * @param credentialStoreInfo */ public void setCredentialStoreInfo(CredentialStoreInfo credentialStoreInfo) { this.credentialStoreInfo = credentialStoreInfo; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Service name:"); sb.append(name); sb.append("\nService type:"); sb.append(serviceType); sb.append("\nversion:"); sb.append(version); sb.append("\ncomment:"); sb.append(comment); //for (PropertyInfo property : getProperties()) { // sb.append("\tProperty name=" + property.getName() + //"\nproperty value=" + property.getValue() + "\ndescription=" + property.getDescription()); //} for (ComponentInfo component : getComponents()) { sb.append("\n\n\nComponent:\n"); sb.append("name="); sb.append(component.getName()); sb.append("\tcategory="); sb.append(component.getCategory()); } return sb.toString(); } /** * Obtain the config types associated with this service. * The returned map is an unmodifiable view. * @return unmodifiable map of config types associated with this service */ public synchronized Map<String, Map<String, Map<String, String>>> getConfigTypeAttributes() { Map<String, Map<String, Map<String, String>>> tmpConfigTypes = configTypes == null ? new HashMap<>() : configTypes; for(String excludedtype : excludedConfigTypes){ tmpConfigTypes.remove(excludedtype); } return Collections.unmodifiableMap(tmpConfigTypes); } /** * Add the given type and set it's attributes. * If the type is marked for exclusion, it will not be added. * * @param type configuration type * @param typeAttributes attributes associated with the type */ public synchronized void setTypeAttributes(String type, Map<String, Map<String, String>> typeAttributes) { if (this.configTypes == null) { configTypes = new HashMap<>(); } configTypes.put(type, typeAttributes); } /** * Set all types and associated attributes. Any previously existing types and * attributes are removed prior to setting the new values. * * @param types map of type attributes */ public synchronized void setAllConfigAttributes(Map<String, Map<String, Map<String, String>>> types) { configTypes = new HashMap<>(); for (Map.Entry<String, Map<String, Map<String, String>>> entry : types.entrySet()) { setTypeAttributes(entry.getKey(), entry.getValue()); } } /** * Determine of the service has a dependency on the provided configuration type. * @param type the config type * @return <code>true</code> if the service defines a dependency on the provided type */ public boolean hasConfigDependency(String type) { return configDependencies != null && configDependencies.contains(type); } /** * Determine if the service contains the specified config type * @param type config type to check * @return true if the service has the specified config type; false otherwise */ public boolean hasConfigType(String type) { return configTypes != null && configTypes.containsKey(type) && !excludedConfigTypes.contains(type); } /** * Determine if the service has a dependency on the provided type and contains any of the provided properties. * This can be used in determining if a property is stale. * @param type the config type * @param keyNames the names of all the config keys for the given type * @return <code>true</code> if the config is stale */ public boolean hasDependencyAndPropertyFor(String type, Collection<String> keyNames) { if (!hasConfigDependency(type)) return false; buildConfigLayout(); Set<String> keys = configLayout.get(type); for (String staleCheck : keyNames) { if (keys != null && keys.contains(staleCheck)) return true; } return false; } /** * Builds the config map specific to this service. */ private void buildConfigLayout() { if (null == configLayout) { synchronized(this) { if (null == configLayout) { configLayout = new HashMap<>(); for (PropertyInfo pi : getProperties()) { String type = pi.getFilename(); int idx = type.indexOf(".xml"); type = type.substring(0, idx); if (!configLayout.containsKey(type)) configLayout.put(type, new HashSet<>()); configLayout.get(type).add(pi.getName()); } } } } } public List<String> getConfigDependencies() { return configDependencies; } public List<String> getConfigDependenciesWithComponents(){ List<String> retVal = new ArrayList<>(); if(configDependencies != null){ retVal.addAll(configDependencies); } if(components != null){ for (ComponentInfo c : components) { if(c.getConfigDependencies() != null){ retVal.addAll(c.getConfigDependencies()); } } } return retVal.size() == 0 ? (configDependencies == null ? null : configDependencies) : retVal; } public void setConfigDependencies(List<String> configDependencies) { this.configDependencies = configDependencies; } public String getSchemaVersion() { if (schemaVersion == null) { return AmbariMetaInfo.SCHEMA_VERSION_2; } else { return schemaVersion; } } public void setSchemaVersion(String schemaVersion) { this.schemaVersion = schemaVersion; } public String getServicePackageFolder() { return servicePackageFolder; } public void setServicePackageFolder(String servicePackageFolder) { this.servicePackageFolder = servicePackageFolder; } public File getServiceUpgradesFolder() { return serviceUpgradesFolder; } public void setServiceUpgradesFolder(File serviceUpgradesFolder) { this.serviceUpgradesFolder = serviceUpgradesFolder; } public File getChecksFolder() { return checksFolder; } public void setChecksFolder(File checksFolder) { this.checksFolder = checksFolder; } /** * Exposes (and initializes on first use) map of os-specific details. * @return map of OS specific details keyed by family */ public Map<String, ServiceOsSpecific> getOsSpecifics() { if (serviceOsSpecificsMap == null) { synchronized (this) { // Double-checked locking pattern if (serviceOsSpecificsMap == null) { Map<String, ServiceOsSpecific> tmpMap = new TreeMap<>(); if (serviceOsSpecifics != null) { for (ServiceOsSpecific osSpecific : serviceOsSpecifics) { tmpMap.put(osSpecific.getOsFamily(), osSpecific); } } serviceOsSpecificsMap = tmpMap; } } } return serviceOsSpecificsMap; } public void setOsSpecifics(Map<String, ServiceOsSpecific> serviceOsSpecificsMap) { this.serviceOsSpecificsMap = serviceOsSpecificsMap; } public List<CustomCommandDefinition> getCustomCommands() { if (customCommands == null) { customCommands = new ArrayList<>(); } return customCommands; } public void setCustomCommands(List<CustomCommandDefinition> customCommands) { this.customCommands = customCommands; } public CommandScriptDefinition getCommandScript() { return commandScript; } public void setCommandScript(CommandScriptDefinition commandScript) { this.commandScript = commandScript; } /** * @param file the file containing the metrics definitions */ public void setMetricsFile(File file) { metricsFile = file; } /** * @return the metrics file, or <code>null</code> if none exists */ public File getMetricsFile() { return metricsFile; } /** * @return the metrics defined for this service */ public Map<String, Map<String, List<MetricDefinition>>> getMetrics() { return metrics; } /** * @param map the metrics for this service */ public void setMetrics(Map<String, Map<String, List<MetricDefinition>>> map) { metrics = map; } /** * @return the configuration directory name */ public String getConfigDir() { return configDir; } /** * @return whether the service is a monitoring service */ public Boolean isMonitoringService() { return monitoringService; } /** * @param monitoringService whether the service is a monitoring service */ public void setMonitoringService(Boolean monitoringService) { this.monitoringService = monitoringService; } /** * @param file the file containing the alert definitions */ public void setAlertsFile(File file) { alertsFile = file; } /** * @return the alerts file, or <code>null</code> if none exists */ public File getAlertsFile() { return alertsFile; } /** * @param file the file containing the alert definitions */ public void setKerberosDescriptorFile(File file) { kerberosDescriptorFile = file; } /** * @return the kerberos descriptor file, or <code>null</code> if none exists */ public File getKerberosDescriptorFile() { return kerberosDescriptorFile; } /** * @return the widgets descriptor file, or <code>null</code> if none exists */ public File getWidgetsDescriptorFile() { return widgetsDescriptorFile; } public void setWidgetsDescriptorFile(File widgetsDescriptorFile) { this.widgetsDescriptorFile = widgetsDescriptorFile; } public StackRoleCommandOrder getRoleCommandOrder() { return roleCommandOrder; } public void setRoleCommandOrder(StackRoleCommandOrder roleCommandOrder) { this.roleCommandOrder = roleCommandOrder; } /** * @return config types this service contains configuration for, but which are primarily related to another service */ public Set<String> getExcludedConfigTypes() { return excludedConfigTypes; } public void setExcludedConfigTypes(Set<String> excludedConfigTypes) { this.excludedConfigTypes = excludedConfigTypes; } //todo: ensure that required properties are never modified... public Map<String, PropertyInfo> getRequiredProperties() { Map<String, PropertyInfo> result = requiredProperties; if (result == null) { synchronized(this) { result = requiredProperties; if (result == null) { requiredProperties = result = new HashMap<>(); List<PropertyInfo> properties = getProperties(); for (PropertyInfo propertyInfo : properties) { if (propertyInfo.isRequireInput()) { result.put(propertyInfo.getName(), propertyInfo); } } } } } return result; } /** * Determine whether or not a restart is required for this service after a host rack info change. * * @return true if a restart is required */ public Boolean isRestartRequiredAfterRackChange() { return restartRequiredAfterRackChange; } /** * Set indicator for required restart after a host rack info change. * * @param restartRequiredAfterRackChange true if a restart is required */ public void setRestartRequiredAfterRackChange(Boolean restartRequiredAfterRackChange) { this.restartRequiredAfterRackChange = restartRequiredAfterRackChange; } public String getThemesDir() { return themesDir; } public void setThemesDir(String themesDir) { this.themesDir = themesDir; } public List<ThemeInfo> getThemes() { return themes; } public void setThemes(List<ThemeInfo> themes) { this.themes = themes; } public Map<String, ThemeInfo> getThemesMap() { if (themesMap == null) { Map<String, ThemeInfo> tmp = new TreeMap<>(); if (themes != null) { for (ThemeInfo theme : themes) { tmp.put(theme.getFileName(), theme); } } themesMap = tmp; } return themesMap; } public void setThemesMap(Map<String, ThemeInfo> themesMap) { this.themesMap = themesMap; } //Quick links configurations public String getQuickLinksConfigurationsDir() { return quickLinksConfigurationsDir; } public void setQuickLinksConfigurationsDir(String quickLinksConfigurationsDir) { this.quickLinksConfigurationsDir = quickLinksConfigurationsDir; } public List<QuickLinksConfigurationInfo> getQuickLinksConfigurations() { return quickLinksConfigurations; } public void setQuickLinksConfigurations(List<QuickLinksConfigurationInfo> quickLinksConfigurations) { this.quickLinksConfigurations = quickLinksConfigurations; } public Map<String, QuickLinksConfigurationInfo> getQuickLinksConfigurationsMap() { if (quickLinksConfigurationsMap == null) { Map<String, QuickLinksConfigurationInfo> tmp = new TreeMap<>(); if (quickLinksConfigurations != null) { for (QuickLinksConfigurationInfo quickLinksConfiguration : quickLinksConfigurations) { tmp.put(quickLinksConfiguration.getFileName(), quickLinksConfiguration); } } quickLinksConfigurationsMap = tmp; } return quickLinksConfigurationsMap; } public void setQuickLinksConfigurationsMap(Map<String, QuickLinksConfigurationInfo> quickLinksConfigurationsMap) { this.quickLinksConfigurationsMap = quickLinksConfigurationsMap; } public List<ServicePropertyInfo> getServicePropertyList() { return servicePropertyList; } public void setServicePropertyList(List<ServicePropertyInfo> servicePropertyList) { this.servicePropertyList = servicePropertyList; afterServicePropertyListSet(); } private void afterServicePropertyListSet(){ validateServiceProperties(); buildServiceProperties(); } /** * Returns the service properties defined in the xml service definition. * @return Service property map */ public Map<String, String> getServiceProperties() { return servicePropertyMap; } /** * Constructs the map that stores the service properties defined in the xml service definition. * The keys are the property names and values the property values. * It ensures that missing required service properties are added with default values. */ private void buildServiceProperties() { if (isValid()) { Map<String, String> properties = Maps.newHashMap(); for (ServicePropertyInfo property : getServicePropertyList()) { properties.put(property.getName(), property.getValue()); } servicePropertyMap = ImmutableMap.copyOf(ensureMandatoryServiceProperties(properties)); } else servicePropertyMap = ImmutableMap.of(); } private Map<String, String> ensureMandatoryServiceProperties(Map<String, String> properties) { return ensureVisibilityServiceProperties(properties); } private Map<String, String> ensureVisibilityServiceProperties(Map<String, String> properties) { if (!properties.containsKey(DEFAULT_SERVICE_INSTALLABLE_PROPERTY.getKey())) properties.put(DEFAULT_SERVICE_INSTALLABLE_PROPERTY.getKey(), DEFAULT_SERVICE_INSTALLABLE_PROPERTY.getValue()); if (!properties.containsKey(DEFAULT_SERVICE_MANAGED_PROPERTY.getKey())) properties.put(DEFAULT_SERVICE_MANAGED_PROPERTY.getKey(), DEFAULT_SERVICE_MANAGED_PROPERTY.getValue()); if (!properties.containsKey(DEFAULT_SERVICE_MONITORED_PROPERTY.getKey())) properties.put(DEFAULT_SERVICE_MONITORED_PROPERTY.getKey(), DEFAULT_SERVICE_MONITORED_PROPERTY.getValue()); return properties; } void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { afterServicePropertyListSet(); } private void validateServiceProperties() { // Verify if there are duplicate service properties by name Multimap<String, ServicePropertyInfo> servicePropsByName = Multimaps.index( getServicePropertyList(), new Function<ServicePropertyInfo, String>() { @Override public String apply(ServicePropertyInfo servicePropertyInfo) { return servicePropertyInfo.getName(); } } ); for (String propertyName: servicePropsByName.keySet()) { if (servicePropsByName.get(propertyName).size() > 1) { setValid(false); addError("Duplicate service property with name '" + propertyName + "' found in " + getName() + ":" + getVersion() + " service definition !"); } } for (ComponentInfo component : getComponents()) { int primaryLogs = 0; for (LogDefinition log : component.getLogs()) { primaryLogs += log.isPrimary() ? 1 : 0; } if (primaryLogs > 1) { setValid(false); addError("More than one primary log exists for the component " + component.getName()); } } // validate credential store information if (credentialStoreInfo != null) { // if both are specified, supported must be true if enabled is false or true. if (credentialStoreInfo.isSupported() != null && credentialStoreInfo.isEnabled() != null) { if (!credentialStoreInfo.isSupported() && credentialStoreInfo.isEnabled()) { setValid(false); addError("Credential store cannot be enabled for service " + getName() + " as it does not support it."); } } // Must be specified if (credentialStoreInfo.isSupported() == null) { setValid(false); addError("Credential store supported is not specified for service " + getName()); } // Must be specified if (credentialStoreInfo.isEnabled() == null) { setValid(false); addError("Credential store enabled is not specified for service " + getName()); } } } public enum Selection { DEFAULT, TECH_PREVIEW, MANDATORY, DEPRECATED } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.util.scopeChooser; import com.intellij.ide.DataManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.util.Condition; import com.intellij.packageDependencies.ChangeListsScopesProvider; import com.intellij.packageDependencies.DependencyValidationManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopesCore; import com.intellij.psi.search.PredefinedSearchScopeProvider; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.psi.search.scope.packageSet.NamedScopeManager; import com.intellij.psi.search.scope.packageSet.NamedScopesHolder; import com.intellij.ui.ComboboxSpeedSearch; import com.intellij.ui.ComboboxWithBrowseButton; import com.intellij.ui.ListCellRendererWrapper; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; public class ScopeChooserCombo extends ComboboxWithBrowseButton implements Disposable { private Project myProject; private boolean mySuggestSearchInLibs; private boolean myPrevSearchFiles; private NamedScopesHolder.ScopeListener myScopeListener; private NamedScopeManager myNamedScopeManager; private DependencyValidationManager myValidationManager; private boolean myCurrentSelection = true; private boolean myUsageView = true; private Condition<ScopeDescriptor> myScopeFilter; private boolean myShowEmptyScopes; private BrowseListener myBrowseListener = null; public ScopeChooserCombo() { super(new IgnoringComboBox(){ @Override protected boolean isIgnored(Object item) { return item instanceof ScopeSeparator; } }); } public ScopeChooserCombo(final Project project, boolean suggestSearchInLibs, boolean prevSearchWholeFiles, String preselect) { this(); init(project, suggestSearchInLibs, prevSearchWholeFiles, preselect); } public void init(final Project project, final String preselect){ init(project, false, true, preselect); } public void init(final Project project, final boolean suggestSearchInLibs, final boolean prevSearchWholeFiles, final String preselect) { init(project, suggestSearchInLibs, prevSearchWholeFiles, preselect, null); } public void init(final Project project, final boolean suggestSearchInLibs, final boolean prevSearchWholeFiles, final Object selection, @Nullable Condition<ScopeDescriptor> scopeFilter) { mySuggestSearchInLibs = suggestSearchInLibs; myPrevSearchFiles = prevSearchWholeFiles; myProject = project; myScopeListener = () -> { SearchScope selectedScope = getSelectedScope(); rebuildModel(); selectItem(selectedScope); }; myScopeFilter = scopeFilter; myNamedScopeManager = NamedScopeManager.getInstance(project); myNamedScopeManager.addScopeListener(myScopeListener); myValidationManager = DependencyValidationManager.getInstance(project); myValidationManager.addScopeListener(myScopeListener); addActionListener(createScopeChooserListener()); final ComboBox<ScopeDescriptor> combo = (ComboBox<ScopeDescriptor>)getComboBox(); combo.setMinimumAndPreferredWidth(JBUI.scale(300)); combo.setRenderer(new ScopeDescriptionWithDelimiterRenderer()); rebuildModel(); selectItem(selection); new ComboboxSpeedSearch(combo) { @Override protected String getElementText(Object element) { if (element instanceof ScopeDescriptor) { final ScopeDescriptor descriptor = (ScopeDescriptor)element; return descriptor.getDisplay(); } return null; } }; } public void setBrowseListener(BrowseListener browseListener) { myBrowseListener = browseListener; } public void setCurrentSelection(boolean currentSelection) { myCurrentSelection = currentSelection; } public void setUsageView(boolean usageView) { myUsageView = usageView; } @Override public void dispose() { super.dispose(); if (myValidationManager != null) { myValidationManager.removeScopeListener(myScopeListener); myValidationManager = null; } if (myNamedScopeManager != null) { myNamedScopeManager.removeScopeListener(myScopeListener); myNamedScopeManager = null; } myScopeListener = null; } private void selectItem(@Nullable Object selection) { if (selection == null) return; JComboBox combo = getComboBox(); DefaultComboBoxModel model = (DefaultComboBoxModel)combo.getModel(); for (int i = 0; i < model.getSize(); i++) { ScopeDescriptor descriptor = (ScopeDescriptor)model.getElementAt(i); if (selection instanceof String && selection.equals(descriptor.getDisplay()) || selection instanceof SearchScope && descriptor.scopeEquals((SearchScope)selection)) { combo.setSelectedIndex(i); break; } } } private ActionListener createScopeChooserListener() { return e -> { final String selection = getSelectedScopeName(); if (myBrowseListener != null) myBrowseListener.onBeforeBrowseStarted(); final EditScopesDialog dlg = EditScopesDialog.showDialog(myProject, selection); if (dlg.isOK()){ rebuildModel(); final NamedScope namedScope = dlg.getSelectedScope(); if (namedScope != null) { selectItem(namedScope.getName()); } } if (myBrowseListener != null) myBrowseListener.onAfterBrowseFinished(); }; } private void rebuildModel() { getComboBox().setModel(createModel()); } @NotNull private DefaultComboBoxModel<ScopeDescriptor> createModel() { final DefaultComboBoxModel<ScopeDescriptor> model = new DefaultComboBoxModel<>(); createPredefinedScopeDescriptors(model); final List<NamedScope> changeLists = ChangeListsScopesProvider.getInstance(myProject).getFilteredScopes(); if (!changeLists.isEmpty()) { model.addElement(new ScopeSeparator("VCS Scopes")); for (NamedScope changeListScope : changeLists) { final GlobalSearchScope scope = GlobalSearchScopesCore.filterScope(myProject, changeListScope); addScopeDescriptor(model, new ScopeDescriptor(scope)); } } final List<ScopeDescriptor> customScopes = new ArrayList<>(); final NamedScopesHolder[] holders = NamedScopesHolder.getAllNamedScopeHolders(myProject); for (NamedScopesHolder holder : holders) { final NamedScope[] scopes = holder.getEditableScopes(); // predefined scopes already included for (NamedScope scope : scopes) { final GlobalSearchScope searchScope = GlobalSearchScopesCore.filterScope(myProject, scope); customScopes.add(new ScopeDescriptor(searchScope)); } } if (!customScopes.isEmpty()) { model.addElement(new ScopeSeparator("Custom Scopes")); for (ScopeDescriptor scope : customScopes) { addScopeDescriptor(model, scope); } } return model; } @Override public Dimension getPreferredSize() { if (isPreferredSizeSet()) { return super.getPreferredSize(); } Dimension preferredSize = super.getPreferredSize(); return new Dimension(Math.min(400, preferredSize.width), preferredSize.height); } @Override public Dimension getMinimumSize() { if (isMinimumSizeSet()) { return super.getMinimumSize(); } Dimension minimumSize = super.getMinimumSize(); return new Dimension(Math.min(200, minimumSize.width), minimumSize.height); } private void createPredefinedScopeDescriptors(@NotNull DefaultComboBoxModel<ScopeDescriptor> model) { @SuppressWarnings("deprecation") final DataContext context = DataManager.getInstance().getDataContext(); for (SearchScope scope : PredefinedSearchScopeProvider.getInstance().getPredefinedScopes(myProject, context, mySuggestSearchInLibs, myPrevSearchFiles, myCurrentSelection, myUsageView, myShowEmptyScopes)) { addScopeDescriptor(model, new ScopeDescriptor(scope)); } for (ScopeDescriptorProvider provider : ScopeDescriptorProvider.EP_NAME.getExtensionList()) { for (ScopeDescriptor scopeDescriptor : provider.getScopeDescriptors(myProject)) { if(myScopeFilter == null || myScopeFilter.value(scopeDescriptor)) { model.addElement(scopeDescriptor); } } } } private void addScopeDescriptor(DefaultComboBoxModel<ScopeDescriptor> model, ScopeDescriptor scopeDescriptor) { if (myScopeFilter == null || myScopeFilter.value(scopeDescriptor)) { model.addElement(scopeDescriptor); } } public void setShowEmptyScopes(boolean showEmptyScopes) { myShowEmptyScopes = showEmptyScopes; } @Nullable public SearchScope getSelectedScope() { final JComboBox combo = getComboBox(); int idx = combo.getSelectedIndex(); return idx < 0 ? null : ((ScopeDescriptor)combo.getSelectedItem()).getScope(); } @Nullable public String getSelectedScopeName() { final JComboBox combo = getComboBox(); int idx = combo.getSelectedIndex(); return idx < 0 ? null : ((ScopeDescriptor)combo.getSelectedItem()).getDisplay(); } private static class ScopeSeparator extends ScopeDescriptor { private final String myText; ScopeSeparator(@NotNull String text) { super(null); myText = text; } @Override public String getDisplay() { return myText; } } private static class ScopeDescriptionWithDelimiterRenderer extends ListCellRendererWrapper<ScopeDescriptor> { @Override public void customize(JList list, ScopeDescriptor value, int index, boolean selected, boolean hasFocus) { if (value != null) { setIcon(value.getDisplayIcon()); setText(value.getDisplay()); } if (value instanceof ScopeSeparator) { setSeparator(); } } } public interface BrowseListener { void onBeforeBrowseStarted(); void onAfterBrowseFinished(); } }
/******************************************************************************* * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved. * * Licensed under the Apache License 2.0. * http://www.apache.org/licenses/LICENSE-2.0 ******************************************************************************/ package com.adobe.aem.importer.impl; import com.adobe.aem.importer.DocImporter; import com.adobe.aem.importer.xml.FilterXmlBuilder; import com.adobe.aem.importer.xml.RejectingEntityResolver; import com.day.cq.commons.jcr.JcrUtil; import net.sf.saxon.Configuration; import net.sf.saxon.jaxp.TransformerImpl; import net.sf.saxon.TransformerFactoryImpl; import net.sf.saxon.lib.UnparsedTextURIResolver; import org.apache.commons.io.IOUtils; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.commons.JcrUtils; import org.apache.jackrabbit.vault.fs.api.ImportMode; import org.apache.jackrabbit.vault.fs.config.ConfigurationException; import org.apache.jackrabbit.vault.fs.io.AccessControlHandling; import org.apache.jackrabbit.vault.fs.io.Importer; import org.apache.jackrabbit.vault.fs.io.JcrArchive; import org.apache.sling.jcr.api.SlingRepository; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URI; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; @Component @org.apache.felix.scr.annotations.Properties({ @Property(name = Constants.SERVICE_DESCRIPTION, value = "AEM Content Importer"), @Property(name = Constants.SERVICE_VENDOR, value = "Adobe")}) @Service(value = DocImporter.class) public class DocImporterImpl implements DocImporter { private static final Logger log = LoggerFactory.getLogger(DocImporterImpl.class); private Session session; private String xsltFilePath; private String masterFileName; private String graphicsFolderName; private String targetPath; private Node importRootNode; private Node sourceFolderNode; private Properties properties; @Reference private SlingRepository slingRepository; @Activate protected final void activate(final Map<String, String> properties) throws Exception {} @Deactivate protected final void deactivate(final Map<String, String> properties) {} private boolean initImport(String gitRepoJcrPath){ try { this.session = slingRepository.loginAdministrative(null); if (!this.session.nodeExists(gitRepoJcrPath)){ log.info("[docs-git-importer] Import root path " + gitRepoJcrPath + " not found!"); return false; } log.info("[docs-git-importer] Import root path: " + gitRepoJcrPath); this.importRootNode = this.session.getNode(gitRepoJcrPath); if (!this.importRootNode.hasNode(DocImporter.CONFIG_FILE_NAME)) { log.info("[docs-git-importer] Config file " + DocImporter.CONFIG_FILE_NAME + " not found!"); return false; } log.info("[docs-git-importer] Config file: " + DocImporter.CONFIG_FILE_NAME); this.properties = new Properties(); this.properties.loadFromXML(JcrUtils.readFile(this.importRootNode.getNode(DocImporter.CONFIG_FILE_NAME))); String sourceFolder = properties.getProperty(DocImporter.CONFIG_PARAM_SOURCE_FOLDER, DocImporter.DEFAULT_SOURCE_FOLDER); if (!this.importRootNode.hasNode(sourceFolder)) { log.info("[docs-git-importer] Source folder " + sourceFolder + " not found!"); return false; } log.info("[docs-git-importer] Source folder: " + sourceFolder); this.sourceFolderNode = importRootNode.getNode(sourceFolder); this.masterFileName = properties.getProperty(DocImporter.CONFIG_PARAM_MASTER_FILE, DocImporter.DEFAULT_MASTER_FILE); if (!this.sourceFolderNode.hasNode(this.masterFileName)){ log.info("[docs-git-importer] Master file " + this.masterFileName + " not found!"); return false; } log.info("[docs-git-importer] Master file: " + this.masterFileName); this.graphicsFolderName = properties.getProperty(DocImporter.CONFIG_PARAM_GRAPHICS_FOLDER, DocImporter.DEFAULT_GRAPHICS_FOLDER); log.info("[docs-git-importer] Graphics folder: " + this.graphicsFolderName); this.targetPath = properties.getProperty(DocImporter.CONFIG_PARAM_TARGET_PATH, DocImporter.DEFAULT_TARGET_PATH); log.info("[docs-git-importer] Target path: " + this.targetPath); String sourceFormat = this.properties.getProperty(DocImporter.CONFIG_PARAM_SOURCE_FORMAT, DocImporter.DEFAULT_SOURCE_FORMAT); log.info("[docs-git-importer] Source format: " + sourceFormat); if (sourceFormat.equalsIgnoreCase(DocImporter.SOURCE_FORMAT_DOCBOOK)) { this.xsltFilePath = DocImporter.DOCBOOK_XSLT_PATH; } else { this.xsltFilePath = DocImporter.DITA_XSLT_PATH; } // Remove any existing imported content log.info("[docs-git-importer] Checking for existing imported content at: " + targetPath); if (session.nodeExists(targetPath)) { session.getNode(targetPath).remove(); log.info("[docs-git-importer] Removed existing imported content at: " + targetPath); } } catch(RepositoryException e) { log.error("[docs-git-importer] ", e); } catch (IOException e) { log.error("[docs-git-importer] ", e); } return true; } public void doImport(String gitRepoJcrPath) { try { if (!initImport(gitRepoJcrPath)){ log.info("[docs-git-importer] initImport failed!"); return; } Node xsltNode = this.session.getNode(xsltFilePath); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new RejectingEntityResolver()); URIResolver uriResolver = new DocImporterURIResolver(xsltNode, this.sourceFolderNode, xmlReader); TransformerFactoryImpl transformerFactoryImpl = new TransformerFactoryImpl(); transformerFactoryImpl.setURIResolver(uriResolver); Transformer transformer = transformerFactoryImpl.newTransformer(new StreamSource(JcrUtils.readFile(xsltNode))); TransformerImpl transformerImpl = (TransformerImpl) transformer; transformerImpl.getUnderlyingController().setUnparsedTextURIResolver(new DocImporterUnparsedTextURIResolver(this.sourceFolderNode)); for (Entry<Object, Object> entry : properties.entrySet()) { transformer.setParameter(entry.getKey().toString(), entry.getValue()); log.info("[docs-git-importer] transformer.setParameter: " + entry.getKey().toString() + " = " + entry.getValue()); } transformer.setParameter("xsltFilePath", this.xsltFilePath); ByteArrayOutputStream output = new ByteArrayOutputStream(); transformer.transform(new SAXSource(xmlReader, new InputSource(JcrUtils.readFile(this.sourceFolderNode.getNode(masterFileName)))), new StreamResult(output)); InputStream result = new ByteArrayInputStream(output.toByteArray()); if (this.session.itemExists(DocImporter.CONTENT_PACKAGE_PATH)){ this.session.removeItem(DocImporter.CONTENT_PACKAGE_PATH); this.session.save(); } Node contentPackageNode = JcrUtils.getOrCreateByPath(DocImporter.CONTENT_PACKAGE_PATH, "nt:folder", "nt:folder", this.session, true); this.session.getWorkspace().copy(DocImporter.CONTENT_PACKAGE_TEMPLATE_PATH + "/META-INF", contentPackageNode.getPath() + "/META-INF"); Node vaultNode = contentPackageNode.getNode("META-INF/vault"); Node contentXMLNode = JcrUtil.createPath(contentPackageNode.getPath() + "/jcr_root" + this.targetPath, "nt:folder", "nt:folder", this.session, true); JcrUtils.putFile(contentXMLNode, ".content.xml", "application/xml", result); if (this.graphicsFolderName != null && this.sourceFolderNode.hasNode(this.graphicsFolderName)) { JcrUtil.copy(this.sourceFolderNode.getNode(graphicsFolderName), contentXMLNode, this.graphicsFolderName); } JcrUtils.putFile(vaultNode, "filter.xml", "application/xml", FilterXmlBuilder.fromRoot(this.targetPath + "/").toStream(this.graphicsFolderName)); JcrArchive archive = new JcrArchive(contentPackageNode, "/"); archive.open(true); Importer importer = new Importer(); importer.getOptions().setImportMode(ImportMode.REPLACE); importer.getOptions().setAccessControlHandling(AccessControlHandling.MERGE); importer.run(archive, contentPackageNode.getSession().getNode("/")); this.session.save(); log.info("[docs-git-importer] session saved."); } catch(RepositoryException e) { log.error("[docs-git-importer] ", e); } catch (TransformerException e) { log.error("[docs-git-importer] ", e); } catch (SAXException e){ log.error("[docs-git-importer] ", e); } catch (IOException e) { log.error("[docs-git-importer] ", e); } catch (ConfigurationException e){ log.error("[docs-git-importer] ", e); } } private class DocImporterURIResolver implements URIResolver { private Node xsltNode; private Node srcNode; private XMLReader xmlReader; public DocImporterURIResolver(Node xsltNode, Node srcNode, XMLReader xmlReader) { this.xsltNode = xsltNode; this.srcNode = srcNode; this.xmlReader = xmlReader; } public Source resolve(String href, String base) throws TransformerException { try { final Node node = (href.endsWith("xsl") ? this.xsltNode.getParent().getNode(href) : this.srcNode.getNode(href)); return new SAXSource(this.xmlReader, new InputSource(JcrUtils.readFile(node))); } catch (RepositoryException e) { throw new TransformerException("Cannot resolve " + href + " in either [parent of " + this.xsltNode + " or " + this.srcNode + "]"); } } } private class DocImporterUnparsedTextURIResolver implements UnparsedTextURIResolver { private Node srcNode; public DocImporterUnparsedTextURIResolver(Node srcNode) { this.srcNode = srcNode; } public Reader resolve(URI absoluteURI, String encoding, Configuration config) throws net.sf.saxon.trans.XPathException { String absolutePath = absoluteURI.getPath(); InputStreamReader isr; // Hardcoded hack, requires that HTML files are always in the html/ subdir of the src/ dir int pos = absolutePath.lastIndexOf("html/"); String relativePath = absolutePath.substring(pos); try { if(this.srcNode.hasNode(relativePath)) { isr = new InputStreamReader(JcrUtils.readFile(this.srcNode.getNode(relativePath))); } else { String message = "<html><body><h2>HTML file " + relativePath + " not found<h2></body></html>"; isr = new InputStreamReader(IOUtils.toInputStream(message, "UTF-8")); log.info("HTML file " + relativePath + " not found"); } return isr; } catch (RepositoryException e) { throw new net.sf.saxon.trans.XPathException("Oops...", e); } catch (IOException e) { throw new net.sf.saxon.trans.XPathException("Oops...", e); } } } }
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2011 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.mail.type; import com.google.common.base.Objects; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlType; import com.zimbra.common.soap.MailConstants; import com.zimbra.soap.base.EmailInfoInterface; import com.zimbra.soap.base.InviteInfoInterface; import com.zimbra.soap.base.MessageInfoInterface; import com.zimbra.soap.type.KeyValuePair; import com.zimbra.soap.json.jackson.annotate.ZimbraJsonAttribute; @XmlAccessorType(XmlAccessType.NONE) @XmlType(propOrder = { "fragment", "emails", "subject", "messageIdHeader", "inReplyTo", "invite", "headers", "contentElems" }) public class MessageInfo extends MessageCommon implements MessageInfoInterface { /** * @zm-api-field-tag msg-id * @zm-api-field-description Message ID */ @XmlAttribute(name=MailConstants.A_ID /* id */, required=false) private String id; /** * @zm-api-field-tag X-Zimbra-Calendar-Intended-For * @zm-api-field-description X-Zimbra-Calendar-Intended-For header */ @XmlAttribute(name=MailConstants.A_CAL_INTENDED_FOR /* cif */, required=false) private String calendarIntendedFor; /** * @zm-api-field-tag orig-id * @zm-api-field-description Message id of the message being replied to/forwarded (outbound messages only) */ @XmlAttribute(name=MailConstants.A_ORIG_ID /* origid */, required=false) private String origId; /** * @zm-api-field-tag reply-type * @zm-api-field-description Reply type - <b>r|w</b> */ @XmlAttribute(name=MailConstants.A_REPLY_TYPE /* rt */, required=false) private String draftReplyType; /** * @zm-api-field-tag identity-id * @zm-api-field-description If set, this specifies the identity being used to compose the message */ @XmlAttribute(name=MailConstants.A_IDENTITY_ID /* idnt */, required=false) private String identityId; /** * @zm-api-field-tag draft-acct-id * @zm-api-field-description Draft account ID */ @XmlAttribute(name=MailConstants.A_FOR_ACCOUNT /* forAcct */, required=false) private String draftAccountId; /** * @zm-api-field-tag auto-send-time * @zm-api-field-description Can optionally set this to specify the time at which the draft should be * automatically sent by the server */ @XmlAttribute(name=MailConstants.A_AUTO_SEND_TIME /* autoSendTime */, required=false) private Long draftAutoSendTime; /** * @zm-api-field-tag date-header * @zm-api-field-description Date header */ @XmlAttribute(name=MailConstants.A_SENT_DATE /* sd */, required=false) private Long sentDate; /** * @zm-api-field-tag resent-date * @zm-api-field-description Resent date */ @XmlAttribute(name=MailConstants.A_RESENT_DATE /* rd */, required=false) private Long resentDate; /** * @zm-api-field-tag part * @zm-api-field-description Part */ @XmlAttribute(name=MailConstants.A_PART /* part */, required=false) private String part; /** * @zm-api-field-tag msg-fragment * @zm-api-field-description First few bytes of the message (probably between 40 and 100 bytes) */ @ZimbraJsonAttribute @XmlElement(name=MailConstants.E_FRAG /* fr */, required=false) private String fragment; /** * @zm-api-field-description Email addresses */ @XmlElement(name=MailConstants.E_EMAIL /* e */, required=false) private List<EmailInfo> emails = Lists.newArrayList(); /** * @zm-api-field-tag msg-subject * @zm-api-field-description Subject */ @ZimbraJsonAttribute @XmlElement(name=MailConstants.E_SUBJECT /* su */, required=false) private String subject; /** * @zm-api-field-tag message-id * @zm-api-field-description Message ID */ @ZimbraJsonAttribute @XmlElement(name=MailConstants.E_MSG_ID_HDR /* mid */, required=false) private String messageIdHeader; /** * @zm-api-field-tag in-reply-to-msg-id * @zm-api-field-description Message-ID header for message being replied to */ @ZimbraJsonAttribute @XmlElement(name=MailConstants.E_IN_REPLY_TO /* irt */, required=false) private String inReplyTo; /** * @zm-api-field-description Parsed out iCalendar invite */ @XmlElement(name=MailConstants.E_INVITE /* inv */, required=false) private InviteInfo invite; /** * @zm-api-field-description Headers */ @XmlElement(name=MailConstants.A_HEADER /* header */, required=false) private List<KeyValuePair> headers = Lists.newArrayList(); /** * @zm-api-field-description Content elements */ @XmlElements({ @XmlElement(name=MailConstants.E_MIMEPART /* mp */, type=PartInfo.class), @XmlElement(name=MailConstants.E_SHARE_NOTIFICATION /* shr */, type=ShareNotification.class), @XmlElement(name=MailConstants.E_DL_SUBSCRIPTION_NOTIFICATION /* dlSubs */, type=DLSubscriptionNotification.class) }) private List<Object> contentElems = Lists.newArrayList(); public MessageInfo() { } public MessageInfo(String id) { this.id = id; } @Override public MessageInfoInterface createFromId(String id) { return new MessageInfo(id); } @Override public void setId(String id) { this.id = id; } @Override public void setCalendarIntendedFor(String calendarIntendedFor) { this.calendarIntendedFor = calendarIntendedFor; } @Override public void setOrigId(String origId) { this.origId = origId; } @Override public void setDraftReplyType(String draftReplyType) { this.draftReplyType = draftReplyType; } @Override public void setIdentityId(String identityId) { this.identityId = identityId; } @Override public void setDraftAccountId(String draftAccountId) { this.draftAccountId = draftAccountId; } @Override public void setDraftAutoSendTime(Long draftAutoSendTime) { this.draftAutoSendTime = draftAutoSendTime; } @Override public void setSentDate(Long sentDate) { this.sentDate = sentDate; } @Override public void setResentDate(Long resentDate) { this.resentDate = resentDate; } @Override public void setPart(String part) { this.part = part; } @Override public void setFragment(String fragment) { this.fragment = fragment; } public void setEmails(Iterable <EmailInfo> emails) { this.emails.clear(); if (emails != null) { Iterables.addAll(this.emails,emails); } } public void addEmail(EmailInfo email) { this.emails.add(email); } @Override public void setSubject(String subject) { this.subject = subject; } @Override public void setMessageIdHeader(String messageIdHeader) { this.messageIdHeader = messageIdHeader; } @Override public void setInReplyTo(String inReplyTo) { this.inReplyTo = inReplyTo; } public void setInvite(InviteInfo invite) { this.invite = invite; } @Override public void setHeaders(Iterable <KeyValuePair> headers) { this.headers.clear(); if (headers != null) { Iterables.addAll(this.headers,headers); } } @Override public void addHeader(KeyValuePair header) { this.headers.add(header); } @Override public void setContentElems(Iterable <Object> contentElems) { this.contentElems.clear(); if (contentElems != null) { Iterables.addAll(this.contentElems,contentElems); } } @Override public void addContentElem(Object contentElem) { this.contentElems.add(contentElem); } @Override public String getId() { return id; } @Override public String getCalendarIntendedFor() { return calendarIntendedFor; } @Override public String getOrigId() { return origId; } @Override public String getDraftReplyType() { return draftReplyType; } @Override public String getIdentityId() { return identityId; } @Override public String getDraftAccountId() { return draftAccountId; } @Override public Long getDraftAutoSendTime() { return draftAutoSendTime; } @Override public Long getSentDate() { return sentDate; } @Override public Long getResentDate() { return resentDate; } @Override public String getPart() { return part; } @Override public String getFragment() { return fragment; } public List<EmailInfo> getEmails() { return Collections.unmodifiableList(emails); } @Override public String getSubject() { return subject; } @Override public String getMessageIdHeader() { return messageIdHeader; } @Override public String getInReplyTo() { return inReplyTo; } public InviteInfo getInvite() { return invite; } @Override public List<KeyValuePair> getHeaders() { return Collections.unmodifiableList(headers); } @Override public List<Object> getContentElems() { return Collections.unmodifiableList(contentElems); } @Override public Objects.ToStringHelper addToStringInfo(Objects.ToStringHelper helper) { helper = super.addToStringInfo(helper); return helper .add("id", id) .add("calendarIntendedFor", calendarIntendedFor) .add("origId", origId) .add("draftReplyType", draftReplyType) .add("identityId", identityId) .add("draftAccountId", draftAccountId) .add("draftAutoSendTime", draftAutoSendTime) .add("sentDate", sentDate) .add("resentDate", resentDate) .add("part", part) .add("fragment", fragment) .add("emails", emails) .add("subject", subject) .add("messageIdHeader", messageIdHeader) .add("inReplyTo", inReplyTo) .add("invite", invite) .add("headers", headers) .add("contentElems", contentElems); } @Override public String toString() { return addToStringInfo(Objects.toStringHelper(this)).toString(); } @Override public void setEmailInterfaces(Iterable<EmailInfoInterface> emails) { setEmails(EmailInfo.fromInterfaces(emails)); } @Override public void addEmailInterface(EmailInfoInterface email) { addEmail((EmailInfo) email); } @Override public void setInviteInterface(InviteInfoInterface invite) { setInvite((InviteInfo) invite); } @Override public List<EmailInfoInterface> getEmailInterfaces() { return EmailInfo.toInterfaces(emails); } @Override public InviteInfoInterface getInvitInterfacee() { return invite; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.indices; import org.elasticsearch.action.admin.indices.rollover.Condition; import org.elasticsearch.action.admin.indices.rollover.MaxAgeCondition; import org.elasticsearch.action.admin.indices.rollover.MaxDocsCondition; import org.elasticsearch.action.admin.indices.rollover.MaxSizeCondition; import org.elasticsearch.action.resync.TransportResyncReplicationAction; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.engine.EngineFactory; import org.elasticsearch.index.mapper.BinaryFieldMapper; import org.elasticsearch.index.mapper.BooleanFieldMapper; import org.elasticsearch.index.mapper.CompletionFieldMapper; import org.elasticsearch.index.mapper.DateFieldMapper; import org.elasticsearch.index.mapper.FieldAliasMapper; import org.elasticsearch.index.mapper.FieldNamesFieldMapper; import org.elasticsearch.index.mapper.GeoPointFieldMapper; import org.elasticsearch.index.mapper.IdFieldMapper; import org.elasticsearch.index.mapper.IgnoredFieldMapper; import org.elasticsearch.index.mapper.IndexFieldMapper; import org.elasticsearch.index.mapper.IpFieldMapper; import org.elasticsearch.index.mapper.KeywordFieldMapper; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.index.mapper.NestedPathFieldMapper; import org.elasticsearch.index.mapper.NumberFieldMapper; import org.elasticsearch.index.mapper.ObjectMapper; import org.elasticsearch.index.mapper.RangeFieldMapper; import org.elasticsearch.index.mapper.RangeType; import org.elasticsearch.index.mapper.RoutingFieldMapper; import org.elasticsearch.index.mapper.SeqNoFieldMapper; import org.elasticsearch.index.mapper.SourceFieldMapper; import org.elasticsearch.index.mapper.TextFieldMapper; import org.elasticsearch.index.mapper.TypeFieldMapper; import org.elasticsearch.index.mapper.VersionFieldMapper; import org.elasticsearch.index.seqno.RetentionLeaseBackgroundSyncAction; import org.elasticsearch.index.seqno.RetentionLeaseSyncAction; import org.elasticsearch.index.seqno.RetentionLeaseSyncer; import org.elasticsearch.index.shard.PrimaryReplicaSyncer; import org.elasticsearch.indices.cluster.IndicesClusterStateService; import org.elasticsearch.indices.mapper.MapperRegistry; import org.elasticsearch.indices.store.IndicesStore; import org.elasticsearch.plugins.MapperPlugin; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; /** * Configures classes and services that are shared by indices on each node. */ public class IndicesModule extends AbstractModule { private final MapperRegistry mapperRegistry; public IndicesModule(List<MapperPlugin> mapperPlugins) { this.mapperRegistry = new MapperRegistry(getMappers(mapperPlugins), getMetadataMappers(mapperPlugins), getFieldFilter(mapperPlugins)); } public static List<NamedWriteableRegistry.Entry> getNamedWriteables() { return Arrays.asList( new NamedWriteableRegistry.Entry(Condition.class, MaxAgeCondition.NAME, MaxAgeCondition::new), new NamedWriteableRegistry.Entry(Condition.class, MaxDocsCondition.NAME, MaxDocsCondition::new), new NamedWriteableRegistry.Entry(Condition.class, MaxSizeCondition.NAME, MaxSizeCondition::new)); } public static List<NamedXContentRegistry.Entry> getNamedXContents() { return Arrays.asList( new NamedXContentRegistry.Entry(Condition.class, new ParseField(MaxAgeCondition.NAME), (p, c) -> MaxAgeCondition.fromXContent(p)), new NamedXContentRegistry.Entry(Condition.class, new ParseField(MaxDocsCondition.NAME), (p, c) -> MaxDocsCondition.fromXContent(p)), new NamedXContentRegistry.Entry(Condition.class, new ParseField(MaxSizeCondition.NAME), (p, c) -> MaxSizeCondition.fromXContent(p)) ); } public static Map<String, Mapper.TypeParser> getMappers(List<MapperPlugin> mapperPlugins) { Map<String, Mapper.TypeParser> mappers = new LinkedHashMap<>(); // builtin mappers for (NumberFieldMapper.NumberType type : NumberFieldMapper.NumberType.values()) { mappers.put(type.typeName(), new NumberFieldMapper.TypeParser(type)); } for (RangeType type : RangeType.values()) { mappers.put(type.typeName(), new RangeFieldMapper.TypeParser(type)); } mappers.put(BooleanFieldMapper.CONTENT_TYPE, new BooleanFieldMapper.TypeParser()); mappers.put(BinaryFieldMapper.CONTENT_TYPE, new BinaryFieldMapper.TypeParser()); DateFieldMapper.Resolution milliseconds = DateFieldMapper.Resolution.MILLISECONDS; mappers.put(milliseconds.type(), new DateFieldMapper.TypeParser(milliseconds)); DateFieldMapper.Resolution nanoseconds = DateFieldMapper.Resolution.NANOSECONDS; mappers.put(nanoseconds.type(), new DateFieldMapper.TypeParser(nanoseconds)); mappers.put(IpFieldMapper.CONTENT_TYPE, new IpFieldMapper.TypeParser()); mappers.put(TextFieldMapper.CONTENT_TYPE, new TextFieldMapper.TypeParser()); mappers.put(KeywordFieldMapper.CONTENT_TYPE, new KeywordFieldMapper.TypeParser()); mappers.put(ObjectMapper.CONTENT_TYPE, new ObjectMapper.TypeParser()); mappers.put(ObjectMapper.NESTED_CONTENT_TYPE, new ObjectMapper.TypeParser()); mappers.put(CompletionFieldMapper.CONTENT_TYPE, new CompletionFieldMapper.TypeParser()); mappers.put(FieldAliasMapper.CONTENT_TYPE, new FieldAliasMapper.TypeParser()); mappers.put(GeoPointFieldMapper.CONTENT_TYPE, new GeoPointFieldMapper.TypeParser()); for (MapperPlugin mapperPlugin : mapperPlugins) { for (Map.Entry<String, Mapper.TypeParser> entry : mapperPlugin.getMappers().entrySet()) { if (mappers.put(entry.getKey(), entry.getValue()) != null) { throw new IllegalArgumentException("Mapper [" + entry.getKey() + "] is already registered"); } } } return Collections.unmodifiableMap(mappers); } private static final Map<String, MetadataFieldMapper.TypeParser> builtInMetadataMappers = initBuiltInMetadataMappers(); private static Map<String, MetadataFieldMapper.TypeParser> initBuiltInMetadataMappers() { Map<String, MetadataFieldMapper.TypeParser> builtInMetadataMappers; // Use a LinkedHashMap for metadataMappers because iteration order matters builtInMetadataMappers = new LinkedHashMap<>(); // _ignored first so that we always load it, even if only _id is requested builtInMetadataMappers.put(IgnoredFieldMapper.NAME, new IgnoredFieldMapper.TypeParser()); // ID second so it will be the first (if no ignored fields) stored field to load // (so will benefit from "fields: []" early termination builtInMetadataMappers.put(IdFieldMapper.NAME, new IdFieldMapper.TypeParser()); builtInMetadataMappers.put(RoutingFieldMapper.NAME, new RoutingFieldMapper.TypeParser()); builtInMetadataMappers.put(IndexFieldMapper.NAME, new IndexFieldMapper.TypeParser()); builtInMetadataMappers.put(SourceFieldMapper.NAME, new SourceFieldMapper.TypeParser()); builtInMetadataMappers.put(TypeFieldMapper.NAME, new TypeFieldMapper.TypeParser()); builtInMetadataMappers.put(NestedPathFieldMapper.NAME, new NestedPathFieldMapper.TypeParser()); builtInMetadataMappers.put(VersionFieldMapper.NAME, new VersionFieldMapper.TypeParser()); builtInMetadataMappers.put(SeqNoFieldMapper.NAME, new SeqNoFieldMapper.TypeParser()); //_field_names must be added last so that it has a chance to see all the other mappers builtInMetadataMappers.put(FieldNamesFieldMapper.NAME, new FieldNamesFieldMapper.TypeParser()); return Collections.unmodifiableMap(builtInMetadataMappers); } public static Map<String, MetadataFieldMapper.TypeParser> getMetadataMappers(List<MapperPlugin> mapperPlugins) { Map<String, MetadataFieldMapper.TypeParser> metadataMappers = new LinkedHashMap<>(); int i = 0; Map.Entry<String, MetadataFieldMapper.TypeParser> fieldNamesEntry = null; for (Map.Entry<String, MetadataFieldMapper.TypeParser> entry : builtInMetadataMappers.entrySet()) { if (i < builtInMetadataMappers.size() - 1) { metadataMappers.put(entry.getKey(), entry.getValue()); } else { assert entry.getKey().equals(FieldNamesFieldMapper.NAME) : "_field_names must be the last registered mapper, order counts"; fieldNamesEntry = entry; } i++; } assert fieldNamesEntry != null; for (MapperPlugin mapperPlugin : mapperPlugins) { for (Map.Entry<String, MetadataFieldMapper.TypeParser> entry : mapperPlugin.getMetadataMappers().entrySet()) { if (entry.getKey().equals(FieldNamesFieldMapper.NAME)) { throw new IllegalArgumentException("Plugin cannot contain metadata mapper [" + FieldNamesFieldMapper.NAME + "]"); } if (metadataMappers.put(entry.getKey(), entry.getValue()) != null) { throw new IllegalArgumentException("MetadataFieldMapper [" + entry.getKey() + "] is already registered"); } } } // we register _field_names here so that it has a chance to see all the other mappers, including from plugins metadataMappers.put(fieldNamesEntry.getKey(), fieldNamesEntry.getValue()); return Collections.unmodifiableMap(metadataMappers); } /** * Returns a set containing all of the builtin metadata fields */ public static Set<String> getBuiltInMetadataFields() { return builtInMetadataMappers.keySet(); } private static Function<String, Predicate<String>> getFieldFilter(List<MapperPlugin> mapperPlugins) { Function<String, Predicate<String>> fieldFilter = MapperPlugin.NOOP_FIELD_FILTER; for (MapperPlugin mapperPlugin : mapperPlugins) { fieldFilter = and(fieldFilter, mapperPlugin.getFieldFilter()); } return fieldFilter; } private static Function<String, Predicate<String>> and(Function<String, Predicate<String>> first, Function<String, Predicate<String>> second) { //the purpose of this method is to not chain no-op field predicates, so that we can easily find out when no plugins plug in //a field filter, hence skip the mappings filtering part as a whole, as it requires parsing mappings into a map. if (first == MapperPlugin.NOOP_FIELD_FILTER) { return second; } if (second == MapperPlugin.NOOP_FIELD_FILTER) { return first; } return index -> { Predicate<String> firstPredicate = first.apply(index); Predicate<String> secondPredicate = second.apply(index); if (firstPredicate == MapperPlugin.NOOP_FIELD_PREDICATE) { return secondPredicate; } if (secondPredicate == MapperPlugin.NOOP_FIELD_PREDICATE) { return firstPredicate; } return firstPredicate.and(secondPredicate); }; } @Override protected void configure() { bind(IndicesStore.class).asEagerSingleton(); bind(IndicesClusterStateService.class).asEagerSingleton(); bind(TransportResyncReplicationAction.class).asEagerSingleton(); bind(PrimaryReplicaSyncer.class).asEagerSingleton(); bind(RetentionLeaseSyncAction.class).asEagerSingleton(); bind(RetentionLeaseBackgroundSyncAction.class).asEagerSingleton(); bind(RetentionLeaseSyncer.class).asEagerSingleton(); } /** * A registry for all field mappers. */ public MapperRegistry getMapperRegistry() { return mapperRegistry; } public Collection<Function<IndexSettings, Optional<EngineFactory>>> getEngineFactories() { return Collections.emptyList(); } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.datasync.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationFsxWindows" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeLocationFsxWindowsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) of the FSx for Windows File Server location that was described. * </p> */ private String locationArn; /** * <p> * The URL of the FSx for Windows File Server location that was described. * </p> */ private String locationUri; /** * <p> * The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File Server * file system. * </p> */ private java.util.List<String> securityGroupArns; /** * <p> * The time that the FSx for Windows File Server location was created. * </p> */ private java.util.Date creationTime; /** * <p> * The user who has the permissions to access files and folders in the FSx for Windows File Server file system. * </p> */ private String user; /** * <p> * The name of the Windows domain that the FSx for Windows File Server belongs to. * </p> */ private String domain; /** * <p> * The Amazon Resource Name (ARN) of the FSx for Windows File Server location that was described. * </p> * * @param locationArn * The Amazon Resource Name (ARN) of the FSx for Windows File Server location that was described. */ public void setLocationArn(String locationArn) { this.locationArn = locationArn; } /** * <p> * The Amazon Resource Name (ARN) of the FSx for Windows File Server location that was described. * </p> * * @return The Amazon Resource Name (ARN) of the FSx for Windows File Server location that was described. */ public String getLocationArn() { return this.locationArn; } /** * <p> * The Amazon Resource Name (ARN) of the FSx for Windows File Server location that was described. * </p> * * @param locationArn * The Amazon Resource Name (ARN) of the FSx for Windows File Server location that was described. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLocationFsxWindowsResult withLocationArn(String locationArn) { setLocationArn(locationArn); return this; } /** * <p> * The URL of the FSx for Windows File Server location that was described. * </p> * * @param locationUri * The URL of the FSx for Windows File Server location that was described. */ public void setLocationUri(String locationUri) { this.locationUri = locationUri; } /** * <p> * The URL of the FSx for Windows File Server location that was described. * </p> * * @return The URL of the FSx for Windows File Server location that was described. */ public String getLocationUri() { return this.locationUri; } /** * <p> * The URL of the FSx for Windows File Server location that was described. * </p> * * @param locationUri * The URL of the FSx for Windows File Server location that was described. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLocationFsxWindowsResult withLocationUri(String locationUri) { setLocationUri(locationUri); return this; } /** * <p> * The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File Server * file system. * </p> * * @return The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File * Server file system. */ public java.util.List<String> getSecurityGroupArns() { return securityGroupArns; } /** * <p> * The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File Server * file system. * </p> * * @param securityGroupArns * The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File * Server file system. */ public void setSecurityGroupArns(java.util.Collection<String> securityGroupArns) { if (securityGroupArns == null) { this.securityGroupArns = null; return; } this.securityGroupArns = new java.util.ArrayList<String>(securityGroupArns); } /** * <p> * The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File Server * file system. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setSecurityGroupArns(java.util.Collection)} or {@link #withSecurityGroupArns(java.util.Collection)} if * you want to override the existing values. * </p> * * @param securityGroupArns * The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File * Server file system. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLocationFsxWindowsResult withSecurityGroupArns(String... securityGroupArns) { if (this.securityGroupArns == null) { setSecurityGroupArns(new java.util.ArrayList<String>(securityGroupArns.length)); } for (String ele : securityGroupArns) { this.securityGroupArns.add(ele); } return this; } /** * <p> * The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File Server * file system. * </p> * * @param securityGroupArns * The Amazon Resource Names (ARNs) of the security groups that are configured for the FSx for Windows File * Server file system. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLocationFsxWindowsResult withSecurityGroupArns(java.util.Collection<String> securityGroupArns) { setSecurityGroupArns(securityGroupArns); return this; } /** * <p> * The time that the FSx for Windows File Server location was created. * </p> * * @param creationTime * The time that the FSx for Windows File Server location was created. */ public void setCreationTime(java.util.Date creationTime) { this.creationTime = creationTime; } /** * <p> * The time that the FSx for Windows File Server location was created. * </p> * * @return The time that the FSx for Windows File Server location was created. */ public java.util.Date getCreationTime() { return this.creationTime; } /** * <p> * The time that the FSx for Windows File Server location was created. * </p> * * @param creationTime * The time that the FSx for Windows File Server location was created. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLocationFsxWindowsResult withCreationTime(java.util.Date creationTime) { setCreationTime(creationTime); return this; } /** * <p> * The user who has the permissions to access files and folders in the FSx for Windows File Server file system. * </p> * * @param user * The user who has the permissions to access files and folders in the FSx for Windows File Server file * system. */ public void setUser(String user) { this.user = user; } /** * <p> * The user who has the permissions to access files and folders in the FSx for Windows File Server file system. * </p> * * @return The user who has the permissions to access files and folders in the FSx for Windows File Server file * system. */ public String getUser() { return this.user; } /** * <p> * The user who has the permissions to access files and folders in the FSx for Windows File Server file system. * </p> * * @param user * The user who has the permissions to access files and folders in the FSx for Windows File Server file * system. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLocationFsxWindowsResult withUser(String user) { setUser(user); return this; } /** * <p> * The name of the Windows domain that the FSx for Windows File Server belongs to. * </p> * * @param domain * The name of the Windows domain that the FSx for Windows File Server belongs to. */ public void setDomain(String domain) { this.domain = domain; } /** * <p> * The name of the Windows domain that the FSx for Windows File Server belongs to. * </p> * * @return The name of the Windows domain that the FSx for Windows File Server belongs to. */ public String getDomain() { return this.domain; } /** * <p> * The name of the Windows domain that the FSx for Windows File Server belongs to. * </p> * * @param domain * The name of the Windows domain that the FSx for Windows File Server belongs to. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeLocationFsxWindowsResult withDomain(String domain) { setDomain(domain); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getLocationArn() != null) sb.append("LocationArn: ").append(getLocationArn()).append(","); if (getLocationUri() != null) sb.append("LocationUri: ").append(getLocationUri()).append(","); if (getSecurityGroupArns() != null) sb.append("SecurityGroupArns: ").append(getSecurityGroupArns()).append(","); if (getCreationTime() != null) sb.append("CreationTime: ").append(getCreationTime()).append(","); if (getUser() != null) sb.append("User: ").append(getUser()).append(","); if (getDomain() != null) sb.append("Domain: ").append(getDomain()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeLocationFsxWindowsResult == false) return false; DescribeLocationFsxWindowsResult other = (DescribeLocationFsxWindowsResult) obj; if (other.getLocationArn() == null ^ this.getLocationArn() == null) return false; if (other.getLocationArn() != null && other.getLocationArn().equals(this.getLocationArn()) == false) return false; if (other.getLocationUri() == null ^ this.getLocationUri() == null) return false; if (other.getLocationUri() != null && other.getLocationUri().equals(this.getLocationUri()) == false) return false; if (other.getSecurityGroupArns() == null ^ this.getSecurityGroupArns() == null) return false; if (other.getSecurityGroupArns() != null && other.getSecurityGroupArns().equals(this.getSecurityGroupArns()) == false) return false; if (other.getCreationTime() == null ^ this.getCreationTime() == null) return false; if (other.getCreationTime() != null && other.getCreationTime().equals(this.getCreationTime()) == false) return false; if (other.getUser() == null ^ this.getUser() == null) return false; if (other.getUser() != null && other.getUser().equals(this.getUser()) == false) return false; if (other.getDomain() == null ^ this.getDomain() == null) return false; if (other.getDomain() != null && other.getDomain().equals(this.getDomain()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getLocationArn() == null) ? 0 : getLocationArn().hashCode()); hashCode = prime * hashCode + ((getLocationUri() == null) ? 0 : getLocationUri().hashCode()); hashCode = prime * hashCode + ((getSecurityGroupArns() == null) ? 0 : getSecurityGroupArns().hashCode()); hashCode = prime * hashCode + ((getCreationTime() == null) ? 0 : getCreationTime().hashCode()); hashCode = prime * hashCode + ((getUser() == null) ? 0 : getUser().hashCode()); hashCode = prime * hashCode + ((getDomain() == null) ? 0 : getDomain().hashCode()); return hashCode; } @Override public DescribeLocationFsxWindowsResult clone() { try { return (DescribeLocationFsxWindowsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package com.kindredgames.wordclues; import com.kindredgames.wordclues.util.KGLog; import com.kindredgames.wordclues.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class CluesWebViewManager //implements ValueCallback<String> { private static final int TOPIC_COMMAND_INDEX = 0; private static final int TOPIC_FIRST_OPTION_INDEX = 1; private static final int TOPIC_SECOND_OPTION_INDEX = 2; private static final int TOPIC_THIRD_OPTION_INDEX = 3; private static final String RESPONSE_OK = "{\"ok\":1}"; private static final String RESPONSE_FAILURE = "{\"ok\":0}"; private GameController controller; private boolean loaded; private List<String> earlyMessages; // private ScalableWebView _webView; // // public void setWebView(ScalableWebView webView) { // _webView = webView; // } public CluesWebViewManager(GameController controller) { // public CluesWebViewManager(Activity activity) { super(); this.controller = controller; this.loaded = false; this.earlyMessages = new ArrayList<String>(); } public boolean shouldOverrideUrlLoading(LoadUrlCallback loadUrlCallback, java.lang.String url) { if (url.startsWith("wmw:")) { String[] components = url.split(":"); // Topic format: command.name/do|destination/some/other/parameters String topic = components.length > 1 ? components[1] : null; String[] topicParams = topic != null ? topic.split("\\.") : null; int callbackId = components.length > 2 ? Integer.parseInt(components[2]) : -1; String argsAsString = null; if (components.length > 3) { try { argsAsString = URLDecoder.decode(components[3], "UTF-8").trim(); } catch (UnsupportedEncodingException exc) { KGLog.e("Error decoding arguments: %s", exc.toString()); return false; } } KGLog.d("Received JS topic=[%s] message[%d]: %s", topic, argsAsString != null ? argsAsString.length() : -1, argsAsString); handleCall(loadUrlCallback, topic, topicParams, callbackId, argsAsString); return false; } // Accept this location change return true; } // @JavascriptInterface // public void handleJavascript(String topic, int callbackId, Object args) { // String[] topicParams = topic != null ? topic.split("\\.") : null; // handleCall(_webView, topic, topicParams, callbackId, args != null ? args.toString() : null); // } public void handleCall(LoadUrlCallback loadUrlCallback, String topic, String[] topicParams, int callbackId, String messageJson) { handleWebViewLoaded(loadUrlCallback); // first incoming message triggers sending all accumulated early messages String response = null; String command = topicParams[TOPIC_COMMAND_INDEX]; String firstOption = topicParams.length - 1 >= TOPIC_FIRST_OPTION_INDEX ? topicParams[TOPIC_FIRST_OPTION_INDEX] : null; String function = firstOption; // only for readability String secondOption = topicParams.length - 1 >= TOPIC_SECOND_OPTION_INDEX ? topicParams[TOPIC_SECOND_OPTION_INDEX] : null; String functionArg = secondOption; // only for readability //String thirdOption = topicParams.count - 1 >= TOPIC_THIRD_OPTION_INDEX ? topicParams[TOPIC_THIRD_OPTION_INDEX] : nil; //String functionSecondArg = thirdOption; // only for readability try { if ("sound".equals(command)) { controller.playSound(firstOption); return; } else if ("get".equals(command)) { response = controller.getUserCache(firstOption); } else if ("set".equals(command)) { response = controller.setUserCache(firstOption, messageJson); } else if ("generate".equals(command)) { if ("game".equals(function)) { response = controller.generateGames(1); controller.setUserCache("game", response); } else if ("games".equals(function)) { response = controller.generateGames(Integer.parseInt(functionArg)); controller.setUserCache("game", response); } } else if ("post".equals(command)) { if ("facebook".equals(function)) { response = controller.postFacebook(Utils.jsonData(messageJson)); } else if ("twitter".equals(function)) { response = controller.postTwitter(Utils.jsonData(messageJson)); } } else if ("display".equals(command)) { if ("gamecenter".equals(function)) { controller.getGameCenter().displayGameCenter(); } } else if ("link".equals(command)) { if ("store".equals(function)) { controller.linkStore(); } else if ("twitter".equals(function)) { controller.linkTwitter(); } else if ("facebook".equals(function)) { controller.linkFacebook(); } else if ("company".equals(function)) { controller.linkCompany(); } else if ("email".equals(function)) { controller.postEmail(Utils.jsonData(messageJson)); } } else if ("store".equals(command)) { if ("enabled".equals(function)) { response = controller.canMakePayments(); } else if ("price".equals(function)) { controller.price(Utils.jsonData(messageJson)); } else if ("buy".equals(function)) { controller.buy(Utils.jsonData(messageJson)); } else if ("owns".equals(function)) { response = controller.owns(Utils.jsonData(messageJson)); } else if ("restore".equals(function)) { controller.restorePurchases(); } } else if ("leaderboard".equals(command)) { if ("get".equals(function)) { response = String.format("{\"value\":\"%d\"}", controller.getGameCenter().getLeaderboardValue(functionArg)); } else if ("set".equals(function)) { controller.getGameCenter().updateLeaderboards(Utils.jsonData(messageJson)); } } else if ("leaderboards".equals(command)) { if ("get".equals(function)) { response = controller.getGameCenter().getLeaderboardValues(new JSONArray(messageJson)).toString(); //response = [self dataToJson:[controller getLeaderboardValues]]; } else if ("set".equals(function)) { controller.getGameCenter().updateLeaderboards(Utils.jsonData(messageJson)); } } else if ("achievements".equals(command)) { if ("get".equals(function)) { response = controller.getAchievementValues(); } else if ("set".equals(function)) { controller.updateAchievements(Utils.jsonData(messageJson)); } } else if ("check".equals(command)) { if ("gamecenter".equals(function)) { response = controller.getGameCenter().checkGameCenter(); } else if ("facebook".equals(function)) { response = controller.canOpenFacebookApp() ? RESPONSE_OK : RESPONSE_FAILURE; } else if ("twitter".equals(function)) { response = controller.canOpenTwitterApp() ? RESPONSE_OK : RESPONSE_FAILURE; } } else if ("error".equals(command)) { JSONObject errorMessage = Utils.jsonData(messageJson); KGLog.e("JS Error: %s", errorMessage.getString("message")); } else { KGLog.e("Unsupported topic: '%s'", topic); return; } } catch (JSONException exc) { KGLog.e(String.format("Exception handling JSON: %s", exc.toString())); } if (callbackId > 0) { // Null is also a valid response //KGLog.d("Returning to JS response: '%s'", response); returnResult(loadUrlCallback, callbackId, topic, response); } } private void returnResult(LoadUrlCallback loadUrlCallback, int callbackId, String topic, String json) { KGLog.d(String.format("Response to JS: topic=%s: %s", topic, json)); respondWithJavaScript(loadUrlCallback, String.format("GAME.bridge.resultForCallback(%d,[%s,%s]);", callbackId, formatStringParameter(topic), formatStringParameter(json))); } private void respondWithJavaScript(final LoadUrlCallback loadUrlCallback, final String response) { //final ValueCallback<String> resultCallback = this; loadUrlCallback.runJavascript(response); } // public void onReceiveValue(String v) { // } private String formatStringParameter(String param) { try { return param == null ? "null" : String.format("'%s'", URLEncoder.encode(param, Utils.ENCODING_UTF8).replaceAll("'", "\\'")); } catch (UnsupportedEncodingException exc) { KGLog.e(exc.toString()); return null; } } public void sendMessageObject(LoadUrlCallback loadUrlCallback, JSONObject response) { sendMessage(loadUrlCallback, response.toString()); } private void sendMessage(LoadUrlCallback loadUrlCallback, String response) { if (loaded) { KGLog.d("Message to JS: %s", response); respondWithJavaScript(loadUrlCallback, String.format("GAME.bridge.response(%s,%s)", formatStringParameter(null), formatStringParameter(response))); } else { KGLog.d("Cached message to JS: %s", response); earlyMessages.add(response); } } private void handleWebViewLoaded(LoadUrlCallback loadUrlCallback) { if (!loaded) { loaded = true; for (String response : earlyMessages) { sendMessage(loadUrlCallback, response); } earlyMessages.clear(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Created on 22.02.2005 * Last modification G.Seryakova * Last modified on 22.02.2005 * * * * scenario */ package org.apache.harmony.test.func.api.java.lang.reflect.F_ArrayTest_01; import java.lang.reflect.Array; import org.apache.harmony.test.func.share.ScenarioTest; /** */ public class F_ArrayTest_01 extends ScenarioTest { String resString = ""; public static void main(String[] args) { System.exit(new F_ArrayTest_01().test(args)); } class MyObject { long num; MyObject(long n) { num = n; } } public int test() { if (!checkBoolean()) { return fail("Fail for boolean: " + resString); } if (!checkByte()) { return fail("Fail for byte: " + resString); } if (!checkChar()) { return fail("Fail for char: " + resString); } if (!checkDouble()) { return fail("Fail for double: " + resString); } if (!checkFloat()) { return fail("Fail for float: " + resString); } if (!checkInt()) { return fail("Fail for int: " + resString); } if (!checkLong()) { return fail("Fail for long: " + resString); } if (!checkShort()) { return fail("Fail for short: " + resString); } if (!checkObject()) { return fail("Fail for MyObject: " + resString); } return pass(); } private boolean checkBoolean() { boolean arr[] = new boolean[10]; for (int i = 0; i < Array.getLength(arr); i++) { if (Math.round(Math.random()) == 0) { arr[i] = false; } else { arr[i] = true; } } boolean arrCopy[] = (boolean[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i] != arrCopy[i]) { log.info(arr[i] + " and " + arrCopy[i]); resString = resString + "Array element not equal for boolean(" + arr[i] + " and " + arrCopy[i] + ");"; return false; } } return true; } private boolean checkByte() { byte arr[] = new byte[100]; for (int i = 0; i < Array.getLength(arr); i++) { arr[i] = (byte) Math.round((Math.random() * Byte.MAX_VALUE)); } byte arrCopy[] = (byte[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i] != arrCopy[i]) { resString = resString + "Array element not equal for byte(" + arr[i] + " and " + arrCopy[i] + ");"; return false; } } return true; } private boolean checkChar() { char arr[] = new char[100]; for (int i = 0; i < Array.getLength(arr); i++) { arr[i] = (char)Math.round((Math.random() * 256)); } char arrCopy[] = (char[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i] != arrCopy[i]) { resString = resString + "Array element not equal for char(" + arr[i] + " and " + arrCopy[i] + ");"; return false; } } return true; } private boolean checkDouble() { double arr[] = new double[100]; for (int i = 0; i < Array.getLength(arr); i++) { arr[i] = (Math.random() * 1000); } double arrCopy[] = (double[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i] != arrCopy[i]) { resString = resString + "Array element not equal for double(" + arr[i] + " and " + arrCopy[i] + ");"; return false; } } return true; } private boolean checkFloat() { float arr[] = new float[100]; for (int i = 0; i < Array.getLength(arr); i++) { arr[i] = (float)(Math.random() * 1000); } float arrCopy[] = (float[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i] != arrCopy[i]) { resString = resString + "Array element not equal for float(" + arr[i] + " and " + arrCopy[i] + ");"; return false; } } return true; } private boolean checkInt() { int arr[] = new int[100]; for (int i = 0; i < Array.getLength(arr); i++) { arr[i] = (int)Math.round((Math.random() * Integer.MAX_VALUE)); } int arrCopy[] = (int[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i] != arrCopy[i]) { resString = resString + "Array element not equal for int(" + arr[i] + " and " + arrCopy[i] + ");"; return false; } } return true; } private boolean checkLong() { long arr[] = new long[100]; for (int i = 0; i < Array.getLength(arr); i++) { arr[i] = Math.round((Math.random() * Long.MAX_VALUE)); } long arrCopy[] = (long[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i] != arrCopy[i]) { resString = resString + "Array element not equal for long(" + arr[i] + " and " + arrCopy[i] + ");"; return false; } } return true; } private boolean checkShort() { short arr[] = new short[100]; for (int i = 0; i < Array.getLength(arr); i++) { arr[i] = (short)Math.round((Math.random() * Short.MAX_VALUE)); } short arrCopy[] = (short[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i] != arrCopy[i]) { resString = resString + "Array element not equal for short(" + arr[i] + " and " + arrCopy[i] + ");"; return false; } } return true; } private boolean checkObject() { MyObject arr[] = new MyObject[100]; for (int i = 0; i < Array.getLength(arr); i++) { arr[i] = new MyObject(Math.round((Math.random() * Long.MAX_VALUE))); } MyObject arrCopy[] = (MyObject[])getCopy(arr); for (int i = 0; i < Array.getLength(arr); i++) { if (arr[i].num != arrCopy[i].num) { resString = resString + "Array element not equal for MyObject(" + arr[i].num + " and " + arrCopy[i].num + ");"; return false; } } return true; } private Object getCopy(Object arr) { Object res = null; Class type = arr.getClass().getComponentType(); res = Array.newInstance(type, Array.getLength(arr)); if (type.isPrimitive()) { if (type.getName().equals("boolean")) { for (int i = 0; i < Array.getLength(arr); i++) { Array.setBoolean(res, i, Array.getBoolean(arr, i)); } } else if (type.getName().equals("byte")) { for (int i = 0; i < Array.getLength(arr); i++) { Array.setByte(res, i, Array.getByte(arr, i)); } } else if (type.getName().equals("char")) { for (int i = 0; i < Array.getLength(arr); i++) { Array.setChar(res, i, Array.getChar(arr, i)); } } else if (type.getName().equals("double")) { for (int i = 0; i < Array.getLength(arr); i++) { Array.setDouble(res, i, Array.getDouble(arr, i)); } } else if (type.getName().equals("float")) { for (int i = 0; i < Array.getLength(arr); i++) { Array.setFloat(res, i, Array.getFloat(arr, i)); } } else if (type.getName().equals("int")) { for (int i = 0; i < Array.getLength(arr); i++) { Array.setInt(res, i, Array.getInt(arr, i)); } } else if (type.getName().equals("long")) { for (int i = 0; i < Array.getLength(arr); i++) { Array.setLong(res, i, Array.getLong(arr, i)); } } else if (type.getName().equals("short")) { for (int i = 0; i < Array.getLength(arr); i++) { Array.setShort(res, i, Array.getShort(arr, i)); } } } else { for (int i = 0; i < Array.getLength(arr); i++) { Array.set(res, i, Array.get(arr, i)); } } return res; } }
/* * Copyright 2015, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.benchmarks.qps; import static io.grpc.benchmarks.Utils.parseBoolean; import static java.lang.Integer.parseInt; import static java.util.Arrays.asList; import io.grpc.ManagedChannel; import io.grpc.benchmarks.Transport; import io.grpc.benchmarks.Utils; import io.grpc.benchmarks.proto.Control.RpcType; import io.grpc.benchmarks.proto.Messages; import io.grpc.benchmarks.proto.Messages.PayloadType; import io.grpc.internal.testing.TestUtils; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; /** * Configuration options for benchmark clients. */ public class ClientConfiguration implements Configuration { private static final ClientConfiguration DEFAULT = new ClientConfiguration(); Transport transport = Transport.NETTY_NIO; boolean tls; boolean testca; String authorityOverride = TestUtils.TEST_SERVER_HOST; boolean useDefaultCiphers; boolean directExecutor; SocketAddress address; int channels = 4; int outstandingRpcsPerChannel = 10; int serverPayload; int clientPayload; int flowControlWindow = Utils.DEFAULT_FLOW_CONTROL_WINDOW; // seconds int duration = 60; // seconds int warmupDuration = 10; int targetQps; String histogramFile; RpcType rpcType = RpcType.UNARY; PayloadType payloadType = PayloadType.COMPRESSABLE; private ClientConfiguration() { } public ManagedChannel newChannel() throws IOException { return Utils.newClientChannel(transport, address, tls, testca, authorityOverride, useDefaultCiphers, flowControlWindow, directExecutor); } public Messages.SimpleRequest newRequest() { return Utils.makeRequest(payloadType, clientPayload, serverPayload); } /** * Constructs a builder for configuring a client application with supported parameters. If no * parameters are provided, all parameters are assumed to be supported. */ static Builder newBuilder(ClientParam... supportedParams) { return new Builder(supportedParams); } static final class Builder extends AbstractConfigurationBuilder<ClientConfiguration> { private final Collection<Param> supportedParams; private Builder(ClientParam... supportedParams) { this.supportedParams = supportedOptionsSet(supportedParams); } @Override protected ClientConfiguration newConfiguration() { return new ClientConfiguration(); } @Override protected Collection<Param> getParams() { return supportedParams; } @Override protected ClientConfiguration build0(ClientConfiguration config) { if (config.tls) { if (!config.transport.tlsSupported) { throw new IllegalArgumentException( "Transport " + config.transport.name().toLowerCase() + " does not support TLS."); } if (config.transport != Transport.OK_HTTP && config.testca && config.address instanceof InetSocketAddress) { // Override the socket address with the host from the testca. InetSocketAddress address = (InetSocketAddress) config.address; config.address = TestUtils.testServerAddress(address.getHostName(), address.getPort()); } } // Verify that the address type is correct for the transport type. config.transport.validateSocketAddress(config.address); return config; } private static Set<Param> supportedOptionsSet(ClientParam... supportedParams) { if (supportedParams.length == 0) { // If no options are supplied, default to including all options. supportedParams = ClientParam.values(); } return Collections.unmodifiableSet(new LinkedHashSet<Param>(asList(supportedParams))); } } enum ClientParam implements AbstractConfigurationBuilder.Param { ADDRESS("STR", "Socket address (host:port) or Unix Domain Socket file name " + "(unix:///path/to/file), depending on the transport selected.", null, true) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.address = Utils.parseSocketAddress(value); } }, CHANNELS("INT", "Number of Channels.", "" + DEFAULT.channels) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.channels = parseInt(value); } }, OUTSTANDING_RPCS("INT", "Number of outstanding RPCs per Channel.", "" + DEFAULT.outstandingRpcsPerChannel) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.outstandingRpcsPerChannel = parseInt(value); } }, CLIENT_PAYLOAD("BYTES", "Payload Size of the Request.", "" + DEFAULT.clientPayload) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.clientPayload = parseInt(value); } }, SERVER_PAYLOAD("BYTES", "Payload Size of the Response.", "" + DEFAULT.serverPayload) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.serverPayload = parseInt(value); } }, TLS("", "Enable TLS.", "" + DEFAULT.tls) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.tls = parseBoolean(value); } }, TESTCA("", "Use the provided Test Certificate for TLS.", "" + DEFAULT.testca) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.testca = parseBoolean(value); } }, USE_DEFAULT_CIPHERS("", "Use the default JDK ciphers for TLS (Used to support Java 7).", "" + DEFAULT.useDefaultCiphers) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.useDefaultCiphers = parseBoolean(value); } }, TRANSPORT("STR", Transport.getDescriptionString(), DEFAULT.transport.name().toLowerCase()) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.transport = Transport.valueOf(value.toUpperCase()); } }, DURATION("SECONDS", "Duration of the benchmark.", "" + DEFAULT.duration) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.duration = parseInt(value); } }, WARMUP_DURATION("SECONDS", "Warmup Duration of the benchmark.", "" + DEFAULT.warmupDuration) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.warmupDuration = parseInt(value); } }, DIRECTEXECUTOR("", "Don't use a threadpool for RPC calls, instead execute calls directly " + "in the transport thread.", "" + DEFAULT.directExecutor) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.directExecutor = parseBoolean(value); } }, SAVE_HISTOGRAM("FILE", "Write the histogram with the latency recordings to file.", null) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.histogramFile = value; } }, STREAMING_RPCS("", "Use Streaming RPCs.", "false") { @Override protected void setClientValue(ClientConfiguration config, String value) { config.rpcType = RpcType.STREAMING; } }, FLOW_CONTROL_WINDOW("BYTES", "The HTTP/2 flow control window.", "" + DEFAULT.flowControlWindow) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.flowControlWindow = parseInt(value); } }, TARGET_QPS("INT", "Average number of QPS to shoot for.", "" + DEFAULT.targetQps, true) { @Override protected void setClientValue(ClientConfiguration config, String value) { config.targetQps = parseInt(value); } }; private final String type; private final String description; private final String defaultValue; private final boolean required; ClientParam(String type, String description, String defaultValue) { this(type, description, defaultValue, false); } ClientParam(String type, String description, String defaultValue, boolean required) { this.type = type; this.description = description; this.defaultValue = defaultValue; this.required = required; } @Override public String getName() { return name().toLowerCase(); } @Override public String getType() { return type; } @Override public String getDescription() { return description; } @Override public String getDefaultValue() { return defaultValue; } @Override public boolean isRequired() { return required; } @Override public void setValue(Configuration config, String value) { setClientValue((ClientConfiguration) config, value); } protected abstract void setClientValue(ClientConfiguration config, String value); } }
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.gmf.esb.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; import org.wso2.developerstudio.eclipse.gmf.esb.AggregateMediator; import org.wso2.developerstudio.eclipse.gmf.esb.AggregateSequenceType; import org.wso2.developerstudio.eclipse.gmf.esb.CompletionMessagesType; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.AggregateMediator} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class AggregateMediatorItemProvider extends MediatorItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AggregateMediatorItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { AggregateMediator mediator = (AggregateMediator) object; if (itemPropertyDescriptors != null) { itemPropertyDescriptors.clear(); } super.getPropertyDescriptors(object); addAggregateIDPropertyDescriptor(object); addCorrelationExpressionPropertyDescriptor(object); addCompletionTimeoutPropertyDescriptor(object); addCompletionMinMessagesTypePropertyDescriptor(object); addCompletionMaxMessagesTypePropertyDescriptor(object); if (mediator.getCompletionMinMessagesType().equals(CompletionMessagesType.VALUE)) { addCompletionMinMessagesValuePropertyDescriptor(object); } else { addCompletionMinMessagesPropertyDescriptor(object); } if (mediator.getCompletionMaxMessagesType().equals(CompletionMessagesType.VALUE)) { addCompletionMaxMessagesValuePropertyDescriptor(object); } else { addCompletionMaxMessagesPropertyDescriptor(object); } addAggregationExpressionPropertyDescriptor(object); addSequenceTypePropertyDescriptor(object); if (mediator.getSequenceType().equals(AggregateSequenceType.REGISTRY_REFERENCE)) { addSequenceKeyPropertyDescriptor(object); } addEnclosingElementPropertyPropertyDescriptor(object); addAggregateElementTypePropertyDescriptor(object); addDescriptionPropertyDescriptor(object); return itemPropertyDescriptors; } /** * This adds a property descriptor for the Aggregate ID feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ protected void addAggregateIDPropertyDescriptor(Object object) { itemPropertyDescriptors .add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_aggregateID_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_aggregateID_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__AGGREGATE_ID, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, "Basic", null)); } protected void addCorrelationExpressionPropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor( ((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_correlationExpression_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_correlationExpression_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION, true, false, false, null, "Basic", null)); } /** * This adds a property descriptor for the Completion Timeout feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ protected void addCompletionTimeoutPropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor( ((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_completionTimeout_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_completionTimeout_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_TIMEOUT, true, false, false, ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Completion Min Messages Type feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ protected void addCompletionMinMessagesTypePropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor( ((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_completionMinMessagesType_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_completionMinMessagesType_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_TYPE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Completion Max Messages Type feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ protected void addCompletionMaxMessagesTypePropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor( ((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_completionMaxMessagesType_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_completionMaxMessagesType_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_TYPE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Completion Min Messages Value feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ protected void addCompletionMinMessagesValuePropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor( ((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_completionMinMessagesValue_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_completionMinMessagesValue_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_VALUE, true, false, false, ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Completion Max Messages Value feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ protected void addCompletionMaxMessagesValuePropertyDescriptor(Object object) { itemPropertyDescriptors.add(createItemPropertyDescriptor( ((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_completionMaxMessagesValue_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_completionMaxMessagesValue_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_VALUE, true, false, false, ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Completion Min Messages feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ protected void addCompletionMinMessagesPropertyDescriptor(Object object) { itemPropertyDescriptors .add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_completionMinMessages_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_completionMinMessages_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_EXPRESSION, true, false, false, ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Completion Max Messages feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ protected void addCompletionMaxMessagesPropertyDescriptor(Object object) { itemPropertyDescriptors .add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_completionMaxMessages_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_completionMaxMessages_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_EXPRESSION, true, false, false, ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Aggregation Expression feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addAggregationExpressionPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_aggregationExpression_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_aggregationExpression_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__AGGREGATION_EXPRESSION, true, false, false, null, getString("_UI_onCompletePropertyCategory"), null)); } /** * This adds a property descriptor for the Sequence Type feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addSequenceTypePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_sequenceType_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_sequenceType_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__SEQUENCE_TYPE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, getString("_UI_onCompletePropertyCategory"), null)); } /** * This adds a property descriptor for the Sequence Key feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addSequenceKeyPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_sequenceKey_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_sequenceKey_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__SEQUENCE_KEY, true, false, false, null, getString("_UI_onCompletePropertyCategory"), null)); } /** * This adds a property descriptor for the Enclosing Element Property feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addEnclosingElementPropertyPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_enclosingElementProperty_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_enclosingElementProperty_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__ENCLOSING_ELEMENT_PROPERTY, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, getString("_UI_BasicPropertyCategory"), null)); } /** * This adds a property descriptor for the Aggregate Element Type feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addAggregateElementTypePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_AggregateMediator_aggregateElementType_feature"), getString("_UI_PropertyDescriptor_description", "_UI_AggregateMediator_aggregateElementType_feature", "_UI_AggregateMediator_type"), EsbPackage.Literals.AGGREGATE_MEDIATOR__AGGREGATE_ELEMENT_TYPE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_EXPRESSION); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_EXPRESSION); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__INPUT_CONNECTOR); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__OUTPUT_CONNECTOR); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__ON_COMPLETE_OUTPUT_CONNECTOR); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__MEDIATOR_FLOW); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__AGGREGATION_EXPRESSION); childrenFeatures.add(EsbPackage.Literals.AGGREGATE_MEDIATOR__SEQUENCE_KEY); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns AggregateMediator.png. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/AggregateMediator.png")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((AggregateMediator)object).getDescription(); return label == null || label.length() == 0 ? getString("_UI_AggregateMediator_type") : getString("_UI_AggregateMediator_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(AggregateMediator.class)) { case EsbPackage.AGGREGATE_MEDIATOR__AGGREGATE_ID: case EsbPackage.AGGREGATE_MEDIATOR__COMPLETION_TIMEOUT: case EsbPackage.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_TYPE: case EsbPackage.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_TYPE: case EsbPackage.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_VALUE: case EsbPackage.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_VALUE: case EsbPackage.AGGREGATE_MEDIATOR__SEQUENCE_TYPE: case EsbPackage.AGGREGATE_MEDIATOR__ENCLOSING_ELEMENT_PROPERTY: case EsbPackage.AGGREGATE_MEDIATOR__AGGREGATE_ELEMENT_TYPE: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case EsbPackage.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION: case EsbPackage.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_EXPRESSION: case EsbPackage.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_EXPRESSION: case EsbPackage.AGGREGATE_MEDIATOR__INPUT_CONNECTOR: case EsbPackage.AGGREGATE_MEDIATOR__OUTPUT_CONNECTOR: case EsbPackage.AGGREGATE_MEDIATOR__ON_COMPLETE_OUTPUT_CONNECTOR: case EsbPackage.AGGREGATE_MEDIATOR__MEDIATOR_FLOW: case EsbPackage.AGGREGATE_MEDIATOR__AGGREGATION_EXPRESSION: case EsbPackage.AGGREGATE_MEDIATOR__SEQUENCE_KEY: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION, EsbFactory.eINSTANCE.createNamespacedProperty())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_EXPRESSION, EsbFactory.eINSTANCE.createNamespacedProperty())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_EXPRESSION, EsbFactory.eINSTANCE.createNamespacedProperty())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__INPUT_CONNECTOR, EsbFactory.eINSTANCE.createAggregateMediatorInputConnector())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__OUTPUT_CONNECTOR, EsbFactory.eINSTANCE.createAggregateMediatorOutputConnector())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__ON_COMPLETE_OUTPUT_CONNECTOR, EsbFactory.eINSTANCE.createAggregateMediatorOnCompleteOutputConnector())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__MEDIATOR_FLOW, EsbFactory.eINSTANCE.createMediatorFlow())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__AGGREGATION_EXPRESSION, EsbFactory.eINSTANCE.createNamespacedProperty())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.AGGREGATE_MEDIATOR__SEQUENCE_KEY, EsbFactory.eINSTANCE.createRegistryKeyProperty())); } /** * This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) { Object childFeature = feature; Object childObject = child; boolean qualify = childFeature == EsbPackage.Literals.AGGREGATE_MEDIATOR__CORRELATION_EXPRESSION || childFeature == EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MIN_MESSAGES_EXPRESSION || childFeature == EsbPackage.Literals.AGGREGATE_MEDIATOR__COMPLETION_MAX_MESSAGES_EXPRESSION || childFeature == EsbPackage.Literals.AGGREGATE_MEDIATOR__AGGREGATION_EXPRESSION; if (qualify) { return getString ("_UI_CreateChild_text2", new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) }); } return super.getCreateChildText(owner, feature, child, selection); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.security.access; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.util.Bytes; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * Represents an authorization for access for the given actions, optionally * restricted to the given column family or column qualifier, over the * given table. If the family property is <code>null</code>, it implies * full table access. */ public class TablePermission extends Permission { private static Log LOG = LogFactory.getLog(TablePermission.class); private TableName table; private byte[] family; private byte[] qualifier; //TODO refactor this class //we need to refacting this into three classes (Global, Table, Namespace) private String namespace; /** Nullary constructor for Writable, do not use */ public TablePermission() { super(); } /** * Create a new permission for the given table and (optionally) column family, * allowing the given actions. * @param table the table * @param family the family, can be null if a global permission on the table * @param assigned the list of allowed actions */ public TablePermission(TableName table, byte[] family, Action... assigned) { this(table, family, null, assigned); } /** * Creates a new permission for the given table, restricted to the given * column family and qualifer, allowing the assigned actions to be performed. * @param table the table * @param family the family, can be null if a global permission on the table * @param assigned the list of allowed actions */ public TablePermission(TableName table, byte[] family, byte[] qualifier, Action... assigned) { super(assigned); this.table = table; this.family = family; this.qualifier = qualifier; } /** * Creates a new permission for the given table, family and column qualifier, * allowing the actions matching the provided byte codes to be performed. * @param table the table * @param family the family, can be null if a global permission on the table * @param actionCodes the list of allowed action codes */ public TablePermission(TableName table, byte[] family, byte[] qualifier, byte[] actionCodes) { super(actionCodes); this.table = table; this.family = family; this.qualifier = qualifier; } /** * Creates a new permission for the given namespace or table, restricted to the given * column family and qualifer, allowing the assigned actions to be performed. * @param namespace * @param table the table * @param family the family, can be null if a global permission on the table * @param assigned the list of allowed actions */ public TablePermission(String namespace, TableName table, byte[] family, byte[] qualifier, Action... assigned) { super(assigned); this.namespace = namespace; this.table = table; this.family = family; this.qualifier = qualifier; } /** * Creates a new permission for the given namespace or table, family and column qualifier, * allowing the actions matching the provided byte codes to be performed. * @param namespace * @param table the table * @param family the family, can be null if a global permission on the table * @param actionCodes the list of allowed action codes */ public TablePermission(String namespace, TableName table, byte[] family, byte[] qualifier, byte[] actionCodes) { super(actionCodes); this.namespace = namespace; this.table = table; this.family = family; this.qualifier = qualifier; } /** * Creates a new permission for the given namespace, * allowing the actions matching the provided byte codes to be performed. * @param namespace * @param actionCodes the list of allowed action codes */ public TablePermission(String namespace, byte[] actionCodes) { super(actionCodes); this.namespace = namespace; } /** * Create a new permission for the given namespace, * allowing the given actions. * @param namespace * @param assigned the list of allowed actions */ public TablePermission(String namespace, Action... assigned) { super(assigned); this.namespace = namespace; } public boolean hasTable() { return table != null; } public TableName getTableName() { return table; } public boolean hasFamily() { return family != null; } public byte[] getFamily() { return family; } public boolean hasQualifier() { return qualifier != null; } public byte[] getQualifier() { return qualifier; } public boolean hasNamespace() { return namespace != null; } public String getNamespace() { return namespace; } /** * Checks that a given table operation is authorized by this permission * instance. * * @param namespace the namespace where the operation is being performed * @param action the action being requested * @return <code>true</code> if the action within the given scope is allowed * by this permission, <code>false</code> */ public boolean implies(String namespace, Action action) { if (!this.namespace.equals(namespace)) { return false; } // check actions return super.implies(action); } /** * Checks that a given table operation is authorized by this permission * instance. * * @param table the table where the operation is being performed * @param family the column family to which the operation is restricted, * if <code>null</code> implies "all" * @param qualifier the column qualifier to which the action is restricted, * if <code>null</code> implies "all" * @param action the action being requested * @return <code>true</code> if the action within the given scope is allowed * by this permission, <code>false</code> */ public boolean implies(TableName table, byte[] family, byte[] qualifier, Action action) { if (!this.table.equals(table)) { return false; } if (this.family != null && (family == null || !Bytes.equals(this.family, family))) { return false; } if (this.qualifier != null && (qualifier == null || !Bytes.equals(this.qualifier, qualifier))) { return false; } // check actions return super.implies(action); } /** * Checks if this permission grants access to perform the given action on * the given table and key value. * @param table the table on which the operation is being performed * @param kv the KeyValue on which the operation is being requested * @param action the action requested * @return <code>true</code> if the action is allowed over the given scope * by this permission, otherwise <code>false</code> */ public boolean implies(TableName table, KeyValue kv, Action action) { if (!this.table.equals(table)) { return false; } if (family != null && (Bytes.compareTo(family, 0, family.length, kv.getBuffer(), kv.getFamilyOffset(), kv.getFamilyLength()) != 0)) { return false; } if (qualifier != null && (Bytes.compareTo(qualifier, 0, qualifier.length, kv.getBuffer(), kv.getQualifierOffset(), kv.getQualifierLength()) != 0)) { return false; } // check actions return super.implies(action); } /** * Returns <code>true</code> if this permission matches the given column * family at least. This only indicates a partial match against the table * and column family, however, and does not guarantee that implies() for the * column same family would return <code>true</code>. In the case of a * column-qualifier specific permission, for example, implies() would still * return false. */ public boolean matchesFamily(TableName table, byte[] family, Action action) { if (!this.table.equals(table)) { return false; } if (this.family != null && (family == null || !Bytes.equals(this.family, family))) { return false; } // ignore qualifier // check actions return super.implies(action); } /** * Returns if the given permission matches the given qualifier. * @param table the table name to match * @param family the column family to match * @param qualifier the qualifier name to match * @param action the action requested * @return <code>true</code> if the table, family and qualifier match, * otherwise <code>false</code> */ public boolean matchesFamilyQualifier(TableName table, byte[] family, byte[] qualifier, Action action) { if (!matchesFamily(table, family, action)) { return false; } else { if (this.qualifier != null && (qualifier == null || !Bytes.equals(this.qualifier, qualifier))) { return false; } } return super.implies(action); } @Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NP_NULL_ON_SOME_PATH", justification="Passed on construction except on constructor not to be used") public boolean equals(Object obj) { if (!(obj instanceof TablePermission)) { return false; } TablePermission other = (TablePermission)obj; if (!(table.equals(other.getTableName()) && ((family == null && other.getFamily() == null) || Bytes.equals(family, other.getFamily())) && ((qualifier == null && other.getQualifier() == null) || Bytes.equals(qualifier, other.getQualifier())) && ((namespace == null && other.getNamespace() == null) || (namespace != null && namespace.equals(other.getNamespace()))) )) { return false; } // check actions return super.equals(other); } @Override public int hashCode() { final int prime = 37; int result = super.hashCode(); if (table != null) { result = prime * result + table.hashCode(); } if (family != null) { result = prime * result + Bytes.hashCode(family); } if (qualifier != null) { result = prime * result + Bytes.hashCode(qualifier); } if (namespace != null) { result = prime * result + namespace.hashCode(); } return result; } public String toString() { StringBuilder str = new StringBuilder("[TablePermission: "); if(namespace != null) { str.append("namespace=").append(namespace) .append(", "); } else if(table != null) { str.append("table=").append(table) .append(", family=") .append(family == null ? null : Bytes.toString(family)) .append(", qualifier=") .append(qualifier == null ? null : Bytes.toString(qualifier)) .append(", "); } else { str.append("actions="); } if (actions != null) { for (int i=0; i<actions.length; i++) { if (i > 0) str.append(","); if (actions[i] != null) str.append(actions[i].toString()); else str.append("NULL"); } } str.append("]"); return str.toString(); } @Override public void readFields(DataInput in) throws IOException { super.readFields(in); byte[] tableBytes = Bytes.readByteArray(in); table = TableName.valueOf(tableBytes); if (in.readBoolean()) { family = Bytes.readByteArray(in); } if (in.readBoolean()) { qualifier = Bytes.readByteArray(in); } if(in.readBoolean()) { namespace = Bytes.toString(Bytes.readByteArray(in)); } } @Override public void write(DataOutput out) throws IOException { super.write(out); Bytes.writeByteArray(out, table.getName()); out.writeBoolean(family != null); if (family != null) { Bytes.writeByteArray(out, family); } out.writeBoolean(qualifier != null); if (qualifier != null) { Bytes.writeByteArray(out, qualifier); } out.writeBoolean(namespace != null); if(namespace != null) { Bytes.writeByteArray(out, Bytes.toBytes(namespace)); } } }
package notes.service.com.servicenotes; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.drive.Drive; import com.google.android.gms.drive.DriveApi; import com.google.android.gms.drive.DriveContents; import com.google.android.gms.drive.DriveFile; import com.google.android.gms.drive.DriveId; import com.google.android.gms.drive.DriveResource; import com.google.android.gms.drive.MetadataChangeSet; import com.google.android.gms.drive.OpenFileActivityBuilder; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import notes.service.com.servicenotes.data.source.sqlite.NotesDatabaseHelper; /** * Created by Imperato on 15/12/2015. */ public class NotesBackupActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final int RESOLVE_CONNECTION_REQUEST_CODE = 1212121; private static final int REQUEST_CODE_CREATOR = 4343434; private static final int REQUEST_CODE_OPENER = 5656565; private GoogleApiClient mGoogleApiClient; private NotesDatabaseHelper mDbHelper; private Button backupButton; private Button restoreButton; private View.OnClickListener backupButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { saveNotes(); } }; private View.OnClickListener restoreButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { restoreNotes(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDbHelper = new NotesDatabaseHelper(this); //mDbHelper.openDataBase(); setContentView(R.layout.activity_display_file); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Drive.API) .addScope(Drive.SCOPE_FILE) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); backupButton = (Button) findViewById(R.id.button4); backupButton.setOnClickListener(backupButtonListener); backupButton.setEnabled(false); restoreButton = (Button) findViewById(R.id.button5); restoreButton.setOnClickListener(restoreButtonListener); restoreButton.setEnabled(false); } @Override public void onConnected(Bundle bundle) { Toast.makeText(getApplicationContext(),"Connected To Google Drive",Toast.LENGTH_SHORT).show(); backupButton.setEnabled(true); restoreButton.setEnabled(true); } @Override protected void onStart(){ super.onStart(); mGoogleApiClient.connect(); } private void saveNotes() { ResultCallback<DriveApi.DriveContentsResult> newFileCallback = new ResultCallback<DriveApi.DriveContentsResult>() { @Override public void onResult(DriveApi.DriveContentsResult result) { MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder() .setMimeType("text/plain").build(); DriveContents contents = result.getDriveContents(); try { ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor(); FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor .getFileDescriptor()); OutputStream os = contents.getOutputStream(); // os.write(mDbHelper.createJsonFromNotes().getBytes("UTF-8")); os.close(); } catch (IOException e) { e.printStackTrace(); } IntentSender intentSender = Drive.DriveApi .newCreateFileActivityBuilder() .setInitialMetadata(metadataChangeSet) .setInitialDriveContents(contents) .build(mGoogleApiClient); try { startIntentSenderForResult(intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { Log.w("Service Notes", "Unable to send intent", e); } } }; Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(newFileCallback); } private void restoreNotes() { IntentSender intentSender = Drive.DriveApi .newOpenFileActivityBuilder() .setMimeType(new String[]{"text/plain", "text/html"}) .build(mGoogleApiClient); try { startIntentSenderForResult( intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { Log.w("Service Notes", "Unable to send intent", e); } } @Override public void onConnectionSuspended(int i) { Toast.makeText(getApplicationContext(),"Connessione sospesa",Toast.LENGTH_SHORT).show(); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { if (connectionResult.hasResolution()) { try { connectionResult.startResolutionForResult(this, RESOLVE_CONNECTION_REQUEST_CODE); } catch (IntentSender.SendIntentException e) { } // Unable to resolve, message user appropriately } else { GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 0).show(); } } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { switch (requestCode) { case RESOLVE_CONNECTION_REQUEST_CODE: if (resultCode == RESULT_OK) { mGoogleApiClient.connect(); } break; case REQUEST_CODE_CREATOR: if (resultCode == RESULT_OK) { Toast.makeText(getApplicationContext(),"All Notes Backed Up",Toast.LENGTH_SHORT).show(); } break; case REQUEST_CODE_OPENER: if (resultCode == RESULT_OK) { DriveId mCurrentDriveId = data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID); DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, mCurrentDriveId); final PendingResult<DriveResource.MetadataResult> metadataResult = file.getMetadata(mGoogleApiClient); final PendingResult<DriveApi.DriveContentsResult> contentsResult = file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY | DriveFile.MODE_WRITE_ONLY, null); file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null) .setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() { @Override public void onResult(DriveApi.DriveContentsResult result) { if (!result.getStatus().isSuccess()) { Toast.makeText(getApplicationContext(),"Error While Restoring Notes",Toast.LENGTH_SHORT).show(); return; } // DriveContents object contains pointers // to the actual byte stream DriveContents contents = result.getDriveContents(); BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream())); StringBuilder builder = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { builder.append(line); } } catch (IOException e) { e.printStackTrace(); } String contentsAsString = builder.toString(); // mDbHelper.createNotesFromJson(contentsAsString); Toast.makeText(getApplicationContext(), "Notes Restored", Toast.LENGTH_SHORT).show(); } }); } default: super.onActivityResult(requestCode, resultCode, data); break; } } }
/*=============================================================================== Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved. Vuforia is a trademark of QUALCOMM Incorporated, registered in the United States and other countries. Trademarks of QUALCOMM Incorporated are used with permission. ===============================================================================*/ package com.brotherjing.client.vuforia.SampleApplication.utils; import android.util.Log; import com.qualcomm.vuforia.Matrix44F; import com.qualcomm.vuforia.Renderer; import com.qualcomm.vuforia.Vec2F; import com.qualcomm.vuforia.Vec3F; import com.qualcomm.vuforia.Vec4F; import com.qualcomm.vuforia.VideoBackgroundConfig; public class SampleMath { private static final String LOGTAG = "SampleMath"; private static float temp[] = new float[16]; private static Vec3F mLineStart = new Vec3F(); private static Vec3F mLineEnd = new Vec3F(); private static Vec3F mIntersection = new Vec3F(); public static Vec2F Vec2FSub(Vec2F v1, Vec2F v2) { temp[0] = v1.getData()[0] - v2.getData()[0]; temp[1] = v1.getData()[1] - v2.getData()[1]; return new Vec2F(temp[0], temp[1]); } public static float Vec2FDist(Vec2F v1, Vec2F v2) { float dx = v1.getData()[0] - v2.getData()[0]; float dy = v1.getData()[1] - v2.getData()[1]; return (float) Math.sqrt(dx * dx + dy * dy); } public static Vec3F Vec3FAdd(Vec3F v1, Vec3F v2) { temp[0] = v1.getData()[0] + v2.getData()[0]; temp[1] = v1.getData()[1] + v2.getData()[1]; temp[2] = v1.getData()[2] + v2.getData()[2]; return new Vec3F(temp[0], temp[1], temp[2]); } public static Vec3F Vec3FSub(Vec3F v1, Vec3F v2) { temp[0] = v1.getData()[0] - v2.getData()[0]; temp[1] = v1.getData()[1] - v2.getData()[1]; temp[2] = v1.getData()[2] - v2.getData()[2]; return new Vec3F(temp[0], temp[1], temp[2]); } public static Vec3F Vec3FScale(Vec3F v, float s) { temp[0] = v.getData()[0] * s; temp[1] = v.getData()[1] * s; temp[2] = v.getData()[2] * s; return new Vec3F(temp[0], temp[1], temp[2]); } public static float Vec3FDot(Vec3F v1, Vec3F v2) { return v1.getData()[0] * v2.getData()[0] + v1.getData()[1] * v2.getData()[1] + v1.getData()[2] * v2.getData()[2]; } public static Vec3F Vec3FCross(Vec3F v1, Vec3F v2) { temp[0] = v1.getData()[1] * v2.getData()[2] - v1.getData()[2] * v2.getData()[1]; temp[1] = v1.getData()[2] * v2.getData()[0] - v1.getData()[0] * v2.getData()[2]; temp[2] = v1.getData()[0] * v2.getData()[1] - v1.getData()[1] * v2.getData()[0]; return new Vec3F(temp[0], temp[1], temp[2]); } public static Vec3F Vec3FNormalize(Vec3F v) { float length = (float) Math .sqrt(v.getData()[0] * v.getData()[0] + v.getData()[1] * v.getData()[1] + v.getData()[2] * v.getData()[2]); if (length != 0.0f) length = 1.0f / length; temp[0] = v.getData()[0] * length; temp[1] = v.getData()[1] * length; temp[2] = v.getData()[2] * length; return new Vec3F(temp[0], temp[1], temp[2]); } public static Vec3F Vec3FTransform(Vec3F v, Matrix44F m) { float lambda; lambda = m.getData()[12] * v.getData()[0] + m.getData()[13] * v.getData()[1] + m.getData()[14] * v.getData()[2] + m.getData()[15]; temp[0] = m.getData()[0] * v.getData()[0] + m.getData()[1] * v.getData()[1] + m.getData()[2] * v.getData()[2] + m.getData()[3]; temp[1] = m.getData()[4] * v.getData()[0] + m.getData()[5] * v.getData()[1] + m.getData()[6] * v.getData()[2] + m.getData()[7]; temp[2] = m.getData()[8] * v.getData()[0] + m.getData()[9] * v.getData()[1] + m.getData()[10] * v.getData()[2] + m.getData()[11]; temp[0] /= lambda; temp[1] /= lambda; temp[2] /= lambda; return new Vec3F(temp[0], temp[1], temp[2]); } public static Vec3F Vec3FTransformNormal(Vec3F v, Matrix44F m) { temp[0] = m.getData()[0] * v.getData()[0] + m.getData()[1] * v.getData()[1] + m.getData()[2] * v.getData()[2]; temp[1] = m.getData()[4] * v.getData()[0] + m.getData()[5] * v.getData()[1] + m.getData()[6] * v.getData()[2]; temp[2] = m.getData()[8] * v.getData()[0] + m.getData()[9] * v.getData()[1] + m.getData()[10] * v.getData()[2]; return new Vec3F(temp[0], temp[1], temp[2]); } public static Vec4F Vec4FTransform(Vec4F v, Matrix44F m) { temp[0] = m.getData()[0] * v.getData()[0] + m.getData()[1] * v.getData()[1] + m.getData()[2] * v.getData()[2] + m.getData()[3] * v.getData()[3]; temp[1] = m.getData()[4] * v.getData()[0] + m.getData()[5] * v.getData()[1] + m.getData()[6] * v.getData()[2] + m.getData()[7] * v.getData()[3]; temp[2] = m.getData()[8] * v.getData()[0] + m.getData()[9] * v.getData()[1] + m.getData()[10] * v.getData()[2] + m.getData()[11] * v.getData()[3]; temp[3] = m.getData()[12] * v.getData()[0] + m.getData()[13] * v.getData()[1] + m.getData()[14] * v.getData()[2] + m.getData()[15] * v.getData()[3]; return new Vec4F(temp[0], temp[1], temp[2], temp[3]); } public static Vec4F Vec4FDiv(Vec4F v, float s) { temp[0] = v.getData()[0] / s; temp[1] = v.getData()[1] / s; temp[2] = v.getData()[2] / s; temp[3] = v.getData()[3] / s; return new Vec4F(temp[0], temp[1], temp[2], temp[3]); } public static Matrix44F Matrix44FIdentity() { Matrix44F r = new Matrix44F(); for (int i = 0; i < 16; i++) temp[i] = 0.0f; temp[0] = 1.0f; temp[5] = 1.0f; temp[10] = 1.0f; temp[15] = 1.0f; r.setData(temp); return r; } public static Matrix44F Matrix44FTranspose(Matrix44F m) { Matrix44F r = new Matrix44F(); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) temp[i * 4 + j] = m.getData()[i + 4 * j]; r.setData(temp); return r; } public static float Matrix44FDeterminate(Matrix44F m) { return m.getData()[12] * m.getData()[9] * m.getData()[6] * m.getData()[3] - m.getData()[8] * m.getData()[13] * m.getData()[6] * m.getData()[3] - m.getData()[12] * m.getData()[5] * m.getData()[10] * m.getData()[3] + m.getData()[4] * m.getData()[13] * m.getData()[10] * m.getData()[3] + m.getData()[8] * m.getData()[5] * m.getData()[14] * m.getData()[3] - m.getData()[4] * m.getData()[9] * m.getData()[14] * m.getData()[3] - m.getData()[12] * m.getData()[9] * m.getData()[2] * m.getData()[7] + m.getData()[8] * m.getData()[13] * m.getData()[2] * m.getData()[7] + m.getData()[12] * m.getData()[1] * m.getData()[10] * m.getData()[7] - m.getData()[0] * m.getData()[13] * m.getData()[10] * m.getData()[7] - m.getData()[8] * m.getData()[1] * m.getData()[14] * m.getData()[7] + m.getData()[0] * m.getData()[9] * m.getData()[14] * m.getData()[7] + m.getData()[12] * m.getData()[5] * m.getData()[2] * m.getData()[11] - m.getData()[4] * m.getData()[13] * m.getData()[2] * m.getData()[11] - m.getData()[12] * m.getData()[1] * m.getData()[6] * m.getData()[11] + m.getData()[0] * m.getData()[13] * m.getData()[6] * m.getData()[11] + m.getData()[4] * m.getData()[1] * m.getData()[14] * m.getData()[11] - m.getData()[0] * m.getData()[5] * m.getData()[14] * m.getData()[11] - m.getData()[8] * m.getData()[5] * m.getData()[2] * m.getData()[15] + m.getData()[4] * m.getData()[9] * m.getData()[2] * m.getData()[15] + m.getData()[8] * m.getData()[1] * m.getData()[6] * m.getData()[15] - m.getData()[0] * m.getData()[9] * m.getData()[6] * m.getData()[15] - m.getData()[4] * m.getData()[1] * m.getData()[10] * m.getData()[15] + m.getData()[0] * m.getData()[5] * m.getData()[10] * m.getData()[15]; } public static Matrix44F Matrix44FInverse(Matrix44F m) { Matrix44F r = new Matrix44F(); float det = 1.0f / Matrix44FDeterminate(m); temp[0] = m.getData()[6] * m.getData()[11] * m.getData()[13] - m.getData()[7] * m.getData()[10] * m.getData()[13] + m.getData()[7] * m.getData()[9] * m.getData()[14] - m.getData()[5] * m.getData()[11] * m.getData()[14] - m.getData()[6] * m.getData()[9] * m.getData()[15] + m.getData()[5] * m.getData()[10] * m.getData()[15]; temp[4] = m.getData()[3] * m.getData()[10] * m.getData()[13] - m.getData()[2] * m.getData()[11] * m.getData()[13] - m.getData()[3] * m.getData()[9] * m.getData()[14] + m.getData()[1] * m.getData()[11] * m.getData()[14] + m.getData()[2] * m.getData()[9] * m.getData()[15] - m.getData()[1] * m.getData()[10] * m.getData()[15]; temp[8] = m.getData()[2] * m.getData()[7] * m.getData()[13] - m.getData()[3] * m.getData()[6] * m.getData()[13] + m.getData()[3] * m.getData()[5] * m.getData()[14] - m.getData()[1] * m.getData()[7] * m.getData()[14] - m.getData()[2] * m.getData()[5] * m.getData()[15] + m.getData()[1] * m.getData()[6] * m.getData()[15]; temp[12] = m.getData()[3] * m.getData()[6] * m.getData()[9] - m.getData()[2] * m.getData()[7] * m.getData()[9] - m.getData()[3] * m.getData()[5] * m.getData()[10] + m.getData()[1] * m.getData()[7] * m.getData()[10] + m.getData()[2] * m.getData()[5] * m.getData()[11] - m.getData()[1] * m.getData()[6] * m.getData()[11]; temp[1] = m.getData()[7] * m.getData()[10] * m.getData()[12] - m.getData()[6] * m.getData()[11] * m.getData()[12] - m.getData()[7] * m.getData()[8] * m.getData()[14] + m.getData()[4] * m.getData()[11] * m.getData()[14] + m.getData()[6] * m.getData()[8] * m.getData()[15] - m.getData()[4] * m.getData()[10] * m.getData()[15]; temp[5] = m.getData()[2] * m.getData()[11] * m.getData()[12] - m.getData()[3] * m.getData()[10] * m.getData()[12] + m.getData()[3] * m.getData()[8] * m.getData()[14] - m.getData()[0] * m.getData()[11] * m.getData()[14] - m.getData()[2] * m.getData()[8] * m.getData()[15] + m.getData()[0] * m.getData()[10] * m.getData()[15]; temp[9] = m.getData()[3] * m.getData()[6] * m.getData()[12] - m.getData()[2] * m.getData()[7] * m.getData()[12] - m.getData()[3] * m.getData()[4] * m.getData()[14] + m.getData()[0] * m.getData()[7] * m.getData()[14] + m.getData()[2] * m.getData()[4] * m.getData()[15] - m.getData()[0] * m.getData()[6] * m.getData()[15]; temp[13] = m.getData()[2] * m.getData()[7] * m.getData()[8] - m.getData()[3] * m.getData()[6] * m.getData()[8] + m.getData()[3] * m.getData()[4] * m.getData()[10] - m.getData()[0] * m.getData()[7] * m.getData()[10] - m.getData()[2] * m.getData()[4] * m.getData()[11] + m.getData()[0] * m.getData()[6] * m.getData()[11]; temp[2] = m.getData()[5] * m.getData()[11] * m.getData()[12] - m.getData()[7] * m.getData()[9] * m.getData()[12] + m.getData()[7] * m.getData()[8] * m.getData()[13] - m.getData()[4] * m.getData()[11] * m.getData()[13] - m.getData()[5] * m.getData()[8] * m.getData()[15] + m.getData()[4] * m.getData()[9] * m.getData()[15]; temp[6] = m.getData()[3] * m.getData()[9] * m.getData()[12] - m.getData()[1] * m.getData()[11] * m.getData()[12] - m.getData()[3] * m.getData()[8] * m.getData()[13] + m.getData()[0] * m.getData()[11] * m.getData()[13] + m.getData()[1] * m.getData()[8] * m.getData()[15] - m.getData()[0] * m.getData()[9] * m.getData()[15]; temp[10] = m.getData()[1] * m.getData()[7] * m.getData()[12] - m.getData()[3] * m.getData()[5] * m.getData()[12] + m.getData()[3] * m.getData()[4] * m.getData()[13] - m.getData()[0] * m.getData()[7] * m.getData()[13] - m.getData()[1] * m.getData()[4] * m.getData()[15] + m.getData()[0] * m.getData()[5] * m.getData()[15]; temp[14] = m.getData()[3] * m.getData()[5] * m.getData()[8] - m.getData()[1] * m.getData()[7] * m.getData()[8] - m.getData()[3] * m.getData()[4] * m.getData()[9] + m.getData()[0] * m.getData()[7] * m.getData()[9] + m.getData()[1] * m.getData()[4] * m.getData()[11] - m.getData()[0] * m.getData()[5] * m.getData()[11]; temp[3] = m.getData()[6] * m.getData()[9] * m.getData()[12] - m.getData()[5] * m.getData()[10] * m.getData()[12] - m.getData()[6] * m.getData()[8] * m.getData()[13] + m.getData()[4] * m.getData()[10] * m.getData()[13] + m.getData()[5] * m.getData()[8] * m.getData()[14] - m.getData()[4] * m.getData()[9] * m.getData()[14]; temp[7] = m.getData()[1] * m.getData()[10] * m.getData()[12] - m.getData()[2] * m.getData()[9] * m.getData()[12] + m.getData()[2] * m.getData()[8] * m.getData()[13] - m.getData()[0] * m.getData()[10] * m.getData()[13] - m.getData()[1] * m.getData()[8] * m.getData()[14] + m.getData()[0] * m.getData()[9] * m.getData()[14]; temp[11] = m.getData()[2] * m.getData()[5] * m.getData()[12] - m.getData()[1] * m.getData()[6] * m.getData()[12] - m.getData()[2] * m.getData()[4] * m.getData()[13] + m.getData()[0] * m.getData()[6] * m.getData()[13] + m.getData()[1] * m.getData()[4] * m.getData()[14] - m.getData()[0] * m.getData()[5] * m.getData()[14]; temp[15] = m.getData()[1] * m.getData()[6] * m.getData()[8] - m.getData()[2] * m.getData()[5] * m.getData()[8] + m.getData()[2] * m.getData()[4] * m.getData()[9] - m.getData()[0] * m.getData()[6] * m.getData()[9] - m.getData()[1] * m.getData()[4] * m.getData()[10] + m.getData()[0] * m.getData()[5] * m.getData()[10]; for (int i = 0; i < 16; i++) temp[i] *= det; r.setData(temp); return r; } public static Vec3F linePlaneIntersection(Vec3F lineStart, Vec3F lineEnd, Vec3F pointOnPlane, Vec3F planeNormal) { Vec3F lineDir = Vec3FSub(lineEnd, lineStart); lineDir = Vec3FNormalize(lineDir); Vec3F planeDir = Vec3FSub(pointOnPlane, lineStart); float n = Vec3FDot(planeNormal, planeDir); float d = Vec3FDot(planeNormal, lineDir); if (Math.abs(d) < 0.00001) { // Line is parallel to plane return null; } float dist = n / d; Vec3F offset = Vec3FScale(lineDir, dist); return Vec3FAdd(lineStart, offset); } private static void projectScreenPointToPlane(Matrix44F inverseProjMatrix, Matrix44F modelViewMatrix, float screenWidth, float screenHeight, Vec2F point, Vec3F planeCenter, Vec3F planeNormal) { // Window Coordinates to Normalized Device Coordinates VideoBackgroundConfig config = Renderer.getInstance() .getVideoBackgroundConfig(); float halfScreenWidth = screenWidth / 2.0f; float halfScreenHeight = screenHeight / 2.0f; float halfViewportWidth = config.getSize().getData()[0] / 2.0f; float halfViewportHeight = config.getSize().getData()[1] / 2.0f; float x = (point.getData()[0] - halfScreenWidth) / halfViewportWidth; float y = (point.getData()[1] - halfScreenHeight) / halfViewportHeight * -1; Vec4F ndcNear = new Vec4F(x, y, -1, 1); Vec4F ndcFar = new Vec4F(x, y, 1, 1); // Normalized Device Coordinates to Eye Coordinates Vec4F pointOnNearPlane = Vec4FTransform(ndcNear, inverseProjMatrix); Vec4F pointOnFarPlane = Vec4FTransform(ndcFar, inverseProjMatrix); pointOnNearPlane = Vec4FDiv(pointOnNearPlane, pointOnNearPlane.getData()[3]); pointOnFarPlane = Vec4FDiv(pointOnFarPlane, pointOnFarPlane.getData()[3]); // Eye Coordinates to Object Coordinates Matrix44F inverseModelViewMatrix = Matrix44FInverse(modelViewMatrix); Vec4F nearWorld = Vec4FTransform(pointOnNearPlane, inverseModelViewMatrix); Vec4F farWorld = Vec4FTransform(pointOnFarPlane, inverseModelViewMatrix); mLineStart = new Vec3F(nearWorld.getData()[0], nearWorld.getData()[1], nearWorld.getData()[2]); mLineEnd = new Vec3F(farWorld.getData()[0], farWorld.getData()[1], farWorld.getData()[2]); mIntersection = linePlaneIntersection(mLineStart, mLineEnd, planeCenter, planeNormal); if (mIntersection == null) Log.e(LOGTAG, "No intersection with the plane"); } public static Vec3F getPointToPlaneIntersection( Matrix44F inverseProjMatrix, Matrix44F modelViewMatrix, float screenWidth, float screenHeight, Vec2F point, Vec3F planeCenter, Vec3F planeNormal) { projectScreenPointToPlane(inverseProjMatrix, modelViewMatrix, screenWidth, screenHeight, point, planeCenter, planeNormal); return mIntersection; } public static Vec3F getPointToPlaneLineStart(Matrix44F inverseProjMatrix, Matrix44F modelViewMatrix, float screenWidth, float screenHeight, Vec2F point, Vec3F planeCenter, Vec3F planeNormal) { projectScreenPointToPlane(inverseProjMatrix, modelViewMatrix, screenWidth, screenHeight, point, planeCenter, planeNormal); return mLineStart; } public static Vec3F getPointToPlaneLineEnd(Matrix44F inverseProjMatrix, Matrix44F modelViewMatrix, float screenWidth, float screenHeight, Vec2F point, Vec3F planeCenter, Vec3F planeNormal) { projectScreenPointToPlane(inverseProjMatrix, modelViewMatrix, screenWidth, screenHeight, point, planeCenter, planeNormal); return mLineEnd; } }
/* * 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.addthis.basis.util; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.instrument.Instrumentation; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * estimates the retained size of an object graph in memory */ public final class MemoryCounter { private static final ConcurrentHashMap<Class<?>, FieldCache[]> fieldCache = new ConcurrentHashMap<>(); private static final Map<Class<?>, MemEstimator> estimators = new IdentityHashMap<>(); private static Instrumentation instrumentation; private static final int booleanClass = boolean.class.hashCode(); private static final int byteClass = byte.class.hashCode(); private static final int charClass = char.class.hashCode(); private static final int shortClass = short.class.hashCode(); private static final int intClass = int.class.hashCode(); private static final int floatClass = float.class.hashCode(); private static final int doubleClass = double.class.hashCode(); private static final int longClass = long.class.hashCode(); public static void premain(String args, Instrumentation inst) { System.out.println("using native jvm instrumentation: " + inst); instrumentation = inst; } public static void registerEstimator(Class<?> clazz, MemEstimator est) { estimators.put(clazz, est); } static { registerEstimator(String.class, new StringEstimator()); } /** * control sizing estimation */ @Retention(RetentionPolicy.RUNTIME) public static @interface Mem { boolean estimate() default true; int size() default -1; } public static interface MemEstimator { public long getMemorySize(Object object); } public static class StringEstimator implements MemEstimator { private static final long base_size = estimateSize(new String("")); @Override public long getMemorySize(Object object) { return base_size + (((String) object).length() * 2); } } private final Map<Object, Object> visited = new IdentityHashMap<>(); private final LinkedList<Object> stack = new LinkedList<>(); /** * public api for static use */ public static long estimateSize(Object o) { return new MemoryCounter().estimate(o); } private long estimate(Object obj) { long result = _estimate(obj); while (!stack.isEmpty()) { result += _estimate(stack.pop()); } return result; } private boolean skipObject(Object obj) { return (obj == null) || visited.containsKey(obj); } /** * cache relevant field info */ private static FieldCache[] getFieldCache(Class<?> clazz) { FieldCache fields[] = fieldCache.get(clazz); if (fields == null) { Field[] rawfields = clazz.getDeclaredFields(); ArrayList<FieldCache> list = new ArrayList<>(rawfields.length); for (Field rawfield : rawfields) { if (!(Modifier.isStatic(rawfield.getModifiers()) || rawfield.isSynthetic())) { FieldCache cachedField = new FieldCache(); cachedField.field = rawfield; if (cachedField.field.getType().isPrimitive()) { cachedField.primitive = getPrimitiveFieldSize(cachedField.field.getType()); } else { cachedField.policy = cachedField.field.getAnnotation(Mem.class); cachedField.field.setAccessible(true); } list.add(cachedField); } } fields = list.toArray(new FieldCache[list.size()]); fieldCache.put(clazz, fields); } return fields; } private long _estimate(Object obj) { if (skipObject(obj)) { return 0; } visited.put(obj, null); long result = 0; Class<?> clazz = obj.getClass(); if (clazz.isArray()) { return _estimateArray(obj); } if (clazz == Thread.class || clazz == ThreadGroup.class) { System.err.println("estimator rejecting " + clazz + " = " + obj); return 0; } MemEstimator est = estimators.get(clazz); if (est != null) { return roundUpToNearestEightBytes(est.getMemorySize(obj)); } if (instrumentation != null) { result = instrumentation.getObjectSize(obj); } while (clazz != null) { FieldCache fields[] = getFieldCache(clazz); for (FieldCache field : fields) { if (field.primitive > 0) { if (instrumentation == null) { result += field.primitive; } } else { Annotation policy = field.policy; if (policy != null) { Mem mp = (Mem) policy; if (mp.size() >= 0) { result += mp.size(); continue; } if (!mp.estimate()) { continue; } } if (instrumentation == null) { result += getPointerSize(); } try { Object toBeDone = field.field.get(obj); if (toBeDone != null) { stack.add(toBeDone); } } catch (IllegalAccessException ex) { assert false; } } } clazz = clazz.getSuperclass(); } return roundUpToNearestEightBytes(result + getClassSize()); } private long roundUpToNearestEightBytes(long result) { long mod = result % 8; if (mod != 0) { result += 8 - mod; } return result; } private long _estimateArray(Object obj) { long result = 16; int length = Array.getLength(obj); if (length != 0) { Class<?> arrayElementClazz = obj.getClass().getComponentType(); if (arrayElementClazz.isPrimitive()) { result += length * getPrimitiveArrayElementSize(arrayElementClazz); } else { for (int i = 0; i < length; i++) { result += getPointerSize() + _estimate(Array.get(obj, i)); } } } return result; } private static int getPrimitiveFieldSize(Class<?> clazz) { int hc = clazz.hashCode(); if (hc == booleanClass) { return 1; } if (hc == byteClass) { return 1; } if (hc == charClass) { return 2; } if (hc == shortClass) { return 2; } if (hc == intClass) { return 4; } if (hc == floatClass) { return 4; } if (hc == doubleClass) { return 8; } if (hc == longClass) { return 8; } return 0; } private static int getPrimitiveArrayElementSize(Class<?> clazz) { return getPrimitiveFieldSize(clazz); } private static int getPointerSize() { return 4; } private static int getClassSize() { return 8; } /** * cache object for a class' field */ private static final class FieldCache { private Field field; private int primitive; private Annotation policy; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.twill.internal.yarn; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.NodeReport; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.YarnClientApplication; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.twill.api.Configs; import org.apache.twill.api.TwillSpecification; import org.apache.twill.internal.ProcessController; import org.apache.twill.internal.ProcessLauncher; import org.apache.twill.internal.appmaster.ApplicationMasterInfo; import org.apache.twill.internal.appmaster.ApplicationMasterProcessLauncher; import org.apache.twill.internal.appmaster.ApplicationSubmitter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import javax.annotation.Nullable; /** * <p> * The service implementation of {@link YarnAppClient} for Apache Hadoop 2.1 and beyond. * * The {@link VersionDetectYarnAppClientFactory} class will decide to return instance of this class for * Apache Hadoop 2.1 and beyond. * </p> */ @SuppressWarnings("unused") public class Hadoop21YarnAppClient implements YarnAppClient { private static final Logger LOG = LoggerFactory.getLogger(Hadoop21YarnAppClient.class); private final Configuration configuration; public Hadoop21YarnAppClient(Configuration configuration) { this.configuration = configuration; } // Creates and starts a yarn client private YarnClient createYarnClient() { YarnClient yarnClient = YarnClient.createYarnClient(); yarnClient.init(configuration); yarnClient.start(); return yarnClient; } @Override public ProcessLauncher<ApplicationMasterInfo> createLauncher(TwillSpecification twillSpec, @Nullable String schedulerQueue) throws Exception { YarnClient yarnClient = createYarnClient(); try { // Request for new application YarnClientApplication application = yarnClient.createApplication(); final GetNewApplicationResponse response = application.getNewApplicationResponse(); final ApplicationId appId = response.getApplicationId(); // Setup the context for application submission final ApplicationSubmissionContext appSubmissionContext = application.getApplicationSubmissionContext(); appSubmissionContext.setApplicationId(appId); appSubmissionContext.setApplicationName(twillSpec.getName()); if (schedulerQueue != null) { appSubmissionContext.setQueue(schedulerQueue); } // Set the resource requirement for AM int memoryMB = configuration.getInt(Configs.Keys.YARN_AM_MEMORY_MB, Configs.Defaults.YARN_AM_MEMORY_MB); final Resource capability = adjustMemory(response, Resource.newInstance(memoryMB, 1)); ApplicationMasterInfo appMasterInfo = new ApplicationMasterInfo(appId, capability.getMemory(), capability.getVirtualCores()); ApplicationSubmitter submitter = new ApplicationSubmitter() { @Override public ProcessController<YarnApplicationReport> submit(YarnLaunchContext context) { ContainerLaunchContext launchContext = context.getLaunchContext(); YarnClient yarnClient = createYarnClient(); try { addRMToken(launchContext, yarnClient, appId); appSubmissionContext.setAMContainerSpec(launchContext); appSubmissionContext.setResource(capability); appSubmissionContext.setMaxAppAttempts(2); yarnClient.submitApplication(appSubmissionContext); return new ProcessControllerImpl(appId); } catch (YarnException | IOException e) { throw new RuntimeException("Failed to submit application " + appId, e); } finally { yarnClient.stop(); } } }; return new ApplicationMasterProcessLauncher(appMasterInfo, submitter); } finally { yarnClient.stop(); } } private Resource adjustMemory(GetNewApplicationResponse response, Resource capability) { int maxMemory = response.getMaximumResourceCapability().getMemory(); int updatedMemory = capability.getMemory(); if (updatedMemory > maxMemory) { capability.setMemory(maxMemory); } return capability; } /** * Adds RM delegation token to the given {@link ContainerLaunchContext} so that the AM can authenticate itself * with RM using the delegation token. */ protected void addRMToken(ContainerLaunchContext context, YarnClient yarnClient, ApplicationId appId) { if (!UserGroupInformation.isSecurityEnabled()) { return; } try { Credentials credentials = YarnUtils.decodeCredentials(context.getTokens()); Configuration config = yarnClient.getConfig(); Token<TokenIdentifier> token = ConverterUtils.convertFromYarn( yarnClient.getRMDelegationToken(new Text(YarnUtils.getYarnTokenRenewer(config))), YarnUtils.getRMAddress(config)); LOG.debug("Added RM delegation token {} for application {}", token, appId); credentials.addToken(token.getService(), token); context.setTokens(YarnUtils.encodeCredentials(credentials)); } catch (YarnException | IOException e) { throw new RuntimeException("Failed to acquire RM delegation token", e); } } @Override public ProcessLauncher<ApplicationMasterInfo> createLauncher(String user, TwillSpecification twillSpec, @Nullable String schedulerQueue) throws Exception { // Ignore user return createLauncher(twillSpec, schedulerQueue); } @Override public ProcessController<YarnApplicationReport> createProcessController(ApplicationId appId) { return new ProcessControllerImpl(appId); } @Override public List<NodeReport> getNodeReports() throws Exception { YarnClient yarnClient = createYarnClient(); try { return yarnClient.getNodeReports(); } finally { yarnClient.stop(); } } private final class ProcessControllerImpl implements ProcessController<YarnApplicationReport> { private final ApplicationId appId; ProcessControllerImpl(ApplicationId appId) { this.appId = appId; } @Override public YarnApplicationReport getReport() { YarnClient yarnClient = createYarnClient(); try { return new Hadoop21YarnApplicationReport(yarnClient.getApplicationReport(appId)); } catch (YarnException | IOException e) { throw new RuntimeException("Failed to get application report for " + appId, e); } finally { yarnClient.stop(); } } @Override public void cancel() { YarnClient yarnClient = createYarnClient(); try { yarnClient.killApplication(appId); } catch (YarnException | IOException e) { throw new RuntimeException("Failed to kill application " + appId, e); } finally { yarnClient.stop(); } } @Override public void close() throws Exception { // no-op } } }
/* * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. */ package gov.nasa.asteroid.hunter.services.impl; import gov.nasa.asteroid.hunter.LoggingHelper; import gov.nasa.asteroid.hunter.Helper; import gov.nasa.asteroid.hunter.models.HelpItem; import gov.nasa.asteroid.hunter.models.HelpItemSearchCriteria; import gov.nasa.asteroid.hunter.models.HelpTopic; import gov.nasa.asteroid.hunter.models.SearchResult; import gov.nasa.asteroid.hunter.services.HelpService; import gov.nasa.asteroid.hunter.services.ServiceException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; /** * <p> * This class is the implementation of HelpService. * </p> * * <p> * This service provides methods to access help contents. * </p> * * <p> * <b>Thread Safety:</b> This class is effectively thread safe (injected * configurations are not considered as thread safety factor). * </p> * * @author albertwang, TCSASSEMBLER * @version 1.0 */ public class HelpServiceImpl extends BasePersistenceService implements HelpService { /** * <p> * Represents the name of the class for logging. * </p> */ private static final String CLASS_NAME = HelpServiceImpl.class.getName(); /** * <p> * Represents the percent mark use for like query in JQL. * </p> */ private static final String PERCENT_MARK = "%"; /** * <p> * Represents the parameter name of the keyword. * </p> */ private static final String KEYWORD_PARAMETER_NAME = "keyword"; /** * <p> * Represents the parameter name of the topic id. * </p> */ private static final String TOPIC_ID_PARAMETER_NAME = "topicId"; /** * <p> * Represents the keyword where cause. * </p> */ private static final String KEYWORD_WHERE_CAUSE = " AND (UPPER(e.content) LIKE UPPER(:keyword) OR UPPER(e.title) LIKE UPPER(:keyword))"; /** * <p> * Represents the topic id where cause. * </p> */ private static final String TOPIC_ID_WHERE_CAUSE = " AND e.topic.id = :topicId"; /** * <p> * Represents the prefix of the where cause. * </p> */ private static final String WHERE_CAUSE_PREFIX = "1 = 1"; /** * <p> * Represents the query to select the topics. * </p> */ private static final String SELECT_TOPIC_QUERY = "SELECT t FROM HelpTopic t"; /** * <p> * This is the default constructor of <code>HelpServiceImpl</code>. * </p> */ public HelpServiceImpl() { // does nothing } /** * <p> * Get all help topics. * </p> * @return the topics * * @throws ServiceException if any error occurred during the operation */ @Override public List<HelpTopic> getHelpTopics() throws ServiceException { // prepare for logging Logger logger = getLogger(); final String signature = CLASS_NAME + ".getHelpTopics()"; // log the entrance LoggingHelper.logEntrance(logger, signature, null, null); try { List<HelpTopic> result = Helper.getResultList(logger, signature, getEntityManager().createQuery(SELECT_TOPIC_QUERY, HelpTopic.class)); // log the exit LoggingHelper.logExit(logger, signature, new Object[] {result}); return result; } catch (ServiceException e) { // log the error and re-throw throw LoggingHelper.logException(logger, signature, e); } } /** * <p> * This method is used to search help items. * </p> * * @param criteria the search criteria * @return the search result. * * @throws IllegalArgumentException if criteria is null or invalid * @throws ServiceException if any other error occurred during the operation * */ @Override public SearchResult<HelpItem> searchHelpItems(HelpItemSearchCriteria criteria) throws ServiceException { // prepare for logging Logger logger = getLogger(); final String signature = CLASS_NAME + ".searchHelperItems(HelpItemSearchCriteria)"; // log the entrance LoggingHelper.logEntrance(logger, signature, new String[] {"criteria"}, new Object[] {criteria}); // validate the parameters Helper.checkBaseSearchParameters(logger, signature, "criteria", criteria, Arrays.asList("id", "title", "content")); StringBuffer sb = new StringBuffer(WHERE_CAUSE_PREFIX); Map<String, Object> queryParameters = new HashMap<String, Object>(); // Append criteria if (criteria.getTopicId() != null) { sb.append(TOPIC_ID_WHERE_CAUSE); queryParameters.put(TOPIC_ID_PARAMETER_NAME, criteria.getTopicId()); } if (criteria.getKeyword() != null && criteria.getKeyword().trim().length() > 0) { sb.append(KEYWORD_WHERE_CAUSE); queryParameters.put(KEYWORD_PARAMETER_NAME, PERCENT_MARK + criteria.getKeyword() + PERCENT_MARK); } try { SearchResult<HelpItem> result = search(criteria, sb.toString(), queryParameters, HelpItem.class); // log the exit LoggingHelper.logExit(logger, signature, new Object[] {result}); return result; } catch (ServiceException e) { // log the exception and re-throw throw LoggingHelper.logException(logger, signature, e); } } /** * <p> * This method is used to retrieve a help item. * </p> * * @param id the ID of the help item * * @return the help item, null will be returned if there's no such entity. * * @throws IllegalArgumentException: if id is not positive * @throws ServiceException if any other error occurred during the operation * */ @Override public HelpItem getHelpItem(long id) throws ServiceException { // prepare for logging Logger logger = getLogger(); final String signature = CLASS_NAME + ".getHelpItem(long)"; // log the entrance LoggingHelper.logEntrance(logger, signature, new String[] { "id" }, new Object[] { id }); // check the parameters Helper.checkPositive(logger, signature, "id", id); try { HelpItem result = getEntityManager().find(HelpItem.class, id); // log the exit LoggingHelper.logExit(logger, signature, new Object[] { result }); return result; } catch (IllegalArgumentException e) { throw LoggingHelper.logException(logger, signature, new ServiceException("Failed to get the result.", e)); } } }
package ca.uhn.fhir.jpa.provider.dstu3; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.hl7.fhir.dstu3.hapi.validation.FhirInstanceValidator; import org.hl7.fhir.dstu3.model.*; import org.hl7.fhir.dstu3.model.Bundle.BundleType; import org.hl7.fhir.dstu3.model.Bundle.HTTPVerb; import org.hl7.fhir.dstu3.model.Enumerations.AdministrativeGender; import org.hl7.fhir.instance.model.api.IIdType; import org.junit.*; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.dao.dstu3.BaseJpaDstu3Test; import ca.uhn.fhir.jpa.provider.SystemProviderDstu2Test; import ca.uhn.fhir.jpa.rp.dstu3.*; import ca.uhn.fhir.jpa.testutil.RandomServerPortProvider; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.EncodingEnum; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.interceptor.SimpleRequestHeaderInterceptor; import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException; import ca.uhn.fhir.rest.server.interceptor.RequestValidatingInterceptor; import ca.uhn.fhir.rest.server.interceptor.ResponseHighlighterInterceptor; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.validation.ResultSeverityEnum; public class SystemProviderDstu3Test extends BaseJpaDstu3Test { private static RestfulServer myRestServer; private static IGenericClient ourClient; private static FhirContext ourCtx; private static CloseableHttpClient ourHttpClient; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SystemProviderDstu3Test.class); private static Server ourServer; private static String ourServerBase; private SimpleRequestHeaderInterceptor mySimpleHeaderInterceptor; @Test public void testTransactionWithInlineConditionalUrl() throws Exception { myDaoConfig.setAllowInlineMatchUrlReferences(true); Patient p = new Patient(); p.addName().setFamily("van de Heuvelcx85ioqWJbI").addGiven("Pietercx85ioqWJbI"); myPatientDao.create(p, mySrd); Organization o = new Organization(); o.addIdentifier().setSystem("urn:oid:2.16.840.1.113883.2.4.6.1").setValue("07-8975469"); myOrganizationDao.create(o, mySrd); //@formatter:off String input = "<Bundle xmlns=\"http://hl7.org/fhir\">\n" + " <id value=\"20160113160203\"/>\n" + " <type value=\"transaction\"/>\n" + " <entry>\n" + " <fullUrl value=\"urn:uuid:c72aa430-2ddc-456e-7a09-dea8264671d8\"/>\n" + " <resource>\n" + " <Encounter>\n" + " <identifier>\n" + " <use value=\"official\"/>\n" + " <system value=\"http://healthcare.example.org/identifiers/encounter\"/>\n" + " <value value=\"845962.8975469\"/>\n" + " </identifier>\n" + " <status value=\"in-progress\"/>\n" + " <class value=\"inpatient\"/>\n" + " <patient>\n" + " <reference value=\"Patient?family=van%20de%20Heuvelcx85ioqWJbI&amp;given=Pietercx85ioqWJbI\"/>\n" + " </patient>\n" + " <serviceProvider>\n" + " <reference value=\"Organization?identifier=urn:oid:2.16.840.1.113883.2.4.6.1|07-8975469\"/>\n" + " </serviceProvider>\n" + " </Encounter>\n" + " </resource>\n" + " <request>\n" + " <method value=\"POST\"/>\n" + " <url value=\"Encounter\"/>\n" + " </request>\n" + " </entry>\n" + "</Bundle>"; //@formatter:off HttpPost req = new HttpPost(ourServerBase); req.setEntity(new StringEntity(input, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); CloseableHttpResponse resp = ourHttpClient.execute(req); try { String encoded = IOUtils.toString(resp.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(encoded); assertThat(encoded, containsString("transaction-response")); } finally { IOUtils.closeQuietly(resp.getEntity().getContent()); } } @Test public void testTransactionDeleteWithDuplicateDeletes() throws Exception { myDaoConfig.setAllowInlineMatchUrlReferences(true); Patient p = new Patient(); p.addName().setFamily("van de Heuvelcx85ioqWJbI").addGiven("Pietercx85ioqWJbI"); IIdType id = myPatientDao.create(p, mySrd).getId().toUnqualifiedVersionless(); ourClient.read().resource(Patient.class).withId(id); Bundle inputBundle = new Bundle(); inputBundle.setType(BundleType.TRANSACTION); inputBundle.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(id.getValue()); inputBundle.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(id.getValue()); inputBundle.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Patient?name=Pietercx85ioqWJbI"); String input = myFhirCtx.newXmlParser().encodeResourceToString(inputBundle); HttpPost req = new HttpPost(ourServerBase + "?_pretty=true"); req.setEntity(new StringEntity(input, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); CloseableHttpResponse resp = ourHttpClient.execute(req); try { String encoded = IOUtils.toString(resp.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(encoded); assertThat(encoded, containsString("transaction-response")); Bundle response = myFhirCtx.newXmlParser().parseResource(Bundle.class, encoded); assertEquals(3, response.getEntry().size()); } finally { IOUtils.closeQuietly(resp.getEntity().getContent()); } try { ourClient.read().resource(Patient.class).withId(id).execute(); fail(); } catch (ResourceGoneException e) { // good } } @Before public void beforeStartServer() throws Exception { if (myRestServer == null) { PatientResourceProvider patientRp = new PatientResourceProvider(); patientRp.setDao(myPatientDao); QuestionnaireResourceProviderDstu3 questionnaireRp = new QuestionnaireResourceProviderDstu3(); questionnaireRp.setDao(myQuestionnaireDao); ObservationResourceProvider observationRp = new ObservationResourceProvider(); observationRp.setDao(myObservationDao); OrganizationResourceProvider organizationRp = new OrganizationResourceProvider(); organizationRp.setDao(myOrganizationDao); RestfulServer restServer = new RestfulServer(ourCtx); restServer.setResourceProviders(patientRp, questionnaireRp, observationRp, organizationRp); restServer.setPlainProviders(mySystemProvider); int myPort = RandomServerPortProvider.findFreePort(); ourServer = new Server(myPort); ServletContextHandler proxyHandler = new ServletContextHandler(); proxyHandler.setContextPath("/"); ourServerBase = "http://localhost:" + myPort + "/fhir/context"; ServletHolder servletHolder = new ServletHolder(); servletHolder.setServlet(restServer); proxyHandler.addServlet(servletHolder, "/fhir/context/*"); ourCtx = FhirContext.forDstu3(); restServer.setFhirContext(ourCtx); ourServer.setHandler(proxyHandler); ourServer.start(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setConnectionManager(connectionManager); ourHttpClient = builder.build(); ourCtx.getRestfulClientFactory().setSocketTimeout(600 * 1000); ourClient = ourCtx.newRestfulGenericClient(ourServerBase); ourClient.setLogRequestAndResponse(true); myRestServer = restServer; } myRestServer.setDefaultResponseEncoding(EncodingEnum.XML); myRestServer.setPagingProvider(myPagingProvider); } @Before public void before() { mySimpleHeaderInterceptor = new SimpleRequestHeaderInterceptor(); ourClient.registerInterceptor(mySimpleHeaderInterceptor); } @SuppressWarnings("deprecation") @After public void after() { myRestServer.setUseBrowserFriendlyContentTypes(true); ourClient.unregisterInterceptor(mySimpleHeaderInterceptor); } @SuppressWarnings("deprecation") @Test public void testResponseUsesCorrectContentType() throws Exception { myRestServer.setUseBrowserFriendlyContentTypes(true); myRestServer.setDefaultResponseEncoding(EncodingEnum.JSON); HttpGet get = new HttpGet(ourServerBase); // get.addHeader("Accept", "application/xml, text/html"); CloseableHttpResponse http = ourHttpClient.execute(get); assertThat(http.getFirstHeader("Content-Type").getValue(), containsString("application/fhir+json")); } /** * FOrmat has changed, source is no longer valid */ @Test @Ignore public void testValidateUsingIncomingResources() throws Exception { FhirInstanceValidator val = new FhirInstanceValidator(myValidationSupport); RequestValidatingInterceptor interceptor = new RequestValidatingInterceptor(); interceptor.addValidatorModule(val); interceptor.setFailOnSeverity(ResultSeverityEnum.ERROR); interceptor.setAddResponseHeaderOnSeverity(ResultSeverityEnum.INFORMATION); myRestServer.registerInterceptor(interceptor); try { InputStream bundleRes = SystemProviderDstu2Test.class.getResourceAsStream("/questionnaire-sdc-profile-example-ussg-fht.xml"); String bundleStr = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); HttpPost req = new HttpPost(ourServerBase); req.setEntity(new StringEntity(bundleStr, ContentType.parse(Constants.CT_FHIR_XML + "; charset=utf-8"))); CloseableHttpResponse resp = ourHttpClient.execute(req); try { String encoded = IOUtils.toString(resp.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(encoded); //@formatter:off assertThat(encoded, containsString("Questionnaire/54127-6/_history/")); //@formatter:on for (Header next : resp.getHeaders(RequestValidatingInterceptor.DEFAULT_RESPONSE_HEADER_NAME)) { ourLog.info(next.toString()); } } finally { IOUtils.closeQuietly(resp.getEntity().getContent()); } } finally { myRestServer.unregisterInterceptor(interceptor); } } @Test public void testEverythingReturnsCorrectFormatInPagingLink() throws Exception { myRestServer.setDefaultResponseEncoding(EncodingEnum.JSON); myRestServer.setPagingProvider(new FifoMemoryPagingProvider(1).setDefaultPageSize(10)); ResponseHighlighterInterceptor interceptor = new ResponseHighlighterInterceptor(); myRestServer.registerInterceptor(interceptor); for (int i = 0; i < 11; i++) { Patient p = new Patient(); p.addName().setFamily("Name" + i); ourClient.create().resource(p).execute(); } HttpGet get = new HttpGet(ourServerBase + "/Patient/$everything"); get.addHeader("Accept", "application/xml, text/html"); CloseableHttpResponse http = ourHttpClient.execute(get); try { String response = IOUtils.toString(http.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(response); assertThat(response, containsString("_format=json")); assertEquals(200, http.getStatusLine().getStatusCode()); } finally { http.close(); } myRestServer.unregisterInterceptor(interceptor); } @Test public void testEverythingReturnsCorrectBundleType() throws Exception { myRestServer.setDefaultResponseEncoding(EncodingEnum.JSON); myRestServer.setPagingProvider(new FifoMemoryPagingProvider(1).setDefaultPageSize(10)); ResponseHighlighterInterceptor interceptor = new ResponseHighlighterInterceptor(); myRestServer.registerInterceptor(interceptor); for (int i = 0; i < 11; i++) { Patient p = new Patient(); p.addName().setFamily("Name" + i); ourClient.create().resource(p).execute(); } HttpGet get = new HttpGet(ourServerBase + "/Patient/$everything"); get.addHeader("Accept", "application/xml+fhir"); CloseableHttpResponse http = ourHttpClient.execute(get); try { String response = IOUtils.toString(http.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(response); assertThat(response, not(containsString("_format"))); assertEquals(200, http.getStatusLine().getStatusCode()); Bundle responseBundle = ourCtx.newXmlParser().parseResource(Bundle.class, response); assertEquals(BundleType.SEARCHSET, responseBundle.getTypeElement().getValue()); } finally { http.close(); } myRestServer.unregisterInterceptor(interceptor); } @Test public void testEverythingType() throws Exception { HttpGet get = new HttpGet(ourServerBase + "/Patient/$everything"); CloseableHttpResponse http = ourHttpClient.execute(get); try { assertEquals(200, http.getStatusLine().getStatusCode()); } finally { http.close(); } } @Test public void testMarkResourcesForReindexing() throws Exception { HttpGet get = new HttpGet(ourServerBase + "/$mark-all-resources-for-reindexing"); CloseableHttpResponse http = ourHttpClient.execute(get); try { String output = IOUtils.toString(http.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(output); assertEquals(200, http.getStatusLine().getStatusCode()); } finally { IOUtils.closeQuietly(http);; } } @Transactional(propagation = Propagation.NEVER) @Test public void testSuggestKeywords() throws Exception { Patient patient = new Patient(); patient.addName().setFamily("testSuggest"); IIdType ptId = myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless(); Observation obs = new Observation(); obs.getCode().setText("ZXCVBNM ASDFGHJKL QWERTYUIOPASDFGHJKL"); obs.getSubject().setReferenceElement(ptId); IIdType obsId = myObservationDao.create(obs, mySrd).getId().toUnqualifiedVersionless(); obs = new Observation(); obs.setId(obsId); obs.getSubject().setReferenceElement(ptId); obs.getCode().setText("ZXCVBNM ASDFGHJKL QWERTYUIOPASDFGHJKL"); myObservationDao.update(obs, mySrd); HttpGet get = new HttpGet(ourServerBase + "/$suggest-keywords?context=Patient/" + ptId.getIdPart() + "/$everything&searchParam=_content&text=zxc&_pretty=true&_format=xml"); CloseableHttpResponse http = ourHttpClient.execute(get); try { assertEquals(200, http.getStatusLine().getStatusCode()); String output = IOUtils.toString(http.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(output); Parameters parameters = ourCtx.newXmlParser().parseResource(Parameters.class, output); assertEquals(2, parameters.getParameter().size()); assertEquals("keyword", parameters.getParameter().get(0).getPart().get(0).getName()); assertEquals(("ZXCVBNM"), ((StringType) parameters.getParameter().get(0).getPart().get(0).getValue()).getValueAsString()); assertEquals("score", parameters.getParameter().get(0).getPart().get(1).getName()); assertEquals(("1.0"), ((DecimalType) parameters.getParameter().get(0).getPart().get(1).getValue()).getValueAsString()); } finally { http.close(); } } @Test public void testSuggestKeywordsInvalid() throws Exception { Patient patient = new Patient(); patient.addName().setFamily("testSuggest"); IIdType ptId = myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless(); Observation obs = new Observation(); obs.getSubject().setReferenceElement(ptId); obs.getCode().setText("ZXCVBNM ASDFGHJKL QWERTYUIOPASDFGHJKL"); myObservationDao.create(obs, mySrd); HttpGet get = new HttpGet(ourServerBase + "/$suggest-keywords"); CloseableHttpResponse http = ourHttpClient.execute(get); try { assertEquals(400, http.getStatusLine().getStatusCode()); String output = IOUtils.toString(http.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(output); assertThat(output, containsString("Parameter 'context' must be provided")); } finally { http.close(); } get = new HttpGet(ourServerBase + "/$suggest-keywords?context=Patient/" + ptId.getIdPart() + "/$everything"); http = ourHttpClient.execute(get); try { assertEquals(400, http.getStatusLine().getStatusCode()); String output = IOUtils.toString(http.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(output); assertThat(output, containsString("Parameter 'searchParam' must be provided")); } finally { http.close(); } get = new HttpGet(ourServerBase + "/$suggest-keywords?context=Patient/" + ptId.getIdPart() + "/$everything&searchParam=aa"); http = ourHttpClient.execute(get); try { assertEquals(400, http.getStatusLine().getStatusCode()); String output = IOUtils.toString(http.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(output); assertThat(output, containsString("Parameter 'text' must be provided")); } finally { http.close(); } } @Test public void testGetOperationDefinition() { OperationDefinition op = ourClient.read(OperationDefinition.class, "-s-get-resource-counts"); assertEquals("get-resource-counts", op.getCode()); } @Test public void testTransactionFromBundle() throws Exception { InputStream bundleRes = SystemProviderDstu3Test.class.getResourceAsStream("/transaction_link_patient_eve.xml"); String bundle = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); String response = ourClient.transaction().withBundle(bundle).prettyPrint().execute(); ourLog.info(response); } @Test public void testTransactionWithIncompleteBundle() throws Exception { Patient patient = new Patient(); patient.setGender(AdministrativeGender.MALE); Bundle bundle = new Bundle(); bundle.setType(BundleType.TRANSACTION); bundle.addEntry().setResource(patient); try { ourClient.transaction().withBundle(bundle).prettyPrint().execute(); fail(); } catch (InvalidRequestException e) { assertThat(e.toString(), containsString("missing or invalid HTTP Verb")); } } @Test public void testTransactionFromBundle2() throws Exception { InputStream bundleRes = SystemProviderDstu3Test.class.getResourceAsStream("/transaction_link_patient_eve_temp.xml"); String bundle = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); String response = ourClient.transaction().withBundle(bundle).prettyPrint().execute(); ourLog.info(response); Bundle resp = ourCtx.newXmlParser().parseResource(Bundle.class, response); IdType id1_1 = new IdType(resp.getEntry().get(0).getResponse().getLocation()); assertEquals("Provenance", id1_1.getResourceType()); IdType id1_2 = new IdType(resp.getEntry().get(1).getResponse().getLocation()); IdType id1_3 = new IdType(resp.getEntry().get(2).getResponse().getLocation()); IdType id1_4 = new IdType(resp.getEntry().get(3).getResponse().getLocation()); /* * Same bundle! */ bundleRes = SystemProviderDstu3Test.class.getResourceAsStream("/transaction_link_patient_eve_temp.xml"); bundle = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); response = ourClient.transaction().withBundle(bundle).prettyPrint().execute(); ourLog.info(response); resp = ourCtx.newXmlParser().parseResource(Bundle.class, response); IdType id2_1 = new IdType(resp.getEntry().get(0).getResponse().getLocation()); IdType id2_2 = new IdType(resp.getEntry().get(1).getResponse().getLocation()); IdType id2_3 = new IdType(resp.getEntry().get(2).getResponse().getLocation()); IdType id2_4 = new IdType(resp.getEntry().get(3).getResponse().getLocation()); assertNotEquals(id1_1.toVersionless(), id2_1.toVersionless()); assertEquals("Provenance", id2_1.getResourceType()); assertEquals(id1_2.toVersionless(), id2_2.toVersionless()); assertEquals(id1_3.toVersionless(), id2_3.toVersionless()); assertEquals(id1_4.toVersionless(), id2_4.toVersionless()); } /** * This is Gramahe's test transaction - it requires some set up in order to work */ // @Test public void testTransactionFromBundle3() throws Exception { InputStream bundleRes = SystemProviderDstu3Test.class.getResourceAsStream("/grahame-transaction.xml"); String bundle = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); String response = ourClient.transaction().withBundle(bundle).prettyPrint().execute(); ourLog.info(response); } @Test public void testTransactionFromBundle4() throws Exception { InputStream bundleRes = SystemProviderDstu3Test.class.getResourceAsStream("/simone_bundle.xml"); String bundle = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); String response = ourClient.transaction().withBundle(bundle).prettyPrint().execute(); ourLog.info(response); Bundle bundleResp = ourCtx.newXmlParser().parseResource(Bundle.class, response); IdType id = new IdType(bundleResp.getEntry().get(0).getResponse().getLocation()); assertEquals("Patient", id.getResourceType()); assertTrue(id.hasIdPart()); assertTrue(id.isIdPartValidLong()); assertTrue(id.hasVersionIdPart()); assertTrue(id.isVersionIdPartValidLong()); } @Test public void testTransactionFromBundle5() throws Exception { InputStream bundleRes = SystemProviderDstu3Test.class.getResourceAsStream("/simone_bundle2.xml"); String bundle = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); try { ourClient.transaction().withBundle(bundle).prettyPrint().execute(); fail(); } catch (InvalidRequestException e) { OperationOutcome oo = (OperationOutcome) e.getOperationOutcome(); assertEquals("Invalid placeholder ID found: uri:uuid:bb0cd4bc-1839-4606-8c46-ba3069e69b1d - Must be of the form 'urn:uuid:[uuid]' or 'urn:oid:[oid]'", oo.getIssue().get(0).getDiagnostics()); assertEquals("processing", oo.getIssue().get(0).getCode().toCode()); } } @Test public void testTransactionFromBundle6() throws Exception { InputStream bundleRes = SystemProviderDstu3Test.class.getResourceAsStream("/simone_bundle3.xml"); String bundle = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); ourClient.transaction().withBundle(bundle).prettyPrint().execute(); // try { // fail(); // } catch (InvalidRequestException e) { // OperationOutcome oo = (OperationOutcome) e.getOperationOutcome(); // assertEquals("Invalid placeholder ID found: uri:uuid:bb0cd4bc-1839-4606-8c46-ba3069e69b1d - Must be of the form 'urn:uuid:[uuid]' or 'urn:oid:[oid]'", oo.getIssue().get(0).getDiagnostics()); // assertEquals("processing", oo.getIssue().get(0).getCode()); // } } @Test public void testTransactionSearch() throws Exception { for (int i = 0; i < 20; i++) { Patient p = new Patient(); p.addName().setFamily("PATIENT_" + i); myPatientDao.create(p, mySrd); } Bundle req = new Bundle(); req.setType(BundleType.TRANSACTION); req.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient?"); Bundle resp = ourClient.transaction().withBundle(req).execute(); ourLog.info(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); assertEquals(1, resp.getEntry().size()); Bundle respSub = (Bundle) resp.getEntry().get(0).getResource(); assertEquals("self", respSub.getLink().get(0).getRelation()); assertEquals(ourServerBase + "/Patient", respSub.getLink().get(0).getUrl()); assertEquals("next", respSub.getLink().get(1).getRelation()); assertThat(respSub.getLink().get(1).getUrl(), containsString("/fhir/context?_getpages")); assertThat(respSub.getEntry().get(0).getFullUrl(), startsWith(ourServerBase + "/Patient/")); assertEquals(Patient.class, respSub.getEntry().get(0).getResource().getClass()); } @Test public void testTransactionCount() throws Exception { for (int i = 0; i < 20; i++) { Patient p = new Patient(); p.addName().setFamily("PATIENT_" + i); myPatientDao.create(p, mySrd); } Bundle req = new Bundle(); req.setType(BundleType.TRANSACTION); req.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient?_summary=count"); Bundle resp = ourClient.transaction().withBundle(req).execute(); ourLog.info(ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); assertEquals(1, resp.getEntry().size()); Bundle respSub = (Bundle) resp.getEntry().get(0).getResource(); assertEquals(20, respSub.getTotal()); assertEquals(0, respSub.getEntry().size()); } @Test public void testTransactionCreateWithPreferHeader() throws Exception { Patient p = new Patient(); p.setActive(true); Bundle req; Bundle resp; // No prefer header req = new Bundle(); req.setType(BundleType.TRANSACTION); req.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setUrl("Patient"); resp = ourClient.transaction().withBundle(req).execute(); assertEquals(null, resp.getEntry().get(0).getResource()); assertEquals("201 Created", resp.getEntry().get(0).getResponse().getStatus()); // Prefer return=minimal mySimpleHeaderInterceptor.setHeaderName(Constants.HEADER_PREFER); mySimpleHeaderInterceptor.setHeaderValue(Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_MINIMAL); req = new Bundle(); req.setType(BundleType.TRANSACTION); req.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setUrl("Patient"); resp = ourClient.transaction().withBundle(req).execute(); assertEquals(null, resp.getEntry().get(0).getResource()); assertEquals("201 Created", resp.getEntry().get(0).getResponse().getStatus()); // Prefer return=representation mySimpleHeaderInterceptor.setHeaderName(Constants.HEADER_PREFER); mySimpleHeaderInterceptor.setHeaderValue(Constants.HEADER_PREFER_RETURN + "=" + Constants.HEADER_PREFER_RETURN_REPRESENTATION); req = new Bundle(); req.setType(BundleType.TRANSACTION); req.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setUrl("Patient"); resp = ourClient.transaction().withBundle(req).execute(); assertEquals(Patient.class, resp.getEntry().get(0).getResource().getClass()); assertEquals("201 Created", resp.getEntry().get(0).getResponse().getStatus()); } @AfterClass public static void afterClassClearContext() throws Exception { ourServer.stop(); TestUtil.clearAllStaticFieldsForUnitTest(); } }
package se.itello.junitparallel; import org.junit.runner.RunWith; import org.junit.runners.Suite; import se.itello.junitparallel.faketests.TestWithManyQuickTests; @RunWith(ParallelProcessSuite.class) @Suite.SuiteClasses({ TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class, TestWithManyQuickTests.class }) public class BigParallelProcessSuite { }
package tw.com.unit; import software.amazon.awssdk.services.ec2.model.Vpc; import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.EasyMockSupport; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import software.amazon.awssdk.services.elasticloadbalancing.model.Instance; import software.amazon.awssdk.services.elasticloadbalancing.model.LoadBalancerDescription; import software.amazon.awssdk.services.elasticloadbalancing.model.Tag; import tw.com.AwsFacade; import tw.com.entity.ProjectAndEnv; import tw.com.entity.SearchCriteria; import tw.com.exceptions.CfnAssistException; import tw.com.exceptions.MustHaveBuildNumber; import tw.com.exceptions.TooManyELBException; import tw.com.providers.LoadBalancerClient; import tw.com.repository.ELBRepository; import tw.com.repository.ResourceRepository; import tw.com.repository.VpcRepository; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @RunWith(EasyMockRunner.class) public class TestELBRepository extends EasyMockSupport { private ELBRepository elbRepository; private LoadBalancerClient elbClient; private VpcRepository vpcRepository; private ResourceRepository cfnRepository; private ProjectAndEnv projAndEnv = new ProjectAndEnv("proj", "testEnv"); @Before public void beforeEachTestRuns() { elbClient = createMock(LoadBalancerClient.class); vpcRepository = createMock(VpcRepository.class); cfnRepository = createMock(ResourceRepository.class); elbRepository = new ELBRepository(elbClient, vpcRepository, cfnRepository); } @Test public void ShouldUseTagIfMoreThanOneELB() throws TooManyELBException { String typeTag = "expectedType"; List<Tag> lb1Tags = new LinkedList<>(); lb1Tags.add(createTag(AwsFacade.TYPE_TAG, "someNonMatchingTag")); List<Tag> lb2Tags = new LinkedList<>(); lb2Tags.add(createTag(AwsFacade.TYPE_TAG, typeTag)); List<LoadBalancerDescription> lbs = new LinkedList<>(); lbs.add(createELBDesc("lb1Name")); lbs.add(createELBDesc("lb2Name")); Vpc vpc = Vpc.builder().vpcId("vpcId").build(); EasyMock.expect(vpcRepository.getCopyOfVpc(projAndEnv)).andReturn(vpc); EasyMock.expect(elbClient.describeLoadBalancers()).andReturn(lbs); EasyMock.expect(elbClient.getTagsFor("lb1Name")).andReturn(lb1Tags); EasyMock.expect(elbClient.getTagsFor("lb2Name")).andReturn(lb2Tags); replayAll(); LoadBalancerDescription result = elbRepository.findELBFor(projAndEnv, typeTag); verifyAll(); assertEquals("lb2Name", result.loadBalancerName()); } private LoadBalancerDescription createELBDesc(String loadBalancerName) { return LoadBalancerDescription.builder().loadBalancerName(loadBalancerName).vpcId("vpcId").build(); } private Tag createTag(String key, String value) { return Tag.builder().key(key).value(value).build(); } @Test public void ShouldThrowIfMoreThanOneELBAndNoMatchingTags() { List<Tag> tags = new LinkedList<>(); tags.add(createTag("someOtherTag","someOtherValue")); List<LoadBalancerDescription> lbs = new LinkedList<>(); lbs.add(createELBDesc("lb1Name")); lbs.add(createELBDesc("lb2Name")); Vpc vpc = Vpc.builder().vpcId("vpcId").build(); EasyMock.expect(vpcRepository.getCopyOfVpc(projAndEnv)).andReturn(vpc); EasyMock.expect(elbClient.describeLoadBalancers()).andReturn(lbs); EasyMock.expect(elbClient.getTagsFor("lb1Name")).andReturn(new LinkedList<>()); EasyMock.expect(elbClient.getTagsFor("lb2Name")).andReturn(tags); replayAll(); try { elbRepository.findELBFor(projAndEnv,"notMatchingAnLB"); fail("should have thrown"); } catch(TooManyELBException expectedException) { // no op } verifyAll(); } @Test public void shouldFetchELBsForTheVPC() throws TooManyELBException { List<LoadBalancerDescription> lbs = new LinkedList<>(); lbs.add(LoadBalancerDescription.builder().loadBalancerName("lb1Name").vpcId("someId").build()); lbs.add(createELBDesc("lb2Name")); Vpc vpc = Vpc.builder().vpcId("vpcId").build(); EasyMock.expect(vpcRepository.getCopyOfVpc(projAndEnv)).andReturn(vpc); EasyMock.expect(elbClient.describeLoadBalancers()).andReturn(lbs); replayAll(); LoadBalancerDescription result = elbRepository.findELBFor(projAndEnv,"ignoredWhenOnlyOneMatchingLB"); assertEquals("lb2Name", result.loadBalancerName()); verifyAll(); } @Test public void shouldRegisterELBs() throws CfnAssistException { Instance insA1 = createInstance("instanceA1"); // initial Instance insA2 = createInstance("instanceA2"); // initial Instance insB1 = createInstance("instanceB1"); // new Instance insB2 = createInstance("instanceB2"); // new List<Instance> instancesThatMatch = new LinkedList<>(); instancesThatMatch.add(insA1); instancesThatMatch.add(insA2); instancesThatMatch.add(insB1); instancesThatMatch.add(insB2); List<Instance> instancesToAdd = new LinkedList<>(); instancesToAdd.add(insB1); instancesToAdd.add(insB2); List<Instance> toRemove = new LinkedList<>(); toRemove.add(insA1); toRemove.add(insA2); String vpcId = "myVPC"; Integer newBuildNumber = 11; projAndEnv.addBuildNumber(newBuildNumber); List<LoadBalancerDescription> initalLoadBalancers = new LinkedList<>(); initalLoadBalancers.add(createElbDescriptionWithInstances(vpcId, insA1, insA2)); List<LoadBalancerDescription> updatedLoadBalancers = new LinkedList<>(); updatedLoadBalancers.add( createElbDescriptionWithInstances(vpcId,insA1, insA2, insB1, insB2)); Vpc vpc = Vpc.builder().vpcId(vpcId).build(); EasyMock.expect(vpcRepository.getCopyOfVpc(projAndEnv)).andStubReturn(vpc); EasyMock.expect(elbClient.describeLoadBalancers()).andReturn(initalLoadBalancers); SearchCriteria criteria = new SearchCriteria(projAndEnv); EasyMock.expect(cfnRepository.getAllInstancesMatchingType(criteria, "typeTag")).andReturn(instancesThatMatch); elbClient.registerInstances(instancesToAdd, "lbName"); EasyMock.expectLastCall(); EasyMock.expect(elbClient.describeLoadBalancers()).andReturn(updatedLoadBalancers); EasyMock.expect(elbClient.degisterInstancesFromLB(toRemove, "lbName")).andReturn(instancesToAdd); replayAll(); List<Instance> result = elbRepository.updateInstancesMatchingBuild(projAndEnv, "typeTag"); assertEquals(2, result.size()); assertEquals(insB1.instanceId(), result.get(0).instanceId()); assertEquals(insB2.instanceId(), result.get(1).instanceId()); verifyAll(); } private LoadBalancerDescription createElbDescriptionWithInstances(String vpcId, Instance... instances) { return LoadBalancerDescription.builder(). vpcId(vpcId). instances(instances). loadBalancerName("lbName").dnsName("dnsName").build(); } private Instance createInstance(String instanceId) { return Instance.builder().instanceId(instanceId).build(); } @Test public void shouldGetInstancesForTheLB() throws TooManyELBException { String vpcId = "myVPC"; Instance insA = createInstance("instanceA"); // associated List<LoadBalancerDescription> theLB = new LinkedList<>(); theLB.add(createElbDescriptionWithInstances(vpcId,insA)); Vpc vpc = Vpc.builder().vpcId(vpcId).build(); EasyMock.expect(vpcRepository.getCopyOfVpc(projAndEnv)).andStubReturn(vpc); EasyMock.expect(elbClient.describeLoadBalancers()).andReturn(theLB); replayAll(); List<Instance> result = elbRepository.findInstancesAssociatedWithLB(projAndEnv,"typeNotUsedWhenOneMatchingLB"); verifyAll(); assertEquals(1, result.size()); assertEquals("instanceA", result.get(0).instanceId()); } @Test public void shouldThrowIfNoBuildNumberIsGiven() throws CfnAssistException { replayAll(); try { elbRepository.updateInstancesMatchingBuild(projAndEnv, "typeTag"); fail("should have thrown"); } catch(MustHaveBuildNumber expectedException) { // no op } verifyAll(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ftpserver.impl; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.ftpserver.ftplet.FtpFile; import org.apache.ftpserver.ftplet.User; /** * <strong>Internal class, do not use directly.</strong> * * This is FTP statistics implementation. * * TODO revisit concurrency, right now we're a bit over zealous with both Atomic* * counters and synchronization * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class DefaultFtpStatistics implements ServerFtpStatistics { private StatisticsObserver observer = null; private FileObserver fileObserver = null; private Date startTime = new Date(); private AtomicInteger uploadCount = new AtomicInteger(0); private AtomicInteger downloadCount = new AtomicInteger(0); private AtomicInteger deleteCount = new AtomicInteger(0); private AtomicInteger mkdirCount = new AtomicInteger(0); private AtomicInteger rmdirCount = new AtomicInteger(0); private AtomicInteger currLogins = new AtomicInteger(0); private AtomicInteger totalLogins = new AtomicInteger(0); private AtomicInteger totalFailedLogins = new AtomicInteger(0); private AtomicInteger currAnonLogins = new AtomicInteger(0); private AtomicInteger totalAnonLogins = new AtomicInteger(0); private AtomicInteger currConnections = new AtomicInteger(0); private AtomicInteger totalConnections = new AtomicInteger(0); private AtomicLong bytesUpload = new AtomicLong(0L); private AtomicLong bytesDownload = new AtomicLong(0L); private static class UserLogins { private Map<InetAddress, AtomicInteger> perAddress = new ConcurrentHashMap<InetAddress, AtomicInteger>(); public UserLogins(InetAddress address) { // init with the first connection totalLogins = new AtomicInteger(1); perAddress.put(address, new AtomicInteger(1)); } public AtomicInteger loginsFromInetAddress(InetAddress address) { AtomicInteger logins = perAddress.get(address); if (logins == null) { logins = new AtomicInteger(0); perAddress.put(address, logins); } return logins; } public AtomicInteger totalLogins; } /** *The user login information. */ private Map<String, UserLogins> userLoginTable = new ConcurrentHashMap<String, UserLogins>(); public static final String LOGIN_NUMBER = "login_number"; /** * Set the observer. */ public void setObserver(final StatisticsObserver observer) { this.observer = observer; } /** * Set the file observer. */ public void setFileObserver(final FileObserver observer) { fileObserver = observer; } // ////////////////////////////////////////////////////// // /////////////// All getter methods ///////////////// /** * Get server start time. */ public Date getStartTime() { if (startTime != null) { return (Date) startTime.clone(); } else { return null; } } /** * Get number of files uploaded. */ public int getTotalUploadNumber() { return uploadCount.get(); } /** * Get number of files downloaded. */ public int getTotalDownloadNumber() { return downloadCount.get(); } /** * Get number of files deleted. */ public int getTotalDeleteNumber() { return deleteCount.get(); } /** * Get total number of bytes uploaded. */ public long getTotalUploadSize() { return bytesUpload.get(); } /** * Get total number of bytes downloaded. */ public long getTotalDownloadSize() { return bytesDownload.get(); } /** * Get total directory created. */ public int getTotalDirectoryCreated() { return mkdirCount.get(); } /** * Get total directory removed. */ public int getTotalDirectoryRemoved() { return rmdirCount.get(); } /** * Get total number of connections. */ public int getTotalConnectionNumber() { return totalConnections.get(); } /** * Get current number of connections. */ public int getCurrentConnectionNumber() { return currConnections.get(); } /** * Get total number of logins. */ public int getTotalLoginNumber() { return totalLogins.get(); } /** * Get total failed login number. */ public int getTotalFailedLoginNumber() { return totalFailedLogins.get(); } /** * Get current number of logins. */ public int getCurrentLoginNumber() { return currLogins.get(); } /** * Get total number of anonymous logins. */ public int getTotalAnonymousLoginNumber() { return totalAnonLogins.get(); } /** * Get current number of anonymous logins. */ public int getCurrentAnonymousLoginNumber() { return currAnonLogins.get(); } /** * Get the login number for the specific user */ public synchronized int getCurrentUserLoginNumber(final User user) { UserLogins userLogins = userLoginTable.get(user.getName()); if (userLogins == null) {// not found the login user's statistics info return 0; } else { return userLogins.totalLogins.get(); } } /** * Get the login number for the specific user from the ipAddress * * @param user * login user account * @param ipAddress * the ip address of the remote user */ public synchronized int getCurrentUserLoginNumber(final User user, final InetAddress ipAddress) { UserLogins userLogins = userLoginTable.get(user.getName()); if (userLogins == null) {// not found the login user's statistics info return 0; } else { return userLogins.loginsFromInetAddress(ipAddress).get(); } } // ////////////////////////////////////////////////////// // /////////////// All setter methods ///////////////// /** * Increment upload count. */ public synchronized void setUpload(final FtpIoSession session, final FtpFile file, final long size) { uploadCount.incrementAndGet(); bytesUpload.addAndGet(size); notifyUpload(session, file, size); } /** * Increment download count. */ public synchronized void setDownload(final FtpIoSession session, final FtpFile file, final long size) { downloadCount.incrementAndGet(); bytesDownload.addAndGet(size); notifyDownload(session, file, size); } /** * Increment delete count. */ public synchronized void setDelete(final FtpIoSession session, final FtpFile file) { deleteCount.incrementAndGet(); notifyDelete(session, file); } /** * Increment make directory count. */ public synchronized void setMkdir(final FtpIoSession session, final FtpFile file) { mkdirCount.incrementAndGet(); notifyMkdir(session, file); } /** * Increment remove directory count. */ public synchronized void setRmdir(final FtpIoSession session, final FtpFile file) { rmdirCount.incrementAndGet(); notifyRmdir(session, file); } /** * Increment open connection count. */ public synchronized void setOpenConnection(final FtpIoSession session) { currConnections.incrementAndGet(); totalConnections.incrementAndGet(); notifyOpenConnection(session); } /** * Decrement open connection count. */ public synchronized void setCloseConnection(final FtpIoSession session) { if (currConnections.get() > 0) { currConnections.decrementAndGet(); } notifyCloseConnection(session); } /** * New login. */ public synchronized void setLogin(final FtpIoSession session) { currLogins.incrementAndGet(); totalLogins.incrementAndGet(); User user = session.getUser(); if ("anonymous".equals(user.getName())) { currAnonLogins.incrementAndGet(); totalAnonLogins.incrementAndGet(); } synchronized (user) {// thread safety is needed. Since the login occurrs // at low frequency, this overhead is endurable UserLogins statisticsTable = userLoginTable.get(user.getName()); if (statisticsTable == null) { // the hash table that records the login information of the user // and its ip address. InetAddress address = null; if (session.getRemoteAddress() instanceof InetSocketAddress) { address = ((InetSocketAddress) session.getRemoteAddress()) .getAddress(); } statisticsTable = new UserLogins(address); userLoginTable.put(user.getName(), statisticsTable); } else { statisticsTable.totalLogins.incrementAndGet(); if (session.getRemoteAddress() instanceof InetSocketAddress) { InetAddress address = ((InetSocketAddress) session .getRemoteAddress()).getAddress(); statisticsTable.loginsFromInetAddress(address) .incrementAndGet(); } } } notifyLogin(session); } /** * Increment failed login count. */ public synchronized void setLoginFail(final FtpIoSession session) { totalFailedLogins.incrementAndGet(); notifyLoginFail(session); } /** * User logout */ public synchronized void setLogout(final FtpIoSession session) { User user = session.getUser(); if (user == null) { return; } currLogins.decrementAndGet(); if ("anonymous".equals(user.getName())) { currAnonLogins.decrementAndGet(); } synchronized (user) { UserLogins userLogins = userLoginTable.get(user.getName()); if (userLogins != null) { userLogins.totalLogins.decrementAndGet(); if (session.getRemoteAddress() instanceof InetSocketAddress) { InetAddress address = ((InetSocketAddress) session .getRemoteAddress()).getAddress(); userLogins.loginsFromInetAddress(address).decrementAndGet(); } } } notifyLogout(session); } // ////////////////////////////////////////////////////////// // /////////////// all observer methods //////////////////// /** * Observer upload notification. */ private void notifyUpload(final FtpIoSession session, final FtpFile file, long size) { StatisticsObserver observer = this.observer; if (observer != null) { observer.notifyUpload(); } FileObserver fileObserver = this.fileObserver; if (fileObserver != null) { fileObserver.notifyUpload(session, file, size); } } /** * Observer download notification. */ private void notifyDownload(final FtpIoSession session, final FtpFile file, final long size) { StatisticsObserver observer = this.observer; if (observer != null) { observer.notifyDownload(); } FileObserver fileObserver = this.fileObserver; if (fileObserver != null) { fileObserver.notifyDownload(session, file, size); } } /** * Observer delete notification. */ private void notifyDelete(final FtpIoSession session, final FtpFile file) { StatisticsObserver observer = this.observer; if (observer != null) { observer.notifyDelete(); } FileObserver fileObserver = this.fileObserver; if (fileObserver != null) { fileObserver.notifyDelete(session, file); } } /** * Observer make directory notification. */ private void notifyMkdir(final FtpIoSession session, final FtpFile file) { StatisticsObserver observer = this.observer; if (observer != null) { observer.notifyMkdir(); } FileObserver fileObserver = this.fileObserver; if (fileObserver != null) { fileObserver.notifyMkdir(session, file); } } /** * Observer remove directory notification. */ private void notifyRmdir(final FtpIoSession session, final FtpFile file) { StatisticsObserver observer = this.observer; if (observer != null) { observer.notifyRmdir(); } FileObserver fileObserver = this.fileObserver; if (fileObserver != null) { fileObserver.notifyRmdir(session, file); } } /** * Observer open connection notification. */ private void notifyOpenConnection(final FtpIoSession session) { StatisticsObserver observer = this.observer; if (observer != null) { observer.notifyOpenConnection(); } } /** * Observer close connection notification. */ private void notifyCloseConnection(final FtpIoSession session) { StatisticsObserver observer = this.observer; if (observer != null) { observer.notifyCloseConnection(); } } /** * Observer login notification. */ private void notifyLogin(final FtpIoSession session) { StatisticsObserver observer = this.observer; if (observer != null) { // is anonymous login User user = session.getUser(); boolean anonymous = false; if (user != null) { String login = user.getName(); anonymous = (login != null) && login.equals("anonymous"); } observer.notifyLogin(anonymous); } } /** * Observer failed login notification. */ private void notifyLoginFail(final FtpIoSession session) { StatisticsObserver observer = this.observer; if (observer != null) { if (session.getRemoteAddress() instanceof InetSocketAddress) { observer.notifyLoginFail(((InetSocketAddress) session .getRemoteAddress()).getAddress()); } } } /** * Observer logout notification. */ private void notifyLogout(final FtpIoSession session) { StatisticsObserver observer = this.observer; if (observer != null) { // is anonymous login User user = session.getUser(); boolean anonymous = false; if (user != null) { String login = user.getName(); anonymous = (login != null) && login.equals("anonymous"); } observer.notifyLogout(anonymous); } } /** * Reset the cumulative counters. */ public synchronized void resetStatisticsCounters() { startTime = new Date(); uploadCount.set(0); downloadCount.set(0); deleteCount.set(0); mkdirCount.set(0); rmdirCount.set(0); totalLogins.set(0); totalFailedLogins.set(0); totalAnonLogins.set(0); totalConnections.set(0); bytesUpload.set(0); bytesDownload.set(0); } }
package com.github.mokkun.playground.activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.database.ContentObserver; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.ViewGroup; import com.github.mokkun.playground.R; import com.github.mokkun.playground.fragment.SessionHistoryFragment; import com.github.mokkun.playground.fragment.SessionTrackerFragment; import com.github.mokkun.playground.service.SensorService; import static com.github.mokkun.playground.database.PlaygroundContentProvider.Content; import static com.github.mokkun.playground.database.PlaygroundContentProvider.Service; import static com.github.mokkun.playground.database.PlaygroundContentProvider.matchUri; public class MainActivity extends AppCompatActivity implements ServiceConnection, SensorService.SensorListener, SessionTrackerFragment.Listener{ private SensorService.SensorBinder mBinder; private SessionTrackerFragment mTrackerFragment; private SessionHistoryFragment mHistoryFragment; private final ContentObserver mContentObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange, Uri uri) { switch (matchUri(uri)) { case Content.SESSIONS: refreshSessionHistoryFragment(); break; default: } } }; //---------------------------------------- // Activity Lifecycle //---------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); ViewPager viewPager = (ViewPager) findViewById(R.id.container); viewPager.setAdapter(sectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } @Override protected void onStart() { super.onStart(); getContentResolver().registerContentObserver(Service.SESSIONS.getUri(), true, mContentObserver); } @Override protected void onResume() { super.onResume(); bindService(new Intent(this, SensorService.class), this, BIND_AUTO_CREATE); } @Override protected void onPause() { super.onPause(); if (mBinder != null) { mBinder = null; unbindService(this); } } @Override protected void onStop() { super.onStop(); getContentResolver().unregisterContentObserver(mContentObserver); } //---------------------------------------- // Sensors //---------------------------------------- @Override public void onSensorStart(long sinceWhen) { startTrackActivity(sinceWhen); } @Override public void onSensorUpdate(@NonNull SensorService.SensorInfo info) { if (mTrackerFragment != null) { mTrackerFragment.updateInfo(info); } } @Override public void onSensorStop() { stopTrackActivity(); } //---------------------------------------- // Service //---------------------------------------- @Override public void onServiceConnected(ComponentName name, IBinder service) { mBinder = (SensorService.SensorBinder) service; mBinder.setListener(this); if (mBinder.isNotTracking()) { stopTrackActivity(); } else { startTrackActivity(mBinder.getTrackingStartTime()); } } @Override public void onServiceDisconnected(ComponentName name) { mBinder = null; } //---------------------------------------- // Activity Tracking //---------------------------------------- @Override public void onTrackActivityStart() { if (mBinder != null) { mBinder.startTracking(); } } @Override public void onTrackActivityStop() { if (mBinder != null) { mBinder.stopTracking(); } } private void startTrackActivity(long sinceWhen) { if (mTrackerFragment != null) { mTrackerFragment.setTrackActivityStartTime(sinceWhen); } } private void stopTrackActivity() { if (mTrackerFragment != null) { mTrackerFragment.setTrackActivityStop(); } } //---------------------------------------- // History //---------------------------------------- private void refreshSessionHistoryFragment() { if (mHistoryFragment != null) { mHistoryFragment.refresh(); } } //---------------------------------------- // Sections Pages //---------------------------------------- private static class Sections { public static final int TRACKER = 0; public static final int HISTORY = 1; } private class SectionsPagerAdapter extends FragmentPagerAdapter { private static final int SECTION_COUNT = 2; public SectionsPagerAdapter(FragmentManager manager) { super(manager); } @Override public Object instantiateItem(ViewGroup container, int position) { final Object item = super.instantiateItem(container, position); switch (position) { case Sections.TRACKER: mTrackerFragment = (SessionTrackerFragment) item; break; case Sections.HISTORY: mHistoryFragment = (SessionHistoryFragment) item; break; default: } return item; } @Override public Fragment getItem(int position) { switch (position) { case Sections.TRACKER: return SessionTrackerFragment.createFragment(); case Sections.HISTORY: return SessionHistoryFragment.createFragment(); } throw new RuntimeException("Invalid fragment adapter position."); } @Override public int getCount() { return SECTION_COUNT; } @Override public CharSequence getPageTitle(int position) { switch (position) { case Sections.TRACKER: return SessionTrackerFragment.getTitle(MainActivity.this); case Sections.HISTORY: return SessionHistoryFragment.getTitle(MainActivity.this); } return null; } } }
package org.motechproject.outbox.server.web; import org.apache.commons.lang.StringEscapeUtils; import org.motechproject.outbox.api.domain.OutboundVoiceMessage; import org.motechproject.outbox.api.domain.OutboundVoiceMessageStatus; import org.motechproject.outbox.api.domain.VoiceMessageType; import org.motechproject.outbox.api.service.VoiceOutboxService; import org.motechproject.server.config.service.PlatformSettingsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 org.springframework.web.servlet.mvc.multiaction.MultiActionController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static java.lang.String.format; /** * Spring MVC controller implementation provides method to handle HTTP requests and generate * VXML documents based on stored in outbox objects and the corresponding Velocity template */ @Controller public class VxmlOutboxController extends MultiActionController { private Logger logger = LoggerFactory.getLogger((this.getClass())); private static final String CONTEXT_PATH = "contextPath"; private static final String ESCAPE = "escape"; private static final String EXTERNAL_ID = "externalId"; private static final String LANGUAGE = "language"; public static final String NO_MESSAGE_TEMPLATE_NAME = "nomsg"; public static final String NO_SAVED_MESSAGE_TEMPLATE_NAME = "noSavedMsg"; public static final String ERROR_MESSAGE_TEMPLATE_NAME = "msgError"; public static final String MESSAGE_MENU_TEMPLATE_NAME = "msgMenu"; public static final String SAVED_MESSAGE_MENU_TEMPLATE_NAME = "savedMsgMenu"; public static final String MESSAGE_SAVED_CONFIRMATION_TEMPLATE_NAME = "msgSavedConf"; public static final String MESSAGE_REMOVED_CONFIRMATION_TEMPLATE_NAME = "msgRemovedConf"; public static final String SAVE_MESSAGE_ERROR_TEMPLATE_NAME = "saveMsgError"; public static final String REMOVE_SAVED_MESSAGE_ERROR_TEMPLATE_NAME = "removeSavedMsgError"; public static final String MESSAGE_ID_PARAM = "mId"; public static final String LANGUAGE_PARAM = "ln"; @Autowired private VoiceOutboxService voiceOutboxService; @Autowired private PlatformSettingsService platformSettingsService; /** * Handles Appointment Reminder HTTP requests and generates a VXML document based on a Velocity template. * The HTTP request may contain an optional 'mId' parameter with value of ID of the message for which * VXML document will be generated. If the "mId" parameter is not passed the next pending voice message * will be obtained from the outbox and a VXML document will be generated for that message * <p></p> * <p></p> * URL to request appointment reminder VoiceXML: * http://{host}:{port}/{motech-platform-server{/module/outbox/vxml/outboxMessage?mId={messageId} */ @RequestMapping(value = "/vxml/outboxMessage") public ModelAndView outboxMessage(HttpServletRequest request, HttpServletResponse response) { logger.info("Generate appointment reminder VXML"); setResponseHeaders(response); //Interim implementation. Party ID will be obtained from the Authentication context //String externalId = "1"; String externalId = request.getParameter("pId"); String messageId = request.getParameter(MESSAGE_ID_PARAM); String language = request.getParameter(LANGUAGE_PARAM); if (language == null) { language = platformSettingsService.getPlatformLanguage("en"); } String contextPath = request.getContextPath(); ModelAndView mav = new ModelAndView(); mav.addObject(CONTEXT_PATH, contextPath); mav.addObject(LANGUAGE, language); mav.addObject(ESCAPE, new StringEscapeUtils()); logInfoMessageID(messageId); OutboundVoiceMessage voiceMessage = null; if (messageId != null) { logger.info(format("Generating VXML for the voice message ID: %s", messageId)); try { voiceMessage = voiceOutboxService.getMessageById(messageId); } catch (Exception e) { logger.error(format("Can not get message by ID: %s %s", messageId, e.getMessage()), e); generatingVXMLWithErrorMessage(mav); return mav; } } else { logger.info("Generating VXML for the next voice message in outbox... "); try { voiceMessage = voiceOutboxService.getNextMessage(externalId, OutboundVoiceMessageStatus.PENDING); } catch (Exception e) { logger.error(format("Can not obtain next message from the outbox of the external ID: %s %s", externalId, e.getMessage()), e); generatingVXMLWithErrorMessage(mav); return mav; } } if (voiceMessage == null) { logger.info(format("There are no more messages in the outbox of the external ID: %s", externalId)); mav.setViewName(NO_MESSAGE_TEMPLATE_NAME); mav.addObject(EXTERNAL_ID, externalId); return mav; } VoiceMessageType voiceMessageType = voiceMessage.getVoiceMessageType(); if (voiceMessageType == null) { logger.error(format("Invalid Outbound voice message: %s Voice message type can not be null.", voiceMessage)); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); mav.addObject(EXTERNAL_ID, externalId); return mav; } logger.debug(voiceMessage.toString()); String templateName = voiceMessageType.getTemplateName(); mav.setViewName((templateName == null) ? voiceMessageType.getVoiceMessageTypeName() : templateName); mav.addObject("message", voiceMessage); return mav; } @RequestMapping(value = "/vxml/messageMenu") public ModelAndView messageMenu(HttpServletRequest request, HttpServletResponse response) { logger.info("Generating the message menu VXML..."); setResponseHeaders(response); ModelAndView mav = new ModelAndView(); String messageId = request.getParameter(MESSAGE_ID_PARAM); String language = request.getParameter(LANGUAGE_PARAM); logInfoMessageID(messageId); if (messageId == null) { logger.error(format("Invalid request - missing parameter: %s", MESSAGE_ID_PARAM)); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); return mav; } OutboundVoiceMessage voiceMessage; try { voiceMessage = voiceOutboxService.getMessageById(messageId); } catch (Exception e) { logger.error(format("Can not get message by ID: %s %s", messageId, e.getMessage()), e); generatingVXMLWithErrorMessage(mav); return mav; } if (voiceMessage == null) { logger.error(format("Can not get message by ID: %sservice returned null", messageId)); generatingVXMLWithErrorMessage(mav); return mav; } if (voiceMessage.getStatus() == OutboundVoiceMessageStatus.SAVED) { mav.setViewName(SAVED_MESSAGE_MENU_TEMPLATE_NAME); } else { try { voiceOutboxService.setMessageStatus(messageId, OutboundVoiceMessageStatus.PLAYED); } catch (Exception e) { logger.error(format("Can not set message status to %s to the message ID: %s", OutboundVoiceMessageStatus.PLAYED, messageId), e); } mav.setViewName(MESSAGE_MENU_TEMPLATE_NAME); } String contextPath = request.getContextPath(); logger.debug(voiceMessage.toString()); logger.debug(mav.getViewName()); mav.addObject(CONTEXT_PATH, contextPath); mav.addObject("message", voiceMessage); mav.addObject(LANGUAGE, language); mav.addObject(ESCAPE, new StringEscapeUtils()); return mav; } @RequestMapping(value = "/vxml/save") public ModelAndView save(HttpServletRequest request, HttpServletResponse response) { logger.info("Saving messageL..."); setResponseHeaders(response); String messageId = request.getParameter(MESSAGE_ID_PARAM); String language = request.getParameter(LANGUAGE_PARAM); ModelAndView mav = new ModelAndView(); String contextPath = request.getContextPath(); mav.setViewName(MESSAGE_SAVED_CONFIRMATION_TEMPLATE_NAME); mav.addObject(CONTEXT_PATH, contextPath); mav.addObject(LANGUAGE, language); mav.addObject(ESCAPE, new StringEscapeUtils()); logInfoMessageID(messageId); if (messageId == null) { logger.error(format("Invalid request - missing parameter: %s", MESSAGE_ID_PARAM)); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); return mav; } try { voiceOutboxService.saveMessage(messageId); } catch (Exception e) { logger.error(format("Can not mark the message with ID: %s as saved in the outbox", messageId), e); mav.setViewName(SAVE_MESSAGE_ERROR_TEMPLATE_NAME); return mav; } //TODO - get exernal ID proper way from security principal or authentication context when it is available String externalId; try { OutboundVoiceMessage message = voiceOutboxService.getMessageById(messageId); externalId = message.getExternalId(); } catch (Exception e) { logger.error(format("Can not obtain message ID: %s to get external ID", messageId)); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); return mav; } mav.addObject("days", voiceOutboxService.getNumDaysKeepSavedMessages()); mav.addObject(EXTERNAL_ID, externalId); return mav; } /** * Handles Outbox HTTP requests to remove saved in the outbox message and generates a VXML document * with message remove confirmation. The generated VXML document based on the msgRemovedConf.vm Velocity template. * <p/> * The message will not be physically removed. The message status will be set to PLAYED. * <p/> * <p></p> * <p></p> * URL to request a saved VoiceXML message from outbox : * http://{host}:{port}>/{motech-platform-server}>/module/outbox/vxml/remove?mId=$message.id&ln={language} */ @RequestMapping(value = "/vxml/remove") public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) { logger.info("Removing saved message message..."); setResponseHeaders(response); String messageId = request.getParameter(MESSAGE_ID_PARAM); String language = request.getParameter(LANGUAGE_PARAM); String contextPath = request.getContextPath(); ModelAndView mav = new ModelAndView(); mav.setViewName(MESSAGE_REMOVED_CONFIRMATION_TEMPLATE_NAME); mav.addObject(CONTEXT_PATH, contextPath); mav.addObject(LANGUAGE, language); mav.addObject(ESCAPE, new StringEscapeUtils()); logInfoMessageID(messageId); if (messageId == null) { logger.error(format("Invalid request - missing parameter: %s", MESSAGE_ID_PARAM)); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); return mav; } try { voiceOutboxService.setMessageStatus(messageId, OutboundVoiceMessageStatus.PLAYED); } catch (Exception e) { logger.error(format("Can not mark the message with ID: %s as PLAYED in the outbox", messageId), e); mav.setViewName(REMOVE_SAVED_MESSAGE_ERROR_TEMPLATE_NAME); return mav; } //TODO - get external ID proper way from security principal or authentication context when it is available String externalId; try { OutboundVoiceMessage message = voiceOutboxService.getMessageById(messageId); externalId = message.getExternalId(); } catch (Exception e) { logger.error(format("Can not obtain message ID: %s to get external ID", messageId)); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); return mav; } logger.debug(format("externalId: %s", externalId)); mav.addObject(EXTERNAL_ID, externalId); return mav; } /** * Handles Outbox HTTP requests and generates a VXML document based on a Velocity template and data saved in the outbox. * <p></p> * <p></p> * URL to request a saved VoiceXML message from outbox : * http://{host}:{port}/{motech-platform-server}/module/outbox/vxml/savedMessage */ @RequestMapping(value = "/vxml/savedMessage") public ModelAndView savedMessage(HttpServletRequest request, HttpServletResponse response) { logger.info("Generate VXML for the next saved in the outbox message"); setResponseHeaders(response); //Interim implementation. Party ID will be obtained from the Authentication context //String externalId = "1"; String externalId = request.getParameter("pId"); String language = request.getParameter(LANGUAGE_PARAM); String contextPath = request.getContextPath(); ModelAndView mav = new ModelAndView(); mav.addObject(CONTEXT_PATH, contextPath); mav.addObject(LANGUAGE, language); mav.addObject(ESCAPE, new StringEscapeUtils()); logger.debug(format("External ID: %s", externalId)); OutboundVoiceMessage voiceMessage = null; logger.info("Generating VXML for the next saved voice message in outbox... "); try { voiceMessage = voiceOutboxService.getNextMessage(externalId, OutboundVoiceMessageStatus.SAVED); } catch (Exception e) { logger.error(format("Can not obtain next saved message from the outbox of the external ID: %s %s", externalId, e.getMessage()), e); generatingVXMLWithErrorMessage(mav); return mav; } if (voiceMessage == null) { logger.info(format("There are no more messages in the outbox of the external ID: %s", externalId)); mav.setViewName(NO_SAVED_MESSAGE_TEMPLATE_NAME); mav.addObject(EXTERNAL_ID, externalId); return mav; } VoiceMessageType voiceMessageType = voiceMessage.getVoiceMessageType(); if (voiceMessageType == null) { logger.error(format("Invalid Outbound voice message: %s Voice message type can not be null.", voiceMessage)); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); mav.addObject(EXTERNAL_ID, externalId); return mav; } String templateName = voiceMessageType.getTemplateName(); if (templateName == null) { templateName = voiceMessageType.getVoiceMessageTypeName(); } mav.setViewName(templateName); mav.addObject("message", voiceMessage); return mav; } private void setResponseHeaders(HttpServletResponse response) { response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); } private void logInfoMessageID(String messageId) { logger.info(format("Message ID: %s", messageId)); } private void generatingVXMLWithErrorMessage(ModelAndView mav) { logger.warn("Generating a VXML with the error message..."); mav.setViewName(ERROR_MESSAGE_TEMPLATE_NAME); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package wssec; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.client.AxisClient; import org.apache.axis.configuration.NullProvider; import org.apache.axis.message.SOAPEnvelope; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ws.security.WSEncryptionPart; import org.apache.ws.security.WSPasswordCallback; import org.apache.ws.security.WSSecurityEngine; import org.apache.ws.security.WSSConfig; import org.apache.ws.security.WSConstants; import org.apache.ws.security.components.crypto.Crypto; import org.apache.ws.security.components.crypto.CryptoFactory; import org.apache.ws.security.message.WSSecSignature; import org.apache.ws.security.message.WSSecHeader; import org.apache.ws.security.message.WSSecTimestamp; import org.apache.ws.security.message.token.BinarySecurity; import org.apache.ws.security.util.WSSecurityUtil; import org.w3c.dom.Document; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Vector; /** * This is a test for the Kerberos Token Profile 1.1 */ public class TestWSSecurityKerberosTokenProfile extends TestCase implements CallbackHandler { private static final Log LOG = LogFactory.getLog(TestWSSecurityKerberosTokenProfile.class); private static final String AP_REQ = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#Kerberosv5_AP_REQ"; private static final String BASE64_NS = WSConstants.SOAPMESSAGE_NS + "#Base64Binary"; private static final String SOAPMSG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<SOAP-ENV:Envelope " + "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + "<SOAP-ENV:Body>" + "<add xmlns=\"http://ws.apache.org/counter/counter_port_type\">" + "<value xmlns=\"\">15</value>" + "</add>" + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>"; private WSSecurityEngine secEngine = new WSSecurityEngine(); private Crypto crypto = CryptoFactory.getInstance(); private MessageContext msgContext; private Message message; /** * TestWSSecurity constructor * <p/> * * @param name name of the test */ public TestWSSecurityKerberosTokenProfile(String name) { super(name); } /** * JUnit suite * <p/> * * @return a junit test suite */ public static Test suite() { return new TestSuite(TestWSSecurityKerberosTokenProfile.class); } /** * Setup method * <p/> * * @throws Exception Thrown when there is a problem in setup */ protected void setUp() throws Exception { AxisClient tmpEngine = new AxisClient(new NullProvider()); msgContext = new MessageContext(tmpEngine); message = getSOAPMessage(); } /** * Constructs a soap envelope * <p/> * * @return soap envelope * @throws Exception if there is any problem constructing the soap envelope */ protected Message getSOAPMessage() throws Exception { InputStream in = new ByteArrayInputStream(SOAPMSG.getBytes()); Message msg = new Message(in); msg.setMessageContext(msgContext); return msg; } /** * A unit test for creating BinarySecurityTokens */ public void testCreateBinarySecurityToken() throws Exception { SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope(); Document doc = unsignedEnvelope.getAsDocument(); WSSConfig.getNewInstance(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); BinarySecurity bst = new BinarySecurity(doc); bst.setValueType(AP_REQ); bst.setEncodingType(BASE64_NS); bst.setToken("12345678".getBytes()); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc); LOG.debug(outputString); } assertTrue(AP_REQ.equals(bst.getValueType())); assertTrue(BASE64_NS.equals(bst.getEncodingType())); assertTrue(bst.getToken() != null); } /** * A test for signing a Kerberos BST */ public void testSignBST() throws Exception { SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope(); Document doc = unsignedEnvelope.getAsDocument(); WSSConfig.getNewInstance(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); BinarySecurity bst = new BinarySecurity(doc); bst.setValueType(AP_REQ); bst.setEncodingType(BASE64_NS); bst.setToken("12345678".getBytes()); bst.setID("Id-" + bst.hashCode()); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); WSSecSignature sign = new WSSecSignature(); sign.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security"); sign.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); Vector parts = new Vector(); WSEncryptionPart encP = new WSEncryptionPart(bst.getID()); parts.add(encP); sign.setParts(parts); Document signedDoc = sign.build(doc, crypto, secHeader); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } verify(signedDoc); } /** * A test for signing a Kerberos BST as well as a Timestamp */ public void testSignBSTTimestamp() throws Exception { SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope(); Document doc = unsignedEnvelope.getAsDocument(); WSSConfig.getNewInstance(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); BinarySecurity bst = new BinarySecurity(doc); bst.setValueType(AP_REQ); bst.setEncodingType(BASE64_NS); bst.setToken("12345678".getBytes()); bst.setID("Id-" + bst.hashCode()); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); WSSecTimestamp timestamp = new WSSecTimestamp(); timestamp.setTimeToLive(600); timestamp.build(doc, secHeader); WSSecSignature sign = new WSSecSignature(); sign.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security"); sign.setKeyIdentifierType(WSConstants.ISSUER_SERIAL); Vector parts = new Vector(); parts.add(new WSEncryptionPart(bst.getID())); parts.add(new WSEncryptionPart(timestamp.getId())); sign.setParts(parts); Document signedDoc = sign.build(doc, crypto, secHeader); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } verify(signedDoc); } /** * Verifies the soap envelope * <p/> * * @param doc * @throws Exception Thrown when there is a problem in verification */ private void verify(Document doc) throws Exception { secEngine.processSecurityHeader(doc, null, this, crypto); if (LOG.isDebugEnabled()) { LOG.debug("Verfied and decrypted message:"); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc); LOG.debug(outputString); } } public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof WSPasswordCallback) { WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; /* * here call a function/method to lookup the password for * the given identifier (e.g. a user name or keystore alias) * e.g.: pc.setPassword(passStore.getPassword(pc.getIdentfifier)) * for Testing we supply a fixed name here. */ pc.setPassword("security"); } else { throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); } } } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice.v2016_03_01.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceFuture; import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in BillingMeters. */ public class BillingMetersInner { /** The Retrofit service to perform REST calls. */ private BillingMetersService service; /** The service client containing this operation class. */ private WebSiteManagementClientImpl client; /** * Initializes an instance of BillingMetersInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public BillingMetersInner(Retrofit retrofit, WebSiteManagementClientImpl client) { this.service = retrofit.create(BillingMetersService.class); this.client = client; } /** * The interface defining all the services for BillingMeters to be * used by Retrofit to perform actually REST calls. */ interface BillingMetersService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.v2016_03_01.BillingMeters list" }) @GET("subscriptions/{subscriptionId}/providers/Microsoft.Web/billingMeters") Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("billingLocation") String billingLocation, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.v2016_03_01.BillingMeters listNext" }) @GET Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;BillingMeterInner&gt; object if successful. */ public PagedList<BillingMeterInner> list() { ServiceResponse<Page<BillingMeterInner>> response = listSinglePageAsync().toBlocking().single(); return new PagedList<BillingMeterInner>(response.body()) { @Override public Page<BillingMeterInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<BillingMeterInner>> listAsync(final ListOperationCallback<BillingMeterInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listSinglePageAsync(), new Func1<String, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BillingMeterInner&gt; object */ public Observable<Page<BillingMeterInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<BillingMeterInner>>, Page<BillingMeterInner>>() { @Override public Page<BillingMeterInner> call(ServiceResponse<Page<BillingMeterInner>> response) { return response.body(); } }); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BillingMeterInner&gt; object */ public Observable<ServiceResponse<Page<BillingMeterInner>>> listWithServiceResponseAsync() { return listSinglePageAsync() .concatMap(new Func1<ServiceResponse<Page<BillingMeterInner>>, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(ServiceResponse<Page<BillingMeterInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;BillingMeterInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<BillingMeterInner>>> listSinglePageAsync() { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String billingLocation = null; return service.list(this.client.subscriptionId(), billingLocation, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<BillingMeterInner>> result = listDelegate(response); return Observable.just(new ServiceResponse<Page<BillingMeterInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param billingLocation Azure Location of billable resource * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;BillingMeterInner&gt; object if successful. */ public PagedList<BillingMeterInner> list(final String billingLocation) { ServiceResponse<Page<BillingMeterInner>> response = listSinglePageAsync(billingLocation).toBlocking().single(); return new PagedList<BillingMeterInner>(response.body()) { @Override public Page<BillingMeterInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param billingLocation Azure Location of billable resource * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<BillingMeterInner>> listAsync(final String billingLocation, final ListOperationCallback<BillingMeterInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listSinglePageAsync(billingLocation), new Func1<String, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param billingLocation Azure Location of billable resource * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BillingMeterInner&gt; object */ public Observable<Page<BillingMeterInner>> listAsync(final String billingLocation) { return listWithServiceResponseAsync(billingLocation) .map(new Func1<ServiceResponse<Page<BillingMeterInner>>, Page<BillingMeterInner>>() { @Override public Page<BillingMeterInner> call(ServiceResponse<Page<BillingMeterInner>> response) { return response.body(); } }); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param billingLocation Azure Location of billable resource * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BillingMeterInner&gt; object */ public Observable<ServiceResponse<Page<BillingMeterInner>>> listWithServiceResponseAsync(final String billingLocation) { return listSinglePageAsync(billingLocation) .concatMap(new Func1<ServiceResponse<Page<BillingMeterInner>>, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(ServiceResponse<Page<BillingMeterInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * ServiceResponse<PageImpl<BillingMeterInner>> * @param billingLocation Azure Location of billable resource * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;BillingMeterInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<BillingMeterInner>>> listSinglePageAsync(final String billingLocation) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.list(this.client.subscriptionId(), billingLocation, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<BillingMeterInner>> result = listDelegate(response); return Observable.just(new ServiceResponse<Page<BillingMeterInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<BillingMeterInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<BillingMeterInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<BillingMeterInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;BillingMeterInner&gt; object if successful. */ public PagedList<BillingMeterInner> listNext(final String nextPageLink) { ServiceResponse<Page<BillingMeterInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<BillingMeterInner>(response.body()) { @Override public Page<BillingMeterInner> nextPage(String nextPageLink) { return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<BillingMeterInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<BillingMeterInner>> serviceFuture, final ListOperationCallback<BillingMeterInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(String nextPageLink) { return listNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BillingMeterInner&gt; object */ public Observable<Page<BillingMeterInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<BillingMeterInner>>, Page<BillingMeterInner>>() { @Override public Page<BillingMeterInner> call(ServiceResponse<Page<BillingMeterInner>> response) { return response.body(); } }); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;BillingMeterInner&gt; object */ public Observable<ServiceResponse<Page<BillingMeterInner>>> listNextWithServiceResponseAsync(final String nextPageLink) { return listNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<BillingMeterInner>>, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(ServiceResponse<Page<BillingMeterInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Gets a list of meters for a given location. * Gets a list of meters for a given location. * ServiceResponse<PageImpl<BillingMeterInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;BillingMeterInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<BillingMeterInner>>> listNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<BillingMeterInner>>>>() { @Override public Observable<ServiceResponse<Page<BillingMeterInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<BillingMeterInner>> result = listNextDelegate(response); return Observable.just(new ServiceResponse<Page<BillingMeterInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<BillingMeterInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<BillingMeterInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<BillingMeterInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } }
/******************************************************************************* com.bnmi.ourmap.daoimpl.PostgresHotspotObjectDAO.java Version: 1.0 ******************************************************************************** Original Authors: Manuel Cuesta, lead programmer <camilocuesta@hotmail.com> Angus Leech, lead designer <alpinefabulist@yahoo.com> Full credits at: <http://www.ourmapmaker.ca/content/about-ourmap/credits> For questions or comments please contact us at: [ourmap@ourmapmaker.ca] ******************************************************************************** OurMap is Copyright (c) 2010, The Banff Centre <ourmap@ourmapmaker.ca> All rights reserved. Published under the terms of the new BSD license. See <www.ourmapmaker.ca/content/about-ourmap> for more information about the OurMap software and the license. Full sourcecode, documentation and license info is also available here: http://github.com/OurMap/OurMap LICENSE: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of The Banff Centre nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************** Revision History / Change Log: Version 1.0 released Oct.2010 ******************************************************************************** Notes: *******************************************************************************/ package com.bnmi.ourmap.daoimpl; import com.inga.dao.BasicDAO; import com.inga.utils.SigarUtils; import com.inga.exception.BDException; import com.inga.exception.NoConnectionException; import com.inga.exception.RegistroNoExisteException; import java.text.SimpleDateFormat; import java.sql.ResultSet; import java.sql.SQLException; import com.inga.utils.SqlClauseHelper; import com.bnmi.ourmap.model.HotspotObject; import com.bnmi.ourmap.model.CriteriosHotspotObject; import com.bnmi.ourmap.dao.HotspotObjectDAO; import java.util.Vector; /* * PostgresHotspotObjectDAO.java * * Created on Thu Feb 11 14:10:18 COT 2010 * by DaoGen2 * Author: Camilo Cuesta * */ public class PostgresHotspotObjectDAO extends BasicDAO implements HotspotObjectDAO { private static SimpleDateFormat _df = new SimpleDateFormat( SigarUtils.FECHA4 ); @SuppressWarnings("unchecked") @Override public Vector<HotspotObject> find(CriteriosHotspotObject criteria) throws NoConnectionException, BDException { Vector<HotspotObject> results = new Vector<HotspotObject>(); String sql = "select * from hotspot_objects"; SqlClauseHelper _sh = new SqlClauseHelper(); if ( criteria.getHotspot() != null ) _sh.addAndClause("hotspot = " + criteria.getHotspot().intValue() ); if ( criteria.getObjectId() != null ) _sh.addAndClause("object_id = " + criteria.getObjectId().intValue() ); if ( criteria.getIndex() != null ) _sh.addAndClause("index = " + criteria.getIndex().intValue() ); if ( criteria.getBlock() != null ) _sh.addAndClause("block = " + criteria.getBlock().intValue() ); String clause = _sh.getClause(); if ( clause.length() > 0 ) sql = sql + " where " + clause; // Aqui' puede especificar el ordenamiento de los registros sql = sql + " order by block, index"; results = executeQuery( sql ); return results; } @Override public HotspotObject get( java.lang.Integer hotspot, java.lang.Integer objectId ) throws NoConnectionException, BDException, RegistroNoExisteException { String sql = "select * from hotspot_objects where hotspot = " + hotspot + " and object_id = " + objectId; Vector results = executeQuery( sql ); if ( results.isEmpty() ) throw new RegistroNoExisteException( "" ); return (HotspotObject) results.firstElement(); } @Override public Integer create(HotspotObject registro) throws NoConnectionException, BDException { int rows = executeUpdate( getCreateStr(registro) ); return new Integer(rows); } public String getCreateStr(HotspotObject registro) { StringBuffer sql = new StringBuffer(); sql.append( "insert into hotspot_objects ("); sql.append("hotspot, object_id, index, block"); sql.append(")"); sql.append(" values ("); if ( registro.getHotspot() == null ) sql.append( "null" + "," ); else sql.append( registro.getHotspot().intValue() + "," ); if ( registro.getObjectId() == null ) sql.append( "null" + "," ); else sql.append( registro.getObjectId().intValue() + "," ); if ( registro.getIndex() == null ) sql.append( "null" + "," ); else sql.append( registro.getIndex().intValue() + "," ); if ( registro.getBlock() == null ) sql.append( "null" ); else sql.append( registro.getBlock().intValue() ); sql.append( ")" ); return sql.toString(); } @Override public int update(HotspotObject registro) throws NoConnectionException, BDException { int rows = executeUpdate( getUpdateStr(registro) ); return rows; } public static String getUpdateStr(HotspotObject registro) { String sql = "update hotspot_objects"; SqlClauseHelper sh = new SqlClauseHelper(); if ( registro.getIndex() != null ) sh.append(",", "index = " + registro.getIndex().intValue() ); if ( registro.getBlock() != null ) sh.append(",", "block = " + registro.getBlock().intValue() ); sql = sql + " set " + sh.getClause() + " where hotspot = " + registro.getHotspot() + " and object_id = " + registro.getObjectId(); return sql.toString(); } @Override public int delete( java.lang.Integer hotspot, java.lang.Integer objectId ) throws NoConnectionException, BDException { int rows = executeUpdate( getDeleteStr(hotspot, objectId) ); return rows; } public static String getDeleteStr(java.lang.Integer hotspot, java.lang.Integer objectId) { String sql = "delete from hotspot_objects where hotspot = " + hotspot + " and object_id = " + objectId; return sql; } @Override protected Vector extract(ResultSet rs ) throws BDException { Vector<HotspotObject> results = new Vector<HotspotObject>(); try { while ( rs.next() ) { try { HotspotObject o = new HotspotObject(); o.setHotspot( new Integer(rs.getInt("hotspot")) ); o.setObjectId( new Integer(rs.getInt("object_id")) ); o.setIndex( new Integer(rs.getInt("index")) ); o.setBlock( new Integer(rs.getInt("block")) ); results.add( o ); } catch (Exception e) { e.printStackTrace(); } } rs.close(); } catch ( SQLException e ) { throw new BDException(e); } return results; } }
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.carbon.integration.common.extensions.usermgt; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.NodeList; import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException; import org.wso2.carbon.automation.engine.FrameworkConstants; import org.wso2.carbon.automation.engine.configurations.AutomationConfiguration; import org.wso2.carbon.automation.engine.configurations.UrlGenerationUtil; import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.integration.common.admin.client.AuthenticatorClient; import org.wso2.carbon.integration.common.admin.client.TenantManagementServiceClient; import org.wso2.carbon.integration.common.admin.client.UserManagementClient; import org.wso2.carbon.integration.common.extensions.utils.AutomationXpathConstants; import org.wso2.carbon.integration.common.extensions.utils.ExtensionCommonConstants; import org.wso2.carbon.integration.common.utils.LoginLogoutClient; import javax.xml.xpath.XPathExpressionException; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; /** * This class is responsible for adding tenants and users * defined under userManagement entry in automation.xml to servers. */ public class UserPopulator { private static final Log log = LogFactory.getLog(UserPopulator.class); private AutomationContext automationContext; private List<String> tenantList; private List<String> rolesList; private List<RemovableData> removableDataList = new ArrayList<RemovableData>(0); private NodeList userNodeList; public UserPopulator(String productGroupName, String instanceName) throws XPathExpressionException { this.automationContext = new AutomationContext(productGroupName, instanceName, TestUserMode.SUPER_TENANT_ADMIN); this.tenantList = getTenantList(); this.rolesList = getRolesList(); } /** * Populate Tenants, Users and Roles * * @throws Exception */ public void populateUsers() throws Exception { // login as carbon super to add tenants LoginLogoutClient loginLogoutUtil = new LoginLogoutClient(automationContext); String sessionCookie = loginLogoutUtil.login(); String backendURL = automationContext.getContextUrls().getBackEndUrl(); TenantManagementServiceClient tenantManagementServiceClient = new TenantManagementServiceClient(backendURL, sessionCookie); for (String tenant : tenantList) { RemovableData removableData = new RemovableData(); removableData.setTenant(tenant); // add tenant, if the tenant is not the Super tenant String tenantType = AutomationXpathConstants.SUPER_TENANT; if (!tenant.equals(FrameworkConstants.SUPER_TENANT_DOMAIN_NAME)) { tenantType = AutomationXpathConstants.TENANTS; String tenantAdminUserName = getTenantAdminUsername(tenantType, tenant); String tenantAdminPassword = getTenantAdminPassword(tenantType, tenant); // if (!tenantManagementServiceClient.getTenant(tenant).getActive()) { tenantManagementServiceClient .addTenant(tenant, tenantAdminPassword, tenantAdminUserName, FrameworkConstants.TENANT_USAGE_PLAN_DEMO); log.info("Added new tenant : " + tenant); // if new tenant added -> need to remove from the system at the end of the test removableData.setNewTenant(true); // } // login as newly added tenant sessionCookie = login(tenantAdminUserName, tenant, tenantAdminPassword, backendURL, UrlGenerationUtil.getManagerHost( automationContext.getInstance())); } removableData.setTenantType(tenantType); UserManagementClient userManagementClient = new UserManagementClient(backendURL, sessionCookie); // add roles to the tenant addRoles(userManagementClient, removableData); // populate users of the current tenant and add roles addTenantUsers(tenantType, tenant, userManagementClient, removableData); // collect RemovableData removableDataList.add(removableData); } } private void addRoles(UserManagementClient userManagementClient, RemovableData removableData) throws Exception { for (String role : rolesList) { if (!userManagementClient.roleNameExists(role)) { List<String> permissions = getPermissionList(role); userManagementClient .addRole(role, null, permissions.toArray(new String[permissions.size()])); log.info("Added role " + role + " with permissions"); // if new role added for existing tenant -> need to remove from the system at the // end of the test if (!removableData.isNewTenant()) { removableData.setNewRole(role); } } } } private void addTenantUsers(String tenantType, String tenant, UserManagementClient userManagementClient, RemovableData removableData) throws Exception { List<String> userList = getUserList(tenant); for (String tenantUser : userList) { String tenantUserUsername = getTenantUserUsername(tenantType, tenant, tenantUser); boolean isTenantUserExist = userManagementClient.getUserList().contains( tenantUserUsername); if (!isTenantUserExist) { String[] rolesToBeAdded = new String[]{FrameworkConstants.ADMIN_ROLE}; List<String> userRoles = new ArrayList<String>(0); NodeList roleList = automationContext.getConfigurationNodeList( String.format(AutomationXpathConstants.TENANT_USER_ROLES, tenantType, tenant, tenantUser)); if (roleList != null && roleList.item(0) != null) { roleList = roleList.item(0).getChildNodes(); for (int i = 0; i < roleList.getLength(); i++) { String role = roleList.item(i).getTextContent(); if (userManagementClient.roleNameExists(role)) { userRoles.add(role); } else { log.error("Role is not exist : " + role); } } if (userRoles.size() > 0) { rolesToBeAdded = userRoles.toArray(new String[userRoles.size()]); } } userManagementClient.addUser(tenantUserUsername, getTenantUserPassword(tenantType, tenant, tenantUser), rolesToBeAdded, null); log.info("User - " + tenantUser + " created in tenant domain of " + " " + tenant); // if new user added for existing tenant -> need to remove from the system at the // end of the test if (!removableData.isNewTenant()) { removableData.setNewUser(tenantUserUsername); } } else { log.info(tenantUser + " is already in " + tenant); } } } /** * Delete Tenants, Users and Roles * * @throws Exception */ public void deleteUsers() throws Exception { String backendURL = automationContext.getContextUrls().getBackEndUrl(); for (RemovableData removableData : removableDataList) { if (removableData.isNewTenant()) { LoginLogoutClient loginLogoutUtil = new LoginLogoutClient(automationContext); String sessionCookie = loginLogoutUtil.login(); // remove tenant TenantManagementServiceClient tenantManagementServiceClient = new TenantManagementServiceClient(backendURL, sessionCookie); tenantManagementServiceClient.deleteTenant(removableData.getTenant()); log.info("Tenant was deleted successfully - " + removableData.getTenant()); } else { String sessionCookie = login( getTenantAdminUsername(removableData.getTenantType(), removableData.getTenant()), removableData.getTenant(), getTenantAdminPassword(removableData.getTenantType(), removableData.getTenant()), backendURL, UrlGenerationUtil.getManagerHost(automationContext.getInstance())); UserManagementClient userManagementClient = new UserManagementClient(backendURL, sessionCookie); for (String user : removableData.getNewUsers()) { // remove users boolean isTenantUserExist = userManagementClient.getUserList().contains(user); if (isTenantUserExist) { userManagementClient.deleteUser(user); log.info("User was deleted successfully - " + user); } } for (String role : removableData.getNewRoles()) { // remove roles if (userManagementClient.roleNameExists(role)) { userManagementClient.deleteRole(role); log.info("Role was deleted successfully - " + role); } } } } } private String getTenantAdminUsername(String tenantType, String tenant) throws XPathExpressionException { return automationContext .getConfigurationValue( String.format(AutomationXpathConstants.ADMIN_USER_USERNAME, tenantType, tenant)); } private String getTenantAdminPassword(String tenantType, String tenant) throws XPathExpressionException { return automationContext .getConfigurationValue( String.format(AutomationXpathConstants.ADMIN_USER_PASSWORD, tenantType, tenant)); } private String getTenantUserUsername(String tenantType, String tenant, String tenantUser) throws XPathExpressionException { return automationContext.getConfigurationValue( String.format(AutomationXpathConstants.TENANT_USER_USERNAME, tenantType, tenant, tenantUser)); } private String getTenantUserPassword(String tenantType, String tenant, String tenantUser) throws XPathExpressionException { return automationContext.getConfigurationValue( String.format(AutomationXpathConstants.TENANT_USER_PASSWORD, tenantType, tenant, tenantUser)); } private String login(String userName, String domain, String password, String backendUrl, String hostName) throws RemoteException, LoginAuthenticationExceptionException, XPathExpressionException { AuthenticatorClient loginClient = new AuthenticatorClient(backendUrl); if (!domain.equals(AutomationConfiguration .getConfigurationValue( ExtensionCommonConstants.SUPER_TENANT_DOMAIN_NAME))) { userName += "@" + domain; } return loginClient.login(userName, password, hostName); } private List<String> getTenantList() throws XPathExpressionException { List<String> tenantList = new ArrayList<String>(0); // add carbon.super tenantList.add(FrameworkConstants.SUPER_TENANT_DOMAIN_NAME); // add other tenants NodeList tenantNodeList = automationContext.getConfigurationNodeList(AutomationXpathConstants.TENANTS_NODE) .item(0) .getChildNodes(); for (int i = 0; i < tenantNodeList.getLength(); i++) { tenantList.add( tenantNodeList.item(i).getAttributes() .getNamedItem(AutomationXpathConstants.DOMAIN).getNodeValue() ); } return tenantList; } private List<String> getUserList(String tenantDomain) throws XPathExpressionException { List<String> userList = new ArrayList<String>(0); // set tenant type String tenantType = AutomationXpathConstants.TENANTS; if (tenantDomain.equals(FrameworkConstants.SUPER_TENANT_DOMAIN_NAME)) { tenantType = AutomationXpathConstants.SUPER_TENANT; } NodeList userNodeList = automationContext .getConfigurationNodeList( String.format(AutomationXpathConstants.USER_NODE, tenantType, tenantDomain)); for (int i = 0; i < userNodeList.getLength(); i++) { userList.add(userNodeList.item(i).getAttributes().getNamedItem("key").getNodeValue()); } return userList; } private List<String> getRolesList() throws XPathExpressionException { List<String> roleList = new ArrayList<String>(0); NodeList roleNodeList = automationContext.getConfigurationNodeList(AutomationXpathConstants.ROLES_NODE); if (roleNodeList != null && roleNodeList.item(0) != null) { roleNodeList = roleNodeList.item(0).getChildNodes(); for (int i = 0; i < roleNodeList.getLength(); i++) { roleList.add(roleNodeList.item(i).getAttributes() .getNamedItem(AutomationXpathConstants.NAME) .getNodeValue()); } } return roleList; } private List<String> getPermissionList(String role) throws XPathExpressionException { List<String> permissionList = new ArrayList<String>(0); NodeList permissionNodeList = automationContext .getConfigurationNodeList( String.format(AutomationXpathConstants.PERMISSIONS_NODE, role)); if (permissionNodeList != null && permissionNodeList.item(0) != null) { permissionNodeList = permissionNodeList.item(0).getChildNodes(); for (int i = 0; i < permissionNodeList.getLength(); i++) { permissionList.add(permissionNodeList.item(i).getTextContent()); } } return permissionList; } private class RemovableData { private String tenant; private String tenantType; private boolean isNewTenant = false; private List<String> newRoles = new ArrayList<String>(0); private List<String> newUsers = new ArrayList<String>(0); public String getTenant() { return tenant; } public void setTenant(String tenant) { this.tenant = tenant; } public String getTenantType() { return tenantType; } public void setTenantType(String tenantType) { this.tenantType = tenantType; } public boolean isNewTenant() { return isNewTenant; } public void setNewTenant(boolean isNewTenant) { this.isNewTenant = isNewTenant; } public List<String> getNewRoles() { return newRoles; } public void setNewRole(String role) { this.newRoles.add(role); } public List<String> getNewUsers() { return newUsers; } public void setNewUser(String user) { this.newUsers.add(user); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Contributors: Dan Milstein // Ray Millard package org.apache.log4j; import java.util.Hashtable; import java.util.Stack; import java.util.Enumeration; import java.util.Vector; import org.apache.log4j.helpers.LogLog; /** The NDC class implements <i>nested diagnostic contexts</i> as defined by Neil Harrison in the article "Patterns for Logging Diagnostic Messages" part of the book "<i>Pattern Languages of Program Design 3</i>" edited by Martin et al. <p>A Nested Diagnostic Context, or NDC in short, is an instrument to distinguish interleaved log output from different sources. Log output is typically interleaved when a server handles multiple clients near-simultaneously. <p>Interleaved log output can still be meaningful if each log entry from different contexts had a distinctive stamp. This is where NDCs come into play. <p><em><b>Note that NDCs are managed on a per thread basis</b></em>. NDC operations such as {@link #push push}, {@link #pop}, {@link #clear}, {@link #getDepth} and {@link #setMaxDepth} affect the NDC of the <em>current</em> thread only. NDCs of other threads remain unaffected. <p>For example, a servlet can build a per client request NDC consisting the clients host name and other information contained in the the request. <em>Cookies</em> are another source of distinctive information. To build an NDC one uses the {@link #push push} operation. Simply put, <p><ul> <li>Contexts can be nested. <p><li>When entering a context, call <code>NDC.push</code>. As a side effect, if there is no nested diagnostic context for the current thread, this method will create it. <p><li>When leaving a context, call <code>NDC.pop</code>. <p><li><b>When exiting a thread make sure to call {@link #remove NDC.remove()}</b>. </ul> <p>There is no penalty for forgetting to match each <code>push</code> operation with a corresponding <code>pop</code>, except the obvious mismatch between the real application context and the context set in the NDC. <p>If configured to do so, {@link PatternLayout} and {@link TTCCLayout} instances automatically retrieve the nested diagnostic context for the current thread without any user intervention. Hence, even if a servlet is serving multiple clients simultaneously, the logs emanating from the same code (belonging to the same category) can still be distinguished because each client request will have a different NDC tag. <p>Heavy duty systems should call the {@link #remove} method when leaving the run method of a thread. This ensures that the memory used by the thread can be freed by the Java garbage collector. There is a mechanism to lazily remove references to dead threads. In practice, this means that you can be a little sloppy and sometimes forget to call {@link #remove} before exiting a thread. <p>A thread may inherit the nested diagnostic context of another (possibly parent) thread using the {@link #inherit inherit} method. A thread may obtain a copy of its NDC with the {@link #cloneStack cloneStack} method and pass the reference to any other thread, in particular to a child. @author Ceki G&uuml;lc&uuml; @since 0.7.0 */ public class NDC { // The synchronized keyword is not used in this class. This may seem // dangerous, especially since the class will be used by // multiple-threads. In particular, all threads share the same // hashtable (the "ht" variable). This is OK since java hashtables // are thread safe. Same goes for Stacks. // More importantly, when inheriting diagnostic contexts the child // thread is handed a clone of the parent's NDC. It follows that // each thread has its own NDC (i.e. stack). static Hashtable ht = new Hashtable(); static int pushCounter = 0; // the number of times push has been called // after the latest call to lazyRemove // The number of times we allow push to be called before we call lazyRemove // 5 is a relatively small number. As such, lazyRemove is not called too // frequently. We thus avoid the cost of creating an Enumeration too often. // The higher this number, the longer is the avarage period for which all // logging calls in all threads are blocked. static final int REAP_THRESHOLD = 5; // No instances allowed. private NDC() {} /** * Get NDC stack for current thread. * @return NDC stack for current thread. */ private static Stack getCurrentStack() { if (ht != null) { return (Stack) ht.get(Thread.currentThread()); } return null; } /** Clear any nested diagnostic information if any. This method is useful in cases where the same thread can be potentially used over and over in different unrelated contexts. <p>This method is equivalent to calling the {@link #setMaxDepth} method with a zero <code>maxDepth</code> argument. @since 0.8.4c */ public static void clear() { Stack stack = getCurrentStack(); if(stack != null) { stack.setSize(0); } } /** Clone the diagnostic context for the current thread. <p>Internally a diagnostic context is represented as a stack. A given thread can supply the stack (i.e. diagnostic context) to a child thread so that the child can inherit the parent thread's diagnostic context. <p>The child thread uses the {@link #inherit inherit} method to inherit the parent's diagnostic context. @return Stack A clone of the current thread's diagnostic context. */ public static Stack cloneStack() { Stack stack = getCurrentStack(); if(stack == null) { return null; } else { return (Stack) stack.clone(); } } /** Inherit the diagnostic context of another thread. <p>The parent thread can obtain a reference to its diagnostic context using the {@link #cloneStack} method. It should communicate this information to its child so that it may inherit the parent's diagnostic context. <p>The parent's diagnostic context is cloned before being inherited. In other words, once inherited, the two diagnostic contexts can be managed independently. <p>In java, a child thread cannot obtain a reference to its parent, unless it is directly handed the reference. Consequently, there is no client-transparent way of inheriting diagnostic contexts. Do you know any solution to this problem? @param stack The diagnostic context of the parent thread. */ public static void inherit(Stack stack) { if(stack != null) { ht.put(Thread.currentThread(), stack); } } /** <font color="#FF4040"><b>Never use this method directly, use the {@link org.apache.log4j.spi.LoggingEvent#getNDC} method instead</b></font>. */ static public String get() { Stack s = getCurrentStack(); if(s != null && !s.isEmpty()) { return ((DiagnosticContext) s.peek()).fullMessage; } else { return null; } } /** * Get the current nesting depth of this diagnostic context. * * @see #setMaxDepth * @since 0.7.5 */ public static int getDepth() { Stack stack = getCurrentStack(); if(stack == null) { return 0; } else { return stack.size(); } } private static void lazyRemove() { if (ht == null) { return; } // The synchronization on ht is necessary to prevent JDK 1.2.x from // throwing ConcurrentModificationExceptions at us. This sucks BIG-TIME. // One solution is to write our own hashtable implementation. Vector v; synchronized(ht) { // Avoid calling clean-up too often. if(++pushCounter <= REAP_THRESHOLD) { return; // We release the lock ASAP. } else { pushCounter = 0; // OK let's do some work. } int misses = 0; v = new Vector(); Enumeration enumeration = ht.keys(); // We give up after 4 straigt missses. That is 4 consecutive // inspected threads in 'ht' that turn out to be alive. // The higher the proportion on dead threads in ht, the higher the // chances of removal. while(enumeration.hasMoreElements() && (misses <= 4)) { Thread t = (Thread) enumeration.nextElement(); if(t.isAlive()) { misses++; } else { misses = 0; v.addElement(t); } } } // synchronized int size = v.size(); for(int i = 0; i < size; i++) { Thread t = (Thread) v.elementAt(i); LogLog.debug("Lazy NDC removal for thread [" + t.getName() + "] ("+ ht.size() + ")."); ht.remove(t); } } /** Clients should call this method before leaving a diagnostic context. <p>The returned value is the value that was pushed last. If no context is available, then the empty string "" is returned. @return String The innermost diagnostic context. */ public static String pop() { Stack stack = getCurrentStack(); if(stack != null && !stack.isEmpty()) { return ((DiagnosticContext) stack.pop()).message; } else { return ""; } } /** Looks at the last diagnostic context at the top of this NDC without removing it. <p>The returned value is the value that was pushed last. If no context is available, then the empty string "" is returned. @return String The innermost diagnostic context. */ public static String peek() { Stack stack = getCurrentStack(); if(stack != null && !stack.isEmpty()) { return ((DiagnosticContext) stack.peek()).message; } else { return ""; } } /** Push new diagnostic context information for the current thread. <p>The contents of the <code>message</code> parameter is determined solely by the client. @param message The new diagnostic context information. */ public static void push(String message) { Stack stack = getCurrentStack(); if(stack == null) { DiagnosticContext dc = new DiagnosticContext(message, null); stack = new Stack(); Thread key = Thread.currentThread(); ht.put(key, stack); stack.push(dc); } else if (stack.isEmpty()) { DiagnosticContext dc = new DiagnosticContext(message, null); stack.push(dc); } else { DiagnosticContext parent = (DiagnosticContext) stack.peek(); stack.push(new DiagnosticContext(message, parent)); } } /** Remove the diagnostic context for this thread. <p>Each thread that created a diagnostic context by calling {@link #push} should call this method before exiting. Otherwise, the memory used by the <b>thread</b> cannot be reclaimed by the VM. <p>As this is such an important problem in heavy duty systems and because it is difficult to always guarantee that the remove method is called before exiting a thread, this method has been augmented to lazily remove references to dead threads. In practice, this means that you can be a little sloppy and occasionally forget to call {@link #remove} before exiting a thread. However, you must call <code>remove</code> sometime. If you never call it, then your application is sure to run out of memory. */ static public void remove() { if (ht != null) { ht.remove(Thread.currentThread()); // Lazily remove dead-thread references in ht. lazyRemove(); } } /** Set maximum depth of this diagnostic context. If the current depth is smaller or equal to <code>maxDepth</code>, then no action is taken. <p>This method is a convenient alternative to multiple {@link #pop} calls. Moreover, it is often the case that at the end of complex call sequences, the depth of the NDC is unpredictable. The <code>setMaxDepth</code> method circumvents this problem. <p>For example, the combination <pre> void foo() { &nbsp; int depth = NDC.getDepth(); &nbsp; ... complex sequence of calls &nbsp; NDC.setMaxDepth(depth); } </pre> ensures that between the entry and exit of foo the depth of the diagnostic stack is conserved. @see #getDepth @since 0.7.5 */ static public void setMaxDepth(int maxDepth) { Stack stack = getCurrentStack(); if(stack != null && maxDepth < stack.size()) { stack.setSize(maxDepth); } } // ===================================================================== private static class DiagnosticContext { String fullMessage; String message; DiagnosticContext(String message, DiagnosticContext parent) { this.message = message; if(parent != null) { fullMessage = parent.fullMessage + ' ' + message; } else { fullMessage = message; } } } }
package com.angkorteam.fintech.pages.charge; import java.util.List; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import com.angkorteam.fintech.Page; import com.angkorteam.fintech.Session; import com.angkorteam.fintech.ddl.MTaxGroup; import com.angkorteam.fintech.dto.Function; import com.angkorteam.fintech.dto.builder.ChargeBuilder; import com.angkorteam.fintech.dto.enums.ChargeCalculation; import com.angkorteam.fintech.dto.enums.ChargeTime; import com.angkorteam.fintech.dto.enums.ChargeType; import com.angkorteam.fintech.helper.ChargeHelper; import com.angkorteam.fintech.layout.Size; import com.angkorteam.fintech.layout.UIBlock; import com.angkorteam.fintech.layout.UIContainer; import com.angkorteam.fintech.layout.UIRow; import com.angkorteam.fintech.pages.ProductDashboardPage; import com.angkorteam.fintech.provider.ChargeCalculationProvider; import com.angkorteam.fintech.provider.ChargeTimeProvider; import com.angkorteam.fintech.provider.CurrencyProvider; import com.angkorteam.fintech.provider.SingleChoiceProvider; import com.angkorteam.framework.models.PageBreadcrumb; import com.angkorteam.framework.wicket.ajax.form.OnChangeAjaxBehavior; import com.angkorteam.framework.wicket.markup.html.form.Button; import com.angkorteam.framework.wicket.markup.html.form.Form; import com.angkorteam.framework.wicket.markup.html.form.select2.Option; import com.angkorteam.framework.wicket.markup.html.form.select2.Select2SingleChoice; import com.google.common.collect.Lists; import io.github.openunirest.http.JsonNode; @AuthorizeInstantiation(Function.ALL_FUNCTION) public class ShareChargeCreatePage extends Page { protected Form<Void> form; protected Button saveButton; protected BookmarkablePageLink<Void> closeLink; protected UIRow row1; protected UIBlock nameBlock; protected UIContainer nameIContainer; protected String nameValue; protected TextField<String> nameField; protected UIBlock currencyBlock; protected UIContainer currencyIContainer; protected CurrencyProvider currencyProvider; protected Option currencyValue; protected Select2SingleChoice<Option> currencyField; protected UIRow row2; protected UIBlock chargeTimeBlock; protected UIContainer chargeTimeIContainer; protected ChargeTimeProvider chargeTimeProvider; protected Option chargeTimeValue; protected Select2SingleChoice<Option> chargeTimeField; protected UIBlock chargeCalculationBlock; protected UIContainer chargeCalculationIContainer; protected ChargeCalculationProvider chargeCalculationProvider; protected Option chargeCalculationValue; protected Select2SingleChoice<Option> chargeCalculationField; protected UIRow row3; protected UIBlock amountBlock; protected UIContainer amountIContainer; protected Double amountValue; protected TextField<Double> amountField; protected UIBlock row3Block1; protected UIRow row4; protected UIBlock activeBlock; protected UIContainer activeIContainer; protected Boolean activeValue; protected CheckBox activeField; protected UIBlock row4Block1; protected UIRow row5; protected UIBlock taxGroupBlock; protected UIContainer taxGroupIContainer; protected SingleChoiceProvider taxGroupProvider; protected Option taxGroupValue; protected Select2SingleChoice<Option> taxGroupField; protected UIBlock row5Block1; @Override public IModel<List<PageBreadcrumb>> buildPageBreadcrumb() { List<PageBreadcrumb> BREADCRUMB = Lists.newArrayList(); { PageBreadcrumb breadcrumb = new PageBreadcrumb(); breadcrumb.setLabel("Admin"); BREADCRUMB.add(breadcrumb); } { PageBreadcrumb breadcrumb = new PageBreadcrumb(); breadcrumb.setLabel("Product"); breadcrumb.setPage(ProductDashboardPage.class); BREADCRUMB.add(breadcrumb); } { PageBreadcrumb breadcrumb = new PageBreadcrumb(); breadcrumb.setLabel("Charge"); breadcrumb.setPage(ChargeBrowsePage.class); BREADCRUMB.add(breadcrumb); } { PageBreadcrumb breadcrumb = new PageBreadcrumb(); breadcrumb.setLabel("Charge Charge Create"); BREADCRUMB.add(breadcrumb); } return Model.ofList(BREADCRUMB); } @Override protected void initComponent() { this.form = new Form<>("form"); this.add(this.form); this.saveButton = new Button("saveButton"); this.saveButton.setOnSubmit(this::saveButtonSubmit); this.form.add(this.saveButton); this.closeLink = new BookmarkablePageLink<>("closeLink", ChargeBrowsePage.class); this.form.add(this.closeLink); this.row1 = UIRow.newUIRow("row1", this.form); this.nameBlock = this.row1.newUIBlock("nameBlock", Size.Six_6); this.nameIContainer = this.nameBlock.newUIContainer("nameIContainer"); this.nameField = new TextField<>("nameField", new PropertyModel<>(this, "nameValue")); this.nameIContainer.add(this.nameField); this.nameIContainer.newFeedback("nameFeedback", this.nameField); this.currencyBlock = this.row1.newUIBlock("currencyBlock", Size.Six_6); this.currencyIContainer = this.currencyBlock.newUIContainer("currencyIContainer"); this.currencyField = new Select2SingleChoice<>("currencyField", new PropertyModel<>(this, "currencyValue"), this.currencyProvider); this.currencyIContainer.add(this.currencyField); this.currencyIContainer.newFeedback("currencyFeedback", this.currencyField); this.row2 = UIRow.newUIRow("row2", this.form); this.chargeTimeBlock = this.row2.newUIBlock("chargeTimeBlock", Size.Six_6); this.chargeTimeIContainer = this.chargeTimeBlock.newUIContainer("chargeTimeIContainer"); this.chargeTimeField = new Select2SingleChoice<>("chargeTimeField", new PropertyModel<>(this, "chargeTimeValue"), this.chargeTimeProvider); this.chargeTimeIContainer.add(this.chargeTimeField); this.chargeTimeIContainer.newFeedback("chargeTimeFeedback", this.chargeTimeField); this.chargeCalculationBlock = this.row2.newUIBlock("chargeCalculationBlock", Size.Six_6); this.chargeCalculationIContainer = this.chargeCalculationBlock.newUIContainer("chargeCalculationIContainer"); this.chargeCalculationField = new Select2SingleChoice<>("chargeCalculationField", new PropertyModel<>(this, "chargeCalculationValue"), this.chargeCalculationProvider); this.chargeCalculationIContainer.add(this.chargeCalculationField); this.chargeCalculationIContainer.newFeedback("chargeCalculationFeedback", this.chargeCalculationField); this.row3 = UIRow.newUIRow("row3", this.form); this.amountBlock = this.row3.newUIBlock("amountBlock", Size.Six_6); this.amountIContainer = this.amountBlock.newUIContainer("amountIContainer"); this.amountField = new TextField<>("amountField", new PropertyModel<>(this, "amountValue")); this.amountIContainer.add(this.amountField); this.amountIContainer.newFeedback("amountFeedback", this.amountField); this.row3Block1 = this.row3.newUIBlock("row3Block1", Size.Six_6); this.row4 = UIRow.newUIRow("row4", this.form); this.activeBlock = this.row4.newUIBlock("activeBlock", Size.Six_6); this.activeIContainer = this.activeBlock.newUIContainer("activeIContainer"); this.activeField = new CheckBox("activeField", new PropertyModel<>(this, "activeValue")); this.activeIContainer.add(this.activeField); this.activeIContainer.newFeedback("activeFeedback", this.activeField); this.row4Block1 = this.row4.newUIBlock("row4Block1", Size.Six_6); this.row5 = UIRow.newUIRow("row5", this.form); this.taxGroupBlock = this.row5.newUIBlock("taxGroupBlock", Size.Six_6); this.taxGroupIContainer = this.taxGroupBlock.newUIContainer("taxGroupIContainer"); this.taxGroupField = new Select2SingleChoice<>("taxGroupField", new PropertyModel<>(this, "taxGroupValue"), this.taxGroupProvider); this.taxGroupIContainer.add(this.taxGroupField); this.taxGroupIContainer.newFeedback("taxGroupFeedback", this.taxGroupField); this.row5Block1 = this.row5.newUIBlock("row5Block1", Size.Six_6); } @Override protected void initData() { this.taxGroupProvider = new SingleChoiceProvider(MTaxGroup.NAME, MTaxGroup.Field.ID, MTaxGroup.Field.NAME); this.chargeCalculationProvider = new ChargeCalculationProvider(); this.chargeCalculationProvider.setValues(ChargeCalculation.Flat, ChargeCalculation.ApprovedAmount); this.chargeTimeProvider = new ChargeTimeProvider(); this.chargeTimeProvider.setValues(ChargeTime.ShareAccountActivate, ChargeTime.SharePurchase, ChargeTime.ShareRedeem); this.currencyProvider = new CurrencyProvider(); } @Override protected void configureMetaData() { this.taxGroupField.setLabel(Model.of("Tax Group")); this.activeField.setRequired(true); this.amountField.setRequired(true); this.amountField.setLabel(Model.of("Amount")); this.chargeCalculationField.setLabel(Model.of("Charge calculation")); this.chargeCalculationField.setRequired(true); this.chargeCalculationField.add(new OnChangeAjaxBehavior()); this.chargeTimeField.setLabel(Model.of("Charge time type")); this.chargeTimeField.setRequired(true); this.chargeTimeField.add(new OnChangeAjaxBehavior()); this.currencyField.setLabel(Model.of("Currency")); this.currencyField.setRequired(true); this.nameField.setLabel(Model.of("Name")); this.nameField.setRequired(true); } protected void saveButtonSubmit(Button button) { ChargeTime chargeTime = null; if (this.chargeTimeValue != null) { chargeTime = ChargeTime.valueOf(this.chargeTimeValue.getId()); } ChargeBuilder builder = new ChargeBuilder(); builder.withChargeAppliesTo(ChargeType.Share); builder.withName(this.nameValue); if (this.currencyValue != null) { builder.withCurrencyCode(this.currencyValue.getId()); } if (this.chargeTimeValue != null) { builder.withChargeTimeType(chargeTime); } if (this.chargeCalculationValue != null) { builder.withChargeCalculationType(ChargeCalculation.valueOf(this.chargeCalculationValue.getId())); } builder.withAmount(this.amountValue); builder.withActive(this.activeValue); if (this.taxGroupValue != null) { builder.withTaxGroupId(this.taxGroupValue.getId()); } JsonNode node = ChargeHelper.create((Session) getSession(), builder.build()); if (reportError(node)) { return; } setResponsePage(ChargeBrowsePage.class); } }
/* * DBeaver - Universal Database Manager * Copyright (C) 2016 Karl Griesser (fullref@gmail.com) * Copyright (C) 2010-2022 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.exasol.model; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ext.exasol.ExasolConstants; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.DBPQualifiedObject; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.exec.DBCLogicalOperator; import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.meta.PropertyLength; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSDataType; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.DBSTypedObject; import java.sql.ResultSet; import java.sql.Types; /** * Exasol data types * * @author Karl Griesser */ public class ExasolDataType extends ExasolObject<DBSObject> implements DBSDataType, DBPQualifiedObject { private static final Log LOG = Log.getLog(ExasolDataType.class); private DBSObject parentNode; // see below private ExasolSchema exasolSchema; private TypeDesc typeDesc; private long exasolTypeId; private Integer length; private Integer scale; private String name; // ----------------------- // Constructors // ----------------------- protected ExasolDataType(DBSObject parent, String name, boolean persisted) { super(parent, name, persisted); } public ExasolDataType(DBSObject owner, ResultSet dbResult) throws DBException { super(owner, JDBCUtils.safeGetString(dbResult, "TYPE_NAME"), true); this.exasolTypeId = JDBCUtils.safeGetLong(dbResult, "TYPE_ID"); this.length = JDBCUtils.safeGetInt(dbResult, "PRECISION"); this.scale = JDBCUtils.safeGetInt(dbResult, "MINIMUM_SCALE"); TypeDesc tempTypeDesc = null; String typeName = JDBCUtils.safeGetString(dbResult, "TYPE_NAME"); int precision = JDBCUtils.safeGetInt(dbResult, "PRECISION"); int minimumScale = JDBCUtils.safeGetInt(dbResult, "MINIMUM_SCALE"); int maximumScale = JDBCUtils.safeGetInt(dbResult, "MAXIMUM_SCALE"); this.name = typeName; switch (name) { case "BIGINT": tempTypeDesc = new TypeDesc(DBPDataKind.NUMERIC, Types.BIGINT, precision, minimumScale, maximumScale, typeName); break; case "INTEGER": tempTypeDesc = new TypeDesc(DBPDataKind.NUMERIC, Types.INTEGER, precision, minimumScale, maximumScale, typeName); break; case ExasolConstants.TYPE_DECIMAL: tempTypeDesc = new TypeDesc(DBPDataKind.NUMERIC, Types.DECIMAL, precision, minimumScale, maximumScale, typeName); break; case "DOUBLE PRECISION": tempTypeDesc = new TypeDesc(DBPDataKind.NUMERIC, Types.DOUBLE, precision, minimumScale, maximumScale, typeName); break; case "FLOAT": tempTypeDesc = new TypeDesc(DBPDataKind.NUMERIC, Types.FLOAT, precision, minimumScale, maximumScale, typeName); break; case "INTERVAL DAY TO SECOND": tempTypeDesc = new TypeDesc(DBPDataKind.STRING, Types.VARCHAR, precision, minimumScale, maximumScale, typeName); break; case "INTERVAL YEAR TO MONTH": tempTypeDesc = new TypeDesc(DBPDataKind.STRING, Types.VARCHAR, precision, minimumScale, maximumScale, typeName); break; case "SMALLINT": tempTypeDesc = new TypeDesc(DBPDataKind.NUMERIC, Types.SMALLINT, precision, minimumScale, maximumScale, typeName); break; case "TINYINT": tempTypeDesc = new TypeDesc(DBPDataKind.NUMERIC, Types.TINYINT, precision, minimumScale, maximumScale, typeName); break; case "GEOMETRY": tempTypeDesc = new TypeDesc(DBPDataKind.STRING, Types.VARCHAR, precision, minimumScale, maximumScale, typeName); break; case "BOOLEAN": tempTypeDesc = new TypeDesc(DBPDataKind.BOOLEAN, Types.BOOLEAN, precision, minimumScale, maximumScale, typeName); break; case ExasolConstants.TYPE_CHAR: tempTypeDesc = new TypeDesc(DBPDataKind.STRING, Types.CHAR, precision, minimumScale, maximumScale, typeName); break; case ExasolConstants.TYPE_VARCHAR: tempTypeDesc = new TypeDesc(DBPDataKind.STRING, Types.VARCHAR, precision, minimumScale, maximumScale, typeName); break; case "LONG VARCHAR": tempTypeDesc = new TypeDesc(DBPDataKind.STRING, Types.LONGNVARCHAR, precision, minimumScale, maximumScale, typeName); break; case "DATE": tempTypeDesc = new TypeDesc(DBPDataKind.DATETIME, Types.DATE, precision, minimumScale, maximumScale, typeName); break; case "TIMESTAMP": tempTypeDesc = new TypeDesc(DBPDataKind.DATETIME, Types.TIMESTAMP, precision, minimumScale, maximumScale, typeName); break; case "TIMESTAMP WITH LOCAL TIME ZONE": tempTypeDesc = new TypeDesc(DBPDataKind.DATETIME, Types.TIMESTAMP_WITH_TIMEZONE, precision, minimumScale, maximumScale, typeName); break; case ExasolConstants.TYPE_HASHTYPE: tempTypeDesc = new TypeDesc(DBPDataKind.STRING, Types.BINARY, precision, minimumScale, maximumScale, typeName); break; default: LOG.error("DataType '" + name + "' is unknown to DBeaver"); } this.typeDesc = tempTypeDesc; } @Override public DBSObject getParentObject() { return parentNode; } @Override public String getTypeName() { return name; } @Override public String getFullTypeName() { return DBUtils.getFullTypeName(this); } public int getEquivalentSqlType() { return typeDesc.sqlType; } @Override public Integer getPrecision() { if (typeDesc.precision != null) { return typeDesc.precision; } else { return 0; } } @Nullable @Override public DBSDataType getComponentType(@NotNull DBRProgressMonitor monitor) throws DBException { return null; } @Override public int getMinScale() { if (typeDesc.minScale != null) { return typeDesc.minScale; } else { return 0; } } @Override public int getMaxScale() { if (typeDesc.maxScale != null) { return typeDesc.maxScale; } else { return 0; } } @NotNull @Override public DBCLogicalOperator[] getSupportedOperators(DBSTypedObject attribute) { return DBUtils.getDefaultOperators(this); } // ----------------- // Properties // ----------------- @NotNull @Override @Property(viewable = true, editable = false, valueTransformer = DBObjectNameCaseTransformer.class, order = 1) public String getName() { return name; } @Property(viewable = true, editable = false, order = 2) public ExasolSchema getSchema() { return exasolSchema; } @Override @Property(viewable = true, editable = false, order = 4) public DBPDataKind getDataKind() { if (typeDesc == null) { return DBPDataKind.UNKNOWN; } else { return typeDesc.dataKind; } } @Override @Property(viewable = true, editable = false, order = 5) public long getMaxLength() { return length; } @Override public long getTypeModifiers() { return 0; } @Override @Property(viewable = true, editable = false, order = 6) public Integer getScale() { return scale; } @Override @Property(viewable = false, editable = false, order = 10) public int getTypeID() { return typeDesc.sqlType; } @Property(viewable = false, editable = false, order = 11) public long getExasolTypeId() { return exasolTypeId; } @Nullable @Override @Property(viewable = false, editable = false, length = PropertyLength.MULTILINE) public String getDescription() { return null; } // -------------- // Helper Objects // -------------- private static final class TypeDesc { private final DBPDataKind dataKind; private final Integer sqlType; private final Integer precision; private final Integer minScale; private final Integer maxScale; @SuppressWarnings("unused") private final String name; private TypeDesc(DBPDataKind dataKind, Integer sqlType, Integer precision, Integer minScale, Integer maxScale, String name) { this.name = name; this.dataKind = dataKind; this.sqlType = sqlType; this.precision = precision; this.minScale = minScale; this.maxScale = maxScale; } } @Override public boolean isPersisted() { return true; } @Override public Object geTypeExtension() { // TODO Auto-generated method stub return null; } @Override public String getFullyQualifiedName(DBPEvaluationContext context) { return name; } }
package com.tinkermode.lumos; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.Switch; import android.widget.TextView; import com.tinkermode.MODEData; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.tinkermode.lumos.R; import com.tinkermode.lumos.managers.DeviceEventDelegator; import com.tinkermode.lumos.managers.DeviceManager; import com.tinkermode.lumos.utils.Logger; import com.tinkermode.lumos.utils.MiscUtils; import com.tinkermode.lumos.utils.ObjectAccessor; import com.tinkermode.lumos.utils.RefreshDone; abstract public class DetailHomeFragment extends ListFragment { final Logger logger = new Logger(getClass().getSimpleName()); List<MODEData.MODEObject> objects; boolean selectionMode; static class Adapter extends ArrayAdapter<MODEData.MODEObject> { static class CustomHolder { CheckBox checkBox; TextView textView; TextView textSubView; int id; boolean selectionMode; Switch switchWidget; } Activity activity; private int resID; private List<MODEData.MODEObject> objects; DetailHomeFragment fragment; final android.os.Handler notifyHandler = new android.os.Handler(); public Set<Integer> checkedId = new HashSet<>(); public Adapter(Activity activity, int resource, List<MODEData.MODEObject> objects, DetailHomeFragment fragment) { super(activity, resource, objects); this.activity = activity; this.resID = resource; this.objects = objects; this.fragment = fragment; } @Override public View getView(final int position, View row, ViewGroup parent) { final ObjectAccessor accessor = ObjectAccessor.CreateObjectAccessor(objects.get(position)); CustomHolder holder = null; if (row == null) { final LayoutInflater inflate = activity.getLayoutInflater(); row = inflate.inflate(resID, null); final int id = accessor.getId(); holder = new CustomHolder(); holder.id = id; // setup CheckBox holder.checkBox = (CheckBox)row.findViewById(R.id.check_box_selection); holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { checkedId.add(id); } else { checkedId.remove(id); } fragment.updateEditMenuIcon(); } }); // setup switch widget final Switch switchWidget = (Switch)row.findViewById(R.id.switch_light); if (switchWidget != null) { holder.switchWidget = switchWidget; final CompoundButton.OnCheckedChangeListener l = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { DeviceManager.getInstance().sendSwitchCommand(activity, accessor.getId(), isChecked); } }; switchWidget.setOnCheckedChangeListener(l); DeviceManager.getInstance().addDeviceDelegate(id, new DeviceEventDelegator() { @Override public void receivedEvent(int deviceId, final boolean status) { notifyHandler.post(new Runnable() { @Override public void run() { // This looks ugly, but otherwise it would repeat on/off between // onCheckedChanged and receivedEvent. switchWidget.setOnCheckedChangeListener(null); switchWidget.setChecked(status); switchWidget.setOnCheckedChangeListener(l); notifyDataSetChanged(); } }); } @Override public void receivedButtonPressed(int deviceId) { } }); } final Object obj = row.findViewById(R.id.list_sub_text); if (obj != null) { holder.textSubView = (TextView)obj; } holder.textView = (TextView)row.findViewById(R.id.list_text); row.setTag(holder); } else { holder = (CustomHolder)row.getTag(); } holder.textView.setText(accessor.getName()); if (holder.textSubView != null) { holder.textSubView.setText(accessor.getSubText()); } final boolean selectionMode = fragment.getSelectionMode(); if (holder.selectionMode != selectionMode) { holder.checkBox.setVisibility(!selectionMode ? View.INVISIBLE : View.VISIBLE); if (holder.switchWidget != null) { holder.switchWidget.setVisibility(selectionMode ? View.INVISIBLE : View.VISIBLE); } holder.selectionMode = selectionMode; } return row; } } Adapter getAdapter() { return (Adapter)getListAdapter(); } int row_resource_id; void setRowResourceID(int row_resource_id) { this.row_resource_id = row_resource_id; } SwipeRefreshLayout swipeRefreshLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { selectionMode = false; setHasOptionsMenu(true); // You don't have to call fetchObjects() here // Because ViewPagerAdapter will call it when fragment is chosen. View view = inflater.inflate(R.layout.fragment_deital_home, container, false); swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipe); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { fetchObjects(new RefreshDone() { @Override public void done() { swipeRefreshLayout.setRefreshing(false); } }); } }); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); MiscUtils.switchListScrollAndPullToRefresh(getListView(), swipeRefreshLayout); } // Kinda hacky, need to research better way. void updateEditMenuIcon() { Activity activity = getActivity(); if (activity != null) { ((DetailHomeActivity) getActivity()).updateMenuItems(); } } boolean getSelectionMode() { return selectionMode; } List<Integer> createDiffIds(List<MODEData.MODEObject> originalObjects, List<MODEData.MODEObject> objects) { final List<Integer> ret = new ArrayList<>(); for (MODEData.MODEObject originalObject : originalObjects) { ObjectAccessor orgAccessor = ObjectAccessor.CreateObjectAccessor(originalObject); boolean found = false; for (MODEData.MODEObject object : objects) { ObjectAccessor accessor = ObjectAccessor.CreateObjectAccessor(object); if (orgAccessor.getId() == accessor.getId()) { found = true; break; } } if (!found) { ret.add(orgAccessor.getId()); } } return ret; } void postUpdate(final List<MODEData.MODEObject> objects) { logger.d("postUpdate"); Activity activity = getActivity(); if (activity == null) { logger.d("Activity is null. Do nothing."); return; } if (getAdapter() == null) { this.objects = objects; Adapter adapter = new Adapter(activity, row_resource_id, this.objects, this); setListAdapter(adapter); } else { final List<MODEData.MODEObject> originalObjects = (List)((ArrayList)this.objects).clone(); this.objects.clear(); for (MODEData.MODEObject device : objects) { this.objects.add(device); } // remove attached delegate, otherwise the delegate will be leaked. final List<Integer> ids = createDiffIds(originalObjects, this.objects); for (int id: ids) { DeviceManager.getInstance().removeDeviceDelegate(id); } getAdapter().notifyDataSetChanged(); } } void cancelSelectionModeInFragment() { getListView().setChoiceMode(ListView.CHOICE_MODE_NONE); selectionMode = false; Adapter adapter = getAdapter(); if (adapter != null) { adapter.notifyDataSetChanged(); } } public void cancelSelectionMode() { final Activity activity = getActivity(); if (activity == null) { logger.e("Activity is null when cancelSlectionMode is called"); return; } ((DetailHomeActivity) activity).cancelSelectionMode(); cancelSelectionModeInFragment(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_change: { getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); selectionMode = true; updateEditMenuIcon(); final Adapter adapter = new Adapter(getActivity(), row_resource_id, objects, this); setListAdapter(adapter); return true; } case R.id.action_delete: { final List<Integer> homeIdList = new ArrayList<Integer>(); for (int homeId: getAdapter().checkedId) { homeIdList.add(homeId); } deleteObjects(homeIdList); cancelSelectionModeInFragment(); return true; } case android.R.id.home: { // This home handling is needed to return from selection mode cancelSelectionModeInFragment(); return true; } } return super.onOptionsItemSelected(item); } int getHomeId() { final Activity activity = getActivity(); if (activity == null) { return 0; } final Bundle bundle = activity.getIntent().getExtras(); if (bundle != null) { return bundle.getInt(DetailHomeActivity.KEY_DETAIL_HOME_ID, 0); } return 0; } String getHomeName() { final Activity activity = getActivity(); if (activity == null) { return ""; } final Bundle bundle = activity.getIntent().getExtras(); if (bundle != null) { return bundle.getString(DetailHomeActivity.KEY_DETAIL_HOME_NAME, ""); } return ""; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { fetchObjects(null); super.onActivityResult(requestCode, resultCode, data); } abstract void deleteObjects(final List<Integer> list); abstract public void fetchObjects(RefreshDone refreshDone); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.streaming; import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.Collection; import java.util.Comparator; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.io.util.DataOutputStreamAndChannel; import org.apache.cassandra.streaming.messages.StreamInitMessage; import org.apache.cassandra.streaming.messages.StreamMessage; import org.apache.cassandra.utils.FBUtilities; /** * ConnectionHandler manages incoming/outgoing message exchange for the {@link StreamSession}. * * <p> * Internally, ConnectionHandler manages thread to receive incoming {@link StreamMessage} and thread to * send outgoing message. Messages are encoded/decoded on those thread and handed to * {@link StreamSession#messageReceived(org.apache.cassandra.streaming.messages.StreamMessage)}. */ public class ConnectionHandler { private static final Logger logger = LoggerFactory.getLogger(ConnectionHandler.class); private final StreamSession session; private IncomingMessageHandler incoming; private OutgoingMessageHandler outgoing; ConnectionHandler(StreamSession session) { this.session = session; this.incoming = new IncomingMessageHandler(session); this.outgoing = new OutgoingMessageHandler(session); } /** * Set up incoming message handler and initiate streaming. * * This method is called once on initiator. * * @throws IOException */ public void initiate() throws IOException { logger.debug("[Stream #{}] Sending stream init for incoming stream", session.planId()); Socket incomingSocket = session.createConnection(); incoming.start(incomingSocket, StreamMessage.CURRENT_VERSION); incoming.sendInitMessage(incomingSocket, true); logger.debug("[Stream #{}] Sending stream init for outgoing stream", session.planId()); Socket outgoingSocket = session.createConnection(); outgoing.start(outgoingSocket, StreamMessage.CURRENT_VERSION); outgoing.sendInitMessage(outgoingSocket, false); } /** * Set up outgoing message handler on receiving side. * * @param socket socket to use for {@link org.apache.cassandra.streaming.ConnectionHandler.OutgoingMessageHandler}. * @param version Streaming message version * @throws IOException */ public void initiateOnReceivingSide(Socket socket, boolean isForOutgoing, int version) throws IOException { if (isForOutgoing) outgoing.start(socket, version); else incoming.start(socket, version); } public ListenableFuture<?> close() { logger.debug("[Stream #{}] Closing stream connection handler on {}", session.planId(), session.peer); ListenableFuture<?> inClosed = incoming == null ? Futures.immediateFuture(null) : incoming.close(); ListenableFuture<?> outClosed = outgoing == null ? Futures.immediateFuture(null) : outgoing.close(); return Futures.allAsList(inClosed, outClosed); } /** * Enqueue messages to be sent. * * @param messages messages to send */ public void sendMessages(Collection<? extends StreamMessage> messages) { for (StreamMessage message : messages) sendMessage(message); } public void sendMessage(StreamMessage message) { if (outgoing.isClosed()) throw new RuntimeException("Outgoing stream handler has been closed"); outgoing.enqueue(message); } /** * @return true if outgoing connection is opened and ready to send messages */ public boolean isOutgoingConnected() { return outgoing != null && !outgoing.isClosed(); } abstract static class MessageHandler implements Runnable { protected final StreamSession session; protected int protocolVersion; protected Socket socket; private final AtomicReference<SettableFuture<?>> closeFuture = new AtomicReference<>(); protected MessageHandler(StreamSession session) { this.session = session; } protected abstract String name(); protected static DataOutputStreamAndChannel getWriteChannel(Socket socket) throws IOException { WritableByteChannel out = socket.getChannel(); // socket channel is null when encrypted(SSL) if (out == null) out = Channels.newChannel(socket.getOutputStream()); return new DataOutputStreamAndChannel(socket.getOutputStream(), out); } protected static ReadableByteChannel getReadChannel(Socket socket) throws IOException { ReadableByteChannel in = socket.getChannel(); // socket channel is null when encrypted(SSL) return in == null ? Channels.newChannel(socket.getInputStream()) : in; } public void sendInitMessage(Socket socket, boolean isForOutgoing) throws IOException { StreamInitMessage message = new StreamInitMessage( FBUtilities.getBroadcastAddress(), session.sessionIndex(), session.planId(), session.description(), isForOutgoing); ByteBuffer messageBuf = message.createMessage(false, protocolVersion); getWriteChannel(socket).write(messageBuf); } public void start(Socket socket, int protocolVersion) { this.socket = socket; this.protocolVersion = protocolVersion; new Thread(this, name() + "-" + session.peer).start(); } public ListenableFuture<?> close() { // Assume it wasn't closed. Not a huge deal if we create a future on a race SettableFuture<?> future = SettableFuture.create(); return closeFuture.compareAndSet(null, future) ? future : closeFuture.get(); } public boolean isClosed() { return closeFuture.get() != null; } protected void signalCloseDone() { closeFuture.get().set(null); // We can now close the socket try { socket.close(); } catch (IOException ignore) {} } } /** * Incoming streaming message handler */ static class IncomingMessageHandler extends MessageHandler { IncomingMessageHandler(StreamSession session) { super(session); } protected String name() { return "STREAM-IN"; } public void run() { try { ReadableByteChannel in = getReadChannel(socket); while (!isClosed()) { // receive message StreamMessage message = StreamMessage.deserialize(in, protocolVersion, session); // Might be null if there is an error during streaming (see FileMessage.deserialize). It's ok // to ignore here since we'll have asked for a retry. if (message != null) { logger.debug("[Stream #{}] Received {}", session.planId(), message); session.messageReceived(message); } } } catch (SocketException e) { // socket is closed close(); } catch (Throwable e) { session.onError(e); } finally { signalCloseDone(); } } } /** * Outgoing file transfer thread */ static class OutgoingMessageHandler extends MessageHandler { /* * All out going messages are queued up into messageQueue. * The size will grow when received streaming request. * * Queue is also PriorityQueue so that prior messages can go out fast. */ private final PriorityBlockingQueue<StreamMessage> messageQueue = new PriorityBlockingQueue<>(64, new Comparator<StreamMessage>() { public int compare(StreamMessage o1, StreamMessage o2) { return o2.getPriority() - o1.getPriority(); } }); OutgoingMessageHandler(StreamSession session) { super(session); } protected String name() { return "STREAM-OUT"; } public void enqueue(StreamMessage message) { messageQueue.put(message); } public void run() { try { DataOutputStreamAndChannel out = getWriteChannel(socket); StreamMessage next; while (!isClosed()) { if ((next = messageQueue.poll(1, TimeUnit.SECONDS)) != null) { logger.debug("[Stream #{}] Sending {}", session.planId(), next); sendMessage(out, next); if (next.type == StreamMessage.Type.SESSION_FAILED) close(); } } // Sends the last messages on the queue while ((next = messageQueue.poll()) != null) sendMessage(out, next); } catch (InterruptedException e) { throw new AssertionError(e); } catch (Throwable e) { session.onError(e); } finally { signalCloseDone(); } } private void sendMessage(DataOutputStreamAndChannel out, StreamMessage message) { try { StreamMessage.serialize(message, out, protocolVersion, session); } catch (SocketException e) { session.onError(e); close(); } catch (IOException e) { session.onError(e); } } } }
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package es.davinciti.liferay.service.base; import com.liferay.portal.kernel.bean.BeanReference; import com.liferay.portal.kernel.bean.IdentifiableBean; import com.liferay.portal.kernel.dao.jdbc.SqlUpdate; import com.liferay.portal.kernel.dao.jdbc.SqlUpdateFactoryUtil; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.service.BaseServiceImpl; import com.liferay.portal.service.persistence.UserPersistence; import es.davinciti.liferay.model.SapEmployee; import es.davinciti.liferay.service.SapEmployeeService; import es.davinciti.liferay.service.persistence.ApplicationStatusPersistence; import es.davinciti.liferay.service.persistence.CalendarioPersistence; import es.davinciti.liferay.service.persistence.ConnectionActionTypesPersistence; import es.davinciti.liferay.service.persistence.ConnectionConfigsPersistence; import es.davinciti.liferay.service.persistence.ConnectionDataPersistence; import es.davinciti.liferay.service.persistence.ConnectionTypesPersistence; import es.davinciti.liferay.service.persistence.CurrenciesCompanyPersistence; import es.davinciti.liferay.service.persistence.CurrencyPersistence; import es.davinciti.liferay.service.persistence.DiasVacacionesPersistence; import es.davinciti.liferay.service.persistence.HistoricoNotaPersistence; import es.davinciti.liferay.service.persistence.LineaGastoCategoriaPersistence; import es.davinciti.liferay.service.persistence.LineaGastoClientePersistence; import es.davinciti.liferay.service.persistence.LineaGastoFamiliaPersistence; import es.davinciti.liferay.service.persistence.LineaGastoPayModePersistence; import es.davinciti.liferay.service.persistence.LineaGastoPersistence; import es.davinciti.liferay.service.persistence.LineaGastoProyectoPersistence; import es.davinciti.liferay.service.persistence.NotaGastoPersistence; import es.davinciti.liferay.service.persistence.OrganizationSageCompanyPersistence; import es.davinciti.liferay.service.persistence.SageEmployeePersistence; import es.davinciti.liferay.service.persistence.SapEmployeePersistence; import es.davinciti.liferay.service.persistence.TipoDiaCalendarPersistence; import javax.sql.DataSource; /** * Provides the base implementation for the sap employee remote service. * * <p> * This implementation exists only as a container for the default service methods generated by ServiceBuilder. All custom service methods should be put in {@link es.davinciti.liferay.service.impl.SapEmployeeServiceImpl}. * </p> * * @author Cmes * @see es.davinciti.liferay.service.impl.SapEmployeeServiceImpl * @see es.davinciti.liferay.service.SapEmployeeServiceUtil * @generated */ public abstract class SapEmployeeServiceBaseImpl extends BaseServiceImpl implements SapEmployeeService, IdentifiableBean { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this class directly. Always use {@link es.davinciti.liferay.service.SapEmployeeServiceUtil} to access the sap employee remote service. */ /** * Returns the application status local service. * * @return the application status local service */ public es.davinciti.liferay.service.ApplicationStatusLocalService getApplicationStatusLocalService() { return applicationStatusLocalService; } /** * Sets the application status local service. * * @param applicationStatusLocalService the application status local service */ public void setApplicationStatusLocalService( es.davinciti.liferay.service.ApplicationStatusLocalService applicationStatusLocalService) { this.applicationStatusLocalService = applicationStatusLocalService; } /** * Returns the application status remote service. * * @return the application status remote service */ public es.davinciti.liferay.service.ApplicationStatusService getApplicationStatusService() { return applicationStatusService; } /** * Sets the application status remote service. * * @param applicationStatusService the application status remote service */ public void setApplicationStatusService( es.davinciti.liferay.service.ApplicationStatusService applicationStatusService) { this.applicationStatusService = applicationStatusService; } /** * Returns the application status persistence. * * @return the application status persistence */ public ApplicationStatusPersistence getApplicationStatusPersistence() { return applicationStatusPersistence; } /** * Sets the application status persistence. * * @param applicationStatusPersistence the application status persistence */ public void setApplicationStatusPersistence( ApplicationStatusPersistence applicationStatusPersistence) { this.applicationStatusPersistence = applicationStatusPersistence; } /** * Returns the calendario local service. * * @return the calendario local service */ public es.davinciti.liferay.service.CalendarioLocalService getCalendarioLocalService() { return calendarioLocalService; } /** * Sets the calendario local service. * * @param calendarioLocalService the calendario local service */ public void setCalendarioLocalService( es.davinciti.liferay.service.CalendarioLocalService calendarioLocalService) { this.calendarioLocalService = calendarioLocalService; } /** * Returns the calendario remote service. * * @return the calendario remote service */ public es.davinciti.liferay.service.CalendarioService getCalendarioService() { return calendarioService; } /** * Sets the calendario remote service. * * @param calendarioService the calendario remote service */ public void setCalendarioService( es.davinciti.liferay.service.CalendarioService calendarioService) { this.calendarioService = calendarioService; } /** * Returns the calendario persistence. * * @return the calendario persistence */ public CalendarioPersistence getCalendarioPersistence() { return calendarioPersistence; } /** * Sets the calendario persistence. * * @param calendarioPersistence the calendario persistence */ public void setCalendarioPersistence( CalendarioPersistence calendarioPersistence) { this.calendarioPersistence = calendarioPersistence; } /** * Returns the connection action types local service. * * @return the connection action types local service */ public es.davinciti.liferay.service.ConnectionActionTypesLocalService getConnectionActionTypesLocalService() { return connectionActionTypesLocalService; } /** * Sets the connection action types local service. * * @param connectionActionTypesLocalService the connection action types local service */ public void setConnectionActionTypesLocalService( es.davinciti.liferay.service.ConnectionActionTypesLocalService connectionActionTypesLocalService) { this.connectionActionTypesLocalService = connectionActionTypesLocalService; } /** * Returns the connection action types remote service. * * @return the connection action types remote service */ public es.davinciti.liferay.service.ConnectionActionTypesService getConnectionActionTypesService() { return connectionActionTypesService; } /** * Sets the connection action types remote service. * * @param connectionActionTypesService the connection action types remote service */ public void setConnectionActionTypesService( es.davinciti.liferay.service.ConnectionActionTypesService connectionActionTypesService) { this.connectionActionTypesService = connectionActionTypesService; } /** * Returns the connection action types persistence. * * @return the connection action types persistence */ public ConnectionActionTypesPersistence getConnectionActionTypesPersistence() { return connectionActionTypesPersistence; } /** * Sets the connection action types persistence. * * @param connectionActionTypesPersistence the connection action types persistence */ public void setConnectionActionTypesPersistence( ConnectionActionTypesPersistence connectionActionTypesPersistence) { this.connectionActionTypesPersistence = connectionActionTypesPersistence; } /** * Returns the connection configs local service. * * @return the connection configs local service */ public es.davinciti.liferay.service.ConnectionConfigsLocalService getConnectionConfigsLocalService() { return connectionConfigsLocalService; } /** * Sets the connection configs local service. * * @param connectionConfigsLocalService the connection configs local service */ public void setConnectionConfigsLocalService( es.davinciti.liferay.service.ConnectionConfigsLocalService connectionConfigsLocalService) { this.connectionConfigsLocalService = connectionConfigsLocalService; } /** * Returns the connection configs remote service. * * @return the connection configs remote service */ public es.davinciti.liferay.service.ConnectionConfigsService getConnectionConfigsService() { return connectionConfigsService; } /** * Sets the connection configs remote service. * * @param connectionConfigsService the connection configs remote service */ public void setConnectionConfigsService( es.davinciti.liferay.service.ConnectionConfigsService connectionConfigsService) { this.connectionConfigsService = connectionConfigsService; } /** * Returns the connection configs persistence. * * @return the connection configs persistence */ public ConnectionConfigsPersistence getConnectionConfigsPersistence() { return connectionConfigsPersistence; } /** * Sets the connection configs persistence. * * @param connectionConfigsPersistence the connection configs persistence */ public void setConnectionConfigsPersistence( ConnectionConfigsPersistence connectionConfigsPersistence) { this.connectionConfigsPersistence = connectionConfigsPersistence; } /** * Returns the connection data local service. * * @return the connection data local service */ public es.davinciti.liferay.service.ConnectionDataLocalService getConnectionDataLocalService() { return connectionDataLocalService; } /** * Sets the connection data local service. * * @param connectionDataLocalService the connection data local service */ public void setConnectionDataLocalService( es.davinciti.liferay.service.ConnectionDataLocalService connectionDataLocalService) { this.connectionDataLocalService = connectionDataLocalService; } /** * Returns the connection data remote service. * * @return the connection data remote service */ public es.davinciti.liferay.service.ConnectionDataService getConnectionDataService() { return connectionDataService; } /** * Sets the connection data remote service. * * @param connectionDataService the connection data remote service */ public void setConnectionDataService( es.davinciti.liferay.service.ConnectionDataService connectionDataService) { this.connectionDataService = connectionDataService; } /** * Returns the connection data persistence. * * @return the connection data persistence */ public ConnectionDataPersistence getConnectionDataPersistence() { return connectionDataPersistence; } /** * Sets the connection data persistence. * * @param connectionDataPersistence the connection data persistence */ public void setConnectionDataPersistence( ConnectionDataPersistence connectionDataPersistence) { this.connectionDataPersistence = connectionDataPersistence; } /** * Returns the connection types local service. * * @return the connection types local service */ public es.davinciti.liferay.service.ConnectionTypesLocalService getConnectionTypesLocalService() { return connectionTypesLocalService; } /** * Sets the connection types local service. * * @param connectionTypesLocalService the connection types local service */ public void setConnectionTypesLocalService( es.davinciti.liferay.service.ConnectionTypesLocalService connectionTypesLocalService) { this.connectionTypesLocalService = connectionTypesLocalService; } /** * Returns the connection types remote service. * * @return the connection types remote service */ public es.davinciti.liferay.service.ConnectionTypesService getConnectionTypesService() { return connectionTypesService; } /** * Sets the connection types remote service. * * @param connectionTypesService the connection types remote service */ public void setConnectionTypesService( es.davinciti.liferay.service.ConnectionTypesService connectionTypesService) { this.connectionTypesService = connectionTypesService; } /** * Returns the connection types persistence. * * @return the connection types persistence */ public ConnectionTypesPersistence getConnectionTypesPersistence() { return connectionTypesPersistence; } /** * Sets the connection types persistence. * * @param connectionTypesPersistence the connection types persistence */ public void setConnectionTypesPersistence( ConnectionTypesPersistence connectionTypesPersistence) { this.connectionTypesPersistence = connectionTypesPersistence; } /** * Returns the currencies company local service. * * @return the currencies company local service */ public es.davinciti.liferay.service.CurrenciesCompanyLocalService getCurrenciesCompanyLocalService() { return currenciesCompanyLocalService; } /** * Sets the currencies company local service. * * @param currenciesCompanyLocalService the currencies company local service */ public void setCurrenciesCompanyLocalService( es.davinciti.liferay.service.CurrenciesCompanyLocalService currenciesCompanyLocalService) { this.currenciesCompanyLocalService = currenciesCompanyLocalService; } /** * Returns the currencies company remote service. * * @return the currencies company remote service */ public es.davinciti.liferay.service.CurrenciesCompanyService getCurrenciesCompanyService() { return currenciesCompanyService; } /** * Sets the currencies company remote service. * * @param currenciesCompanyService the currencies company remote service */ public void setCurrenciesCompanyService( es.davinciti.liferay.service.CurrenciesCompanyService currenciesCompanyService) { this.currenciesCompanyService = currenciesCompanyService; } /** * Returns the currencies company persistence. * * @return the currencies company persistence */ public CurrenciesCompanyPersistence getCurrenciesCompanyPersistence() { return currenciesCompanyPersistence; } /** * Sets the currencies company persistence. * * @param currenciesCompanyPersistence the currencies company persistence */ public void setCurrenciesCompanyPersistence( CurrenciesCompanyPersistence currenciesCompanyPersistence) { this.currenciesCompanyPersistence = currenciesCompanyPersistence; } /** * Returns the currency local service. * * @return the currency local service */ public es.davinciti.liferay.service.CurrencyLocalService getCurrencyLocalService() { return currencyLocalService; } /** * Sets the currency local service. * * @param currencyLocalService the currency local service */ public void setCurrencyLocalService( es.davinciti.liferay.service.CurrencyLocalService currencyLocalService) { this.currencyLocalService = currencyLocalService; } /** * Returns the currency remote service. * * @return the currency remote service */ public es.davinciti.liferay.service.CurrencyService getCurrencyService() { return currencyService; } /** * Sets the currency remote service. * * @param currencyService the currency remote service */ public void setCurrencyService( es.davinciti.liferay.service.CurrencyService currencyService) { this.currencyService = currencyService; } /** * Returns the currency persistence. * * @return the currency persistence */ public CurrencyPersistence getCurrencyPersistence() { return currencyPersistence; } /** * Sets the currency persistence. * * @param currencyPersistence the currency persistence */ public void setCurrencyPersistence(CurrencyPersistence currencyPersistence) { this.currencyPersistence = currencyPersistence; } /** * Returns the dias vacaciones local service. * * @return the dias vacaciones local service */ public es.davinciti.liferay.service.DiasVacacionesLocalService getDiasVacacionesLocalService() { return diasVacacionesLocalService; } /** * Sets the dias vacaciones local service. * * @param diasVacacionesLocalService the dias vacaciones local service */ public void setDiasVacacionesLocalService( es.davinciti.liferay.service.DiasVacacionesLocalService diasVacacionesLocalService) { this.diasVacacionesLocalService = diasVacacionesLocalService; } /** * Returns the dias vacaciones remote service. * * @return the dias vacaciones remote service */ public es.davinciti.liferay.service.DiasVacacionesService getDiasVacacionesService() { return diasVacacionesService; } /** * Sets the dias vacaciones remote service. * * @param diasVacacionesService the dias vacaciones remote service */ public void setDiasVacacionesService( es.davinciti.liferay.service.DiasVacacionesService diasVacacionesService) { this.diasVacacionesService = diasVacacionesService; } /** * Returns the dias vacaciones persistence. * * @return the dias vacaciones persistence */ public DiasVacacionesPersistence getDiasVacacionesPersistence() { return diasVacacionesPersistence; } /** * Sets the dias vacaciones persistence. * * @param diasVacacionesPersistence the dias vacaciones persistence */ public void setDiasVacacionesPersistence( DiasVacacionesPersistence diasVacacionesPersistence) { this.diasVacacionesPersistence = diasVacacionesPersistence; } /** * Returns the historico nota local service. * * @return the historico nota local service */ public es.davinciti.liferay.service.HistoricoNotaLocalService getHistoricoNotaLocalService() { return historicoNotaLocalService; } /** * Sets the historico nota local service. * * @param historicoNotaLocalService the historico nota local service */ public void setHistoricoNotaLocalService( es.davinciti.liferay.service.HistoricoNotaLocalService historicoNotaLocalService) { this.historicoNotaLocalService = historicoNotaLocalService; } /** * Returns the historico nota remote service. * * @return the historico nota remote service */ public es.davinciti.liferay.service.HistoricoNotaService getHistoricoNotaService() { return historicoNotaService; } /** * Sets the historico nota remote service. * * @param historicoNotaService the historico nota remote service */ public void setHistoricoNotaService( es.davinciti.liferay.service.HistoricoNotaService historicoNotaService) { this.historicoNotaService = historicoNotaService; } /** * Returns the historico nota persistence. * * @return the historico nota persistence */ public HistoricoNotaPersistence getHistoricoNotaPersistence() { return historicoNotaPersistence; } /** * Sets the historico nota persistence. * * @param historicoNotaPersistence the historico nota persistence */ public void setHistoricoNotaPersistence( HistoricoNotaPersistence historicoNotaPersistence) { this.historicoNotaPersistence = historicoNotaPersistence; } /** * Returns the linea gasto local service. * * @return the linea gasto local service */ public es.davinciti.liferay.service.LineaGastoLocalService getLineaGastoLocalService() { return lineaGastoLocalService; } /** * Sets the linea gasto local service. * * @param lineaGastoLocalService the linea gasto local service */ public void setLineaGastoLocalService( es.davinciti.liferay.service.LineaGastoLocalService lineaGastoLocalService) { this.lineaGastoLocalService = lineaGastoLocalService; } /** * Returns the linea gasto remote service. * * @return the linea gasto remote service */ public es.davinciti.liferay.service.LineaGastoService getLineaGastoService() { return lineaGastoService; } /** * Sets the linea gasto remote service. * * @param lineaGastoService the linea gasto remote service */ public void setLineaGastoService( es.davinciti.liferay.service.LineaGastoService lineaGastoService) { this.lineaGastoService = lineaGastoService; } /** * Returns the linea gasto persistence. * * @return the linea gasto persistence */ public LineaGastoPersistence getLineaGastoPersistence() { return lineaGastoPersistence; } /** * Sets the linea gasto persistence. * * @param lineaGastoPersistence the linea gasto persistence */ public void setLineaGastoPersistence( LineaGastoPersistence lineaGastoPersistence) { this.lineaGastoPersistence = lineaGastoPersistence; } /** * Returns the linea gasto categoria local service. * * @return the linea gasto categoria local service */ public es.davinciti.liferay.service.LineaGastoCategoriaLocalService getLineaGastoCategoriaLocalService() { return lineaGastoCategoriaLocalService; } /** * Sets the linea gasto categoria local service. * * @param lineaGastoCategoriaLocalService the linea gasto categoria local service */ public void setLineaGastoCategoriaLocalService( es.davinciti.liferay.service.LineaGastoCategoriaLocalService lineaGastoCategoriaLocalService) { this.lineaGastoCategoriaLocalService = lineaGastoCategoriaLocalService; } /** * Returns the linea gasto categoria remote service. * * @return the linea gasto categoria remote service */ public es.davinciti.liferay.service.LineaGastoCategoriaService getLineaGastoCategoriaService() { return lineaGastoCategoriaService; } /** * Sets the linea gasto categoria remote service. * * @param lineaGastoCategoriaService the linea gasto categoria remote service */ public void setLineaGastoCategoriaService( es.davinciti.liferay.service.LineaGastoCategoriaService lineaGastoCategoriaService) { this.lineaGastoCategoriaService = lineaGastoCategoriaService; } /** * Returns the linea gasto categoria persistence. * * @return the linea gasto categoria persistence */ public LineaGastoCategoriaPersistence getLineaGastoCategoriaPersistence() { return lineaGastoCategoriaPersistence; } /** * Sets the linea gasto categoria persistence. * * @param lineaGastoCategoriaPersistence the linea gasto categoria persistence */ public void setLineaGastoCategoriaPersistence( LineaGastoCategoriaPersistence lineaGastoCategoriaPersistence) { this.lineaGastoCategoriaPersistence = lineaGastoCategoriaPersistence; } /** * Returns the linea gasto cliente local service. * * @return the linea gasto cliente local service */ public es.davinciti.liferay.service.LineaGastoClienteLocalService getLineaGastoClienteLocalService() { return lineaGastoClienteLocalService; } /** * Sets the linea gasto cliente local service. * * @param lineaGastoClienteLocalService the linea gasto cliente local service */ public void setLineaGastoClienteLocalService( es.davinciti.liferay.service.LineaGastoClienteLocalService lineaGastoClienteLocalService) { this.lineaGastoClienteLocalService = lineaGastoClienteLocalService; } /** * Returns the linea gasto cliente remote service. * * @return the linea gasto cliente remote service */ public es.davinciti.liferay.service.LineaGastoClienteService getLineaGastoClienteService() { return lineaGastoClienteService; } /** * Sets the linea gasto cliente remote service. * * @param lineaGastoClienteService the linea gasto cliente remote service */ public void setLineaGastoClienteService( es.davinciti.liferay.service.LineaGastoClienteService lineaGastoClienteService) { this.lineaGastoClienteService = lineaGastoClienteService; } /** * Returns the linea gasto cliente persistence. * * @return the linea gasto cliente persistence */ public LineaGastoClientePersistence getLineaGastoClientePersistence() { return lineaGastoClientePersistence; } /** * Sets the linea gasto cliente persistence. * * @param lineaGastoClientePersistence the linea gasto cliente persistence */ public void setLineaGastoClientePersistence( LineaGastoClientePersistence lineaGastoClientePersistence) { this.lineaGastoClientePersistence = lineaGastoClientePersistence; } /** * Returns the linea gasto familia local service. * * @return the linea gasto familia local service */ public es.davinciti.liferay.service.LineaGastoFamiliaLocalService getLineaGastoFamiliaLocalService() { return lineaGastoFamiliaLocalService; } /** * Sets the linea gasto familia local service. * * @param lineaGastoFamiliaLocalService the linea gasto familia local service */ public void setLineaGastoFamiliaLocalService( es.davinciti.liferay.service.LineaGastoFamiliaLocalService lineaGastoFamiliaLocalService) { this.lineaGastoFamiliaLocalService = lineaGastoFamiliaLocalService; } /** * Returns the linea gasto familia remote service. * * @return the linea gasto familia remote service */ public es.davinciti.liferay.service.LineaGastoFamiliaService getLineaGastoFamiliaService() { return lineaGastoFamiliaService; } /** * Sets the linea gasto familia remote service. * * @param lineaGastoFamiliaService the linea gasto familia remote service */ public void setLineaGastoFamiliaService( es.davinciti.liferay.service.LineaGastoFamiliaService lineaGastoFamiliaService) { this.lineaGastoFamiliaService = lineaGastoFamiliaService; } /** * Returns the linea gasto familia persistence. * * @return the linea gasto familia persistence */ public LineaGastoFamiliaPersistence getLineaGastoFamiliaPersistence() { return lineaGastoFamiliaPersistence; } /** * Sets the linea gasto familia persistence. * * @param lineaGastoFamiliaPersistence the linea gasto familia persistence */ public void setLineaGastoFamiliaPersistence( LineaGastoFamiliaPersistence lineaGastoFamiliaPersistence) { this.lineaGastoFamiliaPersistence = lineaGastoFamiliaPersistence; } /** * Returns the linea gasto pay mode local service. * * @return the linea gasto pay mode local service */ public es.davinciti.liferay.service.LineaGastoPayModeLocalService getLineaGastoPayModeLocalService() { return lineaGastoPayModeLocalService; } /** * Sets the linea gasto pay mode local service. * * @param lineaGastoPayModeLocalService the linea gasto pay mode local service */ public void setLineaGastoPayModeLocalService( es.davinciti.liferay.service.LineaGastoPayModeLocalService lineaGastoPayModeLocalService) { this.lineaGastoPayModeLocalService = lineaGastoPayModeLocalService; } /** * Returns the linea gasto pay mode remote service. * * @return the linea gasto pay mode remote service */ public es.davinciti.liferay.service.LineaGastoPayModeService getLineaGastoPayModeService() { return lineaGastoPayModeService; } /** * Sets the linea gasto pay mode remote service. * * @param lineaGastoPayModeService the linea gasto pay mode remote service */ public void setLineaGastoPayModeService( es.davinciti.liferay.service.LineaGastoPayModeService lineaGastoPayModeService) { this.lineaGastoPayModeService = lineaGastoPayModeService; } /** * Returns the linea gasto pay mode persistence. * * @return the linea gasto pay mode persistence */ public LineaGastoPayModePersistence getLineaGastoPayModePersistence() { return lineaGastoPayModePersistence; } /** * Sets the linea gasto pay mode persistence. * * @param lineaGastoPayModePersistence the linea gasto pay mode persistence */ public void setLineaGastoPayModePersistence( LineaGastoPayModePersistence lineaGastoPayModePersistence) { this.lineaGastoPayModePersistence = lineaGastoPayModePersistence; } /** * Returns the linea gasto proyecto local service. * * @return the linea gasto proyecto local service */ public es.davinciti.liferay.service.LineaGastoProyectoLocalService getLineaGastoProyectoLocalService() { return lineaGastoProyectoLocalService; } /** * Sets the linea gasto proyecto local service. * * @param lineaGastoProyectoLocalService the linea gasto proyecto local service */ public void setLineaGastoProyectoLocalService( es.davinciti.liferay.service.LineaGastoProyectoLocalService lineaGastoProyectoLocalService) { this.lineaGastoProyectoLocalService = lineaGastoProyectoLocalService; } /** * Returns the linea gasto proyecto remote service. * * @return the linea gasto proyecto remote service */ public es.davinciti.liferay.service.LineaGastoProyectoService getLineaGastoProyectoService() { return lineaGastoProyectoService; } /** * Sets the linea gasto proyecto remote service. * * @param lineaGastoProyectoService the linea gasto proyecto remote service */ public void setLineaGastoProyectoService( es.davinciti.liferay.service.LineaGastoProyectoService lineaGastoProyectoService) { this.lineaGastoProyectoService = lineaGastoProyectoService; } /** * Returns the linea gasto proyecto persistence. * * @return the linea gasto proyecto persistence */ public LineaGastoProyectoPersistence getLineaGastoProyectoPersistence() { return lineaGastoProyectoPersistence; } /** * Sets the linea gasto proyecto persistence. * * @param lineaGastoProyectoPersistence the linea gasto proyecto persistence */ public void setLineaGastoProyectoPersistence( LineaGastoProyectoPersistence lineaGastoProyectoPersistence) { this.lineaGastoProyectoPersistence = lineaGastoProyectoPersistence; } /** * Returns the nota gasto local service. * * @return the nota gasto local service */ public es.davinciti.liferay.service.NotaGastoLocalService getNotaGastoLocalService() { return notaGastoLocalService; } /** * Sets the nota gasto local service. * * @param notaGastoLocalService the nota gasto local service */ public void setNotaGastoLocalService( es.davinciti.liferay.service.NotaGastoLocalService notaGastoLocalService) { this.notaGastoLocalService = notaGastoLocalService; } /** * Returns the nota gasto remote service. * * @return the nota gasto remote service */ public es.davinciti.liferay.service.NotaGastoService getNotaGastoService() { return notaGastoService; } /** * Sets the nota gasto remote service. * * @param notaGastoService the nota gasto remote service */ public void setNotaGastoService( es.davinciti.liferay.service.NotaGastoService notaGastoService) { this.notaGastoService = notaGastoService; } /** * Returns the nota gasto persistence. * * @return the nota gasto persistence */ public NotaGastoPersistence getNotaGastoPersistence() { return notaGastoPersistence; } /** * Sets the nota gasto persistence. * * @param notaGastoPersistence the nota gasto persistence */ public void setNotaGastoPersistence( NotaGastoPersistence notaGastoPersistence) { this.notaGastoPersistence = notaGastoPersistence; } /** * Returns the organization sage company local service. * * @return the organization sage company local service */ public es.davinciti.liferay.service.OrganizationSageCompanyLocalService getOrganizationSageCompanyLocalService() { return organizationSageCompanyLocalService; } /** * Sets the organization sage company local service. * * @param organizationSageCompanyLocalService the organization sage company local service */ public void setOrganizationSageCompanyLocalService( es.davinciti.liferay.service.OrganizationSageCompanyLocalService organizationSageCompanyLocalService) { this.organizationSageCompanyLocalService = organizationSageCompanyLocalService; } /** * Returns the organization sage company remote service. * * @return the organization sage company remote service */ public es.davinciti.liferay.service.OrganizationSageCompanyService getOrganizationSageCompanyService() { return organizationSageCompanyService; } /** * Sets the organization sage company remote service. * * @param organizationSageCompanyService the organization sage company remote service */ public void setOrganizationSageCompanyService( es.davinciti.liferay.service.OrganizationSageCompanyService organizationSageCompanyService) { this.organizationSageCompanyService = organizationSageCompanyService; } /** * Returns the organization sage company persistence. * * @return the organization sage company persistence */ public OrganizationSageCompanyPersistence getOrganizationSageCompanyPersistence() { return organizationSageCompanyPersistence; } /** * Sets the organization sage company persistence. * * @param organizationSageCompanyPersistence the organization sage company persistence */ public void setOrganizationSageCompanyPersistence( OrganizationSageCompanyPersistence organizationSageCompanyPersistence) { this.organizationSageCompanyPersistence = organizationSageCompanyPersistence; } /** * Returns the sage employee local service. * * @return the sage employee local service */ public es.davinciti.liferay.service.SageEmployeeLocalService getSageEmployeeLocalService() { return sageEmployeeLocalService; } /** * Sets the sage employee local service. * * @param sageEmployeeLocalService the sage employee local service */ public void setSageEmployeeLocalService( es.davinciti.liferay.service.SageEmployeeLocalService sageEmployeeLocalService) { this.sageEmployeeLocalService = sageEmployeeLocalService; } /** * Returns the sage employee remote service. * * @return the sage employee remote service */ public es.davinciti.liferay.service.SageEmployeeService getSageEmployeeService() { return sageEmployeeService; } /** * Sets the sage employee remote service. * * @param sageEmployeeService the sage employee remote service */ public void setSageEmployeeService( es.davinciti.liferay.service.SageEmployeeService sageEmployeeService) { this.sageEmployeeService = sageEmployeeService; } /** * Returns the sage employee persistence. * * @return the sage employee persistence */ public SageEmployeePersistence getSageEmployeePersistence() { return sageEmployeePersistence; } /** * Sets the sage employee persistence. * * @param sageEmployeePersistence the sage employee persistence */ public void setSageEmployeePersistence( SageEmployeePersistence sageEmployeePersistence) { this.sageEmployeePersistence = sageEmployeePersistence; } /** * Returns the sap employee local service. * * @return the sap employee local service */ public es.davinciti.liferay.service.SapEmployeeLocalService getSapEmployeeLocalService() { return sapEmployeeLocalService; } /** * Sets the sap employee local service. * * @param sapEmployeeLocalService the sap employee local service */ public void setSapEmployeeLocalService( es.davinciti.liferay.service.SapEmployeeLocalService sapEmployeeLocalService) { this.sapEmployeeLocalService = sapEmployeeLocalService; } /** * Returns the sap employee remote service. * * @return the sap employee remote service */ public es.davinciti.liferay.service.SapEmployeeService getSapEmployeeService() { return sapEmployeeService; } /** * Sets the sap employee remote service. * * @param sapEmployeeService the sap employee remote service */ public void setSapEmployeeService( es.davinciti.liferay.service.SapEmployeeService sapEmployeeService) { this.sapEmployeeService = sapEmployeeService; } /** * Returns the sap employee persistence. * * @return the sap employee persistence */ public SapEmployeePersistence getSapEmployeePersistence() { return sapEmployeePersistence; } /** * Sets the sap employee persistence. * * @param sapEmployeePersistence the sap employee persistence */ public void setSapEmployeePersistence( SapEmployeePersistence sapEmployeePersistence) { this.sapEmployeePersistence = sapEmployeePersistence; } /** * Returns the tipo dia calendar local service. * * @return the tipo dia calendar local service */ public es.davinciti.liferay.service.TipoDiaCalendarLocalService getTipoDiaCalendarLocalService() { return tipoDiaCalendarLocalService; } /** * Sets the tipo dia calendar local service. * * @param tipoDiaCalendarLocalService the tipo dia calendar local service */ public void setTipoDiaCalendarLocalService( es.davinciti.liferay.service.TipoDiaCalendarLocalService tipoDiaCalendarLocalService) { this.tipoDiaCalendarLocalService = tipoDiaCalendarLocalService; } /** * Returns the tipo dia calendar remote service. * * @return the tipo dia calendar remote service */ public es.davinciti.liferay.service.TipoDiaCalendarService getTipoDiaCalendarService() { return tipoDiaCalendarService; } /** * Sets the tipo dia calendar remote service. * * @param tipoDiaCalendarService the tipo dia calendar remote service */ public void setTipoDiaCalendarService( es.davinciti.liferay.service.TipoDiaCalendarService tipoDiaCalendarService) { this.tipoDiaCalendarService = tipoDiaCalendarService; } /** * Returns the tipo dia calendar persistence. * * @return the tipo dia calendar persistence */ public TipoDiaCalendarPersistence getTipoDiaCalendarPersistence() { return tipoDiaCalendarPersistence; } /** * Sets the tipo dia calendar persistence. * * @param tipoDiaCalendarPersistence the tipo dia calendar persistence */ public void setTipoDiaCalendarPersistence( TipoDiaCalendarPersistence tipoDiaCalendarPersistence) { this.tipoDiaCalendarPersistence = tipoDiaCalendarPersistence; } /** * Returns the counter local service. * * @return the counter local service */ public com.liferay.counter.service.CounterLocalService getCounterLocalService() { return counterLocalService; } /** * Sets the counter local service. * * @param counterLocalService the counter local service */ public void setCounterLocalService( com.liferay.counter.service.CounterLocalService counterLocalService) { this.counterLocalService = counterLocalService; } /** * Returns the resource local service. * * @return the resource local service */ public com.liferay.portal.service.ResourceLocalService getResourceLocalService() { return resourceLocalService; } /** * Sets the resource local service. * * @param resourceLocalService the resource local service */ public void setResourceLocalService( com.liferay.portal.service.ResourceLocalService resourceLocalService) { this.resourceLocalService = resourceLocalService; } /** * Returns the user local service. * * @return the user local service */ public com.liferay.portal.service.UserLocalService getUserLocalService() { return userLocalService; } /** * Sets the user local service. * * @param userLocalService the user local service */ public void setUserLocalService( com.liferay.portal.service.UserLocalService userLocalService) { this.userLocalService = userLocalService; } /** * Returns the user remote service. * * @return the user remote service */ public com.liferay.portal.service.UserService getUserService() { return userService; } /** * Sets the user remote service. * * @param userService the user remote service */ public void setUserService( com.liferay.portal.service.UserService userService) { this.userService = userService; } /** * Returns the user persistence. * * @return the user persistence */ public UserPersistence getUserPersistence() { return userPersistence; } /** * Sets the user persistence. * * @param userPersistence the user persistence */ public void setUserPersistence(UserPersistence userPersistence) { this.userPersistence = userPersistence; } public void afterPropertiesSet() { Class<?> clazz = getClass(); _classLoader = clazz.getClassLoader(); } public void destroy() { } /** * Returns the Spring bean ID for this bean. * * @return the Spring bean ID for this bean */ @Override public String getBeanIdentifier() { return _beanIdentifier; } /** * Sets the Spring bean ID for this bean. * * @param beanIdentifier the Spring bean ID for this bean */ @Override public void setBeanIdentifier(String beanIdentifier) { _beanIdentifier = beanIdentifier; } @Override public Object invokeMethod(String name, String[] parameterTypes, Object[] arguments) throws Throwable { Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); if (contextClassLoader != _classLoader) { currentThread.setContextClassLoader(_classLoader); } try { return _clpInvoker.invokeMethod(name, parameterTypes, arguments); } finally { if (contextClassLoader != _classLoader) { currentThread.setContextClassLoader(contextClassLoader); } } } protected Class<?> getModelClass() { return SapEmployee.class; } protected String getModelClassName() { return SapEmployee.class.getName(); } /** * Performs an SQL query. * * @param sql the sql query */ protected void runSQL(String sql) throws SystemException { try { DataSource dataSource = sapEmployeePersistence.getDataSource(); SqlUpdate sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(dataSource, sql, new int[0]); sqlUpdate.update(); } catch (Exception e) { throw new SystemException(e); } } @BeanReference(type = es.davinciti.liferay.service.ApplicationStatusLocalService.class) protected es.davinciti.liferay.service.ApplicationStatusLocalService applicationStatusLocalService; @BeanReference(type = es.davinciti.liferay.service.ApplicationStatusService.class) protected es.davinciti.liferay.service.ApplicationStatusService applicationStatusService; @BeanReference(type = ApplicationStatusPersistence.class) protected ApplicationStatusPersistence applicationStatusPersistence; @BeanReference(type = es.davinciti.liferay.service.CalendarioLocalService.class) protected es.davinciti.liferay.service.CalendarioLocalService calendarioLocalService; @BeanReference(type = es.davinciti.liferay.service.CalendarioService.class) protected es.davinciti.liferay.service.CalendarioService calendarioService; @BeanReference(type = CalendarioPersistence.class) protected CalendarioPersistence calendarioPersistence; @BeanReference(type = es.davinciti.liferay.service.ConnectionActionTypesLocalService.class) protected es.davinciti.liferay.service.ConnectionActionTypesLocalService connectionActionTypesLocalService; @BeanReference(type = es.davinciti.liferay.service.ConnectionActionTypesService.class) protected es.davinciti.liferay.service.ConnectionActionTypesService connectionActionTypesService; @BeanReference(type = ConnectionActionTypesPersistence.class) protected ConnectionActionTypesPersistence connectionActionTypesPersistence; @BeanReference(type = es.davinciti.liferay.service.ConnectionConfigsLocalService.class) protected es.davinciti.liferay.service.ConnectionConfigsLocalService connectionConfigsLocalService; @BeanReference(type = es.davinciti.liferay.service.ConnectionConfigsService.class) protected es.davinciti.liferay.service.ConnectionConfigsService connectionConfigsService; @BeanReference(type = ConnectionConfigsPersistence.class) protected ConnectionConfigsPersistence connectionConfigsPersistence; @BeanReference(type = es.davinciti.liferay.service.ConnectionDataLocalService.class) protected es.davinciti.liferay.service.ConnectionDataLocalService connectionDataLocalService; @BeanReference(type = es.davinciti.liferay.service.ConnectionDataService.class) protected es.davinciti.liferay.service.ConnectionDataService connectionDataService; @BeanReference(type = ConnectionDataPersistence.class) protected ConnectionDataPersistence connectionDataPersistence; @BeanReference(type = es.davinciti.liferay.service.ConnectionTypesLocalService.class) protected es.davinciti.liferay.service.ConnectionTypesLocalService connectionTypesLocalService; @BeanReference(type = es.davinciti.liferay.service.ConnectionTypesService.class) protected es.davinciti.liferay.service.ConnectionTypesService connectionTypesService; @BeanReference(type = ConnectionTypesPersistence.class) protected ConnectionTypesPersistence connectionTypesPersistence; @BeanReference(type = es.davinciti.liferay.service.CurrenciesCompanyLocalService.class) protected es.davinciti.liferay.service.CurrenciesCompanyLocalService currenciesCompanyLocalService; @BeanReference(type = es.davinciti.liferay.service.CurrenciesCompanyService.class) protected es.davinciti.liferay.service.CurrenciesCompanyService currenciesCompanyService; @BeanReference(type = CurrenciesCompanyPersistence.class) protected CurrenciesCompanyPersistence currenciesCompanyPersistence; @BeanReference(type = es.davinciti.liferay.service.CurrencyLocalService.class) protected es.davinciti.liferay.service.CurrencyLocalService currencyLocalService; @BeanReference(type = es.davinciti.liferay.service.CurrencyService.class) protected es.davinciti.liferay.service.CurrencyService currencyService; @BeanReference(type = CurrencyPersistence.class) protected CurrencyPersistence currencyPersistence; @BeanReference(type = es.davinciti.liferay.service.DiasVacacionesLocalService.class) protected es.davinciti.liferay.service.DiasVacacionesLocalService diasVacacionesLocalService; @BeanReference(type = es.davinciti.liferay.service.DiasVacacionesService.class) protected es.davinciti.liferay.service.DiasVacacionesService diasVacacionesService; @BeanReference(type = DiasVacacionesPersistence.class) protected DiasVacacionesPersistence diasVacacionesPersistence; @BeanReference(type = es.davinciti.liferay.service.HistoricoNotaLocalService.class) protected es.davinciti.liferay.service.HistoricoNotaLocalService historicoNotaLocalService; @BeanReference(type = es.davinciti.liferay.service.HistoricoNotaService.class) protected es.davinciti.liferay.service.HistoricoNotaService historicoNotaService; @BeanReference(type = HistoricoNotaPersistence.class) protected HistoricoNotaPersistence historicoNotaPersistence; @BeanReference(type = es.davinciti.liferay.service.LineaGastoLocalService.class) protected es.davinciti.liferay.service.LineaGastoLocalService lineaGastoLocalService; @BeanReference(type = es.davinciti.liferay.service.LineaGastoService.class) protected es.davinciti.liferay.service.LineaGastoService lineaGastoService; @BeanReference(type = LineaGastoPersistence.class) protected LineaGastoPersistence lineaGastoPersistence; @BeanReference(type = es.davinciti.liferay.service.LineaGastoCategoriaLocalService.class) protected es.davinciti.liferay.service.LineaGastoCategoriaLocalService lineaGastoCategoriaLocalService; @BeanReference(type = es.davinciti.liferay.service.LineaGastoCategoriaService.class) protected es.davinciti.liferay.service.LineaGastoCategoriaService lineaGastoCategoriaService; @BeanReference(type = LineaGastoCategoriaPersistence.class) protected LineaGastoCategoriaPersistence lineaGastoCategoriaPersistence; @BeanReference(type = es.davinciti.liferay.service.LineaGastoClienteLocalService.class) protected es.davinciti.liferay.service.LineaGastoClienteLocalService lineaGastoClienteLocalService; @BeanReference(type = es.davinciti.liferay.service.LineaGastoClienteService.class) protected es.davinciti.liferay.service.LineaGastoClienteService lineaGastoClienteService; @BeanReference(type = LineaGastoClientePersistence.class) protected LineaGastoClientePersistence lineaGastoClientePersistence; @BeanReference(type = es.davinciti.liferay.service.LineaGastoFamiliaLocalService.class) protected es.davinciti.liferay.service.LineaGastoFamiliaLocalService lineaGastoFamiliaLocalService; @BeanReference(type = es.davinciti.liferay.service.LineaGastoFamiliaService.class) protected es.davinciti.liferay.service.LineaGastoFamiliaService lineaGastoFamiliaService; @BeanReference(type = LineaGastoFamiliaPersistence.class) protected LineaGastoFamiliaPersistence lineaGastoFamiliaPersistence; @BeanReference(type = es.davinciti.liferay.service.LineaGastoPayModeLocalService.class) protected es.davinciti.liferay.service.LineaGastoPayModeLocalService lineaGastoPayModeLocalService; @BeanReference(type = es.davinciti.liferay.service.LineaGastoPayModeService.class) protected es.davinciti.liferay.service.LineaGastoPayModeService lineaGastoPayModeService; @BeanReference(type = LineaGastoPayModePersistence.class) protected LineaGastoPayModePersistence lineaGastoPayModePersistence; @BeanReference(type = es.davinciti.liferay.service.LineaGastoProyectoLocalService.class) protected es.davinciti.liferay.service.LineaGastoProyectoLocalService lineaGastoProyectoLocalService; @BeanReference(type = es.davinciti.liferay.service.LineaGastoProyectoService.class) protected es.davinciti.liferay.service.LineaGastoProyectoService lineaGastoProyectoService; @BeanReference(type = LineaGastoProyectoPersistence.class) protected LineaGastoProyectoPersistence lineaGastoProyectoPersistence; @BeanReference(type = es.davinciti.liferay.service.NotaGastoLocalService.class) protected es.davinciti.liferay.service.NotaGastoLocalService notaGastoLocalService; @BeanReference(type = es.davinciti.liferay.service.NotaGastoService.class) protected es.davinciti.liferay.service.NotaGastoService notaGastoService; @BeanReference(type = NotaGastoPersistence.class) protected NotaGastoPersistence notaGastoPersistence; @BeanReference(type = es.davinciti.liferay.service.OrganizationSageCompanyLocalService.class) protected es.davinciti.liferay.service.OrganizationSageCompanyLocalService organizationSageCompanyLocalService; @BeanReference(type = es.davinciti.liferay.service.OrganizationSageCompanyService.class) protected es.davinciti.liferay.service.OrganizationSageCompanyService organizationSageCompanyService; @BeanReference(type = OrganizationSageCompanyPersistence.class) protected OrganizationSageCompanyPersistence organizationSageCompanyPersistence; @BeanReference(type = es.davinciti.liferay.service.SageEmployeeLocalService.class) protected es.davinciti.liferay.service.SageEmployeeLocalService sageEmployeeLocalService; @BeanReference(type = es.davinciti.liferay.service.SageEmployeeService.class) protected es.davinciti.liferay.service.SageEmployeeService sageEmployeeService; @BeanReference(type = SageEmployeePersistence.class) protected SageEmployeePersistence sageEmployeePersistence; @BeanReference(type = es.davinciti.liferay.service.SapEmployeeLocalService.class) protected es.davinciti.liferay.service.SapEmployeeLocalService sapEmployeeLocalService; @BeanReference(type = es.davinciti.liferay.service.SapEmployeeService.class) protected es.davinciti.liferay.service.SapEmployeeService sapEmployeeService; @BeanReference(type = SapEmployeePersistence.class) protected SapEmployeePersistence sapEmployeePersistence; @BeanReference(type = es.davinciti.liferay.service.TipoDiaCalendarLocalService.class) protected es.davinciti.liferay.service.TipoDiaCalendarLocalService tipoDiaCalendarLocalService; @BeanReference(type = es.davinciti.liferay.service.TipoDiaCalendarService.class) protected es.davinciti.liferay.service.TipoDiaCalendarService tipoDiaCalendarService; @BeanReference(type = TipoDiaCalendarPersistence.class) protected TipoDiaCalendarPersistence tipoDiaCalendarPersistence; @BeanReference(type = com.liferay.counter.service.CounterLocalService.class) protected com.liferay.counter.service.CounterLocalService counterLocalService; @BeanReference(type = com.liferay.portal.service.ResourceLocalService.class) protected com.liferay.portal.service.ResourceLocalService resourceLocalService; @BeanReference(type = com.liferay.portal.service.UserLocalService.class) protected com.liferay.portal.service.UserLocalService userLocalService; @BeanReference(type = com.liferay.portal.service.UserService.class) protected com.liferay.portal.service.UserService userService; @BeanReference(type = UserPersistence.class) protected UserPersistence userPersistence; private String _beanIdentifier; private ClassLoader _classLoader; private SapEmployeeServiceClpInvoker _clpInvoker = new SapEmployeeServiceClpInvoker(); }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.segment.indexing.granularity; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.metamx.common.Granularity; import io.druid.granularity.QueryGranularities; import io.druid.jackson.DefaultObjectMapper; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.chrono.ISOChronology; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; public class UniformGranularityTest { private static final ObjectMapper jsonMapper = new DefaultObjectMapper(); @Test public void testSimple() { final GranularitySpec spec = new UniformGranularitySpec( Granularity.DAY, null, Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-11T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ) ); Assert.assertTrue(spec.isRollup()); Assert.assertEquals( Lists.newArrayList( new Interval("2012-01-01T00Z/P1D"), new Interval("2012-01-02T00Z/P1D"), new Interval("2012-01-03T00Z/P1D"), new Interval("2012-01-07T00Z/P1D"), new Interval("2012-01-08T00Z/P1D"), new Interval("2012-01-09T00Z/P1D"), new Interval("2012-01-10T00Z/P1D") ), Lists.newArrayList(spec.bucketIntervals().get()) ); Assert.assertEquals( "2012-01-03T00Z", Optional.of(new Interval("2012-01-03T00Z/2012-01-04T00Z")), spec.bucketInterval(new DateTime("2012-01-03T00Z")) ); Assert.assertEquals( "2012-01-03T01Z", Optional.of(new Interval("2012-01-03T00Z/2012-01-04T00Z")), spec.bucketInterval(new DateTime("2012-01-03T01Z")) ); Assert.assertEquals( "2012-01-04T01Z", Optional.<Interval>absent(), spec.bucketInterval(new DateTime("2012-01-04T01Z")) ); Assert.assertEquals( "2012-01-07T23:59:59.999Z", Optional.of(new Interval("2012-01-07T00Z/2012-01-08T00Z")), spec.bucketInterval(new DateTime("2012-01-07T23:59:59.999Z")) ); Assert.assertEquals( "2012-01-08T01Z", Optional.of(new Interval("2012-01-08T00Z/2012-01-09T00Z")), spec.bucketInterval(new DateTime("2012-01-08T01Z")) ); } @Test public void testRollupSetting() { List<Interval> intervals = Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-11T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ); final GranularitySpec spec = new UniformGranularitySpec(Granularity.DAY, QueryGranularities.NONE, false, intervals, null); Assert.assertFalse(spec.isRollup()); } @Test public void testJson() { final GranularitySpec spec = new UniformGranularitySpec( Granularity.DAY, null, Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-11T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ) ); try { final GranularitySpec rtSpec = jsonMapper.readValue(jsonMapper.writeValueAsString(spec), GranularitySpec.class); Assert.assertEquals( "Round-trip bucketIntervals", spec.bucketIntervals(), rtSpec.bucketIntervals() ); Assert.assertEquals( "Round-trip granularity", spec.getSegmentGranularity(), rtSpec.getSegmentGranularity() ); } catch (Exception e) { throw Throwables.propagate(e); } } @Test public void testEquals() { final GranularitySpec spec = new UniformGranularitySpec( Granularity.DAY, null, Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-11T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ) ); equalsCheck( spec, new UniformGranularitySpec( Granularity.DAY, null, Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-11T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ) ) ); } public void equalsCheck(GranularitySpec spec1, GranularitySpec spec2) { Assert.assertEquals(spec1, spec2); Assert.assertEquals(spec1.hashCode(), spec2.hashCode()); } @Test public void testNotEquals() { final GranularitySpec spec = new UniformGranularitySpec( Granularity.DAY, null, Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-11T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ) ); notEqualsCheck( spec, new UniformGranularitySpec( Granularity.YEAR, null, Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-11T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ) ) ); notEqualsCheck( spec, new UniformGranularitySpec( Granularity.DAY, null, Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-12T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ) ) ); notEqualsCheck( spec, new UniformGranularitySpec( Granularity.DAY, QueryGranularities.ALL, Lists.newArrayList( new Interval("2012-01-08T00Z/2012-01-11T00Z"), new Interval("2012-01-07T00Z/2012-01-08T00Z"), new Interval("2012-01-03T00Z/2012-01-04T00Z"), new Interval("2012-01-01T00Z/2012-01-03T00Z") ) ) ); } @Test public void testTimezone() { final GranularitySpec spec = new UniformGranularitySpec( Granularity.DAY, null, true, Lists.newArrayList( new Interval("2012-01-08T00-08:00/2012-01-11T00-08:00"), new Interval("2012-01-07T00-08:00/2012-01-08T00-08:00"), new Interval("2012-01-03T00-08:00/2012-01-04T00-08:00"), new Interval("2012-01-01T00-08:00/2012-01-03T00-08:00"), new Interval("2012-09-01T00-07:00/2012-09-03T00-07:00") ), "America/Los_Angeles" ); Assert.assertTrue(spec.bucketIntervals().isPresent()); final Optional<SortedSet<Interval>> sortedSetOptional = spec.bucketIntervals(); final SortedSet<Interval> intervals = sortedSetOptional.get(); final ISOChronology chrono = ISOChronology.getInstance(DateTimeZone.forID("America/Los_Angeles")); final ArrayList<Interval> expectedIntervals = Lists.newArrayList( new Interval("2012-01-01/2012-01-02", chrono), new Interval("2012-01-02/2012-01-03", chrono), new Interval("2012-01-03/2012-01-04", chrono), new Interval("2012-01-07/2012-01-08", chrono), new Interval("2012-01-08/2012-01-09", chrono), new Interval("2012-01-09/2012-01-10", chrono), new Interval("2012-01-10/2012-01-11", chrono), new Interval("2012-09-01/2012-09-02", chrono), new Interval("2012-09-02/2012-09-03", chrono) ); Assert.assertEquals(expectedIntervals, new ArrayList<Interval>(intervals)); } private void notEqualsCheck(GranularitySpec spec1, GranularitySpec spec2) { Assert.assertNotEquals(spec1, spec2); Assert.assertNotEquals(spec1.hashCode(), spec2.hashCode()); } }
/* * 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.facebook.presto.sql.planner; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.planner.PlanFragment.NullPartitioning; import com.facebook.presto.sql.planner.PlanFragment.OutputPartitioning; import com.facebook.presto.sql.planner.PlanFragment.PlanDistribution; import com.facebook.presto.sql.planner.plan.ExchangeNode; import com.facebook.presto.sql.planner.plan.OutputNode; import com.facebook.presto.sql.planner.plan.PlanFragmentId; import com.facebook.presto.sql.planner.plan.PlanNode; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.facebook.presto.sql.planner.plan.PlanRewriter; import com.facebook.presto.sql.planner.plan.RemoteSourceNode; import com.facebook.presto.sql.planner.plan.TableCommitNode; import com.facebook.presto.sql.planner.plan.TableScanNode; import com.facebook.presto.sql.planner.plan.ValuesNode; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.in; /** * Splits a logical plan into fragments that can be shipped and executed on distributed nodes */ public class PlanFragmenter { public SubPlan createSubPlans(Plan plan) { Fragmenter fragmenter = new Fragmenter(plan.getSymbolAllocator().getTypes()); FragmentProperties properties = new FragmentProperties(); PlanNode root = PlanRewriter.rewriteWith(fragmenter, plan.getRoot(), properties); SubPlan result = fragmenter.buildFragment(root, properties); result.sanityCheck(); return result; } private static class Fragmenter extends PlanRewriter<FragmentProperties> { private final Map<Symbol, Type> types; private int nextFragmentId; public Fragmenter(Map<Symbol, Type> types) { this.types = types; } private PlanFragmentId nextFragmentId() { return new PlanFragmentId(String.valueOf(nextFragmentId++)); } private SubPlan buildFragment(PlanNode root, FragmentProperties properties) { Set<Symbol> dependencies = SymbolExtractor.extract(root); PlanFragment fragment = new PlanFragment( nextFragmentId(), root, Maps.filterKeys(types, in(dependencies)), properties.getOutputLayout(), properties.getDistribution(), properties.getDistributeBy(), properties.getOutputPartitioning(), properties.getPartitionBy(), properties.getNullPartitionPolicy(), properties.getHash()); return new SubPlan(fragment, properties.getChildren()); } @Override public PlanNode visitOutput(OutputNode node, RewriteContext<FragmentProperties> context) { context.get() .setSingleNodeDistribution() // TODO: add support for distributed output .setOutputLayout(node.getOutputSymbols()) .setUnpartitionedOutput(); return context.defaultRewrite(node, context.get()); } @Override public PlanNode visitTableCommit(TableCommitNode node, RewriteContext<FragmentProperties> context) { context.get().setCoordinatorOnlyDistribution(); return context.defaultRewrite(node, context.get()); } @Override public PlanNode visitTableScan(TableScanNode node, RewriteContext<FragmentProperties> context) { context.get().setSourceDistribution(node.getId()); return context.defaultRewrite(node, context.get()); } @Override public PlanNode visitValues(ValuesNode node, RewriteContext<FragmentProperties> context) { context.get().setSingleNodeDistribution(); return context.defaultRewrite(node, context.get()); } @Override public PlanNode visitExchange(ExchangeNode exchange, RewriteContext<FragmentProperties> context) { ImmutableList.Builder<SubPlan> builder = ImmutableList.builder(); if (exchange.getType() == ExchangeNode.Type.GATHER) { context.get().setSingleNodeDistribution(); for (int i = 0; i < exchange.getSources().size(); i++) { FragmentProperties childProperties = new FragmentProperties(); childProperties.setUnpartitionedOutput(); childProperties.setOutputLayout(exchange.getInputs().get(i)); builder.add(buildSubPlan(exchange.getSources().get(i), childProperties, context)); } } else if (exchange.getType() == ExchangeNode.Type.REPARTITION) { context.get().setFixedDistribution(); FragmentProperties childProperties = new FragmentProperties() .setPartitionedOutput(exchange.getPartitionKeys(), exchange.getHashSymbol()) .setOutputLayout(Iterables.getOnlyElement(exchange.getInputs())); builder.add(buildSubPlan(Iterables.getOnlyElement(exchange.getSources()), childProperties, context)); } else if (exchange.getType() == ExchangeNode.Type.REPARTITION_WITH_NULL_REPLICATION) { context.get().setFixedDistribution(); FragmentProperties childProperties = new FragmentProperties() .setPartitionedOutput(exchange.getPartitionKeys(), exchange.getHashSymbol()) .replicateNulls() .setOutputLayout(Iterables.getOnlyElement(exchange.getInputs())); builder.add(buildSubPlan(Iterables.getOnlyElement(exchange.getSources()), childProperties, context)); } else if (exchange.getType() == ExchangeNode.Type.REPLICATE) { FragmentProperties childProperties = new FragmentProperties(); childProperties.setUnpartitionedOutput(); childProperties.setOutputLayout(Iterables.getOnlyElement(exchange.getInputs())); builder.add(buildSubPlan(Iterables.getOnlyElement(exchange.getSources()), childProperties, context)); } List<SubPlan> children = builder.build(); context.get().addChildren(children); List<PlanFragmentId> childrenIds = children.stream() .map(SubPlan::getFragment) .map(PlanFragment::getId) .collect(toImmutableList()); return new RemoteSourceNode(exchange.getId(), childrenIds, exchange.getOutputSymbols()); } private SubPlan buildSubPlan(PlanNode node, FragmentProperties properties, RewriteContext<FragmentProperties> context) { PlanNode child = context.rewrite(node, properties); return buildFragment(child, properties); } } private static class FragmentProperties { private final List<SubPlan> children = new ArrayList<>(); private Optional<List<Symbol>> outputLayout = Optional.empty(); private Optional<OutputPartitioning> outputPartitioning = Optional.empty(); private Optional<NullPartitioning> nullPartitionPolicy = Optional.empty(); private Optional<List<Symbol>> partitionBy = Optional.empty(); private Optional<Symbol> hash = Optional.empty(); private Optional<PlanDistribution> distribution = Optional.empty(); private PlanNodeId distributeBy; public List<SubPlan> getChildren() { return children; } public FragmentProperties setSingleNodeDistribution() { if (distribution.isPresent()) { PlanDistribution value = distribution.get(); checkState(value == PlanDistribution.SINGLE || value == PlanDistribution.COORDINATOR_ONLY, "Cannot overwrite distribution with %s (currently set to %s)", PlanDistribution.SINGLE, value); } else { distribution = Optional.of(PlanDistribution.SINGLE); } return this; } public FragmentProperties setFixedDistribution() { distribution.ifPresent(current -> checkState(current == PlanDistribution.FIXED, "Cannot set distribution to %s. Already set to %s", PlanDistribution.FIXED, current)); distribution = Optional.of(PlanDistribution.FIXED); return this; } public FragmentProperties setCoordinatorOnlyDistribution() { // only SINGLE can be upgraded to COORDINATOR_ONLY distribution.ifPresent(current -> checkState(distribution.get() == PlanDistribution.SINGLE, "Cannot overwrite distribution with %s (currently set to %s)", PlanDistribution.COORDINATOR_ONLY, distribution.get())); distribution = Optional.of(PlanDistribution.COORDINATOR_ONLY); return this; } public FragmentProperties setSourceDistribution(PlanNodeId source) { if (distribution.isPresent()) { // If already SINGLE or COORDINATOR_ONLY, leave it as is (this is for single-node execution) checkState(distribution.get() == PlanDistribution.SINGLE || distribution.get() == PlanDistribution.COORDINATOR_ONLY, "Cannot overwrite distribution with %s (currently set to %s)", PlanDistribution.SOURCE, distribution.get()); } else { distribution = Optional.of(PlanDistribution.SOURCE); this.distributeBy = source; } return this; } public FragmentProperties setUnpartitionedOutput() { outputPartitioning.ifPresent(current -> { throw new IllegalStateException(String.format("Output overwrite partitioning with %s (currently set to %s)", OutputPartitioning.NONE, current)); }); outputPartitioning = Optional.of(OutputPartitioning.NONE); return this; } public FragmentProperties setOutputLayout(List<Symbol> layout) { outputLayout.ifPresent(current -> { throw new IllegalStateException(String.format("Cannot overwrite output layout with %s (currently set to %s)", layout, current)); }); outputLayout = Optional.of(layout); return this; } public FragmentProperties setPartitionedOutput(Optional<List<Symbol>> partitionKeys, Optional<Symbol> hash) { outputPartitioning.ifPresent(current -> { throw new IllegalStateException(String.format("Cannot overwrite output partitioning with %s (currently set to %s)", OutputPartitioning.HASH, current)); }); if (partitionKeys.isPresent()) { this.outputPartitioning = Optional.of(OutputPartitioning.HASH); this.nullPartitionPolicy = Optional.of(NullPartitioning.HASH); this.partitionBy = partitionKeys.map(ImmutableList::copyOf); this.hash = hash; } else { this.outputPartitioning = Optional.of(OutputPartitioning.ROUND_ROBIN); } return this; } public FragmentProperties replicateNulls() { checkState(outputPartitioning.isPresent() && outputPartitioning.get().equals(OutputPartitioning.HASH), "Can only set null replicate if output partitioning is %s (currently set to %s)", OutputPartitioning.HASH, outputPartitioning); this.nullPartitionPolicy = Optional.of(NullPartitioning.REPLICATE); return this; } public FragmentProperties addChildren(List<SubPlan> children) { this.children.addAll(children); return this; } public List<Symbol> getOutputLayout() { return outputLayout.get(); } public OutputPartitioning getOutputPartitioning() { return outputPartitioning.get(); } public Optional<NullPartitioning> getNullPartitionPolicy() { return nullPartitionPolicy; } public PlanDistribution getDistribution() { return distribution.get(); } public Optional<List<Symbol>> getPartitionBy() { return partitionBy; } public Optional<Symbol> getHash() { return hash; } public PlanNodeId getDistributeBy() { return distributeBy; } } }
/* * Copyright (c) 2008. All rights reserved. */ package ro.isdc.wro.http; import static org.apache.commons.lang3.Validate.notNull; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.Collection; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.isdc.wro.config.Context; import ro.isdc.wro.config.factory.PropertiesAndFilterConfigWroConfigurationFactory; import ro.isdc.wro.config.jmx.WroConfiguration; import ro.isdc.wro.http.handler.RequestHandler; import ro.isdc.wro.http.handler.factory.DefaultRequestHandlerFactory; import ro.isdc.wro.http.handler.factory.RequestHandlerFactory; import ro.isdc.wro.http.support.ResponseHeadersConfigurer; import ro.isdc.wro.http.support.ServletContextAttributeHelper; import ro.isdc.wro.manager.factory.DefaultWroManagerFactory; import ro.isdc.wro.manager.factory.WroManagerFactory; import ro.isdc.wro.model.group.processor.Injector; import ro.isdc.wro.model.group.processor.InjectorBuilder; import ro.isdc.wro.model.resource.locator.ServletContextUriLocator; import ro.isdc.wro.model.resource.locator.support.DispatcherStreamLocator; import ro.isdc.wro.util.ObjectFactory; import ro.isdc.wro.util.WroUtil; /** * Main entry point. Perform the request processing by identifying the type of the requested resource. Depending on the * way it is configured. * * @author Alex Objelean * @created Created on Oct 31, 2008 */ public class WroFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(WroFilter.class); /** * The prefix to use for default mbean name. */ private static final String MBEAN_PREFIX = "wro4j-"; /** * Attribute indicating that the request was passed through {@link WroFilter}. This is required to allow identify * requests for wro resources (example: async resourceWatcher which cannot be executed asynchronously unless a wro * resource was requested). * * @VisibleForTesting */ public static final String ATTRIBUTE_PASSED_THROUGH_FILTER = WroFilter.class.getName() + ".passed_through_filter"; /** * Filter config. */ private FilterConfig filterConfig; private ObjectFactory<WroConfiguration> wroConfigurationFactory; /** * Wro configuration. */ private WroConfiguration wroConfiguration; /** * WroManagerFactory. The core of the optimizer. */ private WroManagerFactory wroManagerFactory; /** * Used to create the collection of requestHandlers to apply */ private RequestHandlerFactory requestHandlerFactory = newRequestHandlerFactory(); private Collection<RequestHandler> requestHandlers; private ResponseHeadersConfigurer headersConfigurer; /** * Flag used to toggle filter processing. When this flag is false, the filter will proceed with chaining. This flag is * true by default. */ private boolean enable = true; private Injector injector; private MBeanServer mbeanServer = null; /** * @return true if the provided request contains an attribute indicating that it was handled through {@link WroFilter} */ public static boolean isPassedThroughyWroFilter(final HttpServletRequest request) { notNull(request); return request.getAttribute(ATTRIBUTE_PASSED_THROUGH_FILTER) != null; } public final void init(final FilterConfig config) throws ServletException { this.filterConfig = config; // invoke createConfiguration method only if the configuration was not set. this.wroConfiguration = createConfiguration(); this.wroManagerFactory = createWroManagerFactory(); this.injector = createInjector(); headersConfigurer = newResponseHeadersConfigurer(); requestHandlers = createRequestHandlers(); registerChangeListeners(); registerMBean(); doInit(config); LOG.info("wro4j version: {}", WroUtil.getImplementationVersion()); LOG.info("wro4j configuration: {}", wroConfiguration); } private Collection<RequestHandler> createRequestHandlers() { requestHandlers = requestHandlerFactory.create(); for (final RequestHandler requestHandler : requestHandlers) { injector.inject(requestHandler); } return requestHandlers; } /** * Creates configuration by looking up in servletContext attributes. If none is found, a new one will be created using * the configuration factory. * * @return {@link WroConfiguration} object. */ private WroConfiguration createConfiguration() { // Extract config from servletContext (if already configured) // TODO use a named helper final WroConfiguration configAttribute = ServletContextAttributeHelper.create(filterConfig).getWroConfiguration(); if (configAttribute != null) { setConfiguration(configAttribute); } return getWroConfigurationFactory().create(); } /** * Creates {@link WroManagerFactory}. */ private WroManagerFactory createWroManagerFactory() { if (wroManagerFactory == null) { final WroManagerFactory managerFactoryAttribute = ServletContextAttributeHelper.create(filterConfig) .getManagerFactory(); LOG.debug("managerFactory attribute: {}", managerFactoryAttribute); wroManagerFactory = managerFactoryAttribute != null ? managerFactoryAttribute : newWroManagerFactory(); } LOG.debug("created managerFactory: {}", wroManagerFactory); return wroManagerFactory; } /** * Expose MBean to tell JMX infrastructure about our MBean (only if jmxEnabled is true). */ private void registerMBean() { if (wroConfiguration.isJmxEnabled()) { try { mbeanServer = getMBeanServer(); final ObjectName name = getMBeanObjectName(); if (!mbeanServer.isRegistered(name)) { mbeanServer.registerMBean(wroConfiguration, name); } } catch (final JMException e) { LOG.error("Exception occured while registering MBean", e); } } } private void unregisterMBean() { try { if (mbeanServer != null && mbeanServer.isRegistered(getMBeanObjectName())) { mbeanServer.unregisterMBean(getMBeanObjectName()); } } catch (final JMException e) { LOG.error("Exception occured while registering MBean", e); } } private ObjectName getMBeanObjectName() throws MalformedObjectNameException { return new ObjectName(newMBeanName(), "type", WroConfiguration.class.getSimpleName()); } /** * @return the name of MBean to be used by JMX to configure wro4j. */ protected String newMBeanName() { String mbeanName = wroConfiguration.getMbeanName(); if (StringUtils.isEmpty(mbeanName)) { final String contextPath = getContextPath(); mbeanName = StringUtils.isEmpty(contextPath) ? "ROOT" : contextPath; mbeanName = MBEAN_PREFIX + mbeanName; } return mbeanName; } /** * @return Context path of the application. */ private String getContextPath() { String contextPath = null; try { contextPath = (String) ServletContext.class.getMethod("getContextPath", new Class<?>[] {}).invoke( filterConfig.getServletContext(), new Object[] {}); } catch (final Exception e) { contextPath = "DEFAULT"; LOG.warn("Couldn't identify contextPath because you are using older version of servlet-api (<2.5). Using " + contextPath + " contextPath."); } return contextPath.replaceFirst(ServletContextUriLocator.PREFIX, ""); } /** * Override this method if you want to provide a different MBeanServer. * * @return {@link MBeanServer} to use for JMX. */ protected MBeanServer getMBeanServer() { return ManagementFactory.getPlatformMBeanServer(); } /** * Register property change listeners. */ private void registerChangeListeners() { wroConfiguration.registerCacheUpdatePeriodChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent event) { // reset cache headers when any property is changed in order to avoid browser caching headersConfigurer = newResponseHeadersConfigurer(); wroManagerFactory.onCachePeriodChanged(valueAsLong(event.getNewValue())); } }); wroConfiguration.registerModelUpdatePeriodChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent event) { headersConfigurer = newResponseHeadersConfigurer(); wroManagerFactory.onModelPeriodChanged(valueAsLong(event.getNewValue())); } }); LOG.debug("Cache & Model change listeners were registered"); } /** * @return the {@link ResponseHeadersConfigurer}. */ protected ResponseHeadersConfigurer newResponseHeadersConfigurer() { return ResponseHeadersConfigurer.fromConfig(wroConfiguration); } /** * @return default implementation of {@link RequestHandlerFactory} */ protected RequestHandlerFactory newRequestHandlerFactory() { return new DefaultRequestHandlerFactory(); } private long valueAsLong(final Object value) { notNull(value); return Long.valueOf(String.valueOf(value)).longValue(); } /** * Custom filter initialization - can be used for extended classes. * * @see Filter#init(FilterConfig). */ protected void doInit(final FilterConfig config) throws ServletException { } public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; if (isFilterActive(request)) { LOG.debug("processing wro request: {}", request.getRequestURI()); try { // add request, response & servletContext to thread local Context.set(Context.webContext(request, response, filterConfig), wroConfiguration); addPassThroughFilterAttribute(request); if (!handledWithRequestHandler(request, response)) { processRequest(request, response); onRequestProcessed(); } } catch (final Exception e) { onException(e, response, chain); } finally { Context.unset(); } } else { chain.doFilter(request, response); } } private void addPassThroughFilterAttribute(final HttpServletRequest request) { request.setAttribute(ATTRIBUTE_PASSED_THROUGH_FILTER, Boolean.TRUE); } private boolean handledWithRequestHandler(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { notNull(requestHandlers, "requestHandlers cannot be null!"); // create injector used for process injectable fields from each requestHandler. for (final RequestHandler requestHandler : requestHandlers) { if (requestHandler.isEnabled() && requestHandler.accept(request)) { requestHandler.handle(request, response); return true; } } return false; } /** * @return {@link Injector} used to inject {@link RequestHandler}'s. * @VisibleForTesting */ Injector createInjector() { return InjectorBuilder.create(wroManagerFactory).build(); } /** * Perform actual processing. */ private void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { setResponseHeaders(response); // process the uri using manager wroManagerFactory.create().process(); } /** * @return true if the filter should be applied or proceed with chain otherwise. */ private boolean isFilterActive(final HttpServletRequest request) { // prevent StackOverflowError by skipping the already included wro request return enable && !DispatcherStreamLocator.isIncludedRequest(request); } /** * Invoked when a {@link Exception} is thrown. Allows custom exception handling. The default implementation proceeds * with filter chaining when exception is thrown. * * @param e * {@link Exception} thrown during request processing. */ protected void onException(final Exception e, final HttpServletResponse response, final FilterChain chain) { LOG.error("Exception occured", e); try { LOG.warn("Cannot process. Proceeding with chain execution."); chain.doFilter(Context.get().getRequest(), response); } catch (final Exception ex) { // should never happen (use debug level to suppress unuseful logs) LOG.debug("Error while chaining the request", ex); } } /** * Method called for each request and responsible for setting response headers, used mostly for cache control. * Override this method if you want to change the way headers are set.<br> * * @param response * {@link HttpServletResponse} object. */ protected void setResponseHeaders(final HttpServletResponse response) { headersConfigurer.setHeaders(response); } /** * Allows external configuration of {@link WroManagerFactory} (ex: using spring IoC). When this value is set, the * default {@link WroManagerFactory} initialization won't work anymore. * <p/> * Note: call this method before {@link WroFilter#init(FilterConfig)} is invoked. * * @param wroManagerFactory * the wroManagerFactory to set */ public void setWroManagerFactory(final WroManagerFactory wroManagerFactory) { this.wroManagerFactory = wroManagerFactory; } /** * @return configured and decorated {@link WroManagerFactory} instance. */ public final WroManagerFactory getWroManagerFactory() { return this.wroManagerFactory; } /** * Sets the RequestHandlerFactory used to create the collection of requestHandlers * * @param requestHandlerFactory * to set */ public void setRequestHandlerFactory(final RequestHandlerFactory requestHandlerFactory) { notNull(requestHandlerFactory); this.requestHandlerFactory = requestHandlerFactory; } /** * Factory method for {@link WroManagerFactory}. * <p/> * Creates a {@link WroManagerFactory} configured in {@link WroConfiguration} using reflection. When no configuration * is found a default implementation is used. * </p> * Note: this method is not invoked during initialization if a {@link WroManagerFactory} is set using * {@link WroFilter#setWroManagerFactory(WroManagerFactory)}. * * @return {@link WroManagerFactory} instance. */ protected WroManagerFactory newWroManagerFactory() { return DefaultWroManagerFactory.create(wroConfigurationFactory); } /** * @return implementation of {@link ObjectFactory<WroConfiguration>} used to create a {@link WroConfiguration} object. */ protected ObjectFactory<WroConfiguration> newWroConfigurationFactory(final FilterConfig filterConfig) { return new PropertiesAndFilterConfigWroConfigurationFactory(filterConfig); } private ObjectFactory<WroConfiguration> getWroConfigurationFactory() { if (wroConfigurationFactory == null) { wroConfigurationFactory = newWroConfigurationFactory(filterConfig); } return wroConfigurationFactory; } public void setWroConfigurationFactory(final ObjectFactory<WroConfiguration> wroConfigurationFactory) { this.wroConfigurationFactory = wroConfigurationFactory; } /** * @return the {@link WroConfiguration} associated with this filter instance. * @VisibleForTesting */ public final WroConfiguration getConfiguration() { return this.wroConfiguration; } /** * Once set, this configuration will be used, instead of the one built by the factory. * * @param config * a not null {@link WroConfiguration} to set. */ public final void setConfiguration(final WroConfiguration config) { notNull(config); wroConfigurationFactory = new ObjectFactory<WroConfiguration>() { public WroConfiguration create() { return config; } }; } /** * Sets the enable flag used to toggle filter. This might be useful when the filter has to be enabled/disabled based * on environment configuration. * * @param enable * flag for enabling the {@link WroFilter}. */ public void setEnable(final boolean enable) { this.enable = enable; } /** * Useful for unit tests to check the post processing. */ protected void onRequestProcessed() { } /** * {@inheritDoc} */ public void destroy() { //Avoid memory leak by unregistering mBean on destroy unregisterMBean(); if (wroManagerFactory != null) { wroManagerFactory.destroy(); } if (wroConfiguration != null) { wroConfiguration.destroy(); } Context.destroy(); } }
/*- * #%L * utils-assertor * %% * Copyright (C) 2016 - 2018 Gilles Landel * %% * 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. * #L% */ package fr.landel.utils.assertor.predicate; import java.util.Locale; import java.util.regex.Pattern; import fr.landel.utils.assertor.Assertor; import fr.landel.utils.assertor.StepAssertor; import fr.landel.utils.assertor.commons.MessageAssertor; import fr.landel.utils.assertor.helper.HelperStep; import fr.landel.utils.assertor.utils.AssertorThrowable; /** * This class define methods that can be applied on the checked * {@link Throwable} object. To provide a result, it's also provide a chain * builder by returning a {@link PredicateAssertorStepThrowable}. The chain looks * like: * * <pre> * {@link PredicateAssertorStepThrowable} &gt; {@link PredicateAssertorStepThrowable} &gt; {@link PredicateAssertorStepThrowable} &gt; {@link PredicateAssertorStepThrowable}... * </pre> * * This chain always starts with a {@link PredicateAssertorStepThrowable} and ends * with {@link PredicateAssertorStepThrowable}. * * @since Aug 3, 2016 * @author Gilles * */ @FunctionalInterface public interface PredicateAssertorStepThrowable<T extends Throwable> extends PredicateAssertorStep<PredicateStepThrowable<T>, T> { /** * {@inheritDoc} */ @Override default PredicateStepThrowable<T> get(final StepAssertor<T> result) { return () -> result; } /** * {@inheritDoc} */ @Override default PredicateAssertorStepThrowable<T> not() { return () -> HelperStep.not(getStep()); } /** * Asserts that the given {@link Throwable} is an instance of {@code clazz} * and has the specified message. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).isInstanceOf(type, "Internal error").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param throwableMessage * the expected throwable message * @return The operator */ default PredicateStepThrowable<T> isInstanceOf(final Class<?> clazz, final CharSequence throwableMessage) { return this.isInstanceOf(clazz, throwableMessage, (CharSequence) null); } /** * Asserts that the given {@link Throwable} is an instance of {@code clazz} * and has the specified message. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).isInstanceOf(type, "Internal error", "not an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param throwableMessage * the expected throwable message * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> isInstanceOf(final Class<?> clazz, final CharSequence throwableMessage, final CharSequence message, final Object... arguments) { return this.isInstanceOf(clazz, throwableMessage, null, message, arguments); } /** * Asserts that the given {@link Throwable} is an instance of {@code clazz} * and has the specified message. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).isInstanceOf(type, "Internal error", Locale.US, "not an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param throwableMessage * the expected throwable message * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> isInstanceOf(final Class<?> clazz, final CharSequence throwableMessage, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.isInstanceOf(this.getStep(), clazz, throwableMessage, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} is an instance of {@code clazz} * and matches the pattern. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).isInstanceOf(type, pattern).orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @return The operator */ default PredicateStepThrowable<T> isInstanceOf(final Class<?> clazz, final Pattern pattern) { return this.isInstanceOf(clazz, pattern, null); } /** * Asserts that the given {@link Throwable} is an instance of {@code clazz} * and matches the pattern. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).isInstanceOf(type, pattern, "not an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> isInstanceOf(final Class<?> clazz, final Pattern pattern, final CharSequence message, final Object... arguments) { return this.isInstanceOf(clazz, pattern, null, message, arguments); } /** * Asserts that the given {@link Throwable} is an instance of {@code clazz} * and matches the pattern. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).isInstanceOf(type, pattern, Locale.US, "not an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> isInstanceOf(final Class<?> clazz, final Pattern pattern, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.isInstanceOf(this.getStep(), clazz, pattern, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} is assignable from {@code clazz} * and has the specified message. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).isAssignableFrom(type, "Internal error").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param throwableMessage * the expected throwable message * @return The operator */ default PredicateStepThrowable<T> isAssignableFrom(final Class<?> clazz, final CharSequence throwableMessage) { return this.isAssignableFrom(clazz, throwableMessage, (CharSequence) null); } /** * Asserts that the given {@link Throwable} is assignable from {@code clazz} * and has the specified message. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).isAssignableFrom(type, "Internal error", "not an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param throwableMessage * the expected throwable message * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> isAssignableFrom(final Class<?> clazz, final CharSequence throwableMessage, final CharSequence message, final Object... arguments) { return this.isAssignableFrom(clazz, throwableMessage, null, message, arguments); } /** * Asserts that the given {@link Throwable} is assignable from {@code clazz} * and has the specified message. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).isAssignableFrom(type, "Internal error", Locale.US, "not an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param throwableMessage * the expected throwable message * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> isAssignableFrom(final Class<?> clazz, final CharSequence throwableMessage, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.isAssignableFrom(this.getStep(), clazz, throwableMessage, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} is assignable from {@code clazz} * and matches the pattern. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).isAssignableFrom(type, pattern).orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @return The operator */ default PredicateStepThrowable<T> isAssignableFrom(final Class<?> clazz, final Pattern pattern) { return this.isAssignableFrom(clazz, pattern, null); } /** * Asserts that the given {@link Throwable} is assignable from {@code clazz} * and matches the pattern. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).isAssignableFrom(type, pattern, "not assignable from").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> isAssignableFrom(final Class<?> clazz, final Pattern pattern, final CharSequence message, final Object... arguments) { return this.isAssignableFrom(clazz, pattern, null, message, arguments); } /** * Asserts that the given {@link Throwable} is assignable from {@code clazz} * and matches the pattern. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).isAssignableFrom(type, pattern, Locale.US, "not assignable from").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> isAssignableFrom(final Class<?> clazz, final Pattern pattern, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.isAssignableFrom(this.getStep(), clazz, pattern, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} has a cause not {@code null} * * <p> * precondition: throwable cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseNotNull().orElseThrow(); * </pre> * * @return The operator */ default PredicateStepThrowable<T> hasCauseNotNull() { return this.hasCauseNotNull(null); } /** * Asserts that the given {@link Throwable} has a cause not {@code null} * * <p> * precondition: throwable cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseNotNull("cause cannot be null").orElseThrow(); * </pre> * * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseNotNull(final CharSequence message, final Object... arguments) { return this.hasCauseNotNull(null, message, arguments); } /** * Asserts that the given {@link Throwable} has a cause not {@code null} * * <p> * precondition: throwable cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseNotNull(Locale.US, "cause cannot be null").orElseThrow(); * </pre> * * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseNotNull(final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.hasCauseNotNull(this.getStep(), MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} has a cause {@code null} * * <p> * precondition: throwable cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseNull().orElseThrow(); * </pre> * * @return The operator */ default PredicateStepThrowable<T> hasCauseNull() { return this.hasCauseNull(null); } /** * Asserts that the given {@link Throwable} has a cause {@code null} * * <p> * precondition: throwable cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseNull("cause must be null").orElseThrow(); * </pre> * * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseNull(final CharSequence message, final Object... arguments) { return this.hasCauseNull(null, message, arguments); } /** * Asserts that the given {@link Throwable} has a cause {@code null} * * <p> * precondition: throwable cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseNull(Locale.US, "cause must be null").orElseThrow(); * </pre> * * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseNull(final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.hasCauseNull(this.getStep(), MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz}. If {@code recursively} is set to true, the method will * check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, true).orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final boolean recursively) { return this.hasCauseAssignableFrom(clazz, recursively, null); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz}. If {@code recursively} is set to true, the method will * check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, true, "not assignable from").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final boolean recursively, final CharSequence message, final Object... arguments) { return this.hasCauseAssignableFrom(clazz, recursively, null, message, arguments); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz}. If {@code recursively} is set to true, the method will * check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, true, Locale.US, "not assignable from").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final boolean recursively, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.hasCauseAssignableFrom(this.getStep(), clazz, recursively, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, exceptionMessage).orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param exceptionMessage * the exception message * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final CharSequence exceptionMessage, final boolean recursively) { return this.hasCauseAssignableFrom(clazz, exceptionMessage, recursively, null); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, exceptionMessage, true, "not assignable from").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param exceptionMessage * the exception message * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final CharSequence exceptionMessage, final boolean recursively, final CharSequence message, final Object... arguments) { return this.hasCauseAssignableFrom(clazz, exceptionMessage, recursively, null, message, arguments); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, exceptionMessage, true, Locale.US, "not assignable from").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param exceptionMessage * the exception message * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final CharSequence exceptionMessage, final boolean recursively, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.hasCauseAssignableFrom(this.getStep(), clazz, exceptionMessage, recursively, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, pattern, true).orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final Pattern pattern, final boolean recursively) { return this.hasCauseAssignableFrom(clazz, pattern, recursively, null); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, pattern, true, "not assignable from").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final Pattern pattern, final boolean recursively, final CharSequence message, final Object... arguments) { return this.hasCauseAssignableFrom(clazz, pattern, recursively, null, message, arguments); } /** * Asserts that the given {@link Throwable} has a cause assignable from * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseAssignableFrom(type, pattern, true, Locale.US, "not assignable from").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseAssignableFrom(final Class<?> clazz, final Pattern pattern, final boolean recursively, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.hasCauseAssignableFrom(this.getStep(), clazz, pattern, recursively, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz}. If {@code recursively} is set to true, the method will * check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, true).orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final boolean recursively) { return this.hasCauseInstanceOf(clazz, recursively, null); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz}. If {@code recursively} is set to true, the method will * check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, true, "not with an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final boolean recursively, final CharSequence message, final Object... arguments) { return this.hasCauseInstanceOf(clazz, recursively, null, message, arguments); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz}. If {@code recursively} is set to true, the method will * check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, true, Locale.US, "not with an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final boolean recursively, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.hasCauseInstanceOf(this.getStep(), clazz, recursively, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, exceptionMessage).orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param exceptionMessage * the exception message * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final CharSequence exceptionMessage, final boolean recursively) { return this.hasCauseInstanceOf(clazz, exceptionMessage, recursively, null); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, exceptionMessage, true, "not with an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param exceptionMessage * the exception message * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final CharSequence exceptionMessage, final boolean recursively, final CharSequence message, final Object... arguments) { return this.hasCauseInstanceOf(clazz, exceptionMessage, recursively, null, message, arguments); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable and clazz cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, exceptionMessage, true, Locale.US, "not with an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param exceptionMessage * the exception message * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final CharSequence exceptionMessage, final boolean recursively, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.hasCauseInstanceOf(this.getStep(), clazz, exceptionMessage, recursively, MessageAssertor.of(locale, message, arguments)); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, pattern, true).orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final Pattern pattern, final boolean recursively) { return this.hasCauseInstanceOf(clazz, pattern, recursively, null); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, pattern, true, "not with an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final Pattern pattern, final boolean recursively, final CharSequence message, final Object... arguments) { return this.hasCauseInstanceOf(clazz, pattern, recursively, null, message, arguments); } /** * Asserts that the given {@link Throwable} has a cause with an instance of * {@code clazz} and matches the pattern. If {@code recursively} is set to * true, the method will check the cause of cause recursively. * * <p> * precondition: throwable, clazz and pattern cannot be null * </p> * * <pre> * Assertor.that(throwable).hasCauseInstanceOf(type, pattern, true, Locale.US, "not with an instance of").orElseThrow(); * </pre> * * @param clazz * The super {@link Class} (super class or interface) * @param pattern * the message pattern * @param recursively * if true, sub causes are checked until a cause has the type and * matches the pattern * @param locale * The locale of the message (only used to format this message, * otherwise use {@link Assertor#setLocale}) * @param message * The message on mismatch * @param arguments * The arguments of the message, use {@link String#format} * @return The operator */ default PredicateStepThrowable<T> hasCauseInstanceOf(final Class<?> clazz, final Pattern pattern, final boolean recursively, final Locale locale, final CharSequence message, final Object... arguments) { return () -> AssertorThrowable.hasCauseInstanceOf(this.getStep(), clazz, pattern, recursively, MessageAssertor.of(locale, message, arguments)); } }
package assignment1; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.border.LineBorder; /** * <h2>SolverFrame</h2> * <p> * The main visual displayer for this application.<br /> * One Frame to rule them all, One Frame to find them,<br /> * One Frame to bring them all and in the darkness bind them. <br /> * This class holds reference to the Model and is used by the Controller * (Driver). Most actions by the user are caught and passed to the Model from * here. * </p> * <p> * From the frame, the user can open files, close the application, take 'steps' * through a Sudoku's solving process and see a quick solve. The steps taken * towards the solution are also displayed, although where they were executed is * not. <br /> * The GUI is very simple. Were there more time alloted for this project, I * would expand into firstly using JTextArea and carats to get the Solution * steps to autoscroll to the bottom of the steps. <br /> * Next I would get a log of not just what steps were taken but -where- each * step was taken in the grid puzzle. Right now the user must see by eye what * has taken place. Once this is implemented, I would work towards allowing the * user to step take a step backwards through the puzzle. <br /> * Were much more time alloted, I would expand into allowing the user to click * buttons in attempts to solve the puzzle by themselves, either through given * methods or directly allowing them attempts at solving the puzzle with the * methods just used to confirm correct choices. * </p> * * @author James Euesden - jee22@aber.ac.uk * @version 1.0 */ @SuppressWarnings("serial") public class SolverFrame extends JFrame implements ActionListener { private SolverCanvas canvas; private boolean gridLoaded = false; private boolean threadRunning = false; private Thread runSolver; private String appTitle = "Sudoku Solver - jee22"; // === Menu Items === private JMenuBar menuBar; private JMenu fileMenu; private JMenuItem openItem; private JMenuItem exitItem; private JFileChooser fileChooser; // === Sidebar Items === private JPanel sidebar; private JButton button; private JButton solveButton; private JPanel stepsPanel; private JScrollPane scroll; private JLabel status; private JLabel stText; /** * <p> * The constructor sets it's own components and prepares the canvas where * the Sudoku grid is displayed to be ready for use too. * </p> * * @param solver * - reference to an opening SudokuSolver to get the application * running. */ public SolverFrame(SudokuSolver solver) { canvas = new SolverCanvas(solver); setupFrameProperties(); setupMenu(); menuBar.add(fileMenu); setupSidebar(); this.add(sidebar, BorderLayout.EAST); this.getContentPane().add(canvas, BorderLayout.CENTER); this.setJMenuBar(menuBar); } /** * <p> * Assigns the properties of this Frame and how it should be displayed to a * user. * </p> * <p> * In particular, the grid is set to a specific size and is unsizable in * order to keep the Sudoku grid displaying correctly with uniformly sized * cells. I felt this was the best choice for such a simple GUI and * application at this point in time. <br /> * The Frame is created in the centre of the users screen and set to 'grey', * the default of most OS general application colours. * </p> */ public void setupFrameProperties() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setMinimumSize(new Dimension(700, 550)); this.pack(); this.setResizable(false); this.setTitle(appTitle); this.setBackground(Color.gray); this.setLocationRelativeTo(null); this.setVisible(true); } /** * <p> * Establishes the attributes of the top bar menu on the frame, allowing the * user to open files and exit the application. * </p> * <p> * Each button the menu bar is given a quick key shortcut for ease of use * and also a command for use with the ActionListener that listens for uses * by the user. <br /> * A small description of each action is given for accessibility sake of * sight impaired users. * </p> */ public void setupMenu() { menuBar = new JMenuBar(); fileMenu = new JMenu("File"); openItem = new JMenuItem("Open"); exitItem = new JMenuItem("Exit"); openItem = new JMenuItem("Open", KeyEvent.VK_O); openItem.setActionCommand("open"); openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit .getDefaultToolkit().getMenuShortcutKeyMask())); openItem.getAccessibleContext().setAccessibleDescription( "Opens a Sudoku .sud file"); fileMenu.add(openItem); exitItem = new JMenuItem("Exit"); exitItem.setActionCommand("exit"); exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, Toolkit .getDefaultToolkit().getMenuShortcutKeyMask())); exitItem.getAccessibleContext().setAccessibleDescription( "Exit Sudoku Solver"); fileMenu.add(exitItem); fileMenu.add(openItem); fileMenu.add(exitItem); openItem.addActionListener(this); exitItem.addActionListener(this); } /** * <p> * Sets the sidebar up for use on the Frame.<br /> * Strict dimensions are set to ensure it doesn't tamper with the Sudoku * grid display. * </p> * <p> * To give the user some help with the application, there are labels that * display the currently open file, buttons to either take steps in solving * the puzzle or a button to auto solve and pause the puzzle. <br /> * As previously stated,were there more time I would work on making a better * JScrollBar implementation. * </p> */ public void setupSidebar() { sidebar = new JPanel(); sidebar.setPreferredSize(new Dimension(200, 500)); stText = new JLabel("File Open: "); stText.setPreferredSize(new Dimension(55, 10)); status = new JLabel("No file Open"); status.setPreferredSize(new Dimension(135, 10)); sidebar.add(stText); sidebar.add(status); button = new JButton("Take Step"); button.addActionListener(this); button.setActionCommand("step"); sidebar.add(button); solveButton = new JButton("Solve Puzzle"); solveButton.addActionListener(this); solveButton.setActionCommand("solve"); sidebar.add(solveButton); stepsPanel = new JPanel(); stepsPanel.setLayout(new BorderLayout()); stepsPanel.setBackground(Color.WHITE); stepsPanel.setBorder(new LineBorder(Color.BLACK)); scroll = new JScrollPane(stepsPanel); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setPreferredSize(new Dimension(180, 400)); sidebar.add(scroll); } /** * <p> * Commands sent by the user from menus and buttons. * </p> * <p> * The open command will stop any running Thread to ensure that if a puzzle * is being solved, the user can't open a new puzzle and have the solving * continue on the new puzzle too. * </p> */ @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("open")) { if (threadRunning) { threadHandler(); } if (openFile()) { stepsPanel.removeAll(); repaint(); gridLoaded = true; } } if (command.equals("exit")) { exit(); } if (command.equals("step")) { if (gridLoaded) { if (threadRunning) { threadHandler(); } canvas.takeStep(); stepsPanel.add(canvas.getSteps()); this.repaint(); } else { // Pop up box to say no sudoku loaded - Future implementation } } /** * <p> * If the user wishes the solve the puzzle, it is first checked if there * is a loaded grid, then if the puzzle is being solved, and if so stops * it, then starts a new Thread and begins running a new solve loop in * SudokuCanvas. <br /> * The Solve button is also changed to 'Stop Solving', useful for * pausing a solve mid way through. * </p> */ if (command.equals("solve")) { if (gridLoaded) { if (threadRunning) { this.threadHandler(); } else { if (!canvas.isSolved()) { runSolver = new Thread(canvas); threadRunning = true; runSolver.start(); stepsPanel.add(canvas.getSteps()); this.repaint(); solveButton.setText("Stop Solving"); } } } else { // Pop up box to say no sudoku loaded } } } /** * <p> * If there is a thread running, often methods that would be otherwise * affected by it's continuation will call this function. <br /> * This method calls to the SudokuCanvas to set a boolean value to false in * order to stop a while loop in the canvas, then interrupts the Thread from * here. <br /> * Once done, the boolean keeping track of if a Thread is running is set to * false and the button stopping/starting the Thread/solver displays a * relevant message. * </p> */ public void threadHandler() { canvas.pause(); runSolver.interrupt(); threadRunning = false; solveButton.setText("Solve Puzzle"); } /** * <p> * Opens a file on the users system to solve * </p> * <p> * Uses <code>JFileChooser</code> to allow the user to select any file in * their system. * </p> * <p> * In order to filter out invalid files, I have created a customer * <code>FileFilter</code> that only displays <code>.sud</code> files. * </p> * <p> * Once a users has selected a file, it passes it through onto the canvas to * open and be displayed. * </p> */ private boolean openFile() { fileChooser = new JFileChooser(); fileChooser.setFileFilter(new SudFileFilter()); int chosen = fileChooser.showOpenDialog(this); if (chosen == JFileChooser.APPROVE_OPTION) { status.setText(fileChooser.getName(fileChooser.getSelectedFile())); canvas.openFile(fileChooser.getSelectedFile()); return true; } else { return false; } } /** * <p> * Exits the program. * </p> */ private void exit() { System.exit(0); } }
/* * Android SDK for Matomo * * @link https://github.com/matomo-org/matomo-android-sdk * @license https://github.com/matomo-org/matomo-sdk-android/blob/master/LICENSE BSD-3 Clause */ package org.matomo.sdk.dispatcher; import android.content.Context; import org.json.JSONArray; import org.junit.Before; import org.junit.Test; import org.matomo.sdk.QueryParams; import org.matomo.sdk.TrackMe; import org.matomo.sdk.tools.Connectivity; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.UUID; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import testhelpers.BaseTest; import testhelpers.TestHelper; import static org.awaitility.Awaitility.await; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @SuppressWarnings("ALL") public class DefaultDispatcherTest extends BaseTest { DefaultDispatcher mDispatcher; @Mock EventCache mEventCache; @Mock PacketSender mPacketSender; @Mock Connectivity mConnectivity; @Mock Context mContext; final String mApiUrl = "http://example.com"; final LinkedBlockingQueue<Event> mEventCacheData = new LinkedBlockingQueue<>(); @Before public void setup() throws Exception { super.setup(); MockitoAnnotations.initMocks(this); when(mConnectivity.isConnected()).thenReturn(true); when(mConnectivity.getType()).thenReturn(Connectivity.Type.MOBILE); doAnswer(invocation -> { mEventCacheData.add((Event) invocation.getArgument(0)); return null; }).when(mEventCache).add(any(Event.class)); when(mEventCache.isEmpty()).then(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { return mEventCacheData.isEmpty(); } }); when(mEventCache.updateState(anyBoolean())).thenAnswer(invocation -> { return (Boolean) invocation.getArgument(0) && !mEventCacheData.isEmpty(); }); doAnswer(invocation -> { List<Event> drainTarget = invocation.getArgument(0); mEventCacheData.drainTo(drainTarget); return null; }).when(mEventCache).drainTo(Matchers.anyList()); doAnswer(invocation -> { List<Event> toRequeue = invocation.getArgument(0); mEventCacheData.addAll(toRequeue); return null; }).when(mEventCache).requeue(Matchers.anyList()); doAnswer(invocation -> { mEventCacheData.clear(); return null; }).when(mEventCache).clear(); mDispatcher = new DefaultDispatcher(mEventCache, mConnectivity, new PacketFactory(mApiUrl), mPacketSender); } @Test public void testClear() { mDispatcher.clear(); verify(mEventCache).clear(); } @Test public void testClear_cleanExit() throws InterruptedException { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); mDispatcher.submit(getTestEvent()); mDispatcher.forceDispatch(); TestHelper.sleep(100); assertThat(dryRunData.size(), is(1)); dryRunData.clear(); when(mConnectivity.isConnected()).thenReturn(false); mDispatcher.submit(getTestEvent()); TestHelper.sleep(100); assertThat(mEventCacheData.size(), is(1)); mDispatcher.clear(); when(mConnectivity.isConnected()).thenReturn(true); mDispatcher.forceDispatch(); TestHelper.sleep(100); assertThat(dryRunData.size(), is(0)); } @Test public void testGetDispatchMode() { assertEquals(DispatchMode.ALWAYS, mDispatcher.getDispatchMode()); mDispatcher.setDispatchMode(DispatchMode.WIFI_ONLY); assertEquals(DispatchMode.WIFI_ONLY, mDispatcher.getDispatchMode()); } @Test public void testDispatchMode_wifiOnly() throws Exception { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); when(mConnectivity.getType()).thenReturn(Connectivity.Type.MOBILE); mDispatcher.setDispatchMode(DispatchMode.WIFI_ONLY); mDispatcher.submit(getTestEvent()); mDispatcher.forceDispatch(); verify(mEventCache, timeout(1000)).updateState(false); verify(mEventCache, never()).drainTo(Matchers.anyList()); when(mConnectivity.getType()).thenReturn(Connectivity.Type.WIFI); mDispatcher.forceDispatch(); await().atMost(1, TimeUnit.SECONDS).until(() -> dryRunData.size(), is(1)); verify(mEventCache).updateState(true); verify(mEventCache).drainTo(Matchers.anyList()); } @Test public void testConnectivityChange() throws Exception { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); when(mConnectivity.isConnected()).thenReturn(false); mDispatcher.submit(getTestEvent()); mDispatcher.forceDispatch(); verify(mEventCache, timeout(1000)).add(any()); verify(mEventCache, never()).drainTo(Matchers.anyList()); assertThat(dryRunData.size(), is(0)); when(mConnectivity.isConnected()).thenReturn(true); mDispatcher.forceDispatch(); await().atMost(1, TimeUnit.SECONDS).until(() -> dryRunData.size(), is(1)); verify(mEventCache).updateState(true); verify(mEventCache).drainTo(Matchers.anyList()); } @Test public void testGetDispatchGzipped() { assertFalse(mDispatcher.getDispatchGzipped()); mDispatcher.setDispatchGzipped(true); assertTrue(mDispatcher.getDispatchGzipped()); verify(mPacketSender).setGzipData(true); } @Test public void testDefaultConnectionTimeout() throws Exception { assertEquals(Dispatcher.DEFAULT_CONNECTION_TIMEOUT, mDispatcher.getConnectionTimeOut()); } @Test public void testSetConnectionTimeout() throws Exception { mDispatcher.setConnectionTimeOut(100); assertEquals(100, mDispatcher.getConnectionTimeOut()); verify(mPacketSender).setTimeout(100); } @Test public void testDefaultDispatchInterval() throws Exception { assertEquals(Dispatcher.DEFAULT_DISPATCH_INTERVAL, mDispatcher.getDispatchInterval()); } @Test public void testForceDispatchTwice() throws Exception { mDispatcher.setDispatchInterval(-1); mDispatcher.setConnectionTimeOut(20); mDispatcher.submit(getTestEvent()); assertTrue(mDispatcher.forceDispatch()); assertFalse(mDispatcher.forceDispatch()); } @Test public void testMultiThreadDispatch() throws Exception { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); mDispatcher.setDispatchInterval(20); final int threadCount = 20; final int queryCount = 100; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>()); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); checkForMIAs(threadCount * queryCount, createdEvents, dryRunData); } @Test public void testForceDispatch() throws Exception { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); mDispatcher.setDispatchInterval(-1L); final int threadCount = 10; final int queryCount = 10; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>()); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); TestHelper.sleep(500); assertEquals(threadCount * queryCount, createdEvents.size()); assertEquals(0, dryRunData.size()); mDispatcher.forceDispatch(); checkForMIAs(threadCount * queryCount, createdEvents, dryRunData); } @Test public void testBatchDispatch() throws Exception { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); mDispatcher.setDispatchInterval(1500); final int threadCount = 5; final int queryCount = 5; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>()); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); await().atMost(2, TimeUnit.SECONDS).until(() -> createdEvents.size(), is(threadCount * queryCount)); assertEquals(0, dryRunData.size()); await().atMost(2, TimeUnit.SECONDS).until(() -> createdEvents.size(), is(threadCount * queryCount)); checkForMIAs(threadCount * queryCount, createdEvents, dryRunData); } @Test public void testBlockingDispatch() throws Exception { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); mDispatcher.setDispatchInterval(-1); final int threadCount = 5; final int queryCount = 5; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>()); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); await().atMost(2, TimeUnit.SECONDS).until(() -> createdEvents.size(), is(threadCount * queryCount)); assertEquals(dryRunData.size(), 0); assertEquals(createdEvents.size(), threadCount * queryCount); mDispatcher.forceDispatchBlocking(); List<String> flattenedQueries = getFlattenedQueries(dryRunData); assertEquals(flattenedQueries.size(), threadCount * queryCount); } @Test public void testBlockingDispatchInFlight() throws Exception { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); mDispatcher.setDispatchInterval(20); final int threadCount = 5; final int queryCount = 5; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>()); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); await().atMost(2, TimeUnit.SECONDS).until(() -> createdEvents.size(), is(threadCount * queryCount)); assertEquals(createdEvents.size(), threadCount * queryCount); assertNotEquals(new ArrayList(dryRunData).size(), 0); mDispatcher.forceDispatchBlocking(); List<String> flattenedQueries = getFlattenedQueries(dryRunData); assertEquals(flattenedQueries.size(), threadCount * queryCount); } @Test public void testBlockingDispatchCollision() throws Exception { final Semaphore lock = new Semaphore(0); final AtomicInteger eventCount = new AtomicInteger(0); mDispatcher.setDispatchInterval(-1); when(mPacketSender.send(any())).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { Packet packet = invocation.getArgument(0); eventCount.addAndGet(packet.getEventCount()); lock.release(); Thread.sleep(100); return true; } }); final int threadCount = 7; final int queryCount = 13; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<>()); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); await().atMost(2, TimeUnit.SECONDS).until(() -> createdEvents.size(), is(threadCount * queryCount)); mDispatcher.forceDispatch(); lock.acquire(); mDispatcher.forceDispatchBlocking(); assertEquals(eventCount.get(), threadCount * queryCount); } @Test public void testBlockingDispatchExceptionMode() { mDispatcher.setDispatchInterval(200); final int threadCount = 5; final int queryCount = 10; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<>()); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); final AtomicInteger sentEvents = new AtomicInteger(0); when(mPacketSender.send(any())).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { Packet packet = invocation.getArgument(0); sentEvents.addAndGet(packet.getEventCount()); mDispatcher.setDispatchMode(DispatchMode.EXCEPTION); return true; } }); await().atMost(2, TimeUnit.SECONDS).until(() -> createdEvents.size(), is(threadCount * queryCount)); mDispatcher.forceDispatchBlocking(); int sentEventCount = sentEvents.get(); assertEquals(sentEventCount, PacketFactory.PAGE_SIZE); assertEquals(mEventCacheData.size() + sentEventCount, threadCount * queryCount); } @Test public void testDispatchRetryWithBackoff() throws Exception { AtomicInteger cnt = new AtomicInteger(0); when(mPacketSender.send(any())).then(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { return cnt.incrementAndGet() > 5; } }); mDispatcher.setDispatchInterval(100); mDispatcher.submit(getTestEvent()); await().atLeast(100, TimeUnit.MILLISECONDS).until(() -> cnt.get() == 1); await().atLeast(100, TimeUnit.MILLISECONDS).until(() -> cnt.get() == 2); await().atMost(1900, TimeUnit.MILLISECONDS).until(() -> cnt.get() == 5); mDispatcher.submit(getTestEvent()); await().atMost(150, TimeUnit.MILLISECONDS).until(() -> cnt.get() == 5); } @Test public void testDispatchInterval() throws Exception { List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); mDispatcher.setDispatchInterval(500); assertThat(dryRunData.isEmpty(), is(true)); mDispatcher.submit(getTestEvent()); await().atLeast(500, TimeUnit.MILLISECONDS).until(() -> dryRunData.size() == 1); } @Test public void testRandomDispatchIntervals() throws Exception { final List<Packet> dryRunData = Collections.synchronizedList(new ArrayList<Packet>()); mDispatcher.setDryRunTarget(dryRunData); final int threadCount = 10; final int queryCount = 100; final List<String> createdEvents = Collections.synchronizedList(new ArrayList<String>()); new Thread(new Runnable() { @Override public void run() { try { while (getFlattenedQueries(new ArrayList<>(dryRunData)).size() != threadCount * queryCount) { mDispatcher.setDispatchInterval(new Random().nextInt(20 - -1) + -1); } } catch (Exception e) {e.printStackTrace();} } }).start(); launchTestThreads(mApiUrl, mDispatcher, threadCount, queryCount, createdEvents); checkForMIAs(threadCount * queryCount, createdEvents, dryRunData); } public static void checkForMIAs(int expectedEvents, List<String> createdEvents, List<Packet> dryRunOutput) throws Exception { int previousEventCount = 0; int previousFlatQueryCount = 0; List<String> flattenedQueries; long lastChange = System.currentTimeMillis(); int nothingHappenedCounter = 0; while (true) { TestHelper.sleep(100); flattenedQueries = getFlattenedQueries(new ArrayList<>(dryRunOutput)); if (flattenedQueries.size() == expectedEvents) { break; } else { flattenedQueries = getFlattenedQueries(new ArrayList<>(dryRunOutput)); int currentEventCount = createdEvents.size(); int currentFlatQueryCount = flattenedQueries.size(); if (previousEventCount != currentEventCount && previousFlatQueryCount != currentFlatQueryCount) { lastChange = System.currentTimeMillis(); previousEventCount = currentEventCount; previousFlatQueryCount = currentFlatQueryCount; nothingHappenedCounter = 0; } else { nothingHappenedCounter++; if (nothingHappenedCounter > 50) assertTrue("Test seems stuck, nothing happens", false); } } } assertEquals(flattenedQueries.size(), expectedEvents); assertEquals(createdEvents.size(), expectedEvents); // We are done, lets make sure can find all send queries in our dispatched results while (!createdEvents.isEmpty()) { String query = createdEvents.remove(0); assertTrue(flattenedQueries.remove(query)); } assertTrue(createdEvents.isEmpty()); assertTrue(flattenedQueries.isEmpty()); } public static void launchTestThreads(final String apiUrl, final Dispatcher dispatcher, int threadCount, final int queryCount, final List<String> createdQueries) { for (int i = 0; i < threadCount; i++) { new Thread(new Runnable() { @Override public void run() { try { for (int j = 0; j < queryCount; j++) { TestHelper.sleep(new Random().nextInt(20 - 0) + 0); TrackMe trackMe = new TrackMe() .set(QueryParams.EVENT_ACTION, UUID.randomUUID().toString()) .set(QueryParams.EVENT_CATEGORY, UUID.randomUUID().toString()) .set(QueryParams.EVENT_NAME, UUID.randomUUID().toString()) .set(QueryParams.EVENT_VALUE, j); dispatcher.submit(trackMe); createdQueries.add(apiUrl + new Event(trackMe.toMap()).getEncodedQuery()); } } catch (Exception e) { e.printStackTrace(); assertFalse(true); } } }).start(); } } public static List<String> getFlattenedQueries(List<Packet> packets) throws Exception { List<String> flattenedQueries = new ArrayList<>(); for (Packet request : packets) { if (request.getPostData() != null) { JSONArray batchedRequests = request.getPostData().getJSONArray("requests"); for (int json = 0; json < batchedRequests.length(); json++) { String unbatchedRequest = request.getTargetURL() + batchedRequests.get(json).toString(); flattenedQueries.add(unbatchedRequest); } } else { flattenedQueries.add(request.getTargetURL()); } } return flattenedQueries; } public static TrackMe getTestEvent() { TrackMe trackMe = new TrackMe(); trackMe.set(QueryParams.SESSION_START, 1); return trackMe; } }
/* * Copyright 2012 GitHub 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.github.mobile.ui; import static android.content.Intent.ACTION_VIEW; import static android.content.Intent.CATEGORY_BROWSABLE; import static org.eclipse.egit.github.core.event.Event.TYPE_COMMIT_COMMENT; import static org.eclipse.egit.github.core.event.Event.TYPE_DOWNLOAD; import static org.eclipse.egit.github.core.event.Event.TYPE_PUSH; import android.app.AlertDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.ListView; import com.github.kevinsawicki.wishlist.SingleTypeAdapter; import com.github.kevinsawicki.wishlist.ViewFinder; import com.github.mobile.R; import com.github.mobile.core.gist.GistEventMatcher; import com.github.mobile.core.issue.IssueEventMatcher; import com.github.mobile.core.repo.RepositoryEventMatcher; import com.github.mobile.core.user.UserEventMatcher; import com.github.mobile.core.user.UserEventMatcher.UserPair; import com.github.mobile.ui.commit.CommitCompareViewActivity; import com.github.mobile.ui.commit.CommitViewActivity; import com.github.mobile.ui.gist.GistsViewActivity; import com.github.mobile.ui.issue.IssuesViewActivity; import com.github.mobile.ui.repo.RepositoryViewActivity; import com.github.mobile.ui.user.NewsListAdapter; import com.github.mobile.util.AvatarLoader; import com.google.inject.Inject; import java.util.List; import org.eclipse.egit.github.core.Commit; import org.eclipse.egit.github.core.CommitComment; import org.eclipse.egit.github.core.Download; import org.eclipse.egit.github.core.Gist; import org.eclipse.egit.github.core.Issue; import org.eclipse.egit.github.core.Repository; import org.eclipse.egit.github.core.User; import org.eclipse.egit.github.core.event.CommitCommentPayload; import org.eclipse.egit.github.core.event.DownloadPayload; import org.eclipse.egit.github.core.event.Event; import org.eclipse.egit.github.core.event.PushPayload; import org.eclipse.egit.github.core.service.EventService; /** * Base news fragment class with utilities for subclasses to built on */ public abstract class NewsFragment extends PagedItemFragment<Event> { /** * Matcher for finding an {@link Issue} from an {@link Event} */ protected final IssueEventMatcher issueMatcher = new IssueEventMatcher(); /** * Matcher for finding a {@link Gist} from an {@link Event} */ protected final GistEventMatcher gistMatcher = new GistEventMatcher(); /** * Matcher for finding a {@link Repository} from an {@link Event} */ protected final RepositoryEventMatcher repoMatcher = new RepositoryEventMatcher(); /** * Matcher for finding a {@link User} from an {@link Event} */ protected final UserEventMatcher userMatcher = new UserEventMatcher(); @Inject private AvatarLoader avatars; /** * Event service */ @Inject protected EventService service; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(R.string.no_news); } @Override public void onListItemClick(ListView l, View v, int position, long id) { Event event = (Event) l.getItemAtPosition(position); if (TYPE_DOWNLOAD.equals(event.getType())) { openDownload(event); return; } if (TYPE_PUSH.equals(event.getType())) { openPush(event); return; } if (TYPE_COMMIT_COMMENT.equals(event.getType())) { openCommitComment(event); return; } Issue issue = issueMatcher.getIssue(event); if (issue != null) { Repository repo = RepositoryEventMatcher.getRepository( event.getRepo(), event.getActor(), event.getOrg()); viewIssue(issue, repo); return; } Gist gist = gistMatcher.getGist(event); if (gist != null) { startActivity(GistsViewActivity.createIntent(gist)); return; } Repository repo = repoMatcher.getRepository(event); if (repo != null) viewRepository(repo); UserPair users = userMatcher.getUsers(event); if (users != null) viewUser(users); } @Override public boolean onListItemLongClick(ListView l, View v, int position, long itemId) { if (!isUsable()) return false; final Event event = (Event) l.getItemAtPosition(position); final Repository repo = RepositoryEventMatcher.getRepository( event.getRepo(), event.getActor(), event.getOrg()); final User user = event.getActor(); if (repo != null && user != null) { final AlertDialog dialog = LightAlertDialog.create(getActivity()); dialog.setTitle(R.string.navigate_to); dialog.setCanceledOnTouchOutside(true); View view = getActivity().getLayoutInflater().inflate( R.layout.nav_dialog, null); ViewFinder finder = new ViewFinder(view); avatars.bind(finder.imageView(R.id.iv_user_avatar), user); avatars.bind(finder.imageView(R.id.iv_repo_avatar), repo.getOwner()); finder.setText(R.id.tv_login, user.getLogin()); finder.setText(R.id.tv_repo_name, repo.generateId()); finder.onClick(R.id.ll_user_area, new OnClickListener() { public void onClick(View v) { dialog.dismiss(); viewUser(user); } }); finder.onClick(R.id.ll_repo_area, new OnClickListener() { public void onClick(View v) { dialog.dismiss(); viewRepository(repo); } }); dialog.setView(view); dialog.show(); return true; } return false; } private void openDownload(Event event) { Download download = ((DownloadPayload) event.getPayload()) .getDownload(); if (download == null) return; String url = download.getHtmlUrl(); if (TextUtils.isEmpty(url)) return; Intent intent = new Intent(ACTION_VIEW, Uri.parse(url)); intent.addCategory(CATEGORY_BROWSABLE); startActivity(intent); } private void openCommitComment(Event event) { Repository repo = RepositoryEventMatcher.getRepository(event.getRepo(), event.getActor(), event.getOrg()); if (repo == null) return; CommitCommentPayload payload = (CommitCommentPayload) event .getPayload(); CommitComment comment = payload.getComment(); if (comment == null) return; String sha = comment.getCommitId(); if (!TextUtils.isEmpty(sha)) startActivity(CommitViewActivity.createIntent(repo, sha)); } private void openPush(Event event) { Repository repo = RepositoryEventMatcher.getRepository(event.getRepo(), event.getActor(), event.getOrg()); if (repo == null) return; PushPayload payload = (PushPayload) event.getPayload(); List<Commit> commits = payload.getCommits(); if (commits == null || commits.isEmpty()) return; if (commits.size() > 1) { String base = payload.getBefore(); String head = payload.getHead(); if (!TextUtils.isEmpty(base) && !TextUtils.isEmpty(head)) startActivity(CommitCompareViewActivity.createIntent(repo, base, head)); } else { Commit commit = commits.get(0); String sha = commit != null ? commit.getSha() : null; if (!TextUtils.isEmpty(sha)) startActivity(CommitViewActivity.createIntent(repo, sha)); } } /** * Start an activity to view the given repository * * @param repository */ protected void viewRepository(Repository repository) { startActivity(RepositoryViewActivity.createIntent(repository)); } /** * Start an activity to view the given {@link UserPair} * <p> * This method does nothing by default, subclasses should override * * @param users */ protected void viewUser(UserPair users) { } /** * Start an activity to view the given {@link User} * * @param user * @return true if new activity started, false otherwise */ protected boolean viewUser(User user) { return false; } /** * Start an activity to view the given {@link Issue} * * @param issue * @param repository */ protected void viewIssue(Issue issue, Repository repository) { if (repository != null) startActivity(IssuesViewActivity.createIntent(issue, repository)); else startActivity(IssuesViewActivity.createIntent(issue)); } @Override protected SingleTypeAdapter<Event> createAdapter(List<Event> items) { return new NewsListAdapter(getActivity().getLayoutInflater(), items.toArray(new Event[items.size()]), avatars); } @Override protected int getLoadingMessage() { return R.string.loading_news; } @Override protected int getErrorMessage(Exception exception) { return R.string.error_news_load; } }
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ * Other contributors include Andrew Wright, Jeffrey Hayes, * Pat Fisher, Mike Judd. */ package jsr166; import junit.framework.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.Vector; import java.util.concurrent.CopyOnWriteArraySet; public class CopyOnWriteArraySetTest extends JSR166TestCase { static CopyOnWriteArraySet<Integer> populatedSet(int n) { CopyOnWriteArraySet<Integer> a = new CopyOnWriteArraySet<Integer>(); assertTrue(a.isEmpty()); for (int i = 0; i < n; i++) a.add(i); assertFalse(a.isEmpty()); assertEquals(n, a.size()); return a; } static CopyOnWriteArraySet populatedSet(Integer[] elements) { CopyOnWriteArraySet<Integer> a = new CopyOnWriteArraySet<Integer>(); assertTrue(a.isEmpty()); for (int i = 0; i < elements.length; i++) a.add(elements[i]); assertFalse(a.isEmpty()); assertEquals(elements.length, a.size()); return a; } /** * Default-constructed set is empty */ public void testConstructor() { CopyOnWriteArraySet a = new CopyOnWriteArraySet(); assertTrue(a.isEmpty()); } /** * Collection-constructed set holds all of its elements */ public void testConstructor3() { Integer[] ints = new Integer[SIZE]; for (int i = 0; i < SIZE-1; ++i) ints[i] = new Integer(i); CopyOnWriteArraySet a = new CopyOnWriteArraySet(Arrays.asList(ints)); for (int i = 0; i < SIZE; ++i) assertTrue(a.contains(ints[i])); } /** * addAll adds each element from the given collection */ public void testAddAll() { CopyOnWriteArraySet full = populatedSet(3); Vector v = new Vector(); v.add(three); v.add(four); v.add(five); full.addAll(v); assertEquals(6, full.size()); } /** * addAll adds each element from the given collection that did not * already exist in the set */ public void testAddAll2() { CopyOnWriteArraySet full = populatedSet(3); Vector v = new Vector(); v.add(three); v.add(four); v.add(one); // will not add this element full.addAll(v); assertEquals(5, full.size()); } /** * add will not add the element if it already exists in the set */ public void testAdd2() { CopyOnWriteArraySet full = populatedSet(3); full.add(one); assertEquals(3, full.size()); } /** * add adds the element when it does not exist in the set */ public void testAdd3() { CopyOnWriteArraySet full = populatedSet(3); full.add(three); assertTrue(full.contains(three)); } /** * clear removes all elements from the set */ public void testClear() { CopyOnWriteArraySet full = populatedSet(3); full.clear(); assertEquals(0, full.size()); } /** * contains returns true for added elements */ public void testContains() { CopyOnWriteArraySet full = populatedSet(3); assertTrue(full.contains(one)); assertFalse(full.contains(five)); } /** * Sets with equal elements are equal */ public void testEquals() { CopyOnWriteArraySet a = populatedSet(3); CopyOnWriteArraySet b = populatedSet(3); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertEquals(a.hashCode(), b.hashCode()); a.add(m1); assertFalse(a.equals(b)); assertFalse(b.equals(a)); b.add(m1); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertEquals(a.hashCode(), b.hashCode()); } /** * containsAll returns true for collections with subset of elements */ public void testContainsAll() { CopyOnWriteArraySet full = populatedSet(3); Vector v = new Vector(); v.add(one); v.add(two); assertTrue(full.containsAll(v)); v.add(six); assertFalse(full.containsAll(v)); } /** * isEmpty is true when empty, else false */ public void testIsEmpty() { CopyOnWriteArraySet empty = new CopyOnWriteArraySet(); CopyOnWriteArraySet full = populatedSet(3); assertTrue(empty.isEmpty()); assertFalse(full.isEmpty()); } /** * iterator() returns an iterator containing the elements of the * set in insertion order */ public void testIterator() { Collection empty = new CopyOnWriteArraySet(); assertFalse(empty.iterator().hasNext()); try { empty.iterator().next(); shouldThrow(); } catch (NoSuchElementException success) {} Integer[] elements = new Integer[SIZE]; for (int i = 0; i < SIZE; i++) elements[i] = i; Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); Iterator it = full.iterator(); for (int j = 0; j < SIZE; j++) { assertTrue(it.hasNext()); assertEquals(elements[j], it.next()); } assertFalse(it.hasNext()); try { it.next(); shouldThrow(); } catch (NoSuchElementException success) {} } /** * iterator remove is unsupported */ public void testIteratorRemove() { CopyOnWriteArraySet full = populatedSet(3); Iterator it = full.iterator(); it.next(); try { it.remove(); shouldThrow(); } catch (UnsupportedOperationException success) {} } /** * toString holds toString of elements */ public void testToString() { assertEquals("[]", new CopyOnWriteArraySet().toString()); CopyOnWriteArraySet full = populatedSet(3); String s = full.toString(); for (int i = 0; i < 3; ++i) assertTrue(s.contains(String.valueOf(i))); assertEquals(new ArrayList(full).toString(), full.toString()); } /** * removeAll removes all elements from the given collection */ public void testRemoveAll() { CopyOnWriteArraySet full = populatedSet(3); Vector v = new Vector(); v.add(one); v.add(two); full.removeAll(v); assertEquals(1, full.size()); } /** * remove removes an element */ public void testRemove() { CopyOnWriteArraySet full = populatedSet(3); full.remove(one); assertFalse(full.contains(one)); assertEquals(2, full.size()); } /** * size returns the number of elements */ public void testSize() { CopyOnWriteArraySet empty = new CopyOnWriteArraySet(); CopyOnWriteArraySet full = populatedSet(3); assertEquals(3, full.size()); assertEquals(0, empty.size()); } /** * toArray() returns an Object array containing all elements from * the set in insertion order */ public void testToArray() { Object[] a = new CopyOnWriteArraySet().toArray(); assertTrue(Arrays.equals(new Object[0], a)); assertSame(Object[].class, a.getClass()); Integer[] elements = new Integer[SIZE]; for (int i = 0; i < SIZE; i++) elements[i] = i; Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); assertTrue(Arrays.equals(elements, full.toArray())); assertSame(Object[].class, full.toArray().getClass()); } /** * toArray(Integer array) returns an Integer array containing all * elements from the set in insertion order */ public void testToArray2() { Collection empty = new CopyOnWriteArraySet(); Integer[] a; a = new Integer[0]; assertSame(a, empty.toArray(a)); a = new Integer[SIZE/2]; Arrays.fill(a, 42); assertSame(a, empty.toArray(a)); assertNull(a[0]); for (int i = 1; i < a.length; i++) assertEquals(42, (int) a[i]); Integer[] elements = new Integer[SIZE]; for (int i = 0; i < SIZE; i++) elements[i] = i; Collections.shuffle(Arrays.asList(elements)); Collection<Integer> full = populatedSet(elements); Arrays.fill(a, 42); assertTrue(Arrays.equals(elements, full.toArray(a))); for (int i = 0; i < a.length; i++) assertEquals(42, (int) a[i]); assertSame(Integer[].class, full.toArray(a).getClass()); a = new Integer[SIZE]; Arrays.fill(a, 42); assertSame(a, full.toArray(a)); assertTrue(Arrays.equals(elements, a)); a = new Integer[2*SIZE]; Arrays.fill(a, 42); assertSame(a, full.toArray(a)); assertTrue(Arrays.equals(elements, Arrays.copyOf(a, SIZE))); assertNull(a[SIZE]); for (int i = SIZE + 1; i < a.length; i++) assertEquals(42, (int) a[i]); } /** * toArray throws an ArrayStoreException when the given array can * not store the objects inside the set */ public void testToArray_ArrayStoreException() { try { CopyOnWriteArraySet c = new CopyOnWriteArraySet(); c.add("zfasdfsdf"); c.add("asdadasd"); c.toArray(new Long[5]); shouldThrow(); } catch (ArrayStoreException success) {} } /** * A deserialized serialized set is equal */ public void testSerialization() throws Exception { Set x = populatedSet(SIZE); Set y = serialClone(x); assertNotSame(y, x); assertEquals(x.size(), y.size()); assertEquals(x.toString(), y.toString()); assertTrue(Arrays.equals(x.toArray(), y.toArray())); assertEquals(x, y); assertEquals(y, x); } /** * addAll is idempotent */ public void testAddAll_idempotent() throws Exception { Set x = populatedSet(SIZE); Set y = new CopyOnWriteArraySet(x); y.addAll(x); assertEquals(x, y); assertEquals(y, x); } }