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.ignite.internal.processors.cache.persistence.db; import java.io.Serializable; import java.util.List; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.cache.CacheRebalanceMode; import org.apache.ignite.cache.CacheWriteSynchronizationMode; import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.cache.query.annotations.QuerySqlField; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.MemoryConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.MemoryPolicyConfiguration; import org.apache.ignite.configuration.PersistentStoreConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; /** * */ public class IgnitePdsPageEvictionTest extends GridCommonAbstractTest { /** IP finder. */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** Test entry count. */ public static final int ENTRY_CNT = 1_000_000; /** Cache name. */ private static final String CACHE_NAME = "cache"; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); MemoryConfiguration memCfg = new MemoryConfiguration(); memCfg.setConcurrencyLevel(Runtime.getRuntime().availableProcessors() * 4); memCfg.setPageSize(1024); MemoryPolicyConfiguration memPlcCfg = new MemoryPolicyConfiguration(); memPlcCfg.setName("dfltMemPlc"); memPlcCfg.setInitialSize(50 * 1024 * 1024); memPlcCfg.setMaxSize(50 * 1024 * 1024); memCfg.setMemoryPolicies(memPlcCfg); memCfg.setDefaultMemoryPolicyName("dfltMemPlc"); cfg.setMemoryConfiguration(memCfg); CacheConfiguration<DbKey, DbValue> ccfg = new CacheConfiguration<>(CACHE_NAME); ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); ccfg.setRebalanceMode(CacheRebalanceMode.NONE); ccfg.setIndexedTypes(DbKey.class, DbValue.class); ccfg.setAffinity(new RendezvousAffinityFunction(false, 32)); cfg.setCacheConfiguration(ccfg); cfg.setPersistentStoreConfiguration(new PersistentStoreConfiguration()); cfg.setDiscoverySpi( new TcpDiscoverySpi() .setIpFinder(IP_FINDER) ); cfg.setMarshaller(null); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { deleteRecursively(U.resolveWorkDirectory(U.defaultWorkDirectory(), "db", false)); stopAllGrids(); startGrids(1); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); deleteRecursively(U.resolveWorkDirectory(U.defaultWorkDirectory(), "db", false)); } /** * @throws Exception if failed. */ public void testPageEvictionSql() throws Exception { IgniteEx ig = grid(0); ig.active(true); try (IgniteDataStreamer<DbKey, DbValue> streamer = ig.dataStreamer(CACHE_NAME)) { for (int i = 0; i < ENTRY_CNT; i++) { streamer.addData(new DbKey(i), new DbValue(i, "value-" + i, Long.MAX_VALUE - i)); if (i > 0 && i % 10_000 == 0) info("Done put: " + i); } } IgniteCache<DbKey, DbValue> cache = ignite(0).cache(CACHE_NAME); for (int i = 0; i < ENTRY_CNT; i++) { assertEquals(Long.MAX_VALUE - i, cache.get(new DbKey(i)).lVal); if (i > 0 && i % 10_000 == 0) info("Done get: " + i); } for (int i = 0; i < ENTRY_CNT; i++) { List<List<?>> rows = cache.query( new SqlFieldsQuery("select lVal from DbValue where iVal=?").setArgs(i) ).getAll(); assertEquals(1, rows.size()); assertEquals(Long.MAX_VALUE - i, rows.get(0).get(0)); if (i > 0 && i % 10_000 == 0) info("Done SQL query: " + i); } } /** * */ private static class DbKey implements Serializable { /** */ private int val; /** * @param val Value. */ private DbKey(int val) { this.val = val; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof DbKey)) return false; DbKey key = (DbKey)o; return val == key.val; } /** {@inheritDoc} */ @Override public int hashCode() { return val; } } /** * */ private static class DbValue implements Serializable { /** */ @QuerySqlField(index = true) private int iVal; /** */ @QuerySqlField(index = true) private String sVal; /** */ @QuerySqlField private long lVal; /** * @param iVal Integer value. * @param sVal String value. * @param lVal Long value. */ private DbValue(int iVal, String sVal, long lVal) { this.iVal = iVal; this.sVal = sVal; this.lVal = lVal; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DbValue dbVal = (DbValue)o; return iVal == dbVal.iVal && lVal == dbVal.lVal && !(sVal != null ? !sVal.equals(dbVal.sVal) : dbVal.sVal != null); } /** {@inheritDoc} */ @Override public int hashCode() { int res = iVal; res = 31 * res + (sVal != null ? sVal.hashCode() : 0); res = 31 * res + (int)(lVal ^ (lVal >>> 32)); return res; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(DbValue.class, this); } } }
/** * 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 net.floodlightcontroller.hasupport.topology; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * This is a utility class that consists of utility/support functions that are * used for repetitive tasks by different topology classes Specifically consists * of functions to parse the Topology updates and calculating md5 hashes, * updates are parsed in O(n) time to get the equivalent JSON representation. * * @author Bhargav Srinivasan, Om Kale * */ public class TopoUtils { private static final Logger logger = LoggerFactory.getLogger(TopoUtils.class); /** * These are the primary key / low frequency fields, which are used to index * the updates in the syncDB. */ private final String[] lowfields = new String[] { "src", "srcPort", "dst", "dstPort", "type" }; /** * Sticks the two updates together in a comma separated manner. * * @param oldUpdate * : Update retrieved from the syncDB (existing value). * @param newUpdate * : Incoming update (new value). * @return : "oldUpdate, newUpdate" */ public String appendUpdate(String oldUpdate, String newUpdate) { StringBuilder updated = new StringBuilder(); updated.append(oldUpdate); updated.append(", "); updated.append(newUpdate); return updated.toString(); } /** * Calculates the MD5 hash of the given String. * * @param Input * String. * @return MD5 hash of the given String. */ public String calculateMD5Hash(String value) { String md5 = new String(); try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(value.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); md5 = bigInt.toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return md5; } /** * MD5 hash of the primary key / low frequency fields for the given updates. * This is used by the packJSON method in order to form the "KEY" for * pushing into the syncDB. * * @param update: * String representation of the JSON form of the LDUpdate. * @param newUpdateMap: * A hashmap which has the <"field", "value"> pairs of the JSON * representation of the incoming updates in the packJSON method. * @return MD5 hash of the primary key fields in the supplied update. */ public String getCMD5Hash(String update, Map<String, String> newUpdateMap) { List<String> cmd5fields = new ArrayList<>(); String cmd5 = new String(); /** * check map for low freq updates */ for (String lf : lowfields) { if (newUpdateMap.containsKey(lf)) { cmd5fields.add(newUpdateMap.get(lf)); } } /** * cmd5fields will contain all low freq field values; take md5 hash of * all values together. */ StringBuilder md5valuesb = new StringBuilder(); for (String t : cmd5fields) { md5valuesb.append(t); } String md5values = new String(); md5values = md5valuesb.toString(); try { TopoUtils myCMD5 = new TopoUtils(); cmd5 = myCMD5.calculateMD5Hash(md5values); // logger.debug("[cmd5Hash] The MD5: {} The Value {}", new Object [] // {cmd5,md5values.toString()}); //use md5values instead of updates. } catch (Exception e) { logger.debug("[cmd5Hash] Exception: enqueueFwd!"); e.printStackTrace(); } return cmd5; } /** * A parser which takes the list of updates as one continuous string and * makes an O(n) pass over them to convert them to a list of JSON objects * which can then be pushed into the FilterQueue. * * @param chunk: * Continuous String representation of an array of Topology * Updates. * @return List of JSON representation of the Topology Updates which were * input. */ public List<String> parseChunk(String chunk) { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> newJson = new HashMap<>(); List<String> jsonInString = new LinkedList<>(); String op = new String(); String src = new String(); String srcPort = new String(); String dst = new String(); String dstPort = new String(); String latency = new String(); String type = new String(); if (!chunk.startsWith("LDUpdate [")) { return jsonInString; } try { while (!chunk.equals("]]")) { /** * pre */ if (chunk.startsWith("LDUpdate [")) { chunk = chunk.substring(10, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk pre: {}", new // Object[] {chunk}); /** * process keywords */ /** * field: operation */ if (chunk.startsWith("operation=")) { chunk = chunk.substring(10, chunk.length()); op = chunk.split(",|]")[0]; // logger.debug("[Assemble Topo Update] Operation=: {}", new // Object[]{op}); chunk = chunk.substring(op.length(), chunk.length()); } if (chunk.startsWith(", ")) { chunk = chunk.substring(2, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk keywords: {}", // new Object[] {chunk}); /** * field: src */ if (chunk.startsWith("src=")) { chunk = chunk.substring(4, chunk.length()); src = chunk.split(",|]")[0]; // logger.debug("[Assemble Topo Update] Src=: {}", new // Object[]{src}); chunk = chunk.substring(src.length(), chunk.length()); } if (chunk.startsWith(", ")) { chunk = chunk.substring(2, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk keywords: {}", // new Object[] {chunk}); /** * field: srcPort */ if (chunk.startsWith("srcPort=")) { chunk = chunk.substring(8, chunk.length()); srcPort = chunk.split(",|]")[0]; // logger.debug("[Assemble Topo Update] SrcPort=: {}", new // Object[]{srcPort}); chunk = chunk.substring(srcPort.length(), chunk.length()); } if (chunk.startsWith(", ")) { chunk = chunk.substring(2, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk keywords: {}", // new Object[] {chunk}); /** * field: dst */ if (chunk.startsWith("dst=")) { chunk = chunk.substring(4, chunk.length()); dst = chunk.split(",|]")[0]; // logger.debug("[Assemble Topo Update] Dst=: {}", new // Object[]{dst}); chunk = chunk.substring(dst.length(), chunk.length()); } if (chunk.startsWith(", ")) { chunk = chunk.substring(2, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk keywords: {}", // new Object[] {chunk}); /** * field: dstPort */ if (chunk.startsWith("dstPort=")) { chunk = chunk.substring(8, chunk.length()); dstPort = chunk.split(",|]")[0]; // logger.debug("[Assemble Topo Update] DstPort=: {}", new // Object[]{dstPort}); chunk = chunk.substring(dstPort.length(), chunk.length()); } if (chunk.startsWith(", ")) { chunk = chunk.substring(2, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk keywords: {}", // new Object[] {chunk}); /** * field: latency */ if (chunk.startsWith("latency=")) { chunk = chunk.substring(8, chunk.length()); latency = chunk.split(",|]")[0]; // logger.debug("[Assemble Topo Update] Latency=: {}", new // Object[]{latency}); chunk = chunk.substring(latency.length(), chunk.length()); } if (chunk.startsWith(", ")) { chunk = chunk.substring(2, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk keywords: {}", // new Object[] {chunk}); /** * field: type */ if (chunk.startsWith("type=")) { chunk = chunk.substring(5, chunk.length()); type = chunk.split(",|]")[0]; // logger.debug("[Assemble Topo Update] Type=: {}", new // Object[]{type}); chunk = chunk.substring(type.length(), chunk.length()); } if (chunk.startsWith(", ")) { chunk = chunk.substring(2, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk keywords: {}", // new Object[] {chunk}); /** * post */ if (chunk.startsWith("], ")) { chunk = chunk.substring(3, chunk.length()); } // logger.debug("\n[Assemble Topo Update] Chunk post: {}", new // Object[] {chunk}); /** * Put it in a JSON. */ if (!op.isEmpty()) { newJson.put("operation", op); } if (!src.isEmpty()) { newJson.put("src", src); } if (!srcPort.isEmpty()) { newJson.put("srcPort", srcPort); } if (!dst.isEmpty()) { newJson.put("dst", dst); } if (!dstPort.isEmpty()) { newJson.put("dstPort", dstPort); } if (!latency.isEmpty()) { newJson.put("latency", latency); } if (!type.isEmpty()) { newJson.put("type", type); } try { jsonInString.add(mapper.writeValueAsString(newJson)); } catch (JsonProcessingException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } return jsonInString; } }
package org.basex.qt3ts.op; import org.basex.tests.bxapi.*; import org.basex.tests.qt3ts.*; /** * Tests for the string-less-than operator (not actually defined as such in F+O). * * @author BaseX Team 2005-15, BSD License * @author Leo Woerteler */ @SuppressWarnings("all") public class OpStringLessThan extends QT3TestSet { /** * A test whose essence is: `'a' lt 'abc'`. . */ @org.junit.Test public void kStringLT1() { final XQuery query = new XQuery( "'a' lt 'abc'", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * A test whose essence is: `not('abc' lt 'a')`. . */ @org.junit.Test public void kStringLT2() { final XQuery query = new XQuery( "not('abc' lt 'a')", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * A test whose essence is: `'a' le 'abc'`. . */ @org.junit.Test public void kStringLT3() { final XQuery query = new XQuery( "'a' le 'abc'", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * A test whose essence is: `not('abc' le 'a')`. . */ @org.junit.Test public void kStringLT4() { final XQuery query = new XQuery( "not('abc' le 'a')", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * A test whose essence is: `'abc' le 'abc'`. . */ @org.junit.Test public void kStringLT5() { final XQuery query = new XQuery( "'abc' le 'abc'", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * Compare two large codepoints. . */ @org.junit.Test public void k2StringLT1() { final XQuery query = new XQuery( "\"\uea60\" lt \"\ud804\udd70\"", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * test string comparison . */ @org.junit.Test public void cbclStringLessThan001() { final XQuery query = new XQuery( "not(string(current-time()) lt \"now\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(false) ); } /** * test string comparison . */ @org.junit.Test public void cbclStringLessThan002() { final XQuery query = new XQuery( "not(string(current-time()) ge \"now\")", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } /** * test string comparison . */ @org.junit.Test public void cbclStringLessThan003() { final XQuery query = new XQuery( "\n" + " not(xs:untypedAtomic(current-time()) lt xs:untypedAtomic(\"now\"))\n" + " ", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(false) ); } /** * test string comparison . */ @org.junit.Test public void cbclStringLessThan004() { final XQuery query = new XQuery( "\n" + " not(xs:untypedAtomic(current-time()) ge xs:untypedAtomic(\"now\"))\n" + " ", ctx); try { result = new QT3Result(query.value()); } catch(final Throwable trw) { result = new QT3Result(trw); } finally { query.close(); } test( assertBoolean(true) ); } }
/* * Copyright 2002-2004 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.richclient.application; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import org.springframework.beans.factory.FactoryBean; import org.springframework.binding.convert.ConversionContext; import org.springframework.binding.convert.ConversionService; import org.springframework.binding.convert.support.AbstractConverter; import org.springframework.binding.convert.support.AbstractFormattingConverter; import org.springframework.binding.convert.support.DefaultConversionService; import org.springframework.binding.format.FormatterFactory; import org.springframework.binding.format.support.StrictNumberFormatterFactory; import org.springframework.richclient.convert.support.CollectionConverter; import org.springframework.richclient.convert.support.ListModelConverter; import org.springframework.util.StringUtils; /** * A factory bean that produces a conversion service installed with most converters * needed by Spring Rich. Subclasses may extend and customize. The factory approach * here is superior to subclassing as it minimizes conversion service constructor logic. * * @author Oliver Hutchison * @author Keith Donald */ public class DefaultConversionServiceFactoryBean implements FactoryBean { private ConversionService conversionService; private FormatterFactory formatterFactory = new StrictNumberFormatterFactory(); public DefaultConversionServiceFactoryBean() { } protected FormatterFactory getFormatterFactory() { return formatterFactory; } public void setFormatterFactory(FormatterFactory formatterFactory) { this.formatterFactory = formatterFactory; } public Object getObject() throws Exception { return getConversionService(); } public Class getObjectType() { return ConversionService.class; } public boolean isSingleton() { return true; } public final ConversionService getConversionService() { if (conversionService == null) { conversionService = createConversionService(); } return conversionService; } /** * Creates the conversion service. Subclasses may override to customize creation. * @return the configured conversion service */ protected ConversionService createConversionService() { DefaultConversionService service = new DefaultConversionService(); service.addConverter(new TextToDate(getFormatterFactory(), true)); service.addConverter(new DateToText(getFormatterFactory(), true)); service.addConverter(new TextToNumber(getFormatterFactory(), true)); service.addConverter(new NumberToText(getFormatterFactory(), true)); service.addConverter(new BooleanToText()); service.addConverter(new TextToBoolean()); service.addConverter(new CollectionConverter()); service.addConverter(new ListModelConverter()); return service; } static final class TextToDate extends AbstractFormattingConverter { private final boolean allowEmpty; protected TextToDate(FormatterFactory formatterFactory, boolean allowEmpty) { super(formatterFactory); this.allowEmpty = allowEmpty; } public Class[] getSourceClasses() { return new Class[] { String.class }; } public Class[] getTargetClasses() { return new Class[] { Date.class }; } protected Object doConvert(Object source, Class targetClass, ConversionContext context) throws Exception { return (!allowEmpty || StringUtils.hasText((String) source)) ? getFormatterFactory().getDateTimeFormatter() .parseValue((String) source, Date.class) : null; } } static final class DateToText extends AbstractFormattingConverter { private final boolean allowEmpty; protected DateToText(FormatterFactory formatterLocator, boolean allowEmpty) { super(formatterLocator); this.allowEmpty = allowEmpty; } public Class[] getSourceClasses() { return new Class[] { Date.class }; } public Class[] getTargetClasses() { return new Class[] { String.class }; } protected Object doConvert(Object source, Class targetClass, ConversionContext context) throws Exception { return (!allowEmpty || source != null) ? getFormatterFactory().getDateTimeFormatter().formatValue(source) : ""; } } static final class TextToNumber extends AbstractFormattingConverter { private final boolean allowEmpty; protected TextToNumber(FormatterFactory formatterLocator, boolean allowEmpty) { super(formatterLocator); this.allowEmpty = allowEmpty; } public Class[] getSourceClasses() { return new Class[] { String.class }; } public Class[] getTargetClasses() { return new Class[] { Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigInteger.class, BigDecimal.class, }; } protected Object doConvert(Object source, Class targetClass, ConversionContext context) throws Exception { return (!allowEmpty || StringUtils.hasText((String) source)) ? getFormatterFactory().getNumberFormatter( targetClass).parseValue((String) source, targetClass) : null; } } static final class NumberToText extends AbstractFormattingConverter { private final boolean allowEmpty; protected NumberToText(FormatterFactory formatterLocator, boolean allowEmpty) { super(formatterLocator); this.allowEmpty = allowEmpty; } public Class[] getSourceClasses() { return new Class[] { Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, BigInteger.class, BigDecimal.class, }; } public Class[] getTargetClasses() { return new Class[] { String.class }; } protected Object doConvert(Object source, Class targetClass, ConversionContext context) throws Exception { return (!allowEmpty || source != null) ? getFormatterFactory().getNumberFormatter(source.getClass()) .formatValue(source) : ""; } } static final class TextToBoolean extends AbstractConverter { public static final String VALUE_TRUE = "true"; public static final String VALUE_FALSE = "false"; public static final String VALUE_ON = "on"; public static final String VALUE_OFF = "off"; public static final String VALUE_YES = "yes"; public static final String VALUE_NO = "no"; public static final String VALUE_1 = "1"; public static final String VALUE_0 = "0"; private String trueString; private String falseString; public TextToBoolean() { } public TextToBoolean(String trueString, String falseString) { this.trueString = trueString; this.falseString = falseString; } public Class[] getSourceClasses() { return new Class[] { String.class }; } public Class[] getTargetClasses() { return new Class[] { Boolean.class }; } protected Object doConvert(Object source, Class targetClass, ConversionContext context) throws Exception { String text = (String) source; if (!StringUtils.hasText(text)) { return null; } else if (this.trueString != null && text.equalsIgnoreCase(this.trueString)) { return Boolean.TRUE; } else if (this.falseString != null && text.equalsIgnoreCase(this.falseString)) { return Boolean.FALSE; } else if (this.trueString == null && (text.equalsIgnoreCase(VALUE_TRUE) || text.equalsIgnoreCase(VALUE_ON) || text.equalsIgnoreCase(VALUE_YES) || text.equals(VALUE_1))) { return Boolean.TRUE; } else if (this.falseString == null && (text.equalsIgnoreCase(VALUE_FALSE) || text.equalsIgnoreCase(VALUE_OFF) || text.equalsIgnoreCase(VALUE_NO) || text.equals(VALUE_0))) { return Boolean.FALSE; } else { throw new IllegalArgumentException("Invalid boolean value [" + text + "]"); } } } static final class BooleanToText extends AbstractConverter { public static final String VALUE_YES = "yes"; public static final String VALUE_NO = "no"; private String trueString; private String falseString; public BooleanToText() { } public BooleanToText(String trueString, String falseString) { this.trueString = trueString; this.falseString = falseString; } public Class[] getSourceClasses() { return new Class[] { Boolean.class }; } public Class[] getTargetClasses() { return new Class[] { String.class }; } protected Object doConvert(Object source, Class targetClass, ConversionContext context) throws Exception { Boolean bool = (Boolean) source; if (this.trueString != null && bool.booleanValue()) { return trueString; } else if (this.falseString != null && !bool.booleanValue()) { return falseString; } else if (bool.booleanValue()) { return VALUE_YES; } else { return VALUE_NO; } } } }
package b_trees_visualizer.data_structure; import java.util.ArrayList; import b_trees_visualizer.graphic_interface.Applet; import b_trees_visualizer.graphic_interface.utility.Pair; public class BTreeNode<E extends Comparable<? super E>> { private int numberOfElements; private ArrayList<E> data; private ArrayList<BTreeNode<E>> children; private ArrayList<Pair<Boolean, E>> recentModifications; private ArrayList<Pair<Boolean, E>> previousModifications; private boolean leaf; private boolean hasFocus; /** ** EFFECT produce a Node for BTree **/ public BTreeNode() { numberOfElements = 0; data = new ArrayList<E>(); children = new ArrayList<BTreeNode<E>>(); recentModifications = new ArrayList<Pair<Boolean, E>>(); previousModifications = new ArrayList<Pair<Boolean, E>>(); leaf = true; hasFocus = false; } /** ** @param data : an ArrayList of integer representing the keys ** EFFECT create a BTree node with the data in the same order ** they are presented in data **/ public BTreeNode (ArrayList<E> data) { this.numberOfElements = data.size(); this.data = data; this.children = new ArrayList<BTreeNode<E>>(this.data.size()+1); for (int i = 0; i <= this.data.size(); i++) { this.children.add(null); } recentModifications = new ArrayList<Pair<Boolean, E>>(); previousModifications = new ArrayList<Pair<Boolean, E>>(); leaf = false; hasFocus = false; } /** ** @return the copy of this **/ public BTreeNode<E> cloneNode() { BTreeNode<E> clonedNode = new BTreeNode<E>(); clonedNode.setNumberOfElements(numberOfElements); clonedNode.data = (ArrayList<E>)data.clone(); for (int i = 0; i < children.size(); i++) { clonedNode.children.add(children.get(i).cloneNode()); } clonedNode.recentModifications = (ArrayList<Pair<Boolean, E>>)recentModifications.clone(); clonedNode.previousModifications = (ArrayList<Pair<Boolean, E>>)previousModifications.clone(); clonedNode.setLeaf(leaf); clonedNode.setFocus(hasFocus); return clonedNode; } public int getNumberOfLeaf () { int numberOfLeaf = 0; if (this.isLeaf()) { return this.numberOfElements; } else { for (BTreeNode<E> n : this.children) { numberOfLeaf += n.getNumberOfLeaf (); } return numberOfLeaf; } } /** ** @return true if the this is a leaf ** false otherwise **/ public boolean isLeaf() { return leaf; } /** ** @param leaf boolean ** EFFECT set the value this.leaf = leaf **/ public void setLeaf(boolean leaf) { this.leaf = leaf; } public boolean isFocused() { return hasFocus; } protected void setFocus(boolean hasFocus) { this.hasFocus = hasFocus; } /** ** @return the number of elements in this **/ public int getNumberOfElements() { return numberOfElements; } /** ** @param numberOfElements an integer ** EFFECT set this.numberOfElements = numberOfElements **/ protected void setNumberOfElements(int numberOfElements) { this.numberOfElements = numberOfElements; } /** ** @return true if this was recently modified **/ public boolean isRecentlyModified() { return !recentModifications.isEmpty(); } /** ** @param i : integer ** @return the Pair containing the recent modification in i **/ public Pair<Boolean, E> getModification(int index) { return recentModifications.get(index); } /** ** @return all the recentModifications **/ public ArrayList<Pair<Boolean, E>> getModifications() { return recentModifications; } /** ** @param modifications : ArrayList ** EFFECT set a new ArrayList of recentModifications **/ public void setRecentModifications(ArrayList<?> modifications) { recentModifications.clear(); recentModifications.addAll((ArrayList<Pair<Boolean, E>>)modifications); } /** ** @param modification a Pair representing the modification ** EFFECT add a modification the recentModifications **/ public void addModification(Pair<Boolean, E> modification) { recentModifications.add(modification); } /** ** EFFECT remove all the recentModifications **/ public void removeModifications() { recentModifications.clear(); } /** ** @return true if this was previously modified **/ public boolean isPreviouslyModified() { return !previousModifications.isEmpty(); } /** ** @return all the previousModifications **/ public ArrayList<Pair<Boolean, E>> getPreviousModifications() { return previousModifications; } /** ** @param modifications : ArrayList ** EFFECT set a new ArrayList of previousModifications **/ public void setPreviouslyModified(ArrayList<?> modifications) { previousModifications.clear(); previousModifications.addAll((ArrayList<Pair<Boolean, E>>)modifications); } /** ** EFFECT remove all the previousModifications **/ public void removePreviousModifications() { previousModifications.clear(); } /** ** @return all the keys added previously or recently to this **/ public ArrayList<E> getAddedKeys() { ArrayList<E> add = new ArrayList<E>(); if (!recentModifications.isEmpty()) { for (Pair<Boolean, E> p : recentModifications) { if (p.getFirst()) { add.add(p.getSecond()); } } } else if (!previousModifications.isEmpty()) { for (Pair<Boolean, E> p : previousModifications) { if (p.getFirst()) { add.add(p.getSecond()); } } } return add; } /** ** @return true if there's at least one modification that is a remove **/ public boolean hasRemovedKeys() { if (!recentModifications.isEmpty()) { for (Pair<Boolean, E> p : recentModifications) { if (!p.getFirst()) { return true; } } } else if (!previousModifications.isEmpty()) { for (Pair<Boolean, E> p : previousModifications) { if (!p.getFirst()) { return true; } } } return false; } /** ** @return the ArrayList containig the keys in this **/ public ArrayList<E> getData() { return data; } /** ** @param index : integer ** @return the element index in data, ** the key in position index in this. **/ public E getKey(int index) { return data.get(index); } /** ** @param index an integer ** @param key, an object E the same of BTreeNode<E> ** @param trackSteps a boolean ** EFFECT set the key in position index in this **/ public void setKey(int index, E key, boolean trackSteps) { if (trackSteps) { addModification(new Pair<Boolean, E>(false, getKey(index))); addModification(new Pair<Boolean, E>(true, key)); } data.set(index, key); } /** ** @param data2, an ArrayList of element E, the same type ** of the object in BTreeNode ** EFFECT appends data2 to this.data **/ public void mergeData(ArrayList<E> data2) { data.addAll(data2); numberOfElements += data2.size(); } /** ** @param key, an object of type E the same of the element in ** BTreeNode ** @param trackSteps a boolean ** EFFECT add key in this preserving the order **/ public void addKey(E key, boolean trackSteps) { int index = 0; while (index < numberOfElements && getKey(index).compareTo(key) < 0) { index++; } data.add(index, key); numberOfElements++; if (trackSteps) { addModification(new Pair<Boolean, E>(true, key)); } } /** ** @param index an integer ** @param trackSteps a boolean ** @return the key in position index in this **/ public E extractKey(int index, boolean trackSteps) { E e = data.remove(index); if (!e.equals(null)) { numberOfElements--; if (trackSteps) { addModification(new Pair<Boolean, E>(false, e)); } } return e; } /** ** @param trackSteps a boolean ** @return the last key in this **/ public E extractLastKey(boolean trackSteps) { return extractKey(numberOfElements - 1, trackSteps); } //CHILDREN public BTreeNode<E> getChild(int index) { try { return children.get(index); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Invalid index on getChild"); return null; } } public void addChild(BTreeNode<E> child) { try { E key = child.getData().get(child.getData().size() - 1); int i = 0; while (i < children.size() && getChild(i).getData().get(0).compareTo(key) < 0) { i++; } children.add(i, child); } catch (NullPointerException e) { System.err.println("The node given as child is null"); } } /** ** @param i : integer ** @param data : an ArrayList of integer representing the data of the child ** EFFECT add the child in position i in this.children **/ public void addChild (int i, ArrayList<E> data) { BTreeNode child = new BTreeNode (data); this.leaf = false; child.setLeaf(false); for (int j = 0; j <= this.data.size(); j++) { this.children.add(null); } this.children.set(i, child); } public BTreeNode<E> extractChild(int index) { return children.remove(index); } public BTreeNode<E> extractLastChild() { return children.remove(children.size() - 1); } public ArrayList<BTreeNode<E>> getChildren() { return children; } //Utility public int getHeightSubtree() { int h = 0; if (!leaf) { h = getChild(0).getHeightSubtree(); } return 1 + h; } public boolean checkNode(int grade) { // if it's a leaf it must not have children and opposite boolean temp = !(leaf ^ children.isEmpty()); // the number of elements must be equal to the data size temp &= numberOfElements == data.size(); // internal nodes must have between grade - 1 and 2*grade - 1 elements temp &= numberOfElements >= grade - 1 && numberOfElements <= 2*grade - 1; // the number of children must be equal to the number of elements + 1 if (!leaf) { temp &= numberOfElements + 1 == children.size(); } //recursive check on child nodes for (int i = 0; i < children.size(); i++) { temp &= getChild(i).checkNode(grade); } return temp; } public boolean equals(BTreeNode<E> node) { boolean result = data.equals(node.getData()); if (result && !leaf) { for (int i = 0; i < children.size(); i++) { result &= getChild(i).equals(node.getChild(i)); } } return result; } public String toString() { String temp = "("; for(BTreeNode<E> n : children) { temp += n.toString(); } return data.toString() + temp + ")"; } public String toStringInOrder() { String temp = ""; for (int i = 0; i < data.size(); i++) { if (!children.isEmpty()) { temp += getChild(i).toStringInOrder(); } temp += getKey(i).toString() + " "; } if (!children.isEmpty()) { temp += getChild(children.size() - 1).toStringInOrder(); } return temp; } public ArrayList<E> toInOrderArrayList() { ArrayList<E> temp = new ArrayList<E>(); for (int i = 0; i < getNumberOfElements(); i++) { if (!children.isEmpty()) { temp.addAll(getChild(i).toInOrderArrayList()); } temp.add(getKey(i)); } if (!children.isEmpty()) { temp.addAll(getChild(children.size() - 1).toInOrderArrayList()); } return temp; } /** * @param x * @return node that contains the searched key if found, otherwise null * Search for a value in the node and returns the node if the value is in it, * otherwise it either returns null if the node it's a leaf or recursively call * the search on the child node in position i. */ public BTreeNode<E> search(E x) { int i = 0; //Search until the end of the array or the searched key is smaller //than the one in position i while(i < data.size() && getKey(i).compareTo(x) < 0) { i++; } //If the key in position i is the searched value, return the node, if (i < numberOfElements && getKey(i).equals(x)) { return this; } //otherwise if the node is a leaf return null. if (leaf) { return null; } //If the node is not a leaf recursively search on the i-th child. return getChild(i).search(x); } /** * @param key * Key to insert in the node's tree. * @param grade * Grade of the tree. * * If the node is a leaf, then it simply adds the key to the node's data array. * If the node is not a leaf, it needs to find the node to put the key in. While doing * so, every time a full node is found (with number of elements equal to 2*grade - 1), * a split is done before continuing with the insertion. */ public void insertKey(E key, int grade, boolean trackSteps) { if (trackSteps) { setFocus(true); } if (leaf) { if (trackSteps) { Applet.stepsP.saveTreeState("Search path"); } addKey(key, trackSteps); if (trackSteps) { Applet.stepsP.saveTreeState("Insert Key"); setFocus(false); } } else { int index = 0; /* The position is chosen by comparing the elements of the data array with * the key that needs to be added to the tree. If the key at the index * position is greater than the key, the child at the index position will * be the one in which the recursive call will be made. As there is always one * more child than the number of elements in the data array, if every key is * greater than the key it will be added to the last child at position * data.size(). */ while (index < numberOfElements && getKey(index).compareTo(key) < 0) { index++; } if (trackSteps) { Applet.stepsP.saveTreeState("Search Path"); setFocus(false); } BTreeNode<E> child = getChild(index); if (child.getNumberOfElements() < 2*grade - 1) { child.insertKey(key, grade, trackSteps); } else { child.nodeSplit(this, index, grade, trackSteps); if (getKey(index).compareTo(key) <= 0) { getChild(index + 1).insertKey(key, grade, trackSteps); } else { getChild(index).insertKey(key, grade, trackSteps); } } } } /** * @param parent * @param index * @param grade * * Given that there are 2*grade - 1 elements in the node, it splits it * in 2 halves and adds the central key (there's always a central * key as the max number of elements is always odd) to the parent * data array. * * ExtractKey already decreases numberOfElements so there's no need to * change it. */ public void nodeSplit(BTreeNode<E> parent, int index, int grade, boolean trackSteps) { if (numberOfElements == 2*grade - 1) { BTreeNode<E> secondHalf = new BTreeNode<E>(); /* Grade is used as index as it's the central + 1 position when the array * is full. The index doesn't need to change as the key is directly removed * from the array, making the successive key step back to the "grade" position. */ for (int i = 0; i < grade - 1; i++) { secondHalf.addKey(extractKey(grade, trackSteps), trackSteps); } secondHalf.setLeaf(leaf); if (!leaf) { for (int i = 0; i < grade; i++) { secondHalf.getChildren().add(children.remove(grade)); } } parent.setLeaf(false); parent.getData().add(index, extractKey(grade - 1, trackSteps)); parent.getChildren().add(index + 1, secondHalf); parent.setNumberOfElements(parent.getNumberOfElements() + 1); if (trackSteps) { parent.addModification(new Pair<Boolean, E>(true, parent.getData().get(index))); Applet.stepsP.saveTreeState("Node Split"); } } } /** * @param key * @param grade * The method removeKey works recursively and has 2 cases: * 1) the node on which the method is executed contains the key. When that happens: * a) if the node is a leaf the key is removed. This can only happen on a * node with at least grade keys. * b) the node isn't a leaf, then there are other 3 possibilities based on the children * relative to the position index of the key that needs to be removed: * - the left child has at least grade keys, so we replace the key that has to * be removed with the key previous to that. * - the left child has grade - 1 keys and the right one has at least grade * keys, so we replace the key with its successor. * - neither of both children has at least grade keys so we merge them and put the * key that needs to be removed in the middle; after that, the recursive call is * done on the result of the merging * 2) if the node doesn't contain the key, the method checkAndFixPath is called on the * child that is the root of the subtree that should contain the key followed by the * recursive call of removeKey. */ public void removeKey(E key, int grade, boolean trackSteps) { if (trackSteps) { setFocus(true); } int index = 0; while (index < numberOfElements && getKey(index).compareTo(key) < 0){ index++; } if (index < numberOfElements && getKey(index).equals(key)) { if (leaf) { if (trackSteps) { Applet.stepsP.saveTreeState("Search path"); } this.extractKey(index, trackSteps); if (trackSteps) { Applet.stepsP.saveTreeState("Remove key"); setFocus(false); } } else { if (trackSteps) { Applet.stepsP.saveTreeState("Search path"); } BTreeNode<E> left = getChild(index); BTreeNode<E> right = getChild(index + 1); if (left.getNumberOfElements() >= grade) { setKey(index, getPrevious(key, grade, trackSteps), trackSteps); if (trackSteps) { Applet.stepsP.saveTreeState("Switch with previous"); setFocus(false); } } else if (right.getNumberOfElements() >= grade) { setKey(index, getNext(key, grade, trackSteps), trackSteps); if (trackSteps) { Applet.stepsP.saveTreeState("Switch with next"); setFocus(false); } } else { setFocus(false); this.nodeMerge(index, left, right, grade, trackSteps); left.removeKey(key, grade, trackSteps); } } } else { if (!leaf) { if (trackSteps) { Applet.stepsP.saveTreeState("Search path"); setFocus(false); } checkAndFixPath(index, key, grade, trackSteps).removeKey(key, grade, trackSteps); } } } /** * @param indexEl * @param childL * @param childR * @param grade * @param trackSteps * nodeMerge takes the key in position indexEl and two nodes and merges them in a single node, * also merging the children. */ public void nodeMerge(int indexEl, BTreeNode<E> childL, BTreeNode<E> childR, int grade, boolean trackSteps) { if (childL.getNumberOfElements() == grade - 1 && childR.getNumberOfElements() == grade - 1) { E temp = extractKey(indexEl, trackSteps); childL.addKey(temp, trackSteps); childL.mergeData(childR.getData()); childL.getChildren().addAll(childR.getChildren()); children.remove(childR); if (trackSteps) { childL.addModification(new Pair<Boolean, E>(true, temp)); addModification(new Pair<Boolean, E>(false, temp)); Applet.stepsP.saveTreeState("Node Merge"); } } } /** * Method that applies merging and exchange of keys between nodes if the * node we have to work in has grade - 1 elements and we need to remove * elements from the tree. There are two branches, of which the second one * has 3 cases: * 1) the child node has at least grade keys, so we leave it like it is * 2) the child node has grade - 1 keys * a) if the index is greater than 0 and his left sibling has at least grade * keys, then we move the key on position index - 1 from data to the child node * and replace it with the last key of his left sibling * b) if the index is smaller than the number of keys in data, the left sibling also * has grade - 1 keys and the right sibling has at least grade keys, then we take * the key to replace the one in data from it. * c) if both the closest siblings have grade - 1 keys, we merge the child with its * left sibling (with the right if the considered child is in position 0). */ public BTreeNode<E> checkAndFixPath(int index, E key, int grade, boolean trackSteps) { BTreeNode<E> child = getChild(index); if (child.getNumberOfElements() >= grade) { return child; } else { //2 if (index > 0 && getChild(index - 1).getNumberOfElements() >= grade) { //a child.addKey(getKey(index - 1), trackSteps); setKey(index - 1, getChild(index - 1).extractLastKey(trackSteps), trackSteps); if (!getChild(index - 1).isLeaf()) { child.addChild(getChild(index - 1).extractLastChild()); } if (trackSteps) { Applet.stepsP.saveTreeState("Rotate right"); } return child; } else if (index < numberOfElements && getChild(index + 1).getNumberOfElements() >= grade) { //b child.addKey(getKey(index), trackSteps); setKey(index, getChild(index + 1).extractKey(0, trackSteps), trackSteps); if (!getChild(index + 1).isLeaf()) { child.addChild(getChild(index + 1).extractChild(0)); } if (trackSteps) { Applet.stepsP.saveTreeState("Rotate left"); } return child; } else { //c if (index > 0) { nodeMerge(index - 1, getChild(index - 1), child, grade, trackSteps); return getChild(index - 1); } else { nodeMerge(index, child, getChild(index + 1), grade, trackSteps); return child; } } } } // Removes the greatest key in the tree which is smaller than key and returns it. public E getPrevious(E key, int grade, boolean trackSteps) { /* This method will never be called on a leaf directly, so it's not necessary * to find the previous key by searching in the node but it will always be * in the last position of data. */ if (leaf && !data.contains((E)key)) { return extractKey(data.size() - 1, trackSteps); } else if (leaf) { int index = 0; while (index < data.size() && getKey(index).compareTo(key) < 0){ index++; } index--; return extractKey(index, trackSteps); } else { // Searches for the index that points to the child in which the method will continue int index = 0; while (index < data.size() && getKey(index).compareTo(key) < 0){ index++; } // If the selected child has less than grade elements, it's fixed so it has at least grade // elements if (getChild(index).getNumberOfElements() >= grade) { return getChild(index).getPrevious(key, grade, trackSteps); } else { return this.checkAndFixPath(index, key, grade, trackSteps).getPrevious(key, grade, trackSteps); } } } // Removes the smallest key in the tree which is greater than the key and returns it public E getNext(E key, int grade, boolean trackSteps) { /* This method will never be called on a leaf directly, so it's not necessary * to find the next key by searching in the node but it will always be * in the first position of data. */ if (leaf && !data.contains((E)key)) { return extractKey(0, trackSteps); } else if (leaf) { int index = 0; while (index < data.size() && getKey(index).compareTo(key) <= 0){ index++; } return extractKey(index, trackSteps); } else { // Searches for the index that points to the child in which the method will continue int index = 0; while (index < data.size() && getKey(index).compareTo(key) <= 0){ index++; } // If the selected child has less than grade elements, it's fixed so it has at least grade // elements if (getChild(index).getNumberOfElements() >= grade) { return getChild(index).getNext(key, grade, trackSteps); } else { return this.checkAndFixPath(index, key, grade, trackSteps).getNext(key, grade, trackSteps); } } } /** ** @return true if all the children of the current node are null **/ public boolean allNullChildren () { for (BTreeNode<E> child : this.children) { if (child != null) {return false;} } return true; } }
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government 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 UNITED STATES GOVERNMENT 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. */ package gov.hhs.fha.nhinc.connectmgr; import java.util.ArrayList; import java.util.HashMap; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.nhinclib.NullChecker; import gov.hhs.fha.nhinc.nhinclib.NhincConstants.GATEWAY_API_LEVEL; import gov.hhs.fha.nhinc.nhinclib.NhincConstants.UDDI_SPEC_VERSION; public class UddiSpecVersionRegistry { private static UddiSpecVersionRegistry instance = null; private transactionWrapper tw = null; protected UddiSpecVersionRegistry() { tw = new transactionWrapper(); } public static UddiSpecVersionRegistry getInstance() { if (instance == null) { return new UddiSpecVersionRegistry(); } return instance; } public ArrayList<UDDI_SPEC_VERSION> getSupportedSpecs(GATEWAY_API_LEVEL apiLevel, NhincConstants.NHIN_SERVICE_NAMES serviceName) { ArrayList<UDDI_SPEC_VERSION> list = new ArrayList<UDDI_SPEC_VERSION>(); HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> map = tw.getAPIToSpecMapping(serviceName); if (map != null) { list = map.get(apiLevel); } return list; } public GATEWAY_API_LEVEL getSupportedGatewayAPI(UDDI_SPEC_VERSION specVersion, NhincConstants.NHIN_SERVICE_NAMES serviceName) { GATEWAY_API_LEVEL api = null; HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> map = tw.getSpecToAPIMapping(serviceName); if (map != null) { api = map.get(specVersion); } return api; } boolean isSupported(GATEWAY_API_LEVEL apiLevel, String specVersion, NhincConstants.NHIN_SERVICE_NAMES serviceName) { if (apiLevel == null && NullChecker.isNullish(specVersion)) { return true; } ArrayList<UDDI_SPEC_VERSION> specs = tw.getAPIToSpecMapping(serviceName).get(apiLevel); if (specs == null) { return false; } for (UDDI_SPEC_VERSION spec : specs) { if (spec.toString().equals(specVersion)) { return true; } } return false; } private class transactionWrapper { private HashMap<NhincConstants.NHIN_SERVICE_NAMES, HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>> apiToSpecMap = null; private HashMap<NhincConstants.NHIN_SERVICE_NAMES, HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>> specToApiMap = null; private transactionWrapper() { apiToSpecMap = new HashMap<NhincConstants.NHIN_SERVICE_NAMES, HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>>(); specToApiMap = new HashMap<NhincConstants.NHIN_SERVICE_NAMES, HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>>(); // Patient Discovery HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> PDApiToSpecMap = new HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>(); ArrayList<UDDI_SPEC_VERSION> PDG1SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); PDG1SpecVersions.add(UDDI_SPEC_VERSION.SPEC_1_0); PDG1SpecVersions.add(UDDI_SPEC_VERSION.SPEC_2_0); PDApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g0, PDG1SpecVersions); apiToSpecMap.put(NhincConstants.NHIN_SERVICE_NAMES.PATIENT_DISCOVERY, PDApiToSpecMap); HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> PDSpecToApiMap = new HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>(); PDSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_1_0, GATEWAY_API_LEVEL.LEVEL_g0); PDSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_2_0, GATEWAY_API_LEVEL.LEVEL_g0); specToApiMap.put(NhincConstants.NHIN_SERVICE_NAMES.PATIENT_DISCOVERY, PDSpecToApiMap); // Document Submission HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> DSApiToSpecMap = new HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>(); ArrayList<UDDI_SPEC_VERSION> DSG0SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); DSG0SpecVersions.add(UDDI_SPEC_VERSION.SPEC_1_1); DSApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g0, DSG0SpecVersions); ArrayList<UDDI_SPEC_VERSION> DSG1SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); DSG1SpecVersions.add(UDDI_SPEC_VERSION.SPEC_2_0); DSApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g1, DSG1SpecVersions); apiToSpecMap.put(NhincConstants.NHIN_SERVICE_NAMES.DOCUMENT_SUBMISSION, DSApiToSpecMap); HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> DSSpecToApiMap = new HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>(); DSSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_1_1, GATEWAY_API_LEVEL.LEVEL_g0); DSSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_2_0, GATEWAY_API_LEVEL.LEVEL_g1); specToApiMap.put(NhincConstants.NHIN_SERVICE_NAMES.DOCUMENT_SUBMISSION, DSSpecToApiMap); // Administrative Distribution HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> ADApiToSpecMap = new HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>(); ArrayList<UDDI_SPEC_VERSION> ADG0SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); ADG0SpecVersions.add(UDDI_SPEC_VERSION.SPEC_1_0); ADApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g0, ADG0SpecVersions); ArrayList<UDDI_SPEC_VERSION> ADG1SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); ADG1SpecVersions.add(UDDI_SPEC_VERSION.SPEC_2_0); ADApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g1, ADG1SpecVersions); apiToSpecMap.put(NhincConstants.NHIN_SERVICE_NAMES.ADMINISTRATIVE_DISTRIBUTION, ADApiToSpecMap); HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> ADSpecToApiMap = new HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>(); ADSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_1_0, GATEWAY_API_LEVEL.LEVEL_g0); ADSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_2_0, GATEWAY_API_LEVEL.LEVEL_g1); specToApiMap.put(NhincConstants.NHIN_SERVICE_NAMES.ADMINISTRATIVE_DISTRIBUTION, ADSpecToApiMap); // Document Query HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> DQApiToSpecMap = new HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>(); ArrayList<UDDI_SPEC_VERSION> DQG0SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); DQG0SpecVersions.add(UDDI_SPEC_VERSION.SPEC_2_0); DQG0SpecVersions.add(UDDI_SPEC_VERSION.SPEC_3_0); DQApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g0, DQG0SpecVersions); apiToSpecMap.put(NhincConstants.NHIN_SERVICE_NAMES.DOCUMENT_QUERY, DQApiToSpecMap); HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> DQSpecToApiMap = new HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>(); DQSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_2_0, GATEWAY_API_LEVEL.LEVEL_g0); DQSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_3_0, GATEWAY_API_LEVEL.LEVEL_g0); specToApiMap.put(NhincConstants.NHIN_SERVICE_NAMES.DOCUMENT_QUERY, DQSpecToApiMap); // Document Retrieve HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> DRApiToSpecMap = new HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>(); ArrayList<UDDI_SPEC_VERSION> DR0SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); DR0SpecVersions.add(UDDI_SPEC_VERSION.SPEC_2_0); DRApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g0, DR0SpecVersions); ArrayList<UDDI_SPEC_VERSION> DRG1SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); DRG1SpecVersions.add(UDDI_SPEC_VERSION.SPEC_3_0); DRApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g1, DRG1SpecVersions); apiToSpecMap.put(NhincConstants.NHIN_SERVICE_NAMES.DOCUMENT_RETRIEVE, DRApiToSpecMap); HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> DRSpecToApiMap = new HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>(); DRSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_2_0, GATEWAY_API_LEVEL.LEVEL_g0); DRSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_3_0, GATEWAY_API_LEVEL.LEVEL_g1); specToApiMap.put(NhincConstants.NHIN_SERVICE_NAMES.DOCUMENT_RETRIEVE, DRSpecToApiMap); // HIEM Subscribe HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> SuApiToSpecMap = new HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>(); ArrayList<UDDI_SPEC_VERSION> Su0SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); Su0SpecVersions.add(UDDI_SPEC_VERSION.SPEC_2_0); SuApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g0, Su0SpecVersions); apiToSpecMap.put(NhincConstants.NHIN_SERVICE_NAMES.HIEM_SUBSCRIBE, SuApiToSpecMap); HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> SuSpecToApiMap = new HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>(); SuSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_2_0, GATEWAY_API_LEVEL.LEVEL_g0); specToApiMap.put(NhincConstants.NHIN_SERVICE_NAMES.HIEM_SUBSCRIBE, SuSpecToApiMap); // HIEM Notify HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> NOApiToSpecMap = new HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>(); ArrayList<UDDI_SPEC_VERSION> NO0SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); NO0SpecVersions.add(UDDI_SPEC_VERSION.SPEC_2_0); NOApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g0, NO0SpecVersions); apiToSpecMap.put(NhincConstants.NHIN_SERVICE_NAMES.HIEM_NOTIFY, NOApiToSpecMap); HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> NOSpecToApiMap = new HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>(); NOSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_2_0, GATEWAY_API_LEVEL.LEVEL_g0); specToApiMap.put(NhincConstants.NHIN_SERVICE_NAMES.HIEM_NOTIFY, NOSpecToApiMap); // HIEM Unsubscribe HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> UnApiToSpecMap = new HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>>(); ArrayList<UDDI_SPEC_VERSION> Un0SpecVersions = new ArrayList<UDDI_SPEC_VERSION>(); Un0SpecVersions.add(UDDI_SPEC_VERSION.SPEC_2_0); UnApiToSpecMap.put(GATEWAY_API_LEVEL.LEVEL_g0, Un0SpecVersions); apiToSpecMap.put(NhincConstants.NHIN_SERVICE_NAMES.HIEM_NOTIFY, UnApiToSpecMap); HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> UnSpecToApiMap = new HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL>(); UnSpecToApiMap.put(UDDI_SPEC_VERSION.SPEC_2_0, GATEWAY_API_LEVEL.LEVEL_g0); specToApiMap.put(NhincConstants.NHIN_SERVICE_NAMES.HIEM_NOTIFY, UnSpecToApiMap); } public HashMap<GATEWAY_API_LEVEL, ArrayList<UDDI_SPEC_VERSION>> getAPIToSpecMapping(NhincConstants.NHIN_SERVICE_NAMES serviceName) { switch (serviceName) { case PATIENT_DISCOVERY_DEFERRED_REQUEST: case PATIENT_DISCOVERY_DEFERRED_RESPONSE: return apiToSpecMap.get(NhincConstants.NHIN_SERVICE_NAMES.PATIENT_DISCOVERY); case DOCUMENT_SUBMISSION_DEFERRED_REQUEST: case DOCUMENT_SUBMISSION_DEFERRED_RESPONSE: return apiToSpecMap.get(NhincConstants.NHIN_SERVICE_NAMES.DOCUMENT_SUBMISSION); default: return apiToSpecMap.get(serviceName); } } public HashMap<UDDI_SPEC_VERSION, GATEWAY_API_LEVEL> getSpecToAPIMapping(NhincConstants.NHIN_SERVICE_NAMES serviceName) { switch (serviceName) { case PATIENT_DISCOVERY_DEFERRED_REQUEST: case PATIENT_DISCOVERY_DEFERRED_RESPONSE: return specToApiMap.get(NhincConstants.NHIN_SERVICE_NAMES.PATIENT_DISCOVERY); case DOCUMENT_SUBMISSION_DEFERRED_REQUEST: case DOCUMENT_SUBMISSION_DEFERRED_RESPONSE: return specToApiMap.get(NhincConstants.NHIN_SERVICE_NAMES.DOCUMENT_SUBMISSION); default: return specToApiMap.get(serviceName); } } } }
package org.apache.rya.indexing.IndexPlanValidator; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import org.apache.rya.indexing.external.tupleSet.ExternalTupleSet; import org.eclipse.rdf4j.query.algebra.BindingSetAssignment; import org.eclipse.rdf4j.query.algebra.Filter; import org.eclipse.rdf4j.query.algebra.Join; import org.eclipse.rdf4j.query.algebra.Projection; import org.eclipse.rdf4j.query.algebra.QueryModelNode; import org.eclipse.rdf4j.query.algebra.StatementPattern; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Sets; public class TupleExecutionPlanGenerator implements IndexTupleGenerator { @Override public Iterator<TupleExpr> getPlans(final Iterator<TupleExpr> indexPlans) { final Iterator<TupleExpr> iter = indexPlans; return new Iterator<TupleExpr>() { private TupleExpr next = null; private boolean hasNextCalled = false; private boolean isEmpty = false; Iterator<TupleExpr> tuples = null; @Override public boolean hasNext() { if (!hasNextCalled && !isEmpty) { if (tuples != null && tuples.hasNext()) { next = tuples.next(); hasNextCalled = true; return true; } else { while (iter.hasNext()) { tuples = getPlans(iter.next()).iterator(); if (tuples == null) { throw new IllegalStateException("Plans cannot be null!"); } next = tuples.next(); hasNextCalled = true; return true; } isEmpty = true; return false; } } else { return !isEmpty; } } @Override public TupleExpr next() { if (hasNextCalled) { hasNextCalled = false; return next; } else if(isEmpty) { throw new NoSuchElementException(); }else { if (this.hasNext()) { hasNextCalled = false; return next; } else { throw new NoSuchElementException(); } } } @Override public void remove() { throw new UnsupportedOperationException("Cannot delete from iterator!"); } }; } private List<TupleExpr> getPlans(final TupleExpr te) { final NodeCollector nc = new NodeCollector(); te.visit(nc); final Set<QueryModelNode> nodeSet = nc.getNodeSet(); final List<Filter> filterList = nc.getFilterSet(); final Projection projection = nc.getProjection().clone(); final List<TupleExpr> queryPlans = Lists.newArrayList(); final Collection<List<QueryModelNode>> plans = Collections2.permutations(nodeSet); for (final List<QueryModelNode> p : plans) { if (p.size() == 0) { throw new IllegalArgumentException("Tuple must contain at least one node!"); } else if (p.size() == 1) { queryPlans.add(te); } else { queryPlans.add(buildTuple(p, filterList, projection)); } } return queryPlans; } private TupleExpr buildTuple(final List<QueryModelNode> nodes, final List<Filter> filters, final Projection projection) { final Projection proj = projection.clone(); Join join = null; join = new Join((TupleExpr) nodes.get(0).clone(), (TupleExpr) nodes.get(1).clone()); for (int i = 2; i < nodes.size(); i++) { join = new Join(join, (TupleExpr) nodes.get(i).clone()); } if (filters.size() == 0) { proj.setArg(join); return proj; } else { TupleExpr queryPlan = join; for (final Filter f : filters) { final Filter filt = f.clone(); filt.setArg(queryPlan); queryPlan = filt; } proj.setArg(queryPlan); return proj; } } public static class NodeCollector extends AbstractQueryModelVisitor<RuntimeException> { private final Set<QueryModelNode> nodeSet = Sets.newHashSet(); private final List<Filter> filterSet = Lists.newArrayList(); private Projection projection; public Projection getProjection() { return projection; } public Set<QueryModelNode> getNodeSet() { return nodeSet; } public List<Filter> getFilterSet() { return filterSet; } @Override public void meet(final Projection node) { projection = node; node.getArg().visit(this); } @Override public void meetNode(final QueryModelNode node) throws RuntimeException { if (node instanceof ExternalTupleSet || node instanceof BindingSetAssignment || node instanceof StatementPattern) { nodeSet.add(node); } super.meetNode(node); } @Override public void meet(final Filter node) { filterSet.add(node); node.getArg().visit(this); } } }
package com.robrua.orianna.api.core; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.robrua.orianna.api.Utils; import com.robrua.orianna.api.dto.BaseRiotAPI; import com.robrua.orianna.type.api.LoadPolicy; import com.robrua.orianna.type.core.summoner.MasteryPage; import com.robrua.orianna.type.core.summoner.RunePage; import com.robrua.orianna.type.core.summoner.Summoner; import com.robrua.orianna.type.dto.summoner.MasteryPages; import com.robrua.orianna.type.dto.summoner.RunePages; public abstract class SummonerAPI { /** * @param summoners * the summoners to get mastery pages for * @return the summoners' mastery pages */ public static List<List<MasteryPage>> getMasteryPages(final List<Summoner> summoners) { final List<Long> IDs = new ArrayList<>(); for(final Summoner summoner : summoners) { IDs.add(summoner.getID()); } return getMasteryPagesByID(IDs); } /** * @param summoners * the summoners to get mastery pages for * @return the summoners' mastery pages */ public static List<List<MasteryPage>> getMasteryPages(final Summoner... summoners) { final List<Long> IDs = new ArrayList<>(); for(final Summoner summoner : summoners) { IDs.add(summoner.getID()); } return getMasteryPagesByID(IDs); } /** * @param summoner * the summoner to get mastery pages for * @return the summoner's mastery pages */ public static List<MasteryPage> getMasteryPages(final Summoner summoner) { return getMasteryPagesByID(summoner.getID()); } /** * @param summonerIDs * the IDs of the summoners to get mastery pages for * @return the summoners' mastery pages */ public static List<List<MasteryPage>> getMasteryPagesByID(final List<Long> summonerIDs) { if(summonerIDs.isEmpty()) { return Collections.emptyList(); } final List<List<MasteryPage>> pages = new ArrayList<>(); final Set<Long> masteryIDs = new HashSet<>(); for(final List<Long> get : Utils.breakUpList(summonerIDs, 40)) { final Map<Long, MasteryPages> pgs = BaseRiotAPI.getSummonersMasteries(get); for(final Long ID : get) { final MasteryPages pg = pgs.get(ID); final List<MasteryPage> forOne = new ArrayList<>(pg.getPages().size()); for(final com.robrua.orianna.type.dto.summoner.MasteryPage p : pg.getPages()) { forOne.add(new MasteryPage(p)); } pages.add(Collections.unmodifiableList(forOne)); masteryIDs.addAll(pg.getMasteryIDs()); } } if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) { RiotAPI.getMasteries(new ArrayList<>(masteryIDs)); } return Collections.unmodifiableList(pages); } /** * @param summonerIDs * the IDs of the summoners to get mastery pages for * @return the summoners' mastery pages */ public static List<List<MasteryPage>> getMasteryPagesByID(final long... summonerIDs) { return getMasteryPagesByID(Utils.convert(summonerIDs)); } /** * @param summonerID * the ID of the summoner to get mastery pages for * @return the summoner's mastery pages */ public static List<MasteryPage> getMasteryPagesByID(final long summonerID) { return getMasteryPagesByID(new long[] {summonerID}).get(0); } /** * @param summonerNames * the names of the summoners to get mastery pages for * @return the summoners' mastery pages */ public static List<List<MasteryPage>> getMasteryPagesByName(final List<String> summonerNames) { return getMasteryPages(getSummonersByName(summonerNames)); } /** * @param summonerNames * the names of the summoners to get mastery pages for * @return the summoners' mastery pages */ public static List<List<MasteryPage>> getMasteryPagesByName(final String... summonerNames) { return getMasteryPages(getSummonersByName(summonerNames)); } /** * @param summonerName * the name of the summoner to get mastery pages for * @return the summoner's mastery pages */ public static List<MasteryPage> getMasteryPagesByName(final String summonerName) { return getMasteryPages(getSummonerByName(summonerName)); } /** * @param summoners * the summoners to get rune pages for * @return the summoners' rune pages */ public static List<List<RunePage>> getRunePages(final List<Summoner> summoners) { final List<Long> IDs = new ArrayList<>(); for(final Summoner summoner : summoners) { IDs.add(summoner.getID()); } return getRunePagesByID(IDs); } /** * @param summoners * the summoners to get rune pages for * @return the summoners' rune pages */ public static List<List<RunePage>> getRunePages(final Summoner... summoners) { final List<Long> IDs = new ArrayList<>(); for(final Summoner summoner : summoners) { IDs.add(summoner.getID()); } return getRunePagesByID(IDs); } /** * @param summoner * the summoner to get rune pages for * @return the summoner's rune pages */ public static List<RunePage> getRunePages(final Summoner summoner) { return getRunePagesByID(summoner.getID()); } /** * @param summonerIDs * the IDs of the summoners to get rune pages for * @return the summoners' rune pages */ public static List<List<RunePage>> getRunePagesByID(final List<Long> summonerIDs) { if(summonerIDs.isEmpty()) { return Collections.emptyList(); } final List<List<RunePage>> pages = new ArrayList<>(); final Set<Long> runeIDs = new HashSet<>(); for(final List<Long> get : Utils.breakUpList(summonerIDs, 40)) { final Map<Long, RunePages> pgs = BaseRiotAPI.getSummonersRunes(get); for(final Long ID : get) { final RunePages pg = pgs.get(ID); final List<RunePage> forOne = new ArrayList<>(pg.getPages().size()); for(final com.robrua.orianna.type.dto.summoner.RunePage p : pg.getPages()) { forOne.add(new RunePage(p)); } pages.add(Collections.unmodifiableList(forOne)); runeIDs.addAll(pg.getRuneIDs()); } } if(RiotAPI.loadPolicy == LoadPolicy.UPFRONT) { RiotAPI.getRunes(new ArrayList<>(runeIDs)); } return Collections.unmodifiableList(pages); } /** * @param summonerIDs * the IDs of the summoners to get rune pages for * @return the summoners' rune pages */ public static List<List<RunePage>> getRunePagesByID(final long... summonerIDs) { return getRunePagesByID(Utils.convert(summonerIDs)); } /** * @param summonerID * the ID of the summoner to get rune pages for * @return the summoner's rune pages */ public static List<RunePage> getRunePagesByID(final long summonerID) { return getRunePagesByID(new long[] {summonerID}).get(0); } /** * @param summonerNames * the names of the summoners to get rune pages for * @return the summoners' rune pages */ public static List<List<RunePage>> getRunePagesByName(final List<String> summonerNames) { return getRunePages(getSummonersByName(summonerNames)); } /** * @param summonerNames * the names of the summoners to get rune pages for * @return the summoners' rune pages */ public static List<List<RunePage>> getRunePagesByName(final String... summonerNames) { return getRunePages(getSummonersByName(summonerNames)); } /** * @param summonerName * the name of the summoner to get rune pages for * @return the summoner's rune pages */ public static List<RunePage> getRunePagesByName(final String summonerName) { return getRunePages(getSummonerByName(summonerName)); } /** * @param ID * the ID of the summoner to get * @return the summoner */ public static Summoner getSummonerByID(final long ID) { return getSummonersByID(ID).get(0); } /** * @param name * the name of the summoner to get * @return the summoners */ public static Summoner getSummonerByName(final String name) { return getSummonersByName(name).get(0); } /** * @param ID * the ID of the summoner to get the names of * @return the summoner's name */ public static String getSummonerName(final long ID) { return getSummonersNames(ID).get(0); } /** * @param IDs * the IDs of the summoners to get * @return the summoners */ public synchronized static List<Summoner> getSummonersByID(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Summoner> summoners = RiotAPI.store.get(Summoner.class, IDs); final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(summoners.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return summoners; } final List<Summoner> gotten = new ArrayList<>(); final List<String> names = new ArrayList<>(); for(final List<Long> get : Utils.breakUpList(toGet, 40)) { final Map<Long, com.robrua.orianna.type.dto.summoner.Summoner> sums = BaseRiotAPI.getSummonersByID(get); for(final Long ID : get) { gotten.add(new Summoner(sums.get(ID))); names.add(sums.get(ID).getName()); } } RiotAPI.store.store(gotten, toGet, false); RiotAPI.store.store(gotten, names, false); int count = 0; for(final Integer id : index) { summoners.set(id, gotten.get(count++)); } return Collections.unmodifiableList(summoners); } /** * @param IDs * the IDs of the summoners to get * @return the summoners */ public static List<Summoner> getSummonersByID(final long... IDs) { return getSummonersByID(Utils.convert(IDs)); } /** * @param names * the names of the summoners to get * @return the summoners */ public synchronized static List<Summoner> getSummonersByName(final List<String> names) { if(names.isEmpty()) { return Collections.emptyList(); } final List<Summoner> summoners = RiotAPI.store.get(Summoner.class, names); final List<String> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < names.size(); i++) { if(summoners.get(i) == null) { toGet.add(names.get(i)); index.add(i); } } if(toGet.isEmpty()) { return summoners; } final List<Summoner> gotten = new ArrayList<>(); final List<String> IDs = new ArrayList<>(); for(final List<String> get : Utils.breakUpList(toGet, 40)) { final Map<String, com.robrua.orianna.type.dto.summoner.Summoner> sums = BaseRiotAPI.getSummonersByName(get); for(final String name : get) { final String std = standardize(name); gotten.add(new Summoner(sums.get(std))); if(sums.get(std) == null) { IDs.add("[" + null + "]"); } else { IDs.add("[" + sums.get(std).getId() + "]"); } } } RiotAPI.store.store(gotten, toGet, false); RiotAPI.store.store(gotten, IDs, false); int count = 0; for(final Integer id : index) { summoners.set(id, gotten.get(count++)); } return Collections.unmodifiableList(summoners); } /** * @param names * the names of the summoners to get * @return the summoners */ public static List<Summoner> getSummonersByName(final String... names) { return getSummonersByName(Arrays.asList(names)); } /** * @param IDs * the IDs of the summoners to get the names of * @return the summoners' names */ public synchronized static List<String> getSummonersNames(final List<Long> IDs) { if(IDs.isEmpty()) { return Collections.emptyList(); } final List<Summoner> summoners = RiotAPI.store.get(Summoner.class, IDs); final List<String> names = new ArrayList<>(summoners.size()); for(final Summoner summoner : summoners) { if(summoner != null) { names.add(summoner.getName()); } else { names.add(null); } } final List<Long> toGet = new ArrayList<>(); final List<Integer> index = new ArrayList<>(); for(int i = 0; i < IDs.size(); i++) { if(summoners.get(i) == null) { toGet.add(IDs.get(i)); index.add(i); } } if(toGet.isEmpty()) { return names; } final List<String> gotten = new ArrayList<>(); for(final List<Long> get : Utils.breakUpList(toGet, 40)) { final Map<Long, String> sums = BaseRiotAPI.getSummonersNames(get); for(final Long ID : get) { gotten.add(sums.get(ID)); } } int count = 0; for(final Integer id : index) { names.set(id, gotten.get(count++)); } return Collections.unmodifiableList(names); } /** * @param IDs * the IDs of the summoners to get the names of * @return the summoners' names */ public static List<String> getSummonersNames(final long... IDs) { return getSummonersNames(Utils.convert(IDs)); } /** * Standardizes a summoner name, which is the summoner name in all lower * case and with spaces removed (per the API spec) * * @param summonerName * the name to standardize * @return the standardized summoner name */ private static String standardize(final String summonerName) { return summonerName.replaceAll(" ", "").toLowerCase(); } }
/* * 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 android.telecom; import android.annotation.IntDef; import android.os.Parcel; import android.os.Parcelable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Represents attributes of video calls. */ public class VideoProfile implements Parcelable { /** @hide */ @Retention(RetentionPolicy.SOURCE) @IntDef({QUALITY_UNKNOWN, QUALITY_HIGH, QUALITY_MEDIUM, QUALITY_LOW, QUALITY_DEFAULT}) public @interface VideoQuality {} /** * "Unknown" video quality. * @hide */ public static final int QUALITY_UNKNOWN = 0; /** * "High" video quality. */ public static final int QUALITY_HIGH = 1; /** * "Medium" video quality. */ public static final int QUALITY_MEDIUM = 2; /** * "Low" video quality. */ public static final int QUALITY_LOW = 3; /** * Use default video quality. */ public static final int QUALITY_DEFAULT = 4; /** @hide */ @Retention(RetentionPolicy.SOURCE) @IntDef( flag = true, value = {STATE_AUDIO_ONLY, STATE_TX_ENABLED, STATE_RX_ENABLED, STATE_BIDIRECTIONAL, STATE_PAUSED}) public @interface VideoState {} /** * Used when answering or dialing a call to indicate that the call does not have a video * component. * <p> * Should <b>not</b> be used in comparison checks to determine if a video state represents an * audio-only call. * <p> * The following, for example, is not the correct way to check if a call is audio-only: * <pre> * {@code * // This is the incorrect way to check for an audio-only call. * if (videoState == VideoProfile.STATE_AUDIO_ONLY) { * // Handle audio-only call. * } * } * </pre> * <p> * Instead, use the {@link VideoProfile#isAudioOnly(int)} helper function to check if a * video state represents an audio-only call: * <pre> * {@code * // This is the correct way to check for an audio-only call. * if (VideoProfile.isAudioOnly(videoState)) { * // Handle audio-only call. * } * } * </pre> */ public static final int STATE_AUDIO_ONLY = 0x0; /** * Video transmission is enabled. */ public static final int STATE_TX_ENABLED = 0x1; /** * Video reception is enabled. */ public static final int STATE_RX_ENABLED = 0x2; /** * Video signal is bi-directional. */ public static final int STATE_BIDIRECTIONAL = STATE_TX_ENABLED | STATE_RX_ENABLED; /** * Video is paused. */ public static final int STATE_PAUSED = 0x4; private final int mVideoState; private final int mQuality; /** * Creates an instance of the VideoProfile * * @param videoState The video state. */ public VideoProfile(@VideoState int videoState) { this(videoState, QUALITY_DEFAULT); } /** * Creates an instance of the VideoProfile * * @param videoState The video state. * @param quality The video quality. */ public VideoProfile(@VideoState int videoState, @VideoQuality int quality) { mVideoState = videoState; mQuality = quality; } /** * The video state of the call. * Valid values: {@link VideoProfile#STATE_AUDIO_ONLY}, * {@link VideoProfile#STATE_BIDIRECTIONAL}, * {@link VideoProfile#STATE_TX_ENABLED}, * {@link VideoProfile#STATE_RX_ENABLED}, * {@link VideoProfile#STATE_PAUSED}. */ @VideoState public int getVideoState() { return mVideoState; } /** * The desired video quality for the call. * Valid values: {@link VideoProfile#QUALITY_HIGH}, {@link VideoProfile#QUALITY_MEDIUM}, * {@link VideoProfile#QUALITY_LOW}, {@link VideoProfile#QUALITY_DEFAULT}. */ @VideoQuality public int getQuality() { return mQuality; } /** * Responsible for creating VideoProfile objects from deserialized Parcels. **/ public static final Parcelable.Creator<VideoProfile> CREATOR = new Parcelable.Creator<VideoProfile> () { /** * Creates a MediaProfile instances from a parcel. * * @param source The parcel. * @return The MediaProfile. */ @Override public VideoProfile createFromParcel(Parcel source) { int state = source.readInt(); int quality = source.readInt(); ClassLoader classLoader = VideoProfile.class.getClassLoader(); return new VideoProfile(state, quality); } @Override public VideoProfile[] newArray(int size) { return new VideoProfile[size]; } }; /** * Describe the kinds of special objects contained in this Parcelable's * marshalled representation. * * @return a bitmask indicating the set of special object types marshalled * by the Parcelable. */ @Override public int describeContents() { return 0; } /** * Flatten this object in to a Parcel. * * @param dest The Parcel in which the object should be written. * @param flags Additional flags about how the object should be written. * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}. */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mVideoState); dest.writeInt(mQuality); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[VideoProfile videoState = "); sb.append(videoStateToString(mVideoState)); sb.append(" videoQuality = "); sb.append(mQuality); sb.append("]"); return sb.toString(); } /** * Generates a string representation of a video state. * * @param videoState The video state. * @return String representation of the video state. */ public static String videoStateToString(@VideoState int videoState) { StringBuilder sb = new StringBuilder(); sb.append("Audio"); if (isAudioOnly(videoState)) { sb.append(" Only"); } else { if (isTransmissionEnabled(videoState)) { sb.append(" Tx"); } if (isReceptionEnabled(videoState)) { sb.append(" Rx"); } if (isPaused(videoState)) { sb.append(" Pause"); } } return sb.toString(); } /** * Indicates whether the video state is audio only. * * @param videoState The video state. * @return {@code True} if the video state is audio only, {@code false} otherwise. */ public static boolean isAudioOnly(@VideoState int videoState) { return !hasState(videoState, VideoProfile.STATE_TX_ENABLED) && !hasState(videoState, VideoProfile.STATE_RX_ENABLED); } /** * Indicates whether video transmission or reception is enabled for a video state. * * @param videoState The video state. * @return {@code True} if video transmission or reception is enabled, {@code false} otherwise. */ public static boolean isVideo(@VideoState int videoState) { return hasState(videoState, VideoProfile.STATE_TX_ENABLED) || hasState(videoState, VideoProfile.STATE_RX_ENABLED) || hasState(videoState, VideoProfile.STATE_BIDIRECTIONAL); } /** * Indicates whether the video state has video transmission enabled. * * @param videoState The video state. * @return {@code True} if video transmission is enabled, {@code false} otherwise. */ public static boolean isTransmissionEnabled(@VideoState int videoState) { return hasState(videoState, VideoProfile.STATE_TX_ENABLED); } /** * Indicates whether the video state has video reception enabled. * * @param videoState The video state. * @return {@code True} if video reception is enabled, {@code false} otherwise. */ public static boolean isReceptionEnabled(@VideoState int videoState) { return hasState(videoState, VideoProfile.STATE_RX_ENABLED); } /** * Indicates whether the video state is bi-directional. * * @param videoState The video state. * @return {@code True} if the video is bi-directional, {@code false} otherwise. */ public static boolean isBidirectional(@VideoState int videoState) { return hasState(videoState, VideoProfile.STATE_BIDIRECTIONAL); } /** * Indicates whether the video state is paused. * * @param videoState The video state. * @return {@code True} if the video is paused, {@code false} otherwise. */ public static boolean isPaused(@VideoState int videoState) { return hasState(videoState, VideoProfile.STATE_PAUSED); } /** * Indicates if a specified state is set in a videoState bit-mask. * * @param videoState The video state bit-mask. * @param state The state to check. * @return {@code True} if the state is set. */ private static boolean hasState(@VideoState int videoState, @VideoState int state) { return (videoState & state) == state; } /** * Represents the camera capabilities important to a Video Telephony provider. */ public static final class CameraCapabilities implements Parcelable { /** * The width of the camera video in pixels. */ private final int mWidth; /** * The height of the camera video in pixels. */ private final int mHeight; /** * Whether the camera supports zoom. */ private final boolean mZoomSupported; /** * The maximum zoom supported by the camera. */ private final float mMaxZoom; /** * Create a call camera capabilities instance. * * @param width The width of the camera video (in pixels). * @param height The height of the camera video (in pixels). */ public CameraCapabilities(int width, int height) { this(width, height, false, 1.0f); } /** * Create a call camera capabilities instance that optionally * supports zoom. * * @param width The width of the camera video (in pixels). * @param height The height of the camera video (in pixels). * @param zoomSupported True when camera supports zoom. * @param maxZoom Maximum zoom supported by camera. * @hide */ public CameraCapabilities(int width, int height, boolean zoomSupported, float maxZoom) { mWidth = width; mHeight = height; mZoomSupported = zoomSupported; mMaxZoom = maxZoom; } /** * Responsible for creating CallCameraCapabilities objects from deserialized Parcels. **/ public static final Parcelable.Creator<CameraCapabilities> CREATOR = new Parcelable.Creator<CameraCapabilities> () { /** * Creates a CallCameraCapabilities instances from a parcel. * * @param source The parcel. * @return The CallCameraCapabilities. */ @Override public CameraCapabilities createFromParcel(Parcel source) { int width = source.readInt(); int height = source.readInt(); boolean supportsZoom = source.readByte() != 0; float maxZoom = source.readFloat(); return new CameraCapabilities(width, height, supportsZoom, maxZoom); } @Override public CameraCapabilities[] newArray(int size) { return new CameraCapabilities[size]; } }; /** * Describe the kinds of special objects contained in this Parcelable's * marshalled representation. * * @return a bitmask indicating the set of special object types marshalled * by the Parcelable. */ @Override public int describeContents() { return 0; } /** * Flatten this object in to a Parcel. * * @param dest The Parcel in which the object should be written. * @param flags Additional flags about how the object should be written. * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}. */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(getWidth()); dest.writeInt(getHeight()); dest.writeByte((byte) (isZoomSupported() ? 1 : 0)); dest.writeFloat(getMaxZoom()); } /** * The width of the camera video in pixels. */ public int getWidth() { return mWidth; } /** * The height of the camera video in pixels. */ public int getHeight() { return mHeight; } /** * Whether the camera supports zoom. * @hide */ public boolean isZoomSupported() { return mZoomSupported; } /** * The maximum zoom supported by the camera. * @hide */ public float getMaxZoom() { return mMaxZoom; } } }
package net.jpountz.lz4; /* * 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. */ import net.jpountz.util.Utils; import net.jpountz.xxhash.StreamingXXHash32; import net.jpountz.xxhash.XXHash32; import net.jpountz.xxhash.XXHashFactory; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.BitSet; /** * A partial implementation of the v1.5.1 LZ4 Frame format. This class is NOT thread safe * Not Supported: * * Dependent blocks * * Legacy streams * * Multiple frames (one LZ4FrameOutputStream is one frame) * * @see <a href="https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md">LZ4 Framing * Format Spec 1.5.1</a> * * Originally based on kafka's KafkaLZ4BlockOutputStream */ public class LZ4FrameOutputStream extends FilterOutputStream { protected static final int INTEGER_BYTES = Integer.SIZE >>> 3; // or Integer.BYTES in Java 1.8 protected static final int LONG_BYTES = Long.SIZE >>> 3; // or Long.BYTES in Java 1.8 static final int MAGIC = 0x184D2204; static final int LZ4_MAX_HEADER_LENGTH = 4 + // magic 1 + // FLG 1 + // BD 8 + // Content Size 1; // HC static final int LZ4_FRAME_INCOMPRESSIBLE_MASK = 0x80000000; static final FLG.Bits[] DEFAULT_FEATURES = new FLG.Bits[]{FLG.Bits.BLOCK_INDEPENDENCE}; static final String CLOSED_STREAM = "The stream is already closed"; public static enum BLOCKSIZE { SIZE_64KB(4), SIZE_256KB(5), SIZE_1MB(6), SIZE_4MB(7); private final int indicator; BLOCKSIZE(int indicator) { this.indicator = indicator; } public int getIndicator() { return this.indicator; } public static BLOCKSIZE valueOf(int indicator) { switch(indicator) { case 7: return SIZE_4MB; case 6: return SIZE_1MB; case 5: return SIZE_256KB; case 4: return SIZE_64KB; default: throw new IllegalArgumentException(String.format("Block size must be 4-7. Cannot use value of [%d]", indicator)); } } } private final LZ4Compressor compressor; private final XXHash32 checksum; private final ByteBuffer buffer; // Buffer for uncompressed input data private final byte[] compressedBuffer; // Only allocated once so it can be reused private final int maxBlockSize; private final long knownSize; private final ByteBuffer intLEBuffer = ByteBuffer.allocate(INTEGER_BYTES).order(ByteOrder.LITTLE_ENDIAN); private FrameInfo frameInfo = null; /** * Create a new {@link OutputStream} that will compress data using the LZ4 algorithm. * * @param out The output stream to compress * @param blockSize The BLOCKSIZE to use * @param bits A set of features to use * @throws IOException */ public LZ4FrameOutputStream(OutputStream out, BLOCKSIZE blockSize, FLG.Bits... bits) throws IOException { this(out, blockSize, -1L, bits); } /** * Create a new {@link OutputStream} that will compress data using the LZ4 algorithm. * * @param out The output stream to compress * @param blockSize The BLOCKSIZE to use * @param knownSize The size of the uncompressed data. A value less than zero means unknown. * @param bits A set of features to use * @throws IOException */ public LZ4FrameOutputStream(OutputStream out, BLOCKSIZE blockSize, long knownSize, FLG.Bits... bits) throws IOException { super(out); compressor = LZ4Factory.fastestInstance().fastCompressor(); checksum = XXHashFactory.fastestInstance().hash32(); frameInfo = new FrameInfo(new FLG(FLG.DEFAULT_VERSION, bits), new BD(blockSize)); maxBlockSize = frameInfo.getBD().getBlockMaximumSize(); buffer = ByteBuffer.allocate(maxBlockSize).order(ByteOrder.LITTLE_ENDIAN); compressedBuffer = new byte[compressor.maxCompressedLength(maxBlockSize)]; if (frameInfo.getFLG().isEnabled(FLG.Bits.CONTENT_SIZE) && knownSize < 0) { throw new IllegalArgumentException("Known size must be greater than zero in order to use the known size feature"); } this.knownSize = knownSize; writeHeader(); } /** * Create a new {@link OutputStream} that will compress data using the LZ4 algorithm. * * @param out The stream to compress * @param blockSize The BLOCKSIZE to use. Default: 4. The block size used during compression. 4=64kb, 5=256kb, 6=1mb, 7=4mb. All other * values will generate an exception * @throws IOException */ public LZ4FrameOutputStream(OutputStream out, BLOCKSIZE blockSize) throws IOException { this(out, blockSize, DEFAULT_FEATURES); } /** * Create a new {@link OutputStream} that will compress data using the LZ4 algorithm. * * @param out The output stream to compress * @throws IOException */ public LZ4FrameOutputStream(OutputStream out) throws IOException { this(out, BLOCKSIZE.SIZE_4MB); } /** * Writes the magic number and frame descriptor to the underlying {@link OutputStream}. * * @throws IOException */ private void writeHeader() throws IOException { final ByteBuffer headerBuffer = ByteBuffer.allocate(LZ4_MAX_HEADER_LENGTH).order(ByteOrder.LITTLE_ENDIAN); headerBuffer.putInt(MAGIC); headerBuffer.put(frameInfo.getFLG().toByte()); headerBuffer.put(frameInfo.getBD().toByte()); if (frameInfo.isEnabled(FLG.Bits.CONTENT_SIZE)) { headerBuffer.putLong(knownSize); } // compute checksum on all descriptor fields final int hash = (checksum.hash(headerBuffer.array(), INTEGER_BYTES, headerBuffer.position() - INTEGER_BYTES, 0) >> 8) & 0xFF; headerBuffer.put((byte) hash); // write out frame descriptor out.write(headerBuffer.array(), 0, headerBuffer.position()); } /** * Compresses buffered data, optionally computes an XXHash32 checksum, and writes the result to the underlying * {@link OutputStream}. * * @throws IOException */ private void writeBlock() throws IOException { if (buffer.position() == 0) { return; } // Make sure there's no stale data Arrays.fill(compressedBuffer, (byte) 0); int compressedLength = compressor.compress(buffer.array(), 0, buffer.position(), compressedBuffer, 0); final byte[] bufferToWrite; final int compressMethod; // Store block uncompressed if compressed length is greater (incompressible) if (compressedLength >= buffer.position()) { compressedLength = buffer.position(); bufferToWrite = Arrays.copyOf(buffer.array(), compressedLength); compressMethod = LZ4_FRAME_INCOMPRESSIBLE_MASK; } else { bufferToWrite = compressedBuffer; compressMethod = 0; } // Write content intLEBuffer.putInt(0, compressedLength | compressMethod); out.write(intLEBuffer.array()); out.write(bufferToWrite, 0, compressedLength); // Calculate and write block checksum if (frameInfo.isEnabled(FLG.Bits.BLOCK_CHECKSUM)) { intLEBuffer.putInt(0, checksum.hash(bufferToWrite, 0, compressedLength, 0)); out.write(intLEBuffer.array()); } buffer.rewind(); } /** * Similar to the {@link #writeBlock()} method. Writes a 0-length block (without block checksum) to signal the end * of the block stream. * * @throws IOException */ private void writeEndMark() throws IOException { intLEBuffer.putInt(0, 0); out.write(intLEBuffer.array()); if (frameInfo.isEnabled(FLG.Bits.CONTENT_CHECKSUM)) { intLEBuffer.putInt(0, frameInfo.currentStreamHash()); out.write(intLEBuffer.array()); } frameInfo.finish(); } @Override public void write(int b) throws IOException { ensureNotFinished(); if (buffer.position() == maxBlockSize) { writeBlock(); } buffer.put((byte) b); if (frameInfo.isEnabled(FLG.Bits.CONTENT_CHECKSUM)) { frameInfo.updateStreamHash(new byte[]{(byte) b}, 0, 1); } } @Override public void write(byte[] b, int off, int len) throws IOException { if ((off < 0) || (len < 0) || (off + len > b.length)) { throw new IndexOutOfBoundsException(); } ensureNotFinished(); // while b will fill the buffer while (len > buffer.remaining()) { int sizeWritten = buffer.remaining(); // fill remaining space in buffer buffer.put(b, off, sizeWritten); if (frameInfo.isEnabled(FLG.Bits.CONTENT_CHECKSUM)) { frameInfo.updateStreamHash(b, off, sizeWritten); } writeBlock(); // compute new offset and length off += sizeWritten; len -= sizeWritten; } buffer.put(b, off, len); if (frameInfo.isEnabled(FLG.Bits.CONTENT_CHECKSUM)) { frameInfo.updateStreamHash(b, off, len); } } @Override public void flush() throws IOException { if (!frameInfo.isFinished()) { writeBlock(); } super.flush(); } /** * A simple state check to ensure the stream is still open. */ private void ensureNotFinished() { if (frameInfo.isFinished()) { throw new IllegalStateException(CLOSED_STREAM); } } @Override public void close() throws IOException { if (!frameInfo.isFinished()) { flush(); writeEndMark(); } super.close(); } public static class FLG { private static final int DEFAULT_VERSION = 1; private final BitSet bitSet; private final int version; public enum Bits { RESERVED_0(0), RESERVED_1(1), CONTENT_CHECKSUM(2), CONTENT_SIZE(3), BLOCK_CHECKSUM(4), BLOCK_INDEPENDENCE(5); private final int position; Bits(int position) { this.position = position; } } public FLG(int version, Bits... bits) { this.bitSet = new BitSet(8); this.version = version; if (bits != null) { for (Bits bit : bits) { bitSet.set(bit.position); } } validate(); } private FLG(int version, byte b) { this.bitSet = BitSet.valueOf(new byte[]{b}); this.version = version; validate(); } public static FLG fromByte(byte flg) { final byte versionMask = (byte)(flg & (3 << 6)); return new FLG(versionMask >>> 6, (byte) (flg ^ versionMask)); } public byte toByte() { return (byte)(bitSet.toByteArray()[0] | ((version & 3) << 6)); } private void validate() { if (bitSet.get(Bits.RESERVED_0.position)) { throw new RuntimeException("Reserved0 field must be 0"); } if (bitSet.get(Bits.RESERVED_1.position)) { throw new RuntimeException("Reserved1 field must be 0"); } if (!bitSet.get(Bits.BLOCK_INDEPENDENCE.position)) { throw new RuntimeException("Dependent block stream is unsupported"); } if (version != DEFAULT_VERSION) { throw new RuntimeException(String.format("Version %d is unsupported", version)); } } public boolean isEnabled(Bits bit) { return bitSet.get(bit.position); } public int getVersion() { return version; } } public static class BD { private static final int RESERVED_MASK = 0x8F; private final BLOCKSIZE blockSizeValue; private BD(BLOCKSIZE blockSizeValue) { this.blockSizeValue = blockSizeValue; } public static BD fromByte(byte bd) { int blockMaximumSize = (bd >>> 4) & 7; if ((bd & RESERVED_MASK) > 0) { throw new RuntimeException("Reserved fields must be 0"); } return new BD(BLOCKSIZE.valueOf(blockMaximumSize)); } // 2^(2n+8) public int getBlockMaximumSize() { return 1 << ((2 * blockSizeValue.getIndicator()) + 8); } public byte toByte() { return (byte) ((blockSizeValue.getIndicator() & 7) << 4); } } public static class FrameInfo { private final FLG flg; private final BD bd; private final StreamingXXHash32 streamHash; private boolean finished = false; public FrameInfo(FLG flg, BD bd) { this.flg = flg; this.bd = bd; this.streamHash = flg.isEnabled(FLG.Bits.CONTENT_CHECKSUM) ? XXHashFactory.fastestInstance().newStreamingHash32(0) : null; } public boolean isEnabled(FLG.Bits bit) { return flg.isEnabled(bit); } public FLG getFLG() { return this.flg; } public BD getBD() { return this.bd; } public void updateStreamHash(byte[] buff, int off, int len) { this.streamHash.update(buff, off, len); } public int currentStreamHash() { return this.streamHash.getValue(); } public void finish() { this.finished = true; } public boolean isFinished() { return this.finished; } } }
package org.persekutuankarlsruhe.webapp; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.apache.commons.validator.routines.EmailValidator; import org.persekutuankarlsruhe.webapp.calendar.CalendarUtil; import org.persekutuankarlsruhe.webapp.email.EmailSendFailedException; import org.persekutuankarlsruhe.webapp.remindpersekutuan.RemindPersekutuanUtil; import org.persekutuankarlsruhe.webapp.remindpersekutuan.Reminder; import org.persekutuankarlsruhe.webapp.remindpersekutuan.ReminderPersekutuanDatastore; import org.persekutuankarlsruhe.webapp.remindpersekutuan.ReminderPersekutuanRegister; import org.persekutuankarlsruhe.webapp.remindpersekutuan.ReminderRegisterAlreadyExistException; import org.persekutuankarlsruhe.webapp.remindpersekutuan.ReminderRegisterAlreadyExistException.RegisterType; import org.persekutuankarlsruhe.webapp.sheets.JadwalPelayanan; import org.persekutuankarlsruhe.webapp.sheets.Orang; import org.persekutuankarlsruhe.webapp.sheets.SheetsDataProvider; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; @Controller public class ReminderPersekutuanController { private static final String ATTRIBUTE_SENT_REMINDERS = "sentReminders"; private static final String ATTRIBUTE_INPUT_NAMA_ERROR = "inputNamaError"; private static final String ATTRIBUTE_INPUT_EMAIL_ERROR = "inputEmailError"; private static final String ATTRIBUTE_INPUT_SELECTIONS_ERROR = "inputSelectionsError"; private static final Logger LOG = Logger.getLogger(ReminderPersekutuanController.class.getName()); private static final String ATTRIBUTE_SUCCESS_MESSAGE = "successMessage"; private static final String ATTRIBUTE_INFO_MESSAGE = "infoMessage"; private static final String ATTRIBUTE_ERROR_MESSAGE = "errorMessage"; private static final String REQUEST_PARAM_NAMA = "nama"; private static final String REQUEST_PARAM_EMAIL = "email"; private static final String REQUEST_PARAM_KEY = "key"; private static final String REQUEST_PARAM_SELECTIONS = "selections"; private static final String ATTRIBUTE_EMAIL = "email"; private static final String ATTRIBUTE_REGISTER = "register"; private static final String REQUEST_PARAM_BUTTON_UBAH = "ubah"; private static final String REQUEST_PARAM_BUTTON_BATAL = "batal"; private static final String REQUEST_PARAM_BUTTON_KIRIM = "kirim"; private static final String REQUEST_PARAM_BUTTON_HAPUS = "hapus"; RemindPersekutuanUtil util = new RemindPersekutuanUtil(); @RequestMapping(value = "/reminder") public String reminderMain(HttpServletRequest request, Model model) throws Exception { handleUserStatus(request, model); return "reminder/home"; } @RequestMapping(value = "/reminder/daftar", method = RequestMethod.GET) public String addReminderForm(HttpServletRequest request, Model model) throws Exception { handleUserStatus(request, model); return "reminder/add"; } @RequestMapping(value = "/reminder/daftar", method = RequestMethod.POST) public String addReminderExecution(HttpServletRequest request, Model model) throws Exception { handleUserStatus(request, model); if (isValidInput(request, model)) { String nama = request.getParameter(REQUEST_PARAM_NAMA); String email = request.getParameter(REQUEST_PARAM_EMAIL); LOG.info("Berusaha mendaftarkan reminder untuk " + nama + " <" + email + ">"); List<Integer> reminderList = new ArrayList<Integer>(); for (String selection : request.getParameterValues(REQUEST_PARAM_SELECTIONS)) { reminderList.add(Integer.parseInt(selection)); } try { ReminderPersekutuanDatastore.getInstance().addRegister(nama, email, reminderList); UserService userService = UserServiceFactory.getUserService(); User currentUser = userService.getCurrentUser(); if (currentUser != null && email.equalsIgnoreCase(currentUser.getEmail())) { ReminderPersekutuanDatastore.getInstance().activateRegister(email); model.addAttribute(ATTRIBUTE_SUCCESS_MESSAGE, "Reminder untuk email " + email + " telah didaftarkan dan telah aktif."); LOG.info("Reminder untuk " + nama + " <" + email + "> berhasil didaftarkan dan diaktifkan."); } else { // Send activation email util.sendEmailAktivasi(nama, email); model.addAttribute(ATTRIBUTE_INFO_MESSAGE, "Reminder berhasil didaftarkan, tapi belum diaktifkan. Cek inbox E-mail (" + email + ") untuk mengaktifkan reminder!"); LOG.info("Reminder untuk " + nama + " <" + email + "> berhasil didaftarkan. Email aktivasi telah dikirim."); } } catch (ReminderRegisterAlreadyExistException e) { RegisterType registerType = e.getRegisterType(); if (registerType == ReminderRegisterAlreadyExistException.RegisterType.ACTIVE) { model.addAttribute(ATTRIBUTE_ERROR_MESSAGE, "Email " + email + " telah didaftarkan sebelumnya dan telah aktif. Klik menu \"Ubah\" untuk mengubah reminder yang telah didaftarkan. Atau periksa inbox Email untuk mengaktifkan pendaftaran"); LOG.info("Gagal mendaftarkan untuk " + nama + " <" + email + ">. Alasan: sudah terdaftar dan sudah aktif."); } else if (registerType == ReminderRegisterAlreadyExistException.RegisterType.INACTIVE) { util.sendEmailAktivasi(nama, email); model.addAttribute(ATTRIBUTE_INFO_MESSAGE, "Reminder telah didaftarkan sebelumnya, tapi belum diaktifkan. Email aktivasi baru saja dikirimkan kembali. Cek inbox E-mail (" + email + ") untuk mengaktifkan reminder!"); LOG.info("Gagal mendaftarkan untuk " + nama + " <" + email + ">. Alasan: Belum diaktifkan. Email aktivasi telah dikirim."); } else { throw new IllegalArgumentException("Invalid Register Type: " + registerType); } } } return "reminder/add"; } private boolean isValidInput(HttpServletRequest request, Model model) { StringBuffer errorMessage = new StringBuffer(); if (StringUtils.isEmpty(request.getParameter(REQUEST_PARAM_NAMA))) { errorMessage.append("<li>Isi field Nama</li>"); model.addAttribute(ATTRIBUTE_INPUT_NAMA_ERROR, true); } String email = request.getParameter(REQUEST_PARAM_EMAIL); if (StringUtils.isEmpty(email)) { errorMessage.append("<li>Isi field Email</li>"); model.addAttribute(ATTRIBUTE_INPUT_EMAIL_ERROR, true); } if (!EmailValidator.getInstance().isValid(email)) { errorMessage.append("<li>Alamat email " + email + " tidak valid!</li>"); model.addAttribute(ATTRIBUTE_INPUT_EMAIL_ERROR, true); } if (request.getParameter(REQUEST_PARAM_SELECTIONS) == null) { errorMessage.append("<li>Pilih reminder yang diinginkan!</li>"); model.addAttribute(ATTRIBUTE_INPUT_SELECTIONS_ERROR, true); } if (errorMessage.length() > 0) { errorMessage.insert(0, "<ul>"); errorMessage.append("</ul>"); model.addAttribute(ATTRIBUTE_ERROR_MESSAGE, errorMessage); return false; } else { return true; } } @RequestMapping(value = "/reminder/ubah", method = RequestMethod.GET) public String editReminderForm(HttpServletRequest request, Model model) throws EmailSendFailedException { String view; User currentUser = handleUserStatus(request, model); String email = request.getParameter(REQUEST_PARAM_EMAIL); String key = request.getParameter(REQUEST_PARAM_KEY); if (StringUtils.isEmpty(email) || StringUtils.isEmpty(key)) { // If the email or key parameter is empty, show the email field only view = tampilkanFormulirUbah(currentUser, model); } else { // request dari email link: show ubah form view = ubahMenggunakanLinkUbah(email, key, model); } return view; } private String tampilkanFormulirUbah(User currentUser, Model model) { String view; if (currentUser != null) { model.addAttribute(ATTRIBUTE_EMAIL, currentUser.getEmail()); LOG.info("Request untuk mengubah reminder untuk Google account " + currentUser.getEmail() + ". Tampilkan formulir untuk mengubah"); } view = "reminder/maintainEnterEmail"; return view; } private String ubahMenggunakanLinkUbah(String email, String key, Model model) throws EmailSendFailedException { String view; ReminderPersekutuanDatastore datastore = ReminderPersekutuanDatastore.getInstance(); LOG.info("Request untuk mengubah reminder untuk " + email + " melalui link email."); try { Entity activeEntity = datastore.getActiveEntity(email); if (key.equals(datastore.getHashValue(activeEntity))) { ReminderPersekutuanRegister register = datastore.getReminderPersekutuanRegister(email); model.addAttribute(ATTRIBUTE_REGISTER, register); view = "reminder/maintainUbah"; LOG.info("Tampilkan formulir untuk mengubah reminder untuk " + email + " (melalui link)"); } else { model.addAttribute(ATTRIBUTE_ERROR_MESSAGE, "Link tidak valid"); view = "reminder/maintainEnterEmail"; LOG.info("Invalid key: " + key + " untuk email " + email + "."); } } catch (EntityNotFoundException e) { LOG.info("Mencoba mengirim aktivasi ke email " + email + " kalau perlu. Atau tampilkan error message."); trySendActivationEmailIfRegistered(model, email); view = "reminder/maintainEnterEmail"; } return view; } @RequestMapping(value = "/reminder/ubah", method = RequestMethod.POST) public String editReminderExecution(HttpServletRequest request, Model model) throws Exception { String view; User currentUser = handleUserStatus(request, model); String email = request.getParameter(REQUEST_PARAM_EMAIL); if (request.getParameter(REQUEST_PARAM_BUTTON_HAPUS) != null) { view = hapusRegister(email, model); } else if (request.getParameter(REQUEST_PARAM_BUTTON_BATAL) != null) { view = "redirect:/reminder/ubah"; } else if (request.getParameter(REQUEST_PARAM_BUTTON_KIRIM) != null) { // show form atau kirim link view = handleRequestPerubahanData(email, currentUser, model); } else if (request.getParameter(REQUEST_PARAM_BUTTON_UBAH) != null) { // simpan perubahan data view = prosesPerubahanData(email, request, model); } else { throw new IllegalStateException("POST request, tetapi tidak ada submit kirim ataupun ubah"); } return view; } private String handleRequestPerubahanData(String email, User currentUser, Model model) throws EmailSendFailedException { String view; try { ReminderPersekutuanRegister register = ReminderPersekutuanDatastore.getInstance() .getReminderPersekutuanRegister(email); if (currentUser != null && email.equalsIgnoreCase(currentUser.getEmail())) { model.addAttribute(ATTRIBUTE_REGISTER, register); view = "reminder/maintainUbah"; LOG.info("Berusaha mengirim update data untuk " + email + " (Google Account)"); } else { util.sendEmailUntukUbahPendaftaran(register); model.addAttribute(ATTRIBUTE_INFO_MESSAGE, "Email konfirmasi untuk mengubah data telah dikirimkan, harap ikuti petunjuk di email yang dikirim ke alamat " + email + " untuk mengubah reminder!"); view = "reminder/maintainEnterEmail"; LOG.info("Konfirmasi untuk ubah reminder untuk " + email + " telah dikirim (Bukan Google Account)"); } } catch (EntityNotFoundException e) { trySendActivationEmailIfRegistered(model, email); view = "reminder/maintainEnterEmail"; } return view; } private String prosesPerubahanData(String email, HttpServletRequest request, Model model) throws EntityNotFoundException, EmailSendFailedException { String view; LOG.info("Menerima pengubahan data untuk " + email); // process update String nama = request.getParameter(REQUEST_PARAM_NAMA); List<Integer> reminderList = new ArrayList<Integer>(); String[] selections = request.getParameterValues(REQUEST_PARAM_SELECTIONS); if (isValidInput(request, model)) { for (String selection : selections) { reminderList.add(Integer.parseInt(selection)); } if (LOG.isLoggable(Level.FINE)) { LOG.fine("Mengubah data untuk Nama: " + nama + "\tEmail: " + email + "\treminderList: " + reminderList); } ReminderPersekutuanDatastore.getInstance().updateRegister(nama, email, reminderList); util.sendEmailStatusReminder(email); model.addAttribute(ATTRIBUTE_SUCCESS_MESSAGE, "Data reminder untuk email " + email + " telah berhasil diubah"); view = "reminder/maintainEnterEmail"; LOG.info("Berhasil mengubah data untuk " + email); } else { model.addAttribute(ATTRIBUTE_REGISTER, ReminderPersekutuanDatastore.getInstance().getReminderPersekutuanRegister(email)); view = "reminder/maintainUbah"; } return view; } private String hapusRegister(String email, Model model) throws EmailSendFailedException { String view; ReminderPersekutuanDatastore datastore = ReminderPersekutuanDatastore.getInstance(); LOG.info("Mencoba menghapus data untuk email " + email); try { ReminderPersekutuanRegister register = datastore.getReminderPersekutuanRegister(email); datastore.deleteRegister(email); model.addAttribute(ATTRIBUTE_SUCCESS_MESSAGE, "Data reminder untuk email " + email + " telah berhasil dihapus."); LOG.info("Berhasil menghapus data untuk email " + email); util.sendEmailHapusData(register); LOG.info("Email konfirmasi penghapusan data telah dikirim ke " + email); } catch (EntityNotFoundException e) { model.addAttribute(ATTRIBUTE_ERROR_MESSAGE, "Tidak bisa menghapus reminder. Email " + email + " belum terdaftar."); LOG.info("Data untuk " + email + " tidak bisa dihapus, karena belum terdaftar"); } view = "reminder/maintainEnterEmail"; return view; } private void trySendActivationEmailIfRegistered(Model model, String email) throws EmailSendFailedException { ReminderPersekutuanDatastore datastore = ReminderPersekutuanDatastore.getInstance(); try { Entity inactiveEntity = datastore.getInactiveEntity(email); util.sendEmailAktivasi(datastore.getName(inactiveEntity), email); model.addAttribute(ATTRIBUTE_INFO_MESSAGE, "Email " + email + " belum diaktifkan. Periksa inbox untuk mengaktifkan reminder!"); LOG.info("Email aktivasi untuk " + email + " terkirim."); } catch (EntityNotFoundException e1) { model.addAttribute(ATTRIBUTE_ERROR_MESSAGE, "Email " + email + " belum terdaftar"); LOG.info("Email" + email + " belum terdaftar."); } } @RequestMapping(value = "/reminder/aktivasi") public String activate(HttpServletRequest request, Model model) { handleUserStatus(request, model); String email = request.getParameter(REQUEST_PARAM_EMAIL); String key = request.getParameter(REQUEST_PARAM_KEY); ReminderPersekutuanDatastore datastore = ReminderPersekutuanDatastore.getInstance(); LOG.info("Mecoba mengaktifkan pendaftaran dengan email " + email + " dan key " + key); if (StringUtils.isEmpty(email) || StringUtils.isEmpty(key)) { model.addAttribute(ATTRIBUTE_ERROR_MESSAGE, "Link aktivasi tidak valid"); } else { try { Entity inactiveEntity = datastore.getInactiveEntity(email); String hashValue = datastore.getHashValue(inactiveEntity); if (key.equals(hashValue)) { datastore.activateRegister(email); model.addAttribute(ATTRIBUTE_SUCCESS_MESSAGE, "Reminder untuk Email " + email + " telah berhasil diaktifkan."); LOG.info("Berhasil mengaktifkan pendaftaran untuk " + email); } else { model.addAttribute(ATTRIBUTE_ERROR_MESSAGE, "Link aktivasi tidak valid"); LOG.info("Link aktivasi untuk " + email + " tidak valid"); } } catch (EntityNotFoundException e) { try { datastore.getActiveEntity(email); model.addAttribute(ATTRIBUTE_INFO_MESSAGE, "Reminder untuk Email " + email + " sudah aktif sebelumnya"); LOG.info("Pendaftaran untuk email " + email + " sudah aktif sebelumnya"); } catch (EntityNotFoundException e1) { model.addAttribute(ATTRIBUTE_ERROR_MESSAGE, "Email " + email + " belum terdaftar"); LOG.info("Pendaftaran untuk email " + email + " belum terdaftar"); } } } return "reminder/activationStatus"; } private User handleUserStatus(HttpServletRequest request, Model model) { String thisUrl = request.getRequestURI(); UserService userService = UserServiceFactory.getUserService(); User currentUser = userService.getCurrentUser(); if (currentUser != null) { model.addAttribute("currentUser", currentUser); model.addAttribute("logoutURL", userService.createLogoutURL(thisUrl)); } else { model.addAttribute("loginURL", userService.createLoginURL(thisUrl)); } return currentUser; } @RequestMapping(value = "/tasks/remindpersekutuan") public String remindPersekutuan(Model model) throws Exception { List<Reminder> sentReminders = new ArrayList<Reminder>(); SheetsDataProvider dataProvider = SheetsDataProvider.createProviderForPersekutuan(); List<JadwalPelayanan> daftarJadwal = dataProvider.getDaftarJadwalPelayananFromSheets(); List<ReminderPersekutuanRegister> allRegisters = ReminderPersekutuanDatastore.getInstance().getAllRegisters(); LOG.info("Mencoba mengirimkan reminder persekutuan. Jadwal: " + daftarJadwal + "\tDaftar Registers:" + allRegisters); for (ReminderPersekutuanRegister register : allRegisters) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Memeriksa apakah perlu mengirimkan reminder untuk register berikut: " + register); } for (Number offset : register.getReminderList()) { int offsetHari = offset.intValue(); // Reminder dikirim jam 8, acara persekutuan pembanding jam // 00:00, jadi antara offsetHari-1 dengan offsetHari JadwalPelayanan jadwalUntukDiingatkan = CalendarUtil.getJadwalTerdekatDalamBbrpHari(daftarJadwal, offsetHari - 1, offsetHari); if (jadwalUntukDiingatkan != null) { Orang orang = new Orang(register.getNama(), register.getEmail()); LOG.info("Mengirim reminder ke " + orang + " untuk jadwal " + jadwalUntukDiingatkan); util.sendReminderPersekutuan(orang, jadwalUntukDiingatkan, offsetHari); sentReminders.add(new Reminder(orang, jadwalUntukDiingatkan.getTanggal())); } } } model.addAttribute(ATTRIBUTE_SENT_REMINDERS, sentReminders); return "reminder/reminderPersekutuanSummary"; } }
/* * 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.plugins; import org.apache.lucene.analysis.util.CharFilterFactory; import org.apache.lucene.analysis.util.TokenFilterFactory; import org.apache.lucene.analysis.util.TokenizerFactory; import org.apache.lucene.codecs.Codec; import org.apache.lucene.codecs.DocValuesFormat; import org.apache.lucene.codecs.PostingsFormat; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.admin.cluster.node.info.PluginsAndModules; import org.elasticsearch.bootstrap.JarHell; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.component.AbstractComponent; import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.io.FileSystemUtils; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.IndexModule; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; 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 static org.elasticsearch.common.io.FileSystemUtils.isAccessibleDirectory; /** * */ public class PluginsService extends AbstractComponent { /** * We keep around a list of plugins and modules */ private final List<Tuple<PluginInfo, Plugin>> plugins; private final PluginsAndModules info; private final Map<Plugin, List<OnModuleReference>> onModuleReferences; static class OnModuleReference { public final Class<? extends Module> moduleClass; public final Method onModuleMethod; OnModuleReference(Class<? extends Module> moduleClass, Method onModuleMethod) { this.moduleClass = moduleClass; this.onModuleMethod = onModuleMethod; } } /** * Constructs a new PluginService * @param settings The settings of the system * @param modulesDirectory The directory modules exist in, or null if modules should not be loaded from the filesystem * @param pluginsDirectory The directory plugins exist in, or null if plugins should not be loaded from the filesystem * @param classpathPlugins Plugins that exist in the classpath which should be loaded */ public PluginsService(Settings settings, Path modulesDirectory, Path pluginsDirectory, Collection<Class<? extends Plugin>> classpathPlugins) { super(settings); info = new PluginsAndModules(); List<Tuple<PluginInfo, Plugin>> pluginsLoaded = new ArrayList<>(); // first we load plugins that are on the classpath. this is for tests and transport clients for (Class<? extends Plugin> pluginClass : classpathPlugins) { Plugin plugin = loadPlugin(pluginClass, settings); PluginInfo pluginInfo = new PluginInfo(plugin.name(), plugin.description(), "NA", pluginClass.getName(), false); if (logger.isTraceEnabled()) { logger.trace("plugin loaded from classpath [{}]", pluginInfo); } pluginsLoaded.add(new Tuple<>(pluginInfo, plugin)); info.addPlugin(pluginInfo); } // load modules if (modulesDirectory != null) { try { List<Bundle> bundles = getModuleBundles(modulesDirectory); List<Tuple<PluginInfo, Plugin>> loaded = loadBundles(bundles); pluginsLoaded.addAll(loaded); for (Tuple<PluginInfo, Plugin> module : loaded) { info.addModule(module.v1()); } } catch (IOException ex) { throw new IllegalStateException("Unable to initialize modules", ex); } } // now, find all the ones that are in plugins/ if (pluginsDirectory != null) { try { List<Bundle> bundles = getPluginBundles(pluginsDirectory); List<Tuple<PluginInfo, Plugin>> loaded = loadBundles(bundles); pluginsLoaded.addAll(loaded); for (Tuple<PluginInfo, Plugin> plugin : loaded) { info.addPlugin(plugin.v1()); } } catch (IOException ex) { throw new IllegalStateException("Unable to initialize plugins", ex); } } plugins = Collections.unmodifiableList(pluginsLoaded); // We need to build a List of plugins for checking mandatory plugins Set<String> pluginsNames = new HashSet<>(); for (Tuple<PluginInfo, Plugin> tuple : plugins) { pluginsNames.add(tuple.v1().getName()); } // Checking expected plugins String[] mandatoryPlugins = settings.getAsArray("plugin.mandatory", null); if (mandatoryPlugins != null) { Set<String> missingPlugins = new HashSet<>(); for (String mandatoryPlugin : mandatoryPlugins) { if (!pluginsNames.contains(mandatoryPlugin) && !missingPlugins.contains(mandatoryPlugin)) { missingPlugins.add(mandatoryPlugin); } } if (!missingPlugins.isEmpty()) { throw new ElasticsearchException("Missing mandatory plugins [" + Strings.collectionToDelimitedString(missingPlugins, ", ") + "]"); } } // we don't log jars in lib/ we really shouldnt log modules, // but for now: just be transparent so we can debug any potential issues Set<String> moduleNames = new HashSet<>(); Set<String> jvmPluginNames = new HashSet<>(); for (PluginInfo moduleInfo : info.getModuleInfos()) { moduleNames.add(moduleInfo.getName()); } for (PluginInfo pluginInfo : info.getPluginInfos()) { jvmPluginNames.add(pluginInfo.getName()); } logger.info("modules {}, plugins {}", moduleNames, jvmPluginNames); Map<Plugin, List<OnModuleReference>> onModuleReferences = new HashMap<>(); for (Tuple<PluginInfo, Plugin> pluginEntry : plugins) { Plugin plugin = pluginEntry.v2(); List<OnModuleReference> list = new ArrayList<>(); for (Method method : plugin.getClass().getMethods()) { if (!method.getName().equals("onModule")) { continue; } // this is a deprecated final method, so all Plugin subclasses have it if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(IndexModule.class)) { continue; } if (method.getParameterTypes().length == 0 || method.getParameterTypes().length > 1) { logger.warn("Plugin: {} implementing onModule with no parameters or more than one parameter", plugin.name()); continue; } Class moduleClass = method.getParameterTypes()[0]; if (!Module.class.isAssignableFrom(moduleClass)) { logger.warn("Plugin: {} implementing onModule by the type is not of Module type {}", plugin.name(), moduleClass); continue; } list.add(new OnModuleReference(moduleClass, method)); } if (!list.isEmpty()) { onModuleReferences.put(plugin, list); } } this.onModuleReferences = Collections.unmodifiableMap(onModuleReferences); } private List<Tuple<PluginInfo, Plugin>> plugins() { return plugins; } public void processModules(Iterable<Module> modules) { for (Module module : modules) { processModule(module); } } public void processModule(Module module) { for (Tuple<PluginInfo, Plugin> plugin : plugins()) { // see if there are onModule references List<OnModuleReference> references = onModuleReferences.get(plugin.v2()); if (references != null) { for (OnModuleReference reference : references) { if (reference.moduleClass.isAssignableFrom(module.getClass())) { try { reference.onModuleMethod.invoke(plugin.v2(), module); } catch (IllegalAccessException | InvocationTargetException e) { logger.warn("plugin {}, failed to invoke custom onModule method", e, plugin.v2().name()); throw new ElasticsearchException("failed to invoke onModule", e); } catch (Exception e) { logger.warn("plugin {}, failed to invoke custom onModule method", e, plugin.v2().name()); throw e; } } } } } } public Settings updatedSettings() { Map<String, String> foundSettings = new HashMap<>(); final Settings.Builder builder = Settings.settingsBuilder(); for (Tuple<PluginInfo, Plugin> plugin : plugins) { Settings settings = plugin.v2().additionalSettings(); for (String setting : settings.getAsMap().keySet()) { String oldPlugin = foundSettings.put(setting, plugin.v1().getName()); if (oldPlugin != null) { throw new IllegalArgumentException("Cannot have additional setting [" + setting + "] " + "in plugin [" + plugin.v1().getName() + "], already added in plugin [" + oldPlugin + "]"); } } builder.put(settings); } return builder.put(this.settings).build(); } public Collection<Module> nodeModules() { List<Module> modules = new ArrayList<>(); for (Tuple<PluginInfo, Plugin> plugin : plugins) { modules.addAll(plugin.v2().nodeModules()); } return modules; } public Collection<Class<? extends LifecycleComponent>> nodeServices() { List<Class<? extends LifecycleComponent>> services = new ArrayList<>(); for (Tuple<PluginInfo, Plugin> plugin : plugins) { services.addAll(plugin.v2().nodeServices()); } return services; } public void onIndexModule(IndexModule indexModule) { for (Tuple<PluginInfo, Plugin> plugin : plugins) { plugin.v2().onIndexModule(indexModule); } } /** * Get information about plugins and modules */ public PluginsAndModules info() { return info; } // a "bundle" is a group of plugins in a single classloader // really should be 1-1, but we are not so fortunate static class Bundle { List<PluginInfo> plugins = new ArrayList<>(); List<URL> urls = new ArrayList<>(); } // similar in impl to getPluginBundles, but DO NOT try to make them share code. // we don't need to inherit all the leniency, and things are different enough. static List<Bundle> getModuleBundles(Path modulesDirectory) throws IOException { // damn leniency if (Files.notExists(modulesDirectory)) { return Collections.emptyList(); } List<Bundle> bundles = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(modulesDirectory)) { for (Path module : stream) { if (FileSystemUtils.isHidden(module)) { continue; // skip over .DS_Store etc } PluginInfo info = PluginInfo.readFromProperties(module); if (!info.isIsolated()) { throw new IllegalStateException("modules must be isolated: " + info); } Bundle bundle = new Bundle(); bundle.plugins.add(info); // gather urls for jar files try (DirectoryStream<Path> jarStream = Files.newDirectoryStream(module, "*.jar")) { for (Path jar : jarStream) { // normalize with toRealPath to get symlinks out of our hair bundle.urls.add(jar.toRealPath().toUri().toURL()); } } bundles.add(bundle); } } return bundles; } static List<Bundle> getPluginBundles(Path pluginsDirectory) throws IOException { ESLogger logger = Loggers.getLogger(PluginsService.class); // TODO: remove this leniency, but tests bogusly rely on it if (!isAccessibleDirectory(pluginsDirectory, logger)) { return Collections.emptyList(); } List<Bundle> bundles = new ArrayList<>(); // a special purgatory for plugins that directly depend on each other bundles.add(new Bundle()); try (DirectoryStream<Path> stream = Files.newDirectoryStream(pluginsDirectory)) { for (Path plugin : stream) { if (FileSystemUtils.isHidden(plugin)) { logger.trace("--- skip hidden plugin file[{}]", plugin.toAbsolutePath()); continue; } logger.trace("--- adding plugin [{}]", plugin.toAbsolutePath()); final PluginInfo info; try { info = PluginInfo.readFromProperties(plugin); } catch (IOException e) { throw new IllegalStateException("Could not load plugin descriptor for existing plugin [" + plugin.getFileName() + "]. Was the plugin built before 2.0?", e); } List<URL> urls = new ArrayList<>(); try (DirectoryStream<Path> jarStream = Files.newDirectoryStream(plugin, "*.jar")) { for (Path jar : jarStream) { // normalize with toRealPath to get symlinks out of our hair urls.add(jar.toRealPath().toUri().toURL()); } } final Bundle bundle; if (info.isIsolated() == false) { bundle = bundles.get(0); // purgatory } else { bundle = new Bundle(); bundles.add(bundle); } bundle.plugins.add(info); bundle.urls.addAll(urls); } } return bundles; } private List<Tuple<PluginInfo,Plugin>> loadBundles(List<Bundle> bundles) { List<Tuple<PluginInfo, Plugin>> plugins = new ArrayList<>(); for (Bundle bundle : bundles) { // jar-hell check the bundle against the parent classloader // pluginmanager does it, but we do it again, in case lusers mess with jar files manually try { final List<URL> jars = new ArrayList<>(); jars.addAll(Arrays.asList(JarHell.parseClassPath())); jars.addAll(bundle.urls); JarHell.checkJarHell(jars.toArray(new URL[0])); } catch (Exception e) { throw new IllegalStateException("failed to load bundle " + bundle.urls + " due to jar hell", e); } // create a child to load the plugins in this bundle ClassLoader loader = URLClassLoader.newInstance(bundle.urls.toArray(new URL[0]), getClass().getClassLoader()); for (PluginInfo pluginInfo : bundle.plugins) { // reload lucene SPI with any new services from the plugin reloadLuceneSPI(loader); final Class<? extends Plugin> pluginClass = loadPluginClass(pluginInfo.getClassname(), loader); final Plugin plugin = loadPlugin(pluginClass, settings); plugins.add(new Tuple<>(pluginInfo, plugin)); } } return Collections.unmodifiableList(plugins); } /** * Reloads all Lucene SPI implementations using the new classloader. * This method must be called after the new classloader has been created to * register the services for use. */ static void reloadLuceneSPI(ClassLoader loader) { // do NOT change the order of these method calls! // Codecs: PostingsFormat.reloadPostingsFormats(loader); DocValuesFormat.reloadDocValuesFormats(loader); Codec.reloadCodecs(loader); // Analysis: CharFilterFactory.reloadCharFilters(loader); TokenFilterFactory.reloadTokenFilters(loader); TokenizerFactory.reloadTokenizers(loader); } private Class<? extends Plugin> loadPluginClass(String className, ClassLoader loader) { try { return loader.loadClass(className).asSubclass(Plugin.class); } catch (ClassNotFoundException e) { throw new ElasticsearchException("Could not find plugin class [" + className + "]", e); } } private Plugin loadPlugin(Class<? extends Plugin> pluginClass, Settings settings) { try { try { return pluginClass.getConstructor(Settings.class).newInstance(settings); } catch (NoSuchMethodException e) { try { return pluginClass.getConstructor().newInstance(); } catch (NoSuchMethodException e1) { throw new ElasticsearchException("No constructor for [" + pluginClass + "]. A plugin class must " + "have either an empty default constructor or a single argument constructor accepting a " + "Settings instance"); } } } catch (Throwable e) { throw new ElasticsearchException("Failed to load plugin class [" + pluginClass.getName() + "]", e); } } }
/* Copyright 2008 Matt Radkie 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. */ /** * @author Matt Radkie */ package rlVizLib.utilities; /** * @deprecated Use The Task Spec from the RLGlue Java Codec. * @author btanner */ public class TaskSpec { TaskSpecDelegate theTSO = null; int TSVersion = 0; public int getVersion(){ return TSVersion; } @SuppressWarnings("deprecation") public TaskSpec(String taskSpec) { String errorAccumulator="Task Spec Parse Results:"; try { theTSO = new TaskSpecV3(taskSpec); TSVersion = 3; } catch (Exception e) { errorAccumulator+="\nParsing as V3: "+e.toString(); } if (theTSO == null) { try { theTSO = new TaskSpecV2(taskSpec); TSVersion = 2; } catch (Exception e) { errorAccumulator+="\nParsing as V2: "+e.toString(); } } if (theTSO == null) { System.err.println("Task spec couldn't be parsed"); throw new IllegalArgumentException(errorAccumulator); } } @Override public String toString() { return theTSO.getStringRepresentation(); } public String dump() { return theTSO.dump(); } //check if obs_min[index] is negative infinity public boolean isObsMinNegInfinity(int index) { return theTSO.isObsMinNegInfinity(index); } //check if action_min[index] is negative infinity public boolean isActionMinNegInfinity(int index) { return theTSO.isActionMinNegInfinity(index); } //check if obs_max[index] is positive infinity public boolean isObsMaxPosInfinity(int index) { return theTSO.isObsMaxPosInfinity(index); } //check if action_max[index] is positive infinity public boolean isActionMaxPosInfinity(int index) { return theTSO.isActionMaxPosInfinity(index); } //check if the value range for observation[index] is known public boolean isObsMinUnknown(int index) { return theTSO.isObsMinUnknown(index); } public boolean isObsMaxUnknown(int index) { return theTSO.isObsMaxUnknown(index); } //check if the value range for action[index] is known public boolean isActionMinUnknown(int index) { return theTSO.isActionMinUnknown(index); } public boolean isActionMaxUnknown(int index) { return theTSO.isActionMaxUnknown(index); } public boolean isMinRewardNegInf() { return theTSO.isMinRewardNegInf(); } public boolean isMaxRewardInf() { return theTSO.isMaxRewardInf(); } public boolean isMinRewardUnknown() { return theTSO.isMinRewardUnknown(); } public boolean isMaxRewardUnknown() { return theTSO.isMaxRewardUnknown(); } public double getTaskSpecVersion() { return theTSO.getVersion(); } public void setVersion(int version) { theTSO.setVersion(version); } public char getEpisodic() { return theTSO.getEpisodic(); } public void setEpisodic(char episodic) { theTSO.setEpisodic(episodic); } public int getObsDim() { return theTSO.getObsDim(); } public void setobsDim(int dim) { theTSO.setObsDim(dim); } public int getNumDiscreteObsDims() { return theTSO.getNumDiscreteObsDims(); } public void setNumDiscreteObsDims(int numDisc) { theTSO.setNumDiscreteObsDims(numDisc); } public int getNumContinuousObsDims() { return theTSO.getNumContinuousObsDims(); } public void setNumContinuousObsDims(int numCont) { theTSO.setNumContinuousObsDims(numCont); } public char[] getObsTypes() { return theTSO.getObsTypes(); } public void setObsTypes(char[] types) { theTSO.setObsTypes(types); } public double[] getObsMins() { return theTSO.getObsMins(); } public void setObsMins(double[] mins) { theTSO.setObsMins(mins); } public double[] getObsMaxs() { return theTSO.getObsMaxs(); } public void setObsMaxs(double[] maxs) { theTSO.setObsMaxs(maxs); } public int getActionDim() { return theTSO.getActionDim(); } public void setActionDim(int dim) { theTSO.setActionDim(dim); } public int getNumDiscreteActionDims() { return theTSO.getNumDiscreteActionDims(); } public void setNumDiscreteActionDims(int numDisc) { theTSO.setNumDiscreteActionDims(numDisc); } public int getNumContinuousActionDims() { return theTSO.getNumContinuousActionDims(); } public void setNumContinuousActionDims(int numCont) { theTSO.setNumContinuousActionDims(numCont); } public char[] getActionTypes() { return theTSO.getActionTypes(); } public void setActionTypes(char[] types) { theTSO.setActionTypes(types); } public double[] getActionMins() { return theTSO.getActionMins(); } public void setActionMins(double[] mins) { theTSO.setActionMins(mins); } public double[] getActionMaxs() { return theTSO.getActionMaxs(); } public void setActionMaxs(double[] maxs) { theTSO.setActionMaxs(maxs); } public double getRewardMax() { return theTSO.getRewardMax(); } public void setRewardMax(double max) { theTSO.setRewardMax(max); } public double getRewardMin() { return theTSO.getRewardMin(); } public void setRewardMin(double min) { theTSO.setRewardMin(min); } public String getExtraString() { return theTSO.getExtraString(); } public void setExtraString(String newString) { theTSO.setExtraString(newString); } public int getParserVersion() { return theTSO.getParserVersion(); } public static void main(String[] args){ String sampleTS="2:e:2_[f,f]_[-1.2,0.6]_[-0.07,0.07]:1_[i]_[0,2]"; TaskSpec theTSO=new TaskSpec(sampleTS); // System.out.println(sampleTS+" is version: "+theTSO.getVersion()); // // // sampleTS="2:e:2_[f,f]_[-1.2,0.6]_[-0.07,0.07]:1_[i]_[0,2]:[]"; // theTSO=new TaskSpec(sampleTS); // System.out.println(sampleTS+" is version: "+theTSO.getVersion()); // // sampleTS="2:e:2_[f,f]_[-1.2,0.6]_[-0.07,0.07]:1_[i]_[0,2]:[0,3]"; // theTSO=new TaskSpec(sampleTS); // System.out.println(sampleTS+" is version: "+theTSO.getVersion()); sampleTS="2:e:2_[f,f]_[-1.2,0.6]_[-0.07,0.07]:1_[i]_[0,2]:[0,3]:Extra strings and stuff here"; theTSO=new TaskSpec(sampleTS); System.out.println(sampleTS+" is version: "+theTSO.getVersion() +"\n" +theTSO.toString()); System.out.println(theTSO.dump()); // sampleTS="2:e:2_[f,f]_[-1.2,0.6]_[-0.07,0.07]:1_[i]_[0,2]:[0,3]:"; // theTSO=new TaskSpec(sampleTS); // System.out.println(sampleTS+" is version: "+theTSO.getVersion()); // // sampleTS="2:e:[0,3]"; // theTSO=new TaskSpec(sampleTS); // System.out.println(sampleTS+" is version: "+theTSO.getVersion()); } }
/* * 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.phoenix.hbase.index.covered; import java.io.IOException; import java.util.Collection; import java.util.List; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.util.Pair; import org.apache.phoenix.hbase.index.builder.BaseIndexBuilder; import org.apache.phoenix.hbase.index.covered.data.LocalHBaseState; import org.apache.phoenix.hbase.index.covered.update.ColumnTracker; import org.apache.phoenix.hbase.index.covered.update.IndexUpdateManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Build covered indexes for phoenix updates. * <p> * Before any call to prePut/preDelete, the row has already been locked. This ensures that we don't need to do any extra * synchronization in the IndexBuilder. * <p> * NOTE: This implementation doesn't cleanup the index when we remove a key-value on compaction or flush, leading to a * bloated index that needs to be cleaned up by a background process. */ public class NonTxIndexBuilder extends BaseIndexBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(NonTxIndexBuilder.class); @Override public void setup(RegionCoprocessorEnvironment env) throws IOException { super.setup(env); } @Override public Collection<Pair<Mutation, byte[]>> getIndexUpdate(Mutation mutation, IndexMetaData indexMetaData, LocalHBaseState localHBaseState) throws IOException { // create a state manager, so we can manage each batch LocalTableState state = new LocalTableState(localHBaseState, mutation); // build the index updates for each group IndexUpdateManager manager = new IndexUpdateManager(indexMetaData); batchMutationAndAddUpdates(manager, state, mutation, indexMetaData); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Found index updates for Mutation: " + mutation + "\n" + manager); } return manager.toMap(); } /** * Split the mutation into batches based on the timestamps of each keyvalue. We need to check each key-value in the * update to see if it matches the others. Generally, this will be the case, but you can add kvs to a mutation that * don't all have the timestamp, so we need to manage everything in batches based on timestamp. * <p> * Adds all the updates in the {@link Mutation} to the state, as a side-effect. * @param state * current state of the row for the mutation. * @param m * mutation to batch * @param indexMetaData TODO * @param updateMap * index updates into which to add new updates. Modified as a side-effect. * * @throws IOException */ private void batchMutationAndAddUpdates(IndexUpdateManager manager, LocalTableState state, Mutation m, IndexMetaData indexMetaData) throws IOException { // The cells of a mutation are broken up into time stamp batches prior to this call (in Indexer). long ts = m.getFamilyCellMap().values().iterator().next().iterator().next().getTimestamp(); Batch batch = new Batch(ts); for (List<Cell> family : m.getFamilyCellMap().values()) { for (Cell kv : family) { batch.add(kv); if(ts != kv.getTimestamp()) { throw new IllegalStateException("Time stamps must match for all cells in a batch"); } } } addMutationsForBatch(manager, batch, state, indexMetaData); } /** * For a single batch, get all the index updates and add them to the updateMap * <p> * This method manages cleaning up the entire history of the row from the given timestamp forward for out-of-order * (e.g. 'back in time') updates. * <p> * If things arrive out of order (client is using custom timestamps) we should still see the index in the correct * order (assuming we scan after the out-of-order update in finished). Therefore, we when we aren't the most recent * update to the index, we need to delete the state at the current timestamp (similar to above), but also issue a * delete for the added index updates at the next newest timestamp of any of the columns in the update; we need to * cleanup the insert so it looks like it was also deleted at that next newest timestamp. However, its not enough to * just update the one in front of us - that column will likely be applied to index entries up the entire history in * front of us, which also needs to be fixed up. * <p> * However, the current update usually will be the most recent thing to be added. In that case, all we need to is * issue a delete for the previous index row (the state of the row, without the update applied) at the current * timestamp. This gets rid of anything currently in the index for the current state of the row (at the timestamp). * Then we can just follow that by applying the pending update and building the index update based on the new row * state. * * @param updateMap * map to update with new index elements * @param batch * timestamp-based batch of edits * @param state * local state to update and pass to the codec * @param indexMetaData TODO * @return <tt>true</tt> if we cleaned up the current state forward (had a back-in-time put), <tt>false</tt> * otherwise * @throws IOException */ private boolean addMutationsForBatch(IndexUpdateManager updateMap, Batch batch, LocalTableState state, IndexMetaData indexMetaData) throws IOException { // need a temporary manager for the current batch. It should resolve any conflicts for the // current batch. Essentially, we can get the case where a batch doesn't change the current // state of the index (all Puts are covered by deletes), in which case we don't want to add // anything // A. Get the correct values for the pending state in the batch // A.1 start by cleaning up the current state - as long as there are key-values in the batch // that are indexed, we need to change the current state of the index. Its up to the codec to // determine if we need to make any cleanup given the pending update. long batchTs = batch.getTimestamp(); state.setPendingUpdates(batch.getKvs()); addCleanupForCurrentBatch(updateMap, batchTs, state, indexMetaData); // A.2 do a single pass first for the updates to the current state state.applyPendingUpdates(); addUpdateForGivenTimestamp(batchTs, state, updateMap, indexMetaData); // FIXME: PHOENIX-4057 do not attempt to issue index updates // for out-of-order mutations since it corrupts the index. return false; } private long addUpdateForGivenTimestamp(long ts, LocalTableState state, IndexUpdateManager updateMap, IndexMetaData indexMetaData) throws IOException { state.setCurrentTimestamp(ts); ts = addCurrentStateMutationsForBatch(updateMap, state, indexMetaData); return ts; } private void addCleanupForCurrentBatch(IndexUpdateManager updateMap, long batchTs, LocalTableState state, IndexMetaData indexMetaData) throws IOException { // get the cleanup for the current state state.setCurrentTimestamp(batchTs); addDeleteUpdatesToMap(updateMap, state, batchTs, indexMetaData); // ignore any index tracking from the delete state.resetTrackedColumns(); } /** * Add the necessary mutations for the pending batch on the local state. Handles rolling up through history to * determine the index changes after applying the batch (for the case where the batch is back in time). * * @param updateMap * to update with index mutations * @param state * current state of the table * @param indexMetaData TODO * @param batch * to apply to the current state * @return the minimum timestamp across all index columns requested. If {@link ColumnTracker#isNewestTime(long)} * returns <tt>true</tt> on the returned timestamp, we know that this <i>was not a back-in-time update</i>. * @throws IOException */ private long addCurrentStateMutationsForBatch(IndexUpdateManager updateMap, LocalTableState state, IndexMetaData indexMetaData) throws IOException { // get the index updates for this current batch Iterable<IndexUpdate> upserts = codec.getIndexUpserts( state, indexMetaData, env.getRegionInfo().getStartKey(), env.getRegionInfo().getEndKey(), false); state.resetTrackedColumns(); /* * go through all the pending updates. If we are sure that all the entries are the latest timestamp, we can just * add the index updates and move on. However, if there are columns that we skip past (based on the timestamp of * the batch), we need to roll back up the history. Regardless of whether or not they are the latest timestamp, * the entries here are going to be correct for the current batch timestamp, so we add them to the updates. The * only thing we really care about it if we need to roll up the history and fix it as we go. */ // timestamp of the next update we need to track long minTs = ColumnTracker.NO_NEWER_PRIMARY_TABLE_ENTRY_TIMESTAMP; for (IndexUpdate update : upserts) { // this is the one bit where we check the timestamps final ColumnTracker tracker = update.getIndexedColumns(); long trackerTs = tracker.getTS(); // update the next min TS we need to track if (trackerTs < minTs) { minTs = tracker.getTS(); } // FIXME: PHOENIX-4057 do not attempt to issue index updates // for out-of-order mutations since it corrupts the index. if (tracker.hasNewerTimestamps()) { continue; } // only make the put if the index update has been setup if (update.isValid()) { byte[] table = update.getTableName(); Mutation mutation = update.getUpdate(); updateMap.addIndexUpdate(table, mutation); } } return minTs; } /** * Get the index deletes from the codec {@link IndexCodec#getIndexDeletes(TableState, IndexMetaData, byte[], byte[])} and then add them to the * update map. * <p> * Expects the {@link LocalTableState} to already be correctly setup (correct timestamp, updates applied, etc). * @param indexMetaData TODO * * @throws IOException */ protected void addDeleteUpdatesToMap(IndexUpdateManager updateMap, LocalTableState state, long ts, IndexMetaData indexMetaData) throws IOException { Iterable<IndexUpdate> cleanup = codec.getIndexDeletes(state, indexMetaData, env.getRegionInfo().getStartKey(), env.getRegionInfo().getEndKey()); if (cleanup != null) { for (IndexUpdate d : cleanup) { if (!d.isValid()) { continue; } // FIXME: PHOENIX-4057 do not attempt to issue index updates // for out-of-order mutations since it corrupts the index. final ColumnTracker tracker = d.getIndexedColumns(); if (tracker.hasNewerTimestamps()) { continue; } // override the timestamps in the delete to match the current batch. Delete remove = (Delete)d.getUpdate(); remove.setTimestamp(ts); updateMap.addIndexUpdate(d.getTableName(), remove); } } } @Override public Collection<Pair<Mutation, byte[]>> getIndexUpdateForFilteredRows(Collection<Cell> filtered, IndexMetaData indexMetaData) throws IOException { // TODO Implement IndexBuilder.getIndexUpdateForFilteredRows return null; } }
package com.google.android.finsky.services; import android.accounts.Account; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import com.android.vending.details.IDetailsService.Stub; import com.android.volley.toolbox.RequestFuture; import com.google.android.finsky.FinskyApp; import com.google.android.finsky.activities.MainActivity; import com.google.android.finsky.analytics.FinskyEventLog; import com.google.android.finsky.api.DfeApi; import com.google.android.finsky.api.DfeUtils; import com.google.android.finsky.api.model.DfeToc; import com.google.android.finsky.api.model.Document; import com.google.android.finsky.appstate.AppStates; import com.google.android.finsky.appstate.WriteThroughInstallerDataStore; import com.google.android.finsky.billing.lightpurchase.LightPurchaseFlowActivity; import com.google.android.finsky.config.G; import com.google.android.finsky.library.Libraries; import com.google.android.finsky.protos.Common.Image; import com.google.android.finsky.protos.Details.DetailsResponse; import com.google.android.finsky.protos.DocV2; import com.google.android.finsky.receivers.Installer; import com.google.android.finsky.utils.FinskyLog; import com.google.android.finsky.utils.PurchaseButtonHelper; import com.google.android.finsky.utils.PurchaseButtonHelper.DocumentAction; import com.google.android.finsky.utils.PurchaseButtonHelper.DocumentActions; import com.google.android.finsky.utils.PurchaseButtonHelper.TextStyle; import com.google.android.finsky.utils.SignatureUtils; import com.google.android.play.utils.config.GservicesValue; import java.util.List; import java.util.Locale; import java.util.concurrent.ExecutionException; public class DetailsService extends Service { private static boolean addImage(Document paramDocument, int paramInt, Bundle paramBundle) { List localList = paramDocument.getImages(paramInt); if ((localList != null) && (!localList.isEmpty())) { Common.Image localImage = (Common.Image)localList.get(0); if (localImage.hasImageUrl) { if ((localImage.hasSupportsFifeUrlOptions) && (localImage.supportsFifeUrlOptions)) {} for (String str = "fife_url";; str = "image_url") { paramBundle.putString(str, localImage.imageUrl); return true; Object[] arrayOfObject = new Object[2]; arrayOfObject[0] = paramDocument.mDocument.docid; arrayOfObject[1] = Integer.valueOf(paramInt); FinskyLog.d("App %s no FIFE URL for %d", arrayOfObject); } } } return false; } public static Bundle getBundle(Context paramContext, Document paramDocument, Account paramAccount, DfeToc paramDfeToc, Installer paramInstaller, AppStates paramAppStates, Libraries paramLibraries, String paramString, FinskyEventLog paramFinskyEventLog) { String str = paramDocument.mDocument.backendDocid; int i = paramDocument.mDocument.backendId; if (i != 3) { Object[] arrayOfObject5 = new Object[2]; arrayOfObject5[0] = str; arrayOfObject5[1] = Integer.valueOf(i); FinskyLog.d("Document %s is not an app, backend=%d", arrayOfObject5); SignatureUtils.logEvent(paramFinskyEventLog, 512, str, "doc-backend", paramString, null); return null; } int j = paramDocument.mDocument.docType; if (j != 1) { Object[] arrayOfObject4 = new Object[2]; arrayOfObject4[0] = str; arrayOfObject4[1] = Integer.valueOf(j); FinskyLog.d("Document %s is not an app, doc_type=%d", arrayOfObject4); SignatureUtils.logEvent(paramFinskyEventLog, 512, str, "doc-type", paramString, null); return null; } PurchaseButtonHelper.DocumentActions localDocumentActions = new PurchaseButtonHelper.DocumentActions(); PurchaseButtonHelper.getDocumentActions(paramAccount, paramInstaller, paramLibraries, paramAppStates, paramDfeToc, 0, paramDocument, localDocumentActions); int k = 0; PurchaseButtonHelper.DocumentAction localDocumentAction; if (k < localDocumentActions.actionCount) { localDocumentAction = localDocumentActions.getAction(k); if ((localDocumentAction.actionType != 7) && (localDocumentAction.actionType != 15) && (localDocumentAction.actionType != 1)) {} } for (;;) { if (localDocumentAction != null) { break label266; } Object[] arrayOfObject3 = new Object[2]; arrayOfObject3[0] = str; arrayOfObject3[1] = localDocumentActions.toString(); FinskyLog.d("App %s has no buy or install action, actions=%s", arrayOfObject3); SignatureUtils.logEvent(paramFinskyEventLog, 512, str, "doc-actions", paramString, null); return null; k++; break; localDocumentAction = null; } label266: Locale localLocale = paramContext.getResources().getConfiguration().locale; Bundle localBundle = new Bundle(); localBundle.putString("title", paramDocument.mDocument.title); localBundle.putString("creator", paramDocument.mDocument.creator.toUpperCase(localLocale)); if (paramDocument.hasRating()) { localBundle.putFloat("star_rating", paramDocument.getStarRating()); localBundle.putLong("rating_count", paramDocument.getRatingCount()); } if (!addImage(paramDocument, 4, localBundle)) { if (!addImage(paramDocument, 0, localBundle)) { break label603; } Object[] arrayOfObject2 = new Object[1]; arrayOfObject2[0] = paramDocument.mDocument.docid; FinskyLog.d("App %s using thumbnail image", arrayOfObject2); } for (;;) { PurchaseButtonHelper.TextStyle localTextStyle = new PurchaseButtonHelper.TextStyle(); PurchaseButtonHelper.getActionStyleForFormat(localDocumentAction, i, false, false, localTextStyle); localBundle.putString("purchase_button_text", localTextStyle.getString(paramContext).toUpperCase(localLocale)); Intent localIntent1 = LightPurchaseFlowActivity.createExternalPurchaseIntent$109c371d(paramDocument.mDocument.backendDocid, paramDocument.mDocument.docid, null, paramDocument.mDocument.backendId, paramDocument.mDocument.docType); localIntent1.setData(Uri.fromParts("detailsservice", str, null)); localBundle.putParcelable("purchase_intent", PendingIntent.getActivity(paramContext, 0, localIntent1, 0)); Uri localUri = new Uri.Builder().scheme("market").authority("details").appendQueryParameter("id", str).appendQueryParameter("api_source", "DetailsService").appendQueryParameter("referrer_package", paramString).build(); Intent localIntent2 = new Intent(paramContext, MainActivity.class); localIntent2.setAction("android.intent.action.VIEW"); localIntent2.setData(localUri); localBundle.putParcelable("details_intent", PendingIntent.getActivity(paramContext, 0, localIntent2, 0)); SignatureUtils.logEvent(paramFinskyEventLog, 512, str, null, paramString, null); return localBundle; label603: Object[] arrayOfObject1 = new Object[1]; arrayOfObject1[0] = paramDocument.mDocument.docid; FinskyLog.d("App %s failed to find any image", arrayOfObject1); } } public IBinder onBind(Intent paramIntent) { new IDetailsService.Stub() { public final Bundle getAppDetails(String paramAnonymousString) throws RemoteException { FinskyApp localFinskyApp = FinskyApp.get(); Account localAccount = localFinskyApp.getCurrentAccount(); if (localAccount == null) { return null; } FinskyEventLog localFinskyEventLog = localFinskyApp.getEventLogger(localAccount); if (!((Boolean)G.enableDetailsApi.get()).booleanValue()) { FinskyLog.d("API access is blocked for all apps", new Object[0]); SignatureUtils.logEvent(localFinskyEventLog, 512, paramAnonymousString, "all-access-blocked", null, null); return null; } String str1 = SignatureUtils.getCallingAppIfAuthorized(DetailsService.this, paramAnonymousString, G.enableThirdPartyDetailsApi, localFinskyEventLog, 512); if (str1 == null) { return null; } FinskyLog.d("Received app details request for %s from %s", new Object[] { paramAnonymousString, str1 }); String str2 = DfeUtils.createDetailsUrlFromId(paramAnonymousString); DfeApi localDfeApi = FinskyApp.get().getDfeApi(null); RequestFuture localRequestFuture = RequestFuture.newFuture(); localDfeApi.getDetails(str2, true, true, null, localRequestFuture, localRequestFuture); try { Details.DetailsResponse localDetailsResponse = (Details.DetailsResponse)localRequestFuture.get(); localDocV2 = localDetailsResponse.docV2; if (localDocV2 == null) { FinskyLog.d("No doc in details response for %s", new Object[] { paramAnonymousString }); SignatureUtils.logEvent(localFinskyEventLog, 512, paramAnonymousString, "empty-details-response", str1, null); return null; } } catch (InterruptedException localInterruptedException) { FinskyLog.d("Interrupted while trying to retrieve app details", new Object[0]); SignatureUtils.logEvent(localFinskyEventLog, 512, paramAnonymousString, "fetch-interrupted", str1, null); return null; } catch (ExecutionException localExecutionException) { DocV2 localDocV2; Throwable localThrowable = localExecutionException.getCause(); if (localThrowable == null) {} for (String str3 = null;; str3 = localThrowable.getClass().getSimpleName()) { FinskyLog.d("Unable to retrieve app details: %s", new Object[] { str3 }); SignatureUtils.logEvent(localFinskyEventLog, 512, paramAnonymousString, "fetch-error", str1, str3); return null; } DfeToc localDfeToc = localFinskyApp.mToc; Installer localInstaller = localFinskyApp.mInstaller; AppStates localAppStates = localFinskyApp.mAppStates; localAppStates.mStateStore.load(); Libraries localLibraries = localFinskyApp.mLibraries; localLibraries.blockingLoad(); DetailsService localDetailsService = DetailsService.this; Document localDocument = new Document(localDocV2); return DetailsService.getBundle(localDetailsService, localDocument, localAccount, localDfeToc, localInstaller, localAppStates, localLibraries, str1, localFinskyEventLog); } } }; } } /* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar * Qualified Name: com.google.android.finsky.services.DetailsService * JD-Core Version: 0.7.0.1 */
package com.sap.jam.oauth.client; import java.security.KeyFactory; import java.security.PublicKey; import java.security.PrivateKey; import java.security.Signature; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.io.ByteArrayInputStream; import javax.crypto.Cipher; /** * This utility class has various helpers for working with signatures, certificates, * and private keys. * * For example, generation of a signature, ie, signing data with a private key 2) Verification of such * signatures, ie, verifying signature with a public key/certificate * * Public facing functions fall into one of these two buckets, variations are * overloaded based on different input parameters and renamed based on different * output values (ie, we like to handle base64 encoding so the caller doesn't * need to) * * the notion of a "raw signature" is one that is stored as a java byte array, * and has not been base64 encoded */ public final class SignatureUtil { private final static String SIGNATURE_ALGORITHM = "SHA1withRSA"; private final static String PRIVATE_KEY_ALGORITHM = "RSA"; private final static String PUBLIC_CERT_ALGORITHM = "X.509"; /** * Signature Generation functions all functions take the form signature = * f(private key, signature base) * */ public static String generateBase64Signature( final String privateKeyBase64, final byte[] signatureBase) { return Base64Util.encode(generateRawSignature(makePrivateKey(privateKeyBase64), signatureBase)); } public static String generateBase64Signature(final PrivateKey privateKey, final byte[] signatureBase) { return Base64Util.encode(generateRawSignature(privateKey, signatureBase)); } public static byte[] generateRawSignature(final String privateKeyBase64, final byte[] signatureBase) { return generateRawSignature(makePrivateKey(privateKeyBase64), signatureBase); } public static byte[] generateRawSignature(final PrivateKey privateKey, final byte[] signatureBase) { try { final Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initSign(privateKey); sig.update(signatureBase); return sig.sign(); } catch (final InvalidKeyException e) { throw new RuntimeException("Invalid private key: " + e.getMessage(), e); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Unknown signature generation algorithm (" + SIGNATURE_ALGORITHM + ") " + e.getMessage(), e); } catch (final java.security.SignatureException e) { throw new RuntimeException("Error encountered while signing: " + e.getMessage(), e); } } /** * Signature Verification functions all functions take the form success = * f(public key, signature, signature base) * */ public static boolean verifyBase64Signature(final String base64Certificate, final String base64Signature, final byte[] signatureBase) { return verifyRawSignature(makePublicKey(base64Certificate), getRawSignatureFromBase64(base64Signature), signatureBase); } public static boolean verifyBase64Signature(final PublicKey publicKey, final String base64Signature, final byte[] signatureBase) { return verifyRawSignature(publicKey, getRawSignatureFromBase64(base64Signature), signatureBase); } public static boolean verifyRawSignature(final String base64Certificate, final byte[] rawSignature, final byte[] signatureBase) { return verifyRawSignature(makePublicKey(base64Certificate), rawSignature, signatureBase); } public static boolean verifyRawSignature(final PublicKey publicKey, final byte[] rawSignature, final byte[] signatureBase) { try { final Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signatureBase); return sig.verify(rawSignature); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Unknown signature verification algorithm (" + SIGNATURE_ALGORITHM + ") " + e.getMessage(), e); } catch (final InvalidKeyException e) { throw new RuntimeException("Invalid public key: " + e.getMessage(), e); } catch (final java.security.SignatureException e) { throw new RuntimeException("Error encountered while verifying signature: " + e.getMessage(), e); } } /** * Utility helper functions prevent duplication of work over the various * overloads */ /** * convert basee64 signature to a raw signature */ private static byte[] getRawSignatureFromBase64(final String signature) { return Base64Util.decode(signature); } /** * convert a base64 encoded certificate into a java object public key */ public static PublicKey makePublicKey(final String certificateBase64) { if (certificateBase64 == null || certificateBase64.isEmpty()) { throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty."); } try { final CertificateFactory cf = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM); final Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(Base64Util.decode(certificateBase64))); return certificate.getPublicKey(); } catch (final CertificateException e) { throw new RuntimeException("Unable to generate certificates (" + PUBLIC_CERT_ALGORITHM + ") " + e.getMessage(), e); } } /** * convert a base64 encoded private key into a java object private key */ public static PrivateKey makePrivateKey(final String privateKeyBase64) { if (privateKeyBase64 == null || privateKeyBase64.isEmpty()) { throw new IllegalArgumentException("Supplied 'privateKeyBase64' argument is null or empty."); } try { final KeyFactory key_factory = KeyFactory.getInstance(PRIVATE_KEY_ALGORITHM); final PKCS8EncodedKeySpec private_key_spec = new PKCS8EncodedKeySpec(Base64Util.decode(privateKeyBase64)); return key_factory.generatePrivate(private_key_spec); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Invalid algorithm (" + PRIVATE_KEY_ALGORITHM + "): " + e.getMessage(), e); } catch (final InvalidKeySpecException e) { throw new RuntimeException("Invalid KeySpec: " + e.getMessage(), e); } } public static X509Certificate makeCertificate(String certificateBase64) { if (certificateBase64 == null || certificateBase64.isEmpty()) { throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty."); } try { byte[] certRaw = Base64Util.decode(certificateBase64); CertificateFactory certFactory = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM); return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certRaw)); } catch (Exception e) { throw new RuntimeException("Unable to deserialize supplied X509 certificate.", e); } } /** * @return true if encrypting then decrypting a small test string roundtrips. */ public static boolean validatePrivateKeyCertificateCompatibility(PrivateKey privateKey, X509Certificate certificate) { return validatePrivateKeyPublicKeyCompatibility(privateKey, certificate.getPublicKey()); } /** * @return true if encrypting then decrypting a small test string roundtrips. */ public static boolean validatePrivateKeyPublicKeyCompatibility(PrivateKey privateKey, PublicKey publicKey) { String plainData = "Some text for encryption"; try { byte[] encryptedData = encrypt(plainData.getBytes("UTF-8"), publicKey); byte[] decryptedData = decrypt(encryptedData, privateKey); String plainDataRoundTrip = new String(decryptedData, "UTF-8"); if (plainData.equals(plainDataRoundTrip)) { return true; } } catch (Exception e) { return false; } return false; } static byte[] encrypt(byte[] plainData, PublicKey pubKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] encryptedData = cipher.doFinal(plainData); return encryptedData; } static byte[] decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedData = cipher.doFinal(encryptedData); return decryptedData; } /** * Returns XML suitable for use in .NET code with the RSACryptoServiceProvider.FromXmlString method. * This RSACryptoServiceProvider object can be used in the .NET version of the OAuth libraries in the areas * where we use a PrivateKey object in the Java libraries. * An explanation of the XML used for key formats is here: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsa.toxmlstring.aspx * Thanks to http://www.jensign.com/JavaScience/PvkConvert/ for pointing out that leading zeros must be trimmed for .NET. */ public static String privateKeyToDotNetXml(PrivateKey privateKey) { try{ StringBuilder sb = new StringBuilder(); RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey)privateKey; sb.append("<RSAKeyValue>") ; sb.append("<Modulus>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getModulus().toByteArray())) + "</Modulus>"); sb.append("<Exponent>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPublicExponent().toByteArray())) + "</Exponent>"); sb.append("<P>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrimeP().toByteArray())) + "</P>"); sb.append("<Q>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrimeQ().toByteArray())) + "</Q>"); sb.append("<DP>" +Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrimeExponentP().toByteArray())) + "</DP>"); sb.append("<DQ>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrimeExponentQ().toByteArray())) + "</DQ>"); sb.append("<InverseQ>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getCrtCoefficient().toByteArray())) + "</InverseQ>"); sb.append("<D>" + Base64Util.encode(removeLeadingZeros(rsaPrivateKey.getPrivateExponent().toByteArray())) + "</D>"); sb.append("</RSAKeyValue>") ; return sb.toString(); } catch(Exception e) { throw new IllegalArgumentException("Could not convert PrivateKey to Dot Net XML.", e); } } /** * Returns XML suitable for use in .NET code with the RSACryptoServiceProvider.FromXmlString method. * This RSACryptoServiceProvider object can be used in the .NET version of the OAuth libraries in the areas * where we use a PublicKey object in the Java libraries. * An explanation of the XML used for key formats is here: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsa.toxmlstring.aspx * Thanks to http://www.jensign.com/JavaScience/PvkConvert/ for pointing out that leading zeros must be trimmed for .NET. */ public static String publicKeyToDotNetXml(PublicKey publicKey) { try{ StringBuilder sb = new StringBuilder(); RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey; sb.append("<RSAKeyValue>") ; sb.append("<Modulus>" + Base64Util.encode(removeLeadingZeros(rsaPublicKey.getModulus().toByteArray())) + "</Modulus>"); sb.append("<Exponent>" + Base64Util.encode(removeLeadingZeros(rsaPublicKey.getPublicExponent().toByteArray())) + "</Exponent>"); sb.append("</RSAKeyValue>") ; return sb.toString(); } catch(Exception e) { throw new IllegalArgumentException("Could not convert PublicKey to Dot Net XML.", e); } } private static byte[] removeLeadingZeros(byte[] data) { int len = data.length; if (len < 1) { throw new IllegalArgumentException("non-empty byte array expected."); } int pos; for (pos = 0; pos < len && data[pos] == 0; ++pos) { } if (pos >= len) { throw new IllegalArgumentException("array of zeros not expected."); } if (pos > 0) { byte[] trimmedData = new byte[len - pos]; System.arraycopy(data, pos, trimmedData, 0, len - pos); return trimmedData; } return data; } }
/* * Copyright (c) 2013 by Gerrit Grunwald * * 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 eu.hansolo.enzo.matrixsegment.skin; import eu.hansolo.enzo.common.Util; import eu.hansolo.enzo.matrixsegment.MatrixSegment; import javafx.collections.ListChangeListener; import javafx.scene.control.Skin; import javafx.scene.control.SkinBase; import javafx.scene.effect.BlurType; import javafx.scene.effect.DropShadow; import javafx.scene.effect.InnerShadow; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static eu.hansolo.enzo.matrixsegment.MatrixSegment.Dot; public class MatrixSegmentSkin extends SkinBase<MatrixSegment> implements Skin<MatrixSegment> { private static final double PREFERRED_WIDTH = 71; private static final double PREFERRED_HEIGHT = 100; private static final double MINIMUM_WIDTH = 5; private static final double MINIMUM_HEIGHT = 5; private static final double MAXIMUM_WIDTH = 1024; private static final double MAXIMUM_HEIGHT = 1024; private static double aspectRatio; private Map<MatrixSegment.Dot, Region> dotMap; private List<Region> highlights; private double size; private double width; private double height; private Pane pane; private Region background; private InnerShadow backgroundInnerShadow; private InnerShadow backgroundInnerHighlight; private InnerShadow dotInnerShadow; private DropShadow glow; private Region d57; private Region d47; private Region d37; private Region d27; private Region d17; private Region d56; private Region d46; private Region d36; private Region d26; private Region d16; private Region d55; private Region d45; private Region d35; private Region d25; private Region d15; private Region d54; private Region d44; private Region d34; private Region d24; private Region d14; private Region d53; private Region d43; private Region d33; private Region d23; private Region d13; private Region d52; private Region d42; private Region d32; private Region d22; private Region d12; private Region d51; private Region d41; private Region d31; private Region d21; private Region d11; private Region d57h; private Region d47h; private Region d37h; private Region d27h; private Region d17h; private Region d56h; private Region d46h; private Region d36h; private Region d26h; private Region d16h; private Region d55h; private Region d45h; private Region d35h; private Region d25h; private Region d15h; private Region d54h; private Region d44h; private Region d34h; private Region d24h; private Region d14h; private Region d53h; private Region d43h; private Region d33h; private Region d23h; private Region d13h; private Region d52h; private Region d42h; private Region d32h; private Region d22h; private Region d12h; private Region d51h; private Region d41h; private Region d31h; private Region d21h; private Region d11h; // ******************** Constructors ************************************** public MatrixSegmentSkin(final MatrixSegment CONTROL) { super(CONTROL); aspectRatio = PREFERRED_HEIGHT / PREFERRED_WIDTH; dotMap = new HashMap<>(35); highlights = new ArrayList<>(35); pane = new Pane(); init(); initGraphics(); registerListeners(); } // ******************** Initialization ************************************ private void init() { if (Double.compare(getSkinnable().getPrefWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getPrefHeight(), 0.0) <= 0 || Double.compare(getSkinnable().getWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getHeight(), 0.0) <= 0) { if (getSkinnable().getPrefWidth() > 0 && getSkinnable().getPrefHeight() > 0) { getSkinnable().setPrefSize(getSkinnable().getPrefWidth(), getSkinnable().getPrefHeight()); } else { getSkinnable().setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); } } if (Double.compare(getSkinnable().getMinWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getMinHeight(), 0.0) <= 0) { getSkinnable().setMinSize(MINIMUM_WIDTH, MINIMUM_HEIGHT); } if (Double.compare(getSkinnable().getMaxWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getMaxHeight(), 0.0) <= 0) { getSkinnable().setMaxSize(MAXIMUM_WIDTH, MAXIMUM_HEIGHT); } if (getSkinnable().getPrefWidth() != PREFERRED_WIDTH || getSkinnable().getPrefHeight() != PREFERRED_HEIGHT) { aspectRatio = getSkinnable().getPrefHeight() / getSkinnable().getPrefWidth(); } } private void initGraphics() { background = new Region(); background.getStyleClass().setAll("background"); backgroundInnerShadow = new InnerShadow(); backgroundInnerShadow.setOffsetY(-1.0); backgroundInnerShadow.setRadius(1.0 / 310.0 * PREFERRED_WIDTH); backgroundInnerShadow.setColor(Color.rgb(0, 0, 0, 0.65)); backgroundInnerShadow.setBlurType(BlurType.TWO_PASS_BOX); backgroundInnerHighlight = new InnerShadow(); backgroundInnerHighlight.setOffsetY(1.0); backgroundInnerHighlight.setRadius(1.0 / 310.0 * PREFERRED_WIDTH); backgroundInnerHighlight.setColor(Color.rgb(200, 200, 200, 0.65)); backgroundInnerHighlight.setBlurType(BlurType.TWO_PASS_BOX); backgroundInnerHighlight.setInput(backgroundInnerShadow); background.setEffect(backgroundInnerHighlight); dotInnerShadow = new InnerShadow(); dotInnerShadow.setRadius(0.025 * PREFERRED_WIDTH); dotInnerShadow.setColor(Color.rgb(0, 0, 0, 0.65)); dotInnerShadow.setBlurType(BlurType.TWO_PASS_BOX); glow = new DropShadow(); glow.setInput(dotInnerShadow); glow.setRadius(0.032 * PREFERRED_WIDTH); glow.setColor(getSkinnable().getColor()); glow.setBlurType(BlurType.TWO_PASS_BOX); // dot definitions d57 = new Region(); d57.getStyleClass().add("dot-off"); d57.setEffect(dotInnerShadow); dotMap.put(Dot.D57, d57); d47 = new Region(); d47.getStyleClass().add("dot-off"); d47.setEffect(dotInnerShadow); dotMap.put(Dot.D47, d47); d37 = new Region(); d37.getStyleClass().add("dot-off"); d37.setEffect(dotInnerShadow); dotMap.put(Dot.D37, d37); d27 = new Region(); d27.getStyleClass().add("dot-off"); d27.setEffect(dotInnerShadow); dotMap.put(Dot.D27, d27); d17 = new Region(); d17.getStyleClass().add("dot-off"); d17.setEffect(dotInnerShadow); dotMap.put(Dot.D17, d17); d56 = new Region(); d56.getStyleClass().add("dot-off"); d56.setEffect(dotInnerShadow); dotMap.put(Dot.D56, d56); d46 = new Region(); d46.getStyleClass().add("dot-off"); d46.setEffect(dotInnerShadow); dotMap.put(Dot.D46, d46); d36 = new Region(); d36.getStyleClass().add("dot-off"); d36.setEffect(dotInnerShadow); dotMap.put(Dot.D36, d36); d26 = new Region(); d26.getStyleClass().add("dot-off"); d26.setEffect(dotInnerShadow); dotMap.put(Dot.D26, d26); d16 = new Region(); d16.getStyleClass().add("dot-off"); d16.setEffect(dotInnerShadow); dotMap.put(Dot.D16, d16); d55 = new Region(); d55.getStyleClass().add("dot-off"); d55.setEffect(dotInnerShadow); dotMap.put(Dot.D55, d55); d45 = new Region(); d45.getStyleClass().add("dot-off"); d45.setEffect(dotInnerShadow); dotMap.put(Dot.D45, d45); d35 = new Region(); d35.getStyleClass().add("dot-off"); d35.setEffect(dotInnerShadow); dotMap.put(Dot.D35, d35); d25 = new Region(); d25.getStyleClass().add("dot-off"); d25.setEffect(dotInnerShadow); dotMap.put(Dot.D25, d25); d15 = new Region(); d15.getStyleClass().add("dot-off"); d15.setEffect(dotInnerShadow); dotMap.put(Dot.D15, d15); d54 = new Region(); d54.getStyleClass().add("dot-off"); d54.setEffect(dotInnerShadow); dotMap.put(Dot.D54, d54); d44 = new Region(); d44.getStyleClass().add("dot-off"); d44.setEffect(dotInnerShadow); dotMap.put(Dot.D44, d44); d34 = new Region(); d34.getStyleClass().add("dot-off"); d34.setEffect(dotInnerShadow); dotMap.put(Dot.D34, d34); d24 = new Region(); d24.getStyleClass().add("dot-off"); d24.setEffect(dotInnerShadow); dotMap.put(Dot.D24, d24); d14 = new Region(); d14.getStyleClass().add("dot-off"); d14.setEffect(dotInnerShadow); dotMap.put(Dot.D14, d14); d53 = new Region(); d53.getStyleClass().add("dot-off"); d53.setEffect(dotInnerShadow); dotMap.put(Dot.D53, d53); d43 = new Region(); d43.getStyleClass().add("dot-off"); d43.setEffect(dotInnerShadow); dotMap.put(Dot.D43, d43); d33 = new Region(); d33.getStyleClass().add("dot-off"); d33.setEffect(dotInnerShadow); dotMap.put(Dot.D33, d33); d23 = new Region(); d23.getStyleClass().add("dot-off"); d23.setEffect(dotInnerShadow); dotMap.put(Dot.D23, d23); d13 = new Region(); d13.getStyleClass().add("dot-off"); d13.setEffect(dotInnerShadow); dotMap.put(Dot.D13, d13); d52 = new Region(); d52.getStyleClass().add("dot-off"); d52.setEffect(dotInnerShadow); dotMap.put(Dot.D52, d52); d42 = new Region(); d42.getStyleClass().add("dot-off"); d42.setEffect(dotInnerShadow); dotMap.put(Dot.D42, d42); d32 = new Region(); d32.getStyleClass().add("dot-off"); d32.setEffect(dotInnerShadow); dotMap.put(Dot.D32, d32); d22 = new Region(); d22.getStyleClass().add("dot-off"); d22.setEffect(dotInnerShadow); dotMap.put(Dot.D22, d22); d12 = new Region(); d12.getStyleClass().add("dot-off"); d12.setEffect(dotInnerShadow); dotMap.put(Dot.D12, d12); d51 = new Region(); d51.getStyleClass().add("dot-off"); d51.setEffect(dotInnerShadow); dotMap.put(Dot.D51, d51); d41 = new Region(); d41.getStyleClass().add("dot-off"); d41.setEffect(dotInnerShadow); dotMap.put(Dot.D41, d41); d31 = new Region(); d31.getStyleClass().add("dot-off"); d31.setEffect(dotInnerShadow); dotMap.put(Dot.D31, d31); d21 = new Region(); d21.getStyleClass().add("dot-off"); d21.setEffect(dotInnerShadow); dotMap.put(Dot.D21, d21); d11 = new Region(); d11.getStyleClass().add("dot-off"); d11.setEffect(dotInnerShadow); dotMap.put(Dot.D11, d11); // highlight definitions d57h = new Region(); d57h.getStyleClass().add("dot-highlight"); highlights.add(d57h); d47h = new Region(); d47h.getStyleClass().add("dot-highlight"); highlights.add(d47h); d37h = new Region(); d37h.getStyleClass().add("dot-highlight"); highlights.add(d37h); d27h = new Region(); d27h.getStyleClass().add("dot-highlight"); highlights.add(d27h); d17h = new Region(); d17h.getStyleClass().add("dot-highlight"); highlights.add(d17h); d56h = new Region(); d56h.getStyleClass().add("dot-highlight"); highlights.add(d56h); d46h = new Region(); d46h.getStyleClass().add("dot-highlight"); highlights.add(d46h); d36h = new Region(); d36h.getStyleClass().add("dot-highlight"); highlights.add(d36h); d26h = new Region(); d26h.getStyleClass().add("dot-highlight"); highlights.add(d26h); d16h = new Region(); d16h.getStyleClass().add("dot-highlight"); highlights.add(d16h); d55h = new Region(); d55h.getStyleClass().add("dot-highlight"); highlights.add(d55h); d45h = new Region(); d45h.getStyleClass().add("dot-highlight"); highlights.add(d45h); d35h = new Region(); d35h.getStyleClass().add("dot-highlight"); highlights.add(d35h); d25h = new Region(); d25h.getStyleClass().add("dot-highlight"); highlights.add(d25h); d15h = new Region(); d15h.getStyleClass().add("dot-highlight"); highlights.add(d15h); d54h = new Region(); d54h.getStyleClass().add("dot-highlight"); highlights.add(d54h); d44h = new Region(); d44h.getStyleClass().add("dot-highlight"); highlights.add(d44h); d34h = new Region(); d34h.getStyleClass().add("dot-highlight"); highlights.add(d34h); d24h = new Region(); d24h.getStyleClass().add("dot-highlight"); highlights.add(d24h); d14h = new Region(); d14h.getStyleClass().add("dot-highlight"); highlights.add(d14h); d53h = new Region(); d53h.getStyleClass().add("dot-highlight"); highlights.add(d53h); d43h = new Region(); d43h.getStyleClass().add("dot-highlight"); highlights.add(d43h); d33h = new Region(); d33h.getStyleClass().add("dot-highlight"); highlights.add(d33h); d23h = new Region(); d23h.getStyleClass().add("dot-highlight"); highlights.add(d23h); d13h = new Region(); d13h.getStyleClass().add("dot-highlight"); highlights.add(d13h); d52h = new Region(); d52h.getStyleClass().add("dot-highlight"); highlights.add(d52h); d42h = new Region(); d42h.getStyleClass().add("dot-highlight"); highlights.add(d42h); d32h = new Region(); d32h.getStyleClass().add("dot-highlight"); highlights.add(d32h); d22h = new Region(); d22h.getStyleClass().add("dot-highlight"); highlights.add(d22h); d12h = new Region(); d12h.getStyleClass().add("dot-highlight"); highlights.add(d12h); d51h = new Region(); d51h.getStyleClass().add("dot-highlight"); highlights.add(d51h); d41h = new Region(); d41h.getStyleClass().add("dot-highlight"); highlights.add(d41h); d31h = new Region(); d31h.getStyleClass().add("dot-highlight"); highlights.add(d31h); d21h = new Region(); d21h.getStyleClass().add("dot-highlight"); highlights.add(d21h); d11h = new Region(); d11h.getStyleClass().add("dot-highlight"); highlights.add(d11h); pane.getChildren().setAll(background, d57, d47, d37, d27, d17, d56, d46, d36, d26, d16, d55, d45, d35, d25, d15, d54, d44, d34, d24, d14, d53, d43, d33, d23, d13, d52, d42, d32, d22, d12, d51, d41, d31, d21, d11, d57h, d47h, d37h, d27h, d17h, d56h, d46h, d36h, d26h, d16h, d55h, d45h, d35h, d25h, d15h, d54h, d44h, d34h, d24h, d14h, d53h, d43h, d33h, d23h, d13h, d52h, d42h, d32h, d22h, d12h, d51h, d41h, d31h, d21h, d11h); getChildren().setAll(pane); resize(); updateMatrix(); updateMatrixColor(); for (Region highlight : highlights) { highlight.setOpacity(getSkinnable().isHighlightsVisible() ? 1 : 0); } } private void registerListeners() { getSkinnable().widthProperty().addListener(observable -> handleControlPropertyChanged("RESIZE") ); getSkinnable().heightProperty().addListener(observable -> handleControlPropertyChanged("RESIZE") ); getSkinnable().prefWidthProperty().addListener(observable -> handleControlPropertyChanged("PREF_SIZE") ); getSkinnable().prefHeightProperty().addListener(observable -> handleControlPropertyChanged("PREF_SIZE") ); getSkinnable().colorProperty().addListener(observable -> handleControlPropertyChanged("COLOR") ); getSkinnable().backgroundVisibleProperty().addListener(observable -> handleControlPropertyChanged("BACKGROUND") ); getSkinnable().highlightsVisibleProperty().addListener(observable -> handleControlPropertyChanged("HIGHLIGHTS") ); getSkinnable().characterProperty().addListener(observable -> handleControlPropertyChanged("CHARACTER") ); getSkinnable().glowEnabledProperty().addListener(observable -> handleControlPropertyChanged("GLOW") ); getSkinnable().getStyleClass().addListener(new ListChangeListener<String>() { @Override public void onChanged(Change<? extends String> change) { resize(); } }); } // ******************** Methods ******************************************* protected void handleControlPropertyChanged(final String PROPERTY) { if ("RESIZE".equals(PROPERTY)) { resize(); } else if ("PREF_SIZE".equals(PROPERTY)) { aspectRatio = getSkinnable().getPrefHeight() / getSkinnable().getPrefWidth(); } else if ("COLOR".equals(PROPERTY)) { updateMatrixColor(); } else if ("BACKGROUND".equals(PROPERTY)) { background.setOpacity(getSkinnable().isBackgroundVisible() ? 1 : 0); } else if ("HIGHLIGHTS".equals(PROPERTY)) { for (Region highlight : highlights) { highlight.setOpacity(getSkinnable().isHighlightsVisible() ? 1 : 0); } } else if ("CHARACTER".equals(PROPERTY)) { updateMatrix(); } else if ("GLOW".equals(PROPERTY)) { updateMatrix(); } } @Override protected double computeMinWidth(final double HEIGHT, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { return super.computeMinWidth(Math.max(MINIMUM_HEIGHT, HEIGHT - TOP_INSET - BOTTOM_INSET), TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computeMinHeight(final double WIDTH, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { return super.computeMinHeight(Math.max(MINIMUM_WIDTH, WIDTH - LEFT_INSET - RIGHT_INSET), TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computeMaxWidth(final double HEIGHT, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { return super.computeMaxWidth(Math.min(MAXIMUM_HEIGHT, HEIGHT - TOP_INSET - BOTTOM_INSET), TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computeMaxHeight(final double WIDTH, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { return super.computeMaxHeight(Math.min(MAXIMUM_WIDTH, WIDTH - LEFT_INSET - RIGHT_INSET), TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computePrefWidth(final double HEIGHT, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { double prefHeight = PREFERRED_HEIGHT; if (HEIGHT != -1) { prefHeight = Math.max(0, HEIGHT - TOP_INSET - BOTTOM_INSET); } return super.computePrefWidth(prefHeight, TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } @Override protected double computePrefHeight(final double WIDTH, double TOP_INSET, double RIGHT_INSET, double BOTTOM_INSET, double LEFT_INSET) { double prefWidth = PREFERRED_WIDTH; if (WIDTH != -1) { prefWidth = Math.max(0, WIDTH - LEFT_INSET - RIGHT_INSET); } return super.computePrefHeight(prefWidth, TOP_INSET, RIGHT_INSET, BOTTOM_INSET, LEFT_INSET); } // ******************** Update ******************************************** public void updateMatrixColor() { getSkinnable().setStyle("-dot-on-color: " + Util.colorToCss(getSkinnable().getColor()) + ";"); //getSkinnable().setBackground(new Background(new BackgroundFill(getSkinnable().getColor(), null, null))); glow.setColor(getSkinnable().getColor()); } public void updateMatrix() { final int ASCII = getSkinnable().getCharacter().isEmpty() ? 20 : getSkinnable().getCharacter().toUpperCase().charAt(0); if (getSkinnable().getCustomDotMapping().isEmpty()) { for (Dot dot : dotMap.keySet()) { if (getSkinnable().getDotMapping().containsKey(ASCII)) { if (getSkinnable().getDotMapping().get(ASCII).contains(dot)) { dotMap.get(dot).getStyleClass().setAll("dot-on"); dotMap.get(dot).setEffect(getSkinnable().isGlowEnabled() ? glow : dotInnerShadow); } else { dotMap.get(dot).getStyleClass().setAll("dot-off"); dotMap.get(dot).setEffect(dotInnerShadow); } } else { dotMap.get(dot).getStyleClass().setAll("dot-off"); dotMap.get(dot).setEffect(dotInnerShadow); } } } else { for (Dot dot : dotMap.keySet()) { if (getSkinnable().getCustomDotMapping().containsKey(ASCII)) { if (getSkinnable().getCustomDotMapping().get(ASCII).contains(dot)) { dotMap.get(dot).getStyleClass().setAll("dot-on"); dotMap.get(dot).setEffect(getSkinnable().isGlowEnabled() ? glow : dotInnerShadow); } else { dotMap.get(dot).getStyleClass().setAll("dot-off"); dotMap.get(dot).setEffect(dotInnerShadow); } } else { dotMap.get(dot).getStyleClass().setAll("dot-off"); dotMap.get(dot).setEffect(dotInnerShadow); } } } } // ******************** Resizing ****************************************** private void resize() { size = getSkinnable().getWidth() < getSkinnable().getHeight() ? getSkinnable().getWidth() : getSkinnable().getHeight(); width = getSkinnable().getWidth(); height = getSkinnable().getHeight(); if (aspectRatio * width > height) { width = 1 / (aspectRatio / height); } else if (1 / (aspectRatio / height) > width) { height = aspectRatio * width; } if (width > 0 && height > 0) { // resize the background background.setPrefSize(width, height); backgroundInnerShadow.setRadius(0.0025 * size); backgroundInnerHighlight.setRadius(0.0025 * size); dotInnerShadow.setRadius(0.025 * width); glow.setRadius(0.032 * width); // resize the dots double dotWidth = 0.13548387096774195 * width; double dotHeight = 0.0967741935483871 * height; for (Region dot : dotMap.values()) { dot.setPrefSize(dotWidth, dotHeight); } d57.setTranslateX(0.832258064516129 * width); d57.setTranslateY(0.880184331797235 * height); d47.setTranslateX(0.632258064516129 * width); d47.setTranslateY(0.880184331797235 * height); d37.setTranslateX(0.432258064516129 * width); d37.setTranslateY(0.880184331797235 * height); d27.setTranslateX(0.23225806451612904 * width); d27.setTranslateY(0.880184331797235 * height); d17.setTranslateX(0.03225806451612903 * width); d17.setTranslateY(0.880184331797235 * height); d56.setTranslateX(0.832258064516129 * width); d56.setTranslateY(0.7373271889400922 * height); d46.setTranslateX(0.632258064516129 * width); d46.setTranslateY(0.7373271889400922 * height); d36.setTranslateX(0.432258064516129 * width); d36.setTranslateY(0.7373271889400922 * height); d26.setTranslateX(0.23225806451612904 * width); d26.setTranslateY(0.7373271889400922 * height); d16.setTranslateX(0.03225806451612903 * width); d16.setTranslateY(0.7373271889400922 * height); d55.setTranslateX(0.832258064516129 * width); d55.setTranslateY(0.5944700460829493 * height); d45.setTranslateX(0.632258064516129 * width); d45.setTranslateY(0.5944700460829493 * height); d35.setTranslateX(0.432258064516129 * width); d35.setTranslateY(0.5944700460829493 * height); d25.setTranslateX(0.23225806451612904 * width); d25.setTranslateY(0.5944700460829493 * height); d15.setTranslateX(0.03225806451612903 * width); d15.setTranslateY(0.5944700460829493 * height); d54.setTranslateX(0.832258064516129 * width); d54.setTranslateY(0.45161290322580644 * height); d44.setTranslateX(0.632258064516129 * width); d44.setTranslateY(0.45161290322580644 * height); d34.setTranslateX(0.432258064516129 * width); d34.setTranslateY(0.45161290322580644 * height); d24.setTranslateX(0.23225806451612904 * width); d24.setTranslateY(0.45161290322580644 * height); d14.setTranslateX(0.03225806451612903 * width); d14.setTranslateY(0.45161290322580644 * height); d53.setTranslateX(0.832258064516129 * width); d53.setTranslateY(0.3087557603686636 * height); d43.setTranslateX(0.632258064516129 * width); d43.setTranslateY(0.3087557603686636 * height); d33.setTranslateX(0.432258064516129 * width); d33.setTranslateY(0.3087557603686636 * height); d23.setTranslateX(0.23225806451612904 * width); d23.setTranslateY(0.3087557603686636 * height); d13.setTranslateX(0.03225806451612903 * width); d13.setTranslateY(0.3087557603686636 * height); d52.setTranslateX(0.832258064516129 * width); d52.setTranslateY(0.16589861751152074 * height); d42.setTranslateX(0.632258064516129 * width); d42.setTranslateY(0.16589861751152074 * height); d32.setTranslateX(0.432258064516129 * width); d32.setTranslateY(0.16589861751152074 * height); d22.setTranslateX(0.23225806451612904 * width); d22.setTranslateY(0.16589861751152074 * height); d12.setTranslateX(0.03225806451612903 * width); d12.setTranslateY(0.16589861751152074 * height); d51.setTranslateX(0.832258064516129 * width); d51.setTranslateY(0.02304147465437788 * height); d41.setTranslateX(0.632258064516129 * width); d41.setTranslateY(0.02304147465437788 * height); d31.setTranslateX(0.432258064516129 * width); d31.setTranslateY(0.02304147465437788 * height); d21.setTranslateX(0.23225806451612904 * width); d21.setTranslateY(0.02304147465437788 * height); d11.setTranslateX(0.03225806451612903 * width); d11.setTranslateY(0.02304147465437788 * height); // resize the highlights double highlightWidth = 0.07741935483870968 * width; double highlightHeight = 0.03456221198156682 * height; for (Region highlight : highlights) { highlight.setPrefSize(highlightWidth, highlightHeight); } d57h.setTranslateX(0.8612903225806452 * width); d57h.setTranslateY(0.8894009216589862 * height); d47h.setTranslateX(0.6612903225806451 * width); d47h.setTranslateY(0.8894009216589862 * height); d37h.setTranslateX(0.4612903225806452 * width); d37h.setTranslateY(0.8894009216589862 * height); d27h.setTranslateX(0.26129032258064516 * width); d27h.setTranslateY(0.8894009216589862 * height); d17h.setTranslateX(0.06129032258064516 * width); d17h.setTranslateY(0.8894009216589862 * height); d56h.setTranslateX(0.8612903225806452 * width); d56h.setTranslateY(0.7465437788018433 * height); d46h.setTranslateX(0.6612903225806451 * width); d46h.setTranslateY(0.7465437788018433 * height); d36h.setTranslateX(0.4612903225806452 * width); d36h.setTranslateY(0.7465437788018433 * height); d26h.setTranslateX(0.26129032258064516 * width); d26h.setTranslateY(0.7465437788018433 * height); d16h.setTranslateX(0.06129032258064516 * width); d16h.setTranslateY(0.7465437788018433 * height); d55h.setTranslateX(0.8612903225806452 * width); d55h.setTranslateY(0.6036866359447005 * height); d45h.setTranslateX(0.6612903225806451 * width); d45h.setTranslateY(0.6036866359447005 * height); d35h.setTranslateX(0.4612903225806452 * width); d35h.setTranslateY(0.6036866359447005 * height); d25h.setTranslateX(0.26129032258064516 * width); d25h.setTranslateY(0.6036866359447005 * height); d15h.setTranslateX(0.06129032258064516 * width); d15h.setTranslateY(0.6036866359447005 * height); d54h.setTranslateX(0.8612903225806452 * width); d54h.setTranslateY(0.4608294930875576 * height); d44h.setTranslateX(0.6612903225806451 * width); d44h.setTranslateY(0.4608294930875576 * height); d34h.setTranslateX(0.4612903225806452 * width); d34h.setTranslateY(0.4608294930875576 * height); d24h.setTranslateX(0.26129032258064516 * width); d24h.setTranslateY(0.4608294930875576 * height); d14h.setTranslateX(0.06129032258064516 * width); d14h.setTranslateY(0.4608294930875576 * height); d53h.setTranslateX(0.8612903225806452 * width); d53h.setTranslateY(0.31797235023041476 * height); d43h.setTranslateX(0.6612903225806451 * width); d43h.setTranslateY(0.31797235023041476 * height); d33h.setTranslateX(0.4612903225806452 * width); d33h.setTranslateY(0.31797235023041476 * height); d23h.setTranslateX(0.26129032258064516 * width); d23h.setTranslateY(0.31797235023041476 * height); d13h.setTranslateX(0.06129032258064516 * width); d13h.setTranslateY(0.31797235023041476 * height); d52h.setTranslateX(0.8612903225806452 * width); d52h.setTranslateY(0.17511520737327188 * height); d42h.setTranslateX(0.6612903225806451 * width); d42h.setTranslateY(0.17511520737327188 * height); d32h.setTranslateX(0.4612903225806452 * width); d32h.setTranslateY(0.17511520737327188 * height); d22h.setTranslateX(0.26129032258064516 * width); d22h.setTranslateY(0.17511520737327188 * height); d12h.setTranslateX(0.06129032258064516 * width); d12h.setTranslateY(0.17511520737327188 * height); d51h.setTranslateX(0.8612903225806452 * width); d51h.setTranslateY(0.03225806451612903 * height); d41h.setTranslateX(0.6612903225806451 * width); d41h.setTranslateY(0.03225806451612903 * height); d31h.setTranslateX(0.4612903225806452 * width); d31h.setTranslateY(0.03225806451612903 * height); d21h.setTranslateX(0.26129032258064516 * width); d21h.setTranslateY(0.03225806451612903 * height); d11h.setTranslateX(0.06129032258064516 * width); d11h.setTranslateY(0.03225806451612903 * height); } } }
package com.hazelcast.simulator.worker; import com.hazelcast.simulator.common.messaging.Message; import com.hazelcast.simulator.probes.probes.IntervalProbe; import com.hazelcast.simulator.probes.probes.Probes; import com.hazelcast.simulator.probes.probes.ProbesConfiguration; import com.hazelcast.simulator.probes.probes.ProbesType; import com.hazelcast.simulator.probes.probes.Result; import com.hazelcast.simulator.probes.probes.SimpleProbe; import com.hazelcast.simulator.test.TestCase; import com.hazelcast.simulator.test.TestContext; import com.hazelcast.simulator.test.TestPhase; import com.hazelcast.simulator.test.annotations.Performance; import com.hazelcast.simulator.test.annotations.Receive; import com.hazelcast.simulator.test.annotations.Run; import com.hazelcast.simulator.test.annotations.RunWithWorker; import com.hazelcast.simulator.test.annotations.Setup; import com.hazelcast.simulator.test.annotations.Teardown; import com.hazelcast.simulator.test.annotations.Verify; import com.hazelcast.simulator.test.annotations.Warmup; import com.hazelcast.simulator.utils.AnnotationFilter.TeardownFilter; import com.hazelcast.simulator.utils.AnnotationFilter.VerifyFilter; import com.hazelcast.simulator.utils.AnnotationFilter.WarmupFilter; import com.hazelcast.simulator.utils.ThreadSpawner; import com.hazelcast.simulator.worker.tasks.AbstractWorker; import com.hazelcast.simulator.worker.tasks.IWorker; import com.hazelcast.util.Clock; import org.apache.log4j.Logger; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; 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.concurrent.ConcurrentHashMap; import static com.hazelcast.simulator.utils.AnnotationReflectionUtils.getAtMostOneMethodWithoutArgs; import static com.hazelcast.simulator.utils.AnnotationReflectionUtils.getAtMostOneVoidMethodSkipArgsCheck; import static com.hazelcast.simulator.utils.AnnotationReflectionUtils.getAtMostOneVoidMethodWithoutArgs; import static com.hazelcast.simulator.utils.AnnotationReflectionUtils.getValueFromNameAnnotation; import static com.hazelcast.simulator.utils.AnnotationReflectionUtils.getValueFromNameAnnotations; import static com.hazelcast.simulator.utils.PropertyBindingSupport.bindOptionalProperty; import static com.hazelcast.simulator.utils.ReflectionUtils.getField; import static com.hazelcast.simulator.utils.ReflectionUtils.injectObjectToInstance; import static com.hazelcast.simulator.utils.ReflectionUtils.invokeMethod; import static java.lang.String.format; /** * Since the test is based on annotations there is no API we can call easily. * That is the task of this test container. * * @param <T> Class of type {@link com.hazelcast.simulator.test.TestContext} */ public class TestContainer<T extends TestContext> { /** * List of optional test properties, which are allowed to be defined in the properties file, but not in the test class. */ public static final Set<String> OPTIONAL_TEST_PROPERTIES; private static final Logger LOGGER = Logger.getLogger(TestContainer.class); private enum OptionalTestProperties { THREAD_COUNT("threadCount"), WORKER_PROBE_TYPE("workerProbeType"), LOG_FREQUENCY("logFrequency"); private final String propertyName; OptionalTestProperties(String propertyName) { this.propertyName = propertyName; } } static { Set<String> optionalTestProperties = new HashSet<String>(); for (OptionalTestProperties optionalTestProperty : OptionalTestProperties.values()) { optionalTestProperties.add(optionalTestProperty.propertyName); } OPTIONAL_TEST_PROPERTIES = Collections.unmodifiableSet(optionalTestProperties); } // properties int threadCount = 10; String workerProbeType = ProbesType.WORKER.getName(); private final Object testClassInstance; private final Class testClassType; private final T testContext; private final ProbesConfiguration probesConfiguration; private final TestCase testCase; private final Map<String, SimpleProbe<?, ?>> probeMap = new ConcurrentHashMap<String, SimpleProbe<?, ?>>(); private Method runMethod; private Method runWithWorkerMethod; private Method setupMethod; private Object[] setupArguments; private Method localWarmupMethod; private Method globalWarmupMethod; private Method localVerifyMethod; private Method globalVerifyMethod; private Method localTeardownMethod; private Method globalTeardownMethod; private Method operationCountMethod; private Method messageConsumerMethod; private IWorker operationCountWorkerInstance; private ThreadSpawner workerThreadSpawner; public TestContainer(Object testObject, T testContext, ProbesConfiguration probesConfiguration, TestCase testCase) { if (testObject == null) { throw new NullPointerException(); } if (testContext == null) { throw new NullPointerException(); } this.testClassInstance = testObject; this.testClassType = testObject.getClass(); this.testContext = testContext; this.probesConfiguration = probesConfiguration; this.testCase = testCase; initMethods(); } public Map<String, Result<?>> getProbeResults() { Map<String, Result<?>> results = new HashMap<String, Result<?>>(probeMap.size()); for (Map.Entry<String, SimpleProbe<?, ?>> entry : probeMap.entrySet()) { String probeName = entry.getKey(); SimpleProbe<?, ?> probe = entry.getValue(); if (!probe.isDisabled()) { Result<?> result = probe.getResult(); results.put(probeName, result); } } return results; } public T getTestContext() { return testContext; } public long getOperationCount() { try { Long count = invokeMethod((operationCountWorkerInstance != null) ? operationCountWorkerInstance : testClassInstance, operationCountMethod); return (count == null ? -1 : count); } catch (Exception e) { LOGGER.debug("Exception while retrieving operation count from " + testCase.getId() + ": " + e.getMessage()); return -1; } } public List<String> getStackTraces() throws Exception { if (workerThreadSpawner == null) { return Collections.emptyList(); } return workerThreadSpawner.getStackTraces(); } public void sendMessage(Message message) throws Exception { invokeMethod(testClassInstance, messageConsumerMethod, message); } public void invoke(TestPhase testPhase) throws Exception { switch (testPhase) { case SETUP: invokeMethod(testClassInstance, setupMethod, setupArguments); break; case LOCAL_WARMUP: invokeMethod(testClassInstance, localWarmupMethod); break; case GLOBAL_WARMUP: invokeMethod(testClassInstance, globalWarmupMethod); break; case RUN: run(); break; case GLOBAL_VERIFY: invokeMethod(testClassInstance, globalVerifyMethod); break; case LOCAL_VERIFY: invokeMethod(testClassInstance, localVerifyMethod); break; case GLOBAL_TEARDOWN: invokeMethod(testClassInstance, globalTeardownMethod); break; case LOCAL_TEARDOWN: invokeMethod(testClassInstance, localTeardownMethod); break; default: throw new UnsupportedOperationException("Unsupported test phase: " + testPhase); } } private void run() throws Exception { long now = Clock.currentTimeMillis(); for (SimpleProbe probe : probeMap.values()) { probe.startProbing(now); } if (runWithWorkerMethod != null) { invokeRunWithWorkerMethod(now); } else { invokeMethod(testClassInstance, runMethod); } now = Clock.currentTimeMillis(); for (SimpleProbe probe : probeMap.values()) { probe.stopProbing(now); } } private void initMethods() { try { runMethod = getAtMostOneVoidMethodWithoutArgs(testClassType, Run.class); runWithWorkerMethod = getAtMostOneMethodWithoutArgs(testClassType, RunWithWorker.class, IWorker.class); if (!(runMethod == null ^ runWithWorkerMethod == null)) { throw new IllegalTestException( format("Test must contain either %s or %s method", Run.class, RunWithWorker.class)); } setupMethod = getAtMostOneVoidMethodSkipArgsCheck(testClassType, Setup.class); if (setupMethod != null) { assertSetupArguments(setupMethod); setupArguments = getSetupArguments(setupMethod); } localWarmupMethod = getAtMostOneVoidMethodWithoutArgs(testClassType, Warmup.class, new WarmupFilter(false)); globalWarmupMethod = getAtMostOneVoidMethodWithoutArgs(testClassType, Warmup.class, new WarmupFilter(true)); localVerifyMethod = getAtMostOneVoidMethodWithoutArgs(testClassType, Verify.class, new VerifyFilter(false)); globalVerifyMethod = getAtMostOneVoidMethodWithoutArgs(testClassType, Verify.class, new VerifyFilter(true)); localTeardownMethod = getAtMostOneVoidMethodWithoutArgs(testClassType, Teardown.class, new TeardownFilter(false)); globalTeardownMethod = getAtMostOneVoidMethodWithoutArgs(testClassType, Teardown.class, new TeardownFilter(true)); operationCountMethod = getAtMostOneMethodWithoutArgs(testClassType, Performance.class, Long.TYPE); messageConsumerMethod = getAtMostOneVoidMethodSkipArgsCheck(testClassType, Receive.class); if (messageConsumerMethod != null) { assertArguments(messageConsumerMethod, Message.class); } } catch (Exception e) { throw new IllegalTestException(e.getMessage()); } injectDependencies(); } private void assertSetupArguments(Method method) { Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length < 1) { return; } boolean testContextFound = false; boolean illegalArgumentFound = false; for (Class<?> parameterType : parameterTypes) { boolean isObject = parameterType.isAssignableFrom(Object.class); if (!isObject && parameterType.isAssignableFrom(TestContext.class)) { testContextFound = true; } else if (!parameterType.isAssignableFrom(IntervalProbe.class) || isObject) { illegalArgumentFound = true; break; } } if (!testContextFound || illegalArgumentFound) { throw new IllegalTestException( format("Method %s.%s must have argument of type %s and zero or more arguments of type %s", testClassType, method, TestContext.class, SimpleProbe.class)); } } private void assertArguments(Method method, Class... arguments) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != arguments.length) { throw new IllegalTestException( format("Method %s must have %s arguments, but %s arguments found", method, arguments.length, parameterTypes.length)); } for (int i = 0; i < arguments.length; i++) { if (!parameterTypes[i].isAssignableFrom(arguments[i])) { throw new IllegalTestException( format("Method %s has argument of type %s at index %d where type %s is expected", method, parameterTypes[i], i + 1, arguments[i])); } } } private Object[] getSetupArguments(Method setupMethod) { Class[] parameterTypes = setupMethod.getParameterTypes(); Annotation[][] parameterAnnotations = setupMethod.getParameterAnnotations(); Object[] arguments = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { arguments[i] = getSetupArgumentForParameterType(parameterTypes[i], parameterAnnotations[i], i); } return arguments; } private Object getSetupArgumentForParameterType(Class<?> parameterType, Annotation[] parameterAnnotations, int index) { if (parameterType.isAssignableFrom(TestContext.class)) { return testContext; } String probeName = getValueFromNameAnnotations(parameterAnnotations, "Probe" + index); if (IntervalProbe.class.equals(parameterType)) { return getOrCreateConcurrentProbe(probeName, IntervalProbe.class); } if (SimpleProbe.class.equals(parameterType)) { SimpleProbe probe = getOrCreateConcurrentProbe(probeName, SimpleProbe.class); probeMap.put(probeName, probe); return probe; } throw new IllegalTestException(format("Unknown parameter type %s at index %s in setup method", parameterType, index)); } private void injectDependencies() { Field[] fields = testClassType.getDeclaredFields(); for (Field field : fields) { String probeName = getValueFromNameAnnotation(field); if (SimpleProbe.class.equals(field.getType())) { SimpleProbe probe = getOrCreateConcurrentProbe(probeName, SimpleProbe.class); injectObjectToInstance(testClassInstance, field, probe); } else if (IntervalProbe.class.equals(field.getType())) { IntervalProbe probe = getOrCreateConcurrentProbe(probeName, IntervalProbe.class); injectObjectToInstance(testClassInstance, field, probe); } } } @SuppressWarnings("unchecked") private <P extends SimpleProbe> P getOrCreateConcurrentProbe(String probeName, Class<P> targetClassType) { SimpleProbe<?, ?> probe = probeMap.get(probeName); if (probe == null) { probe = Probes.createConcurrentProbe(probeName, targetClassType, probesConfiguration); probeMap.put(probeName, probe); return (P) probe; } if (!probe.getClass().isAssignableFrom(targetClassType)) { throw new IllegalArgumentException(format("Probe \"%s\" of type %s does not match requested probe type %s", probeName, probe.getClass().getSimpleName(), targetClassType.getSimpleName())); } return (P) probe; } private void invokeRunWithWorkerMethod(long now) throws Exception { bindOptionalProperty(this, testCase, OptionalTestProperties.THREAD_COUNT.propertyName); bindOptionalProperty(this, testCase, OptionalTestProperties.WORKER_PROBE_TYPE.propertyName); String testId = (testContext.getTestId().isEmpty() ? "Default" : testContext.getTestId()); String probeName = testId + "IntervalProbe"; if (ProbesType.getProbeType((workerProbeType)) == null) { LOGGER.warn("Illegal argument workerProbeType: " + workerProbeType); workerProbeType = ProbesType.WORKER.getName(); } LOGGER.info(format("Spawning %d worker threads for test %s with %s probe", threadCount, testId, workerProbeType)); if (threadCount <= 0) { return; } // create instance to get class of worker Class workerClass = invokeMethod(testClassInstance, runWithWorkerMethod).getClass(); Field testContextField = getField(workerClass, "testContext", TestContext.class); Field intervalProbeField = getField(workerClass, "intervalProbe", IntervalProbe.class); Method optionalMethod = getAtMostOneMethodWithoutArgs(workerClass, Performance.class, Long.TYPE); if (optionalMethod != null) { operationCountMethod = optionalMethod; } // create one concurrent probe per test and inject it in all worker instances of the test probesConfiguration.addConfig(probeName, workerProbeType); IntervalProbe intervalProbe = getOrCreateConcurrentProbe(probeName, IntervalProbe.class); intervalProbe.startProbing(now); operationCountMethod = getAtMostOneMethodWithoutArgs(AbstractWorker.class, Performance.class, Long.TYPE); // spawn worker and wait for completion spawnWorkerThreads(testContextField, intervalProbeField, intervalProbe); // call the afterCompletion method on a single instance of the worker operationCountWorkerInstance.afterCompletion(); } private void spawnWorkerThreads(Field testContextField, Field intervalProbeField, IntervalProbe intervalProbe) throws Exception { workerThreadSpawner = new ThreadSpawner(testContext.getTestId()); for (int i = 0; i < threadCount; i++) { IWorker worker = invokeMethod(testClassInstance, runWithWorkerMethod); if (testContextField != null) { injectObjectToInstance(worker, testContextField, testContext); } if (intervalProbeField != null) { injectObjectToInstance(worker, intervalProbeField, intervalProbe); } bindOptionalProperty(worker, testCase, OptionalTestProperties.LOG_FREQUENCY.propertyName); operationCountWorkerInstance = worker; workerThreadSpawner.spawn(worker); } workerThreadSpawner.awaitCompletion(); } boolean hasProbe(String probeName) { return probeMap.keySet().contains(probeName); } }
/* * Copyright (C) 2017 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.google.android.exoplayer2.text.ssa; import android.text.TextUtils; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.text.Cue; import com.google.android.exoplayer2.text.SimpleSubtitleDecoder; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Log; import com.google.android.exoplayer2.util.LongArray; import com.google.android.exoplayer2.util.ParsableByteArray; import com.google.android.exoplayer2.util.Util; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A {@link SimpleSubtitleDecoder} for SSA/ASS. */ public final class SsaDecoder extends SimpleSubtitleDecoder { private static final String TAG = "SsaDecoder"; private static final Pattern SSA_TIMECODE_PATTERN = Pattern.compile( "(?:(\\d+):)?(\\d+):(\\d+)(?::|\\.)(\\d+)"); private static final String FORMAT_LINE_PREFIX = "Format: "; private static final String DIALOGUE_LINE_PREFIX = "Dialogue: "; private final boolean haveInitializationData; private int formatKeyCount; private int formatStartIndex; private int formatEndIndex; private int formatTextIndex; public SsaDecoder() { this(null); } /** * @param initializationData Optional initialization data for the decoder. If not null or empty, * the initialization data must consist of two byte arrays. The first must contain an SSA * format line. The second must contain an SSA header that will be assumed common to all * samples. */ public SsaDecoder(List<byte[]> initializationData) { super("SsaDecoder"); if (initializationData != null && !initializationData.isEmpty()) { haveInitializationData = true; String formatLine = Util.fromUtf8Bytes(initializationData.get(0)); Assertions.checkArgument(formatLine.startsWith(FORMAT_LINE_PREFIX)); parseFormatLine(formatLine); parseHeader(new ParsableByteArray(initializationData.get(1))); } else { haveInitializationData = false; } } @Override protected SsaSubtitle decode(byte[] bytes, int length, boolean reset) { ArrayList<Cue> cues = new ArrayList<>(); LongArray cueTimesUs = new LongArray(); ParsableByteArray data = new ParsableByteArray(bytes, length); if (!haveInitializationData) { parseHeader(data); } parseEventBody(data, cues, cueTimesUs); Cue[] cuesArray = new Cue[cues.size()]; cues.toArray(cuesArray); long[] cueTimesUsArray = cueTimesUs.toArray(); return new SsaSubtitle(cuesArray, cueTimesUsArray); } /** * Parses the header of the subtitle. * * @param data A {@link ParsableByteArray} from which the header should be read. */ private void parseHeader(ParsableByteArray data) { String currentLine; while ((currentLine = data.readLine()) != null) { // TODO: Parse useful data from the header. if (currentLine.startsWith("[Events]")) { // We've reached the event body. return; } } } /** * Parses the event body of the subtitle. * * @param data A {@link ParsableByteArray} from which the body should be read. * @param cues A list to which parsed cues will be added. * @param cueTimesUs An array to which parsed cue timestamps will be added. */ private void parseEventBody(ParsableByteArray data, List<Cue> cues, LongArray cueTimesUs) { String currentLine; while ((currentLine = data.readLine()) != null) { if (!haveInitializationData && currentLine.startsWith(FORMAT_LINE_PREFIX)) { parseFormatLine(currentLine); } else if (currentLine.startsWith(DIALOGUE_LINE_PREFIX)) { parseDialogueLine(currentLine, cues, cueTimesUs); } } } /** * Parses a format line. * * @param formatLine The line to parse. */ private void parseFormatLine(String formatLine) { String[] values = TextUtils.split(formatLine.substring(FORMAT_LINE_PREFIX.length()), ","); formatKeyCount = values.length; formatStartIndex = C.INDEX_UNSET; formatEndIndex = C.INDEX_UNSET; formatTextIndex = C.INDEX_UNSET; for (int i = 0; i < formatKeyCount; i++) { String key = Util.toLowerInvariant(values[i].trim()); switch (key) { case "start": formatStartIndex = i; break; case "end": formatEndIndex = i; break; case "text": formatTextIndex = i; break; default: // Do nothing. break; } } if (formatStartIndex == C.INDEX_UNSET || formatEndIndex == C.INDEX_UNSET || formatTextIndex == C.INDEX_UNSET) { // Set to 0 so that parseDialogueLine skips lines until a complete format line is found. formatKeyCount = 0; } } /** * Parses a dialogue line. * * @param dialogueLine The line to parse. * @param cues A list to which parsed cues will be added. * @param cueTimesUs An array to which parsed cue timestamps will be added. */ private void parseDialogueLine(String dialogueLine, List<Cue> cues, LongArray cueTimesUs) { if (formatKeyCount == 0) { Log.w(TAG, "Skipping dialogue line before complete format: " + dialogueLine); return; } String[] lineValues = dialogueLine.substring(DIALOGUE_LINE_PREFIX.length()) .split(",", formatKeyCount); if (lineValues.length != formatKeyCount) { Log.w(TAG, "Skipping dialogue line with fewer columns than format: " + dialogueLine); return; } long startTimeUs = SsaDecoder.parseTimecodeUs(lineValues[formatStartIndex]); if (startTimeUs == C.TIME_UNSET) { Log.w(TAG, "Skipping invalid timing: " + dialogueLine); return; } long endTimeUs = C.TIME_UNSET; String endTimeString = lineValues[formatEndIndex]; if (!endTimeString.trim().isEmpty()) { endTimeUs = SsaDecoder.parseTimecodeUs(endTimeString); if (endTimeUs == C.TIME_UNSET) { Log.w(TAG, "Skipping invalid timing: " + dialogueLine); return; } } String text = lineValues[formatTextIndex] .replaceAll("\\{.*?\\}", "") .replaceAll("\\\\N", "\n") .replaceAll("\\\\n", "\n"); cues.add(new Cue(text)); cueTimesUs.add(startTimeUs); if (endTimeUs != C.TIME_UNSET) { cues.add(null); cueTimesUs.add(endTimeUs); } } /** * Parses an SSA timecode string. * * @param timeString The string to parse. * @return The parsed timestamp in microseconds. */ public static long parseTimecodeUs(String timeString) { Matcher matcher = SSA_TIMECODE_PATTERN.matcher(timeString); if (!matcher.matches()) { return C.TIME_UNSET; } long timestampUs = Long.parseLong(matcher.group(1)) * 60 * 60 * C.MICROS_PER_SECOND; timestampUs += Long.parseLong(matcher.group(2)) * 60 * C.MICROS_PER_SECOND; timestampUs += Long.parseLong(matcher.group(3)) * C.MICROS_PER_SECOND; timestampUs += Long.parseLong(matcher.group(4)) * 10000; // 100ths of a second. return timestampUs; } }
/* * Copyright 2015 Ayuget * * 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.ayuget.redface.ui.activity; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.customtabs.CustomTabsIntent; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import com.ayuget.redface.BuildConfig; import com.ayuget.redface.RedfaceApp; import com.ayuget.redface.R; import com.ayuget.redface.settings.RedfaceSettings; import com.ayuget.redface.ui.customtabs.CustomTabActivityHelper; import com.ayuget.redface.ui.misc.ThemeManager; import com.ayuget.redface.ui.misc.UiUtils; import com.ayuget.redface.util.ViewServer; import io.fabric.sdk.android.Fabric; import com.crashlytics.android.Crashlytics; import com.squareup.otto.Bus; import javax.inject.Inject; import butterknife.ButterKnife; import rx.Subscription; import rx.subscriptions.CompositeSubscription; public class BaseActivity extends AppCompatActivity { @Inject RedfaceSettings settings; @Inject Bus bus; @Inject ThemeManager themeManager; private CompositeSubscription subscriptions; private CustomTabActivityHelper customTab; /** * Dummy callback, no necessary warmup for now */ private final CustomTabActivityHelper.ConnectionCallback customTabConnect = new CustomTabActivityHelper.ConnectionCallback() { @Override public void onCustomTabsConnected() { } @Override public void onCustomTabsDisconnected() { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fabric.with(this, new Crashlytics()); RedfaceApp app = RedfaceApp.get(this); app.inject(this); initializeTheme(); // Proper RxJava subscriptions management with CompositeSubscription subscriptions = new CompositeSubscription(); // Necessary to inspect view hierarchy if (BuildConfig.DEBUG) { ViewServer.get(this).addWindow(this); } customTab = new CustomTabActivityHelper(); customTab.setConnectionCallback(customTabConnect); } @Override protected void onStart() { super.onStart(); // Proper RxJava subscriptions management with CompositeSubscription subscriptions = new CompositeSubscription(); bus.register(this); customTab.bindCustomTabsService(this); } @Override protected void onStop() { super.onStop(); bus.unregister(this); customTab.unbindCustomTabsService(this); subscriptions.unsubscribe(); } @Override protected void onResume() { super.onResume(); if (themeManager.isRefreshNeeded()) { themeManager.setRefreshNeeded(false); refreshTheme(); } if (BuildConfig.DEBUG) { ViewServer.get(this).setFocusedWindow(this); } } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); ButterKnife.inject(this); } /** * Sets the content view and calls the appropriate Ui initialization callbacks * based on the saved instance state */ public void setContentView(int layoutResID, Bundle savedInstanceState) { super.setContentView(layoutResID); ButterKnife.inject(this); onInitUiState(); if (savedInstanceState == null) { onSetupUiState(); } else { onRestoreUiState(savedInstanceState); } } /** * Initializes UI state. Always called when setContentView(layoutResID, savedInstanceState) is called */ protected void onInitUiState() { } /** * Sets up UI state, called if no saved instance state was provided when the activity was created */ protected void onSetupUiState() { } /** * Custom callback to restore (mostly fragments) state, because onRestoreInstanceState() is called * too late in the activity lifecycle * @param savedInstanceState saved state */ protected void onRestoreUiState(Bundle savedInstanceState) { } @Override protected void onDestroy() { customTab.setConnectionCallback(null); super.onDestroy(); if (BuildConfig.DEBUG) { ViewServer.get(this).removeWindow(this); } } protected void initializeTheme() { getWindow().setBackgroundDrawable(null); setTheme(themeManager.getActiveThemeStyle()); // Status bar color is forced this way (thus overriding the statusBarColor attributes in the // theme) because of a weird issue of status bar color not respecting the active theme // on context change (orientation, ...) if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ getWindow().setStatusBarColor(UiUtils.getStatusBarBackgroundColor(this)); } } protected void subscribe(Subscription s) { subscriptions.add(s); } public void refreshTheme() { finish(); Intent intent = new Intent(this, TopicsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); finish(); } public DrawerLayout getDrawerLayout() { return (DrawerLayout) findViewById(R.id.hfr_drawer_layout); } public RedfaceSettings getSettings() { return settings; } public void openLink(String url) { if (settings.isInternalBrowserEnabled()) { CustomTabActivityHelper.openCustomTab( this, new CustomTabsIntent.Builder() .setToolbarColor(UiUtils.getInternalBrowserToolbarColor(this)) .build(), Uri.parse(url)); } else { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } } }
/* * Copyright 2018 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 androidx.biometric; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.text.TextUtils; import android.util.Log; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.RestrictTo; import androidx.biometric.BiometricManager.Authenticators; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentManager; import androidx.lifecycle.DefaultLifecycleObserver; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStoreOwner; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.ref.WeakReference; import java.security.Signature; import java.util.concurrent.Executor; import javax.crypto.Cipher; import javax.crypto.Mac; /** * A class that manages a system-provided biometric prompt. On devices running Android 9.0 (API 28) * and above, this will show a system-provided authentication prompt, using one of the device's * supported biometric modalities (fingerprint, iris, face, etc). Prior to Android 9.0, this will * instead show a custom fingerprint authentication dialog. The prompt will persist across * configuration changes unless explicitly canceled. For security reasons, the prompt will be * dismissed when the client application is no longer in the foreground. * * <p>To persist authentication across configuration changes, developers should (re)create the * prompt every time the activity/fragment is created. Instantiating the prompt with a new * callback early in the fragment/activity lifecycle (e.g. in {@code onCreate()}) will allow the * ongoing authentication session's callbacks to be received by the new fragment/activity instance. * Note that {@code cancelAuthentication()} should not be called, and {@code authenticate()} does * not need to be invoked during activity/fragment creation. */ public class BiometricPrompt { private static final String TAG = "BiometricPromptCompat"; /** * There is no error, and the user can successfully authenticate. */ static final int BIOMETRIC_SUCCESS = 0; /** * The hardware is unavailable. Try again later. */ public static final int ERROR_HW_UNAVAILABLE = 1; /** * The sensor was unable to process the current image. */ public static final int ERROR_UNABLE_TO_PROCESS = 2; /** * The current operation has been running too long and has timed out. * * <p>This is intended to prevent programs from waiting for the biometric sensor indefinitely. * The timeout is platform and sensor-specific, but is generally on the order of ~30 seconds. */ public static final int ERROR_TIMEOUT = 3; /** * The operation can't be completed because there is not enough device storage remaining. */ public static final int ERROR_NO_SPACE = 4; /** * The operation was canceled because the biometric sensor is unavailable. This may happen when * the user is switched, the device is locked, or another pending operation prevents it. */ public static final int ERROR_CANCELED = 5; /** * The operation was canceled because the API is locked out due to too many attempts. This * occurs after 5 failed attempts, and lasts for 30 seconds. */ public static final int ERROR_LOCKOUT = 7; /** * The operation failed due to a vendor-specific error. * * <p>This error code may be used by hardware vendors to extend this list to cover errors that * don't fall under one of the other predefined categories. Vendors are responsible for * providing the strings for these errors. * * <p>These messages are typically reserved for internal operations such as enrollment but may * be used to express any error that is not otherwise covered. In this case, applications are * expected to show the error message, but they are advised not to rely on the message ID, since * this may vary by vendor and device. */ public static final int ERROR_VENDOR = 8; /** * The operation was canceled because {@link #ERROR_LOCKOUT} occurred too many times. Biometric * authentication is disabled until the user unlocks with their device credential (i.e. PIN, * pattern, or password). */ public static final int ERROR_LOCKOUT_PERMANENT = 9; /** * The user canceled the operation. * * <p>Upon receiving this, applications should use alternate authentication, such as a password. * The application should also provide the user a way of returning to biometric authentication, * such as a button. */ public static final int ERROR_USER_CANCELED = 10; /** * The user does not have any biometrics enrolled. */ public static final int ERROR_NO_BIOMETRICS = 11; /** * The device does not have the required authentication hardware. */ public static final int ERROR_HW_NOT_PRESENT = 12; /** * The user pressed the negative button. */ public static final int ERROR_NEGATIVE_BUTTON = 13; /** * The device does not have pin, pattern, or password set up. */ public static final int ERROR_NO_DEVICE_CREDENTIAL = 14; /** * A security vulnerability has been discovered with one or more hardware sensors. The * affected sensor(s) are unavailable until a security update has addressed the issue. */ public static final int ERROR_SECURITY_UPDATE_REQUIRED = 15; /** * An error code that may be returned during authentication. * @hide */ @IntDef({ ERROR_HW_UNAVAILABLE, ERROR_UNABLE_TO_PROCESS, ERROR_TIMEOUT, ERROR_NO_SPACE, ERROR_CANCELED, ERROR_LOCKOUT, ERROR_VENDOR, ERROR_LOCKOUT_PERMANENT, ERROR_USER_CANCELED, ERROR_NO_BIOMETRICS, ERROR_HW_NOT_PRESENT, ERROR_NEGATIVE_BUTTON, ERROR_NO_DEVICE_CREDENTIAL }) @RestrictTo(RestrictTo.Scope.LIBRARY) @Retention(RetentionPolicy.SOURCE) public @interface AuthenticationError {} /** * Authentication type reported by {@link AuthenticationResult} when the user authenticated via * an unknown method. * * <p>This value may be returned on older Android versions due to partial incompatibility * with a newer API. It does NOT necessarily imply that the user authenticated with a method * other than those represented by {@link #AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL} and * {@link #AUTHENTICATION_RESULT_TYPE_BIOMETRIC}. */ public static final int AUTHENTICATION_RESULT_TYPE_UNKNOWN = -1; /** * Authentication type reported by {@link AuthenticationResult} when the user authenticated by * entering their device PIN, pattern, or password. */ public static final int AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL = 1; /** * Authentication type reported by {@link AuthenticationResult} when the user authenticated by * presenting some form of biometric (e.g. fingerprint or face). */ public static final int AUTHENTICATION_RESULT_TYPE_BIOMETRIC = 2; /** * The authentication type that was used, as reported by {@link AuthenticationResult}. */ @IntDef({ AUTHENTICATION_RESULT_TYPE_UNKNOWN, AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL, AUTHENTICATION_RESULT_TYPE_BIOMETRIC }) @Retention(RetentionPolicy.SOURCE) @interface AuthenticationResultType {} /** * Tag used to identify the {@link BiometricFragment} attached to the client activity/fragment. */ private static final String BIOMETRIC_FRAGMENT_TAG = "androidx.biometric.BiometricFragment"; /** * A wrapper class for the crypto objects supported by {@link BiometricPrompt}. */ public static class CryptoObject { @Nullable private final Signature mSignature; @Nullable private final Cipher mCipher; @Nullable private final Mac mMac; @Nullable private final android.security.identity.IdentityCredential mIdentityCredential; /** * Creates a crypto object that wraps the given signature object. * * @param signature The signature to be associated with this crypto object. */ public CryptoObject(@NonNull Signature signature) { mSignature = signature; mCipher = null; mMac = null; mIdentityCredential = null; } /** * Creates a crypto object that wraps the given cipher object. * * @param cipher The cipher to be associated with this crypto object. */ public CryptoObject(@NonNull Cipher cipher) { mSignature = null; mCipher = cipher; mMac = null; mIdentityCredential = null; } /** * Creates a crypto object that wraps the given MAC object. * * @param mac The MAC to be associated with this crypto object. */ public CryptoObject(@NonNull Mac mac) { mSignature = null; mCipher = null; mMac = mac; mIdentityCredential = null; } /** * Creates a crypto object that wraps the given identity credential object. * * @param identityCredential The identity credential to be associated with this crypto * object. */ @RequiresApi(Build.VERSION_CODES.R) public CryptoObject( @NonNull android.security.identity.IdentityCredential identityCredential) { mSignature = null; mCipher = null; mMac = null; mIdentityCredential = identityCredential; } /** * Gets the signature object associated with this crypto object. * * @return The signature, or {@code null} if none is associated with this object. */ @Nullable public Signature getSignature() { return mSignature; } /** * Gets the cipher object associated with this crypto object. * * @return The cipher, or {@code null} if none is associated with this object. */ @Nullable public Cipher getCipher() { return mCipher; } /** * Gets the MAC object associated with this crypto object. * * @return The MAC, or {@code null} if none is associated with this object. */ @Nullable public Mac getMac() { return mMac; } /** * Gets the identity credential object associated with this crypto object. * * @return The identity credential, or {@code null} if none is associated with this object. */ @RequiresApi(Build.VERSION_CODES.R) @Nullable public android.security.identity.IdentityCredential getIdentityCredential() { return mIdentityCredential; } } /** * A container for data passed to {@link AuthenticationCallback#onAuthenticationSucceeded( * AuthenticationResult)} when the user has successfully authenticated. */ public static class AuthenticationResult { private final CryptoObject mCryptoObject; @AuthenticationResultType private final int mAuthenticationType; AuthenticationResult( CryptoObject crypto, @AuthenticationResultType int authenticationType) { mCryptoObject = crypto; mAuthenticationType = authenticationType; } /** * Gets the {@link CryptoObject} associated with this transaction. * * @return The {@link CryptoObject} provided to {@code authenticate()}. */ @Nullable public CryptoObject getCryptoObject() { return mCryptoObject; } /** * Gets the type of authentication (e.g. device credential or biometric) that was * requested from and successfully provided by the user. * * @return An integer representing the type of authentication that was used. * * @see #AUTHENTICATION_RESULT_TYPE_UNKNOWN * @see #AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL * @see #AUTHENTICATION_RESULT_TYPE_BIOMETRIC */ @AuthenticationResultType public int getAuthenticationType() { return mAuthenticationType; } } /** * A collection of methods that may be invoked by {@link BiometricPrompt} during authentication. */ public abstract static class AuthenticationCallback { /** * Called when an unrecoverable error has been encountered and authentication has stopped. * * <p>After this method is called, no further events will be sent for the current * authentication session. * * @param errorCode An integer ID associated with the error. * @param errString A human-readable string that describes the error. */ public void onAuthenticationError( @AuthenticationError int errorCode, @NonNull CharSequence errString) {} /** * Called when a biometric (e.g. fingerprint, face, etc.) is recognized, indicating that the * user has successfully authenticated. * * <p>After this method is called, no further events will be sent for the current * authentication session. * * @param result An object containing authentication-related data. */ public void onAuthenticationSucceeded(@NonNull AuthenticationResult result) {} /** * Called when a biometric (e.g. fingerprint, face, etc.) is presented but not recognized as * belonging to the user. */ public void onAuthenticationFailed() {} } /** * A set of configurable options for how the {@link BiometricPrompt} should appear and behave. */ public static class PromptInfo { /** * A builder used to set individual options for the {@link PromptInfo} class. */ public static class Builder { // Mutable options to be set on the builder. @Nullable private CharSequence mTitle = null; @Nullable private CharSequence mSubtitle = null; @Nullable private CharSequence mDescription = null; @Nullable private CharSequence mNegativeButtonText = null; private boolean mIsConfirmationRequired = true; private boolean mIsDeviceCredentialAllowed = false; @BiometricManager.AuthenticatorTypes private int mAllowedAuthenticators = 0; /** * Required: Sets the title for the prompt. * * @param title The title to be displayed on the prompt. * @return This builder. */ @NonNull public Builder setTitle(@NonNull CharSequence title) { mTitle = title; return this; } /** * Optional: Sets the subtitle for the prompt. * * @param subtitle The subtitle to be displayed on the prompt. * @return This builder. */ @NonNull public Builder setSubtitle(@Nullable CharSequence subtitle) { mSubtitle = subtitle; return this; } /** * Optional: Sets the description for the prompt. * * @param description The description to be displayed on the prompt. * @return This builder. */ @NonNull public Builder setDescription(@Nullable CharSequence description) { mDescription = description; return this; } /** * Required: Sets the text for the negative button on the prompt. * * <p>Note that this option is incompatible with device credential authentication and * must NOT be set if the latter is enabled via {@link #setAllowedAuthenticators(int)} * or {@link #setDeviceCredentialAllowed(boolean)}. * * @param negativeButtonText The label to be used for the negative button on the prompt. * @return This builder. */ @SuppressWarnings("deprecation") @NonNull public Builder setNegativeButtonText(@NonNull CharSequence negativeButtonText) { mNegativeButtonText = negativeButtonText; return this; } /** * Optional: Sets a system hint for whether to require explicit user confirmation after * a passive biometric (e.g. iris or face) has been recognized but before * {@link AuthenticationCallback#onAuthenticationSucceeded(AuthenticationResult)} is * called. Defaults to {@code true}. * * <p>Disabling this option is generally only appropriate for frequent, low-value * transactions, such as re-authenticating for a previously authorized application. * * <p>Also note that, as it is merely a hint, this option may be ignored by the system. * For example, the system may choose to instead always require confirmation if the user * has disabled passive authentication for their device in Settings. Additionally, this * option will be ignored on devices running OS versions prior to Android 10 (API 29). * * @param confirmationRequired Whether this option should be enabled. * @return This builder. */ @NonNull public Builder setConfirmationRequired(boolean confirmationRequired) { mIsConfirmationRequired = confirmationRequired; return this; } /** * Optional: Sets whether the user should be given the option to authenticate with * their device PIN, pattern, or password instead of a biometric. Defaults to * {@code false}. * * <p>Note that this option is incompatible with * {@link PromptInfo.Builder#setNegativeButtonText(CharSequence)} and must NOT be * enabled if the latter is set. * * <p>Before enabling this option, developers should check whether the device is secure * by calling {@link android.app.KeyguardManager#isDeviceSecure()}. If the device is not * secure, authentication will fail with {@link #ERROR_NO_DEVICE_CREDENTIAL}. * * <p>On versions prior to Android 10 (API 29), calls to * {@link #cancelAuthentication()} will not work as expected after the * user has chosen to authenticate with their device credential. This is because the * library internally launches a separate activity (by calling * {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent(CharSequence, * CharSequence)}) that does not have a public API for cancellation. * * @param deviceCredentialAllowed Whether this option should be enabled. * @return This builder. * * @deprecated Use {@link #setAllowedAuthenticators(int)} instead. */ @SuppressWarnings("deprecation") @Deprecated @NonNull public Builder setDeviceCredentialAllowed(boolean deviceCredentialAllowed) { mIsDeviceCredentialAllowed = deviceCredentialAllowed; return this; } /** * Optional: Specifies the type(s) of authenticators that may be invoked by * {@link BiometricPrompt} to authenticate the user. Available authenticator types are * defined in {@link Authenticators} and can be combined via bitwise OR. Defaults to: * <ul> * <li>{@link Authenticators#BIOMETRIC_WEAK} for non-crypto authentication, or</li> * <li>{@link Authenticators#BIOMETRIC_STRONG} for crypto-based authentication.</li> * </ul> * * <p>Note that not all combinations of authenticator types are supported prior to * Android 11 (API 30). Specifically, {@code DEVICE_CREDENTIAL} alone is unsupported * prior to API 30, and {@code BIOMETRIC_STRONG | DEVICE_CREDENTIAL} is unsupported on * API 28-29. Setting an unsupported value on an affected Android version will result in * an error when calling {@link #build()}. * * <p>This method should be preferred over {@link #setDeviceCredentialAllowed(boolean)} * and overrides the latter if both are used. Using this method to enable device * credential authentication (with {@link Authenticators#DEVICE_CREDENTIAL}) will * replace the negative button on the prompt, making it an error to also call * {@link #setNegativeButtonText(CharSequence)}. * * <p>If this method is used and no authenticator of any of the specified types is * available at the time {@code authenticate()} is called, * {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)} will be * invoked with an appropriate error code. * * @param allowedAuthenticators A bit field representing all valid authenticator types * that may be invoked by the prompt. * @return This builder. */ @NonNull public Builder setAllowedAuthenticators( @BiometricManager.AuthenticatorTypes int allowedAuthenticators) { mAllowedAuthenticators = allowedAuthenticators; return this; } /** * Creates a {@link PromptInfo} object with the specified options. * * @return The {@link PromptInfo} object. * * @throws IllegalArgumentException If any required option is not set, or if any * illegal combination of options is present. */ @NonNull public PromptInfo build() { if (TextUtils.isEmpty(mTitle)) { throw new IllegalArgumentException("Title must be set and non-empty."); } if (!AuthenticatorUtils.isSupportedCombination(mAllowedAuthenticators)) { throw new IllegalArgumentException("Authenticator combination is unsupported " + "on API " + Build.VERSION.SDK_INT + ": " + AuthenticatorUtils.convertToString(mAllowedAuthenticators)); } final boolean isDeviceCredentialAllowed = mAllowedAuthenticators != 0 ? AuthenticatorUtils.isDeviceCredentialAllowed(mAllowedAuthenticators) : mIsDeviceCredentialAllowed; if (TextUtils.isEmpty(mNegativeButtonText) && !isDeviceCredentialAllowed) { throw new IllegalArgumentException("Negative text must be set and non-empty."); } if (!TextUtils.isEmpty(mNegativeButtonText) && isDeviceCredentialAllowed) { throw new IllegalArgumentException("Negative text must not be set if device " + "credential authentication is allowed."); } return new PromptInfo( mTitle, mSubtitle, mDescription, mNegativeButtonText, mIsConfirmationRequired, mIsDeviceCredentialAllowed, mAllowedAuthenticators); } } // Immutable fields for the prompt info object. @NonNull private final CharSequence mTitle; @Nullable private final CharSequence mSubtitle; @Nullable private final CharSequence mDescription; @Nullable private final CharSequence mNegativeButtonText; private final boolean mIsConfirmationRequired; private final boolean mIsDeviceCredentialAllowed; @BiometricManager.AuthenticatorTypes private final int mAllowedAuthenticators; // Prevent direct instantiation. @SuppressWarnings("WeakerAccess") /* synthetic access */ PromptInfo( @NonNull CharSequence title, @Nullable CharSequence subtitle, @Nullable CharSequence description, @Nullable CharSequence negativeButtonText, boolean confirmationRequired, boolean deviceCredentialAllowed, @BiometricManager.AuthenticatorTypes int allowedAuthenticators) { mTitle = title; mSubtitle = subtitle; mDescription = description; mNegativeButtonText = negativeButtonText; mIsConfirmationRequired = confirmationRequired; mIsDeviceCredentialAllowed = deviceCredentialAllowed; mAllowedAuthenticators = allowedAuthenticators; } /** * Gets the title for the prompt. * * @return The title to be displayed on the prompt. * * @see Builder#setTitle(CharSequence) */ @NonNull public CharSequence getTitle() { return mTitle; } /** * Gets the subtitle for the prompt. * * @return The subtitle to be displayed on the prompt. * * @see Builder#setSubtitle(CharSequence) */ @Nullable public CharSequence getSubtitle() { return mSubtitle; } /** * Gets the description for the prompt. * * @return The description to be displayed on the prompt. * * @see Builder#setDescription(CharSequence) */ @Nullable public CharSequence getDescription() { return mDescription; } /** * Gets the text for the negative button on the prompt. * * @return The label to be used for the negative button on the prompt, or an empty string if * not set. * * @see Builder#setNegativeButtonText(CharSequence) */ @NonNull public CharSequence getNegativeButtonText() { return mNegativeButtonText != null ? mNegativeButtonText : ""; } /** * Checks if the confirmation required option is enabled for the prompt. * * @return Whether this option is enabled. * * @see Builder#setConfirmationRequired(boolean) */ public boolean isConfirmationRequired() { return mIsConfirmationRequired; } /** * Checks if the device credential allowed option is enabled for the prompt. * * @return Whether this option is enabled. * * @see Builder#setDeviceCredentialAllowed(boolean) * * @deprecated Will be removed with {@link Builder#setDeviceCredentialAllowed(boolean)}. */ @SuppressWarnings({"deprecation", "DeprecatedIsStillUsed"}) @Deprecated public boolean isDeviceCredentialAllowed() { return mIsDeviceCredentialAllowed; } /** * Gets the type(s) of authenticators that may be invoked by the prompt. * * @return A bit field representing all valid authenticator types that may be invoked by * the prompt, or 0 if not set. * * @see Builder#setAllowedAuthenticators(int) */ @BiometricManager.AuthenticatorTypes public int getAllowedAuthenticators() { return mAllowedAuthenticators; } } /** * A lifecycle observer that clears the client callback reference held by a * {@link BiometricViewModel} when the lifecycle owner is destroyed. */ private static class ResetCallbackObserver implements DefaultLifecycleObserver { @NonNull private final WeakReference<BiometricViewModel> mViewModelRef; ResetCallbackObserver(@NonNull BiometricViewModel viewModel) { mViewModelRef = new WeakReference<>(viewModel); } @Override public void onDestroy(@NonNull LifecycleOwner owner) { if (mViewModelRef.get() != null) { mViewModelRef.get().resetClientCallback(); } } } /** * The fragment manager that will be used to attach the prompt to the client activity. */ @Nullable private FragmentManager mClientFragmentManager; /** * Constructs a {@link BiometricPrompt}, which can be used to prompt the user to authenticate * with a biometric such as fingerprint or face. The prompt can be shown to the user by calling * {@code authenticate()} and persists across device configuration changes by default. * * <p>If authentication is in progress, calling this constructor to recreate the prompt will * also update the {@link AuthenticationCallback} for the current session. Thus, this method * should be called by the client activity each time the configuration changes * (e.g. in {@code onCreate()}). * * @param activity The activity of the client application that will host the prompt. * @param callback The object that will receive and process authentication events. * * @see #BiometricPrompt(Fragment, AuthenticationCallback) * @see #BiometricPrompt(FragmentActivity, Executor, AuthenticationCallback) * @see #BiometricPrompt(Fragment, Executor, AuthenticationCallback) */ @SuppressWarnings("ConstantConditions") public BiometricPrompt( @NonNull FragmentActivity activity, @NonNull AuthenticationCallback callback) { if (activity == null) { throw new IllegalArgumentException("FragmentActivity must not be null."); } if (callback == null) { throw new IllegalArgumentException("AuthenticationCallback must not be null."); } final FragmentManager fragmentManager = activity.getSupportFragmentManager(); final BiometricViewModel viewModel = getViewModel(activity); init(fragmentManager, viewModel, null /* executor */, callback); } /** * Constructs a {@link BiometricPrompt}, which can be used to prompt the user to authenticate * with a biometric such as fingerprint or face. The prompt can be shown to the user by calling * {@code authenticate()} and persists across device configuration changes by default. * * <p>If authentication is in progress, calling this constructor to recreate the prompt will * also update the {@link AuthenticationCallback} for the current session. Thus, this method * should be called by the client fragment each time the configuration changes * (e.g. in {@code onCreate()}). * * @param fragment The fragment of the client application that will host the prompt. * @param callback The object that will receive and process authentication events. * * @see #BiometricPrompt(FragmentActivity, AuthenticationCallback) * @see #BiometricPrompt(FragmentActivity, Executor, AuthenticationCallback) * @see #BiometricPrompt(Fragment, Executor, AuthenticationCallback) */ @SuppressWarnings("ConstantConditions") public BiometricPrompt(@NonNull Fragment fragment, @NonNull AuthenticationCallback callback) { if (fragment == null) { throw new IllegalArgumentException("Fragment must not be null."); } if (callback == null) { throw new IllegalArgumentException("AuthenticationCallback must not be null."); } final FragmentManager fragmentManager = fragment.getChildFragmentManager(); final BiometricViewModel viewModel = getViewModel(getHostActivityOrContext(fragment)); addObservers(fragment, viewModel); init(fragmentManager, viewModel, null /* executor */, callback); } /** * Constructs a {@link BiometricPrompt}, which can be used to prompt the user to authenticate * with a biometric such as fingerprint or face. The prompt can be shown to the user by calling * {@code authenticate()} and persists across device configuration changes by default. * * <p>If authentication is in progress, calling this constructor to recreate the prompt will * also update the {@link Executor} and {@link AuthenticationCallback} for the current session. * Thus, this method should be called by the client activity each time the configuration changes * (e.g. in {@code onCreate()}). * * @param activity The activity of the client application that will host the prompt. * @param executor The executor that will be used to run {@link AuthenticationCallback} methods. * @param callback The object that will receive and process authentication events. * * @see #BiometricPrompt(FragmentActivity, AuthenticationCallback) * @see #BiometricPrompt(Fragment, AuthenticationCallback) * @see #BiometricPrompt(Fragment, Executor, AuthenticationCallback) */ @SuppressLint("LambdaLast") @SuppressWarnings("ConstantConditions") public BiometricPrompt( @NonNull FragmentActivity activity, @NonNull Executor executor, @NonNull AuthenticationCallback callback) { if (activity == null) { throw new IllegalArgumentException("FragmentActivity must not be null."); } if (executor == null) { throw new IllegalArgumentException("Executor must not be null."); } if (callback == null) { throw new IllegalArgumentException("AuthenticationCallback must not be null."); } final FragmentManager fragmentManager = activity.getSupportFragmentManager(); final BiometricViewModel viewModel = getViewModel(activity); init(fragmentManager, viewModel, executor, callback); } /** * Constructs a {@link BiometricPrompt}, which can be used to prompt the user to authenticate * with a biometric such as fingerprint or face. The prompt can be shown to the user by calling * {@code authenticate()} and persists across device configuration changes by default. * * <p>If authentication is in progress, calling this constructor to recreate the prompt will * also update the {@link Executor} and {@link AuthenticationCallback} for the current session. * Thus, this method should be called by the client fragment each time the configuration changes * (e.g. in {@code onCreate()}). * * @param fragment The fragment of the client application that will host the prompt. * @param executor The executor that will be used to run {@link AuthenticationCallback} methods. * @param callback The object that will receive and process authentication events. * * @see #BiometricPrompt(FragmentActivity, AuthenticationCallback) * @see #BiometricPrompt(Fragment, AuthenticationCallback) * @see #BiometricPrompt(FragmentActivity, Executor, AuthenticationCallback) */ @SuppressLint("LambdaLast") @SuppressWarnings("ConstantConditions") public BiometricPrompt( @NonNull Fragment fragment, @NonNull Executor executor, @NonNull AuthenticationCallback callback) { if (fragment == null) { throw new IllegalArgumentException("Fragment must not be null."); } if (executor == null) { throw new IllegalArgumentException("Executor must not be null."); } if (callback == null) { throw new IllegalArgumentException("AuthenticationCallback must not be null."); } final FragmentManager fragmentManager = fragment.getChildFragmentManager(); final BiometricViewModel viewModel = getViewModel(getHostActivityOrContext(fragment)); addObservers(fragment, viewModel); init(fragmentManager, viewModel, executor, callback); } /** * Initializes or updates the data needed by the prompt. * * @param fragmentManager The fragment manager that will be used to attach the prompt. * @param viewModel A biometric view model tied to the lifecycle of the client activity. * @param executor The executor that will be used to run callback methods, or * {@link null} if a default executor should be used. * @param callback The object that will receive and process authentication events. */ private void init( @Nullable FragmentManager fragmentManager, @Nullable BiometricViewModel viewModel, @Nullable Executor executor, @NonNull AuthenticationCallback callback) { mClientFragmentManager = fragmentManager; if (viewModel != null) { if (executor != null) { viewModel.setClientExecutor(executor); } viewModel.setClientCallback(callback); } } /** * Shows the biometric prompt to the user. The prompt survives lifecycle changes by default. To * cancel authentication and dismiss the prompt, use {@link #cancelAuthentication()}. * * <p>Calling this method invokes crypto-based authentication, which is incompatible with * <strong>Class 2</strong> (formerly <strong>Weak</strong>) biometrics and (prior to Android * 11) device credential. Therefore, it is an error for {@code info} to explicitly allow any * of these authenticator types on an incompatible Android version. * * @param info An object describing the appearance and behavior of the prompt. * @param crypto A crypto object to be associated with this authentication. * * @throws IllegalArgumentException If any of the allowed authenticator types specified by * {@code info} do not support crypto-based authentication. * * @see #authenticate(PromptInfo) * @see PromptInfo.Builder#setAllowedAuthenticators(int) */ @SuppressWarnings("ConstantConditions") public void authenticate(@NonNull PromptInfo info, @NonNull CryptoObject crypto) { if (info == null) { throw new IllegalArgumentException("PromptInfo cannot be null."); } if (crypto == null) { throw new IllegalArgumentException("CryptoObject cannot be null."); } // Ensure that all allowed authenticators support crypto auth. @BiometricManager.AuthenticatorTypes final int authenticators = AuthenticatorUtils.getConsolidatedAuthenticators(info, crypto); if (AuthenticatorUtils.isWeakBiometricAllowed(authenticators)) { throw new IllegalArgumentException("Crypto-based authentication is not supported for " + "Class 2 (Weak) biometrics."); } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R && AuthenticatorUtils.isDeviceCredentialAllowed(authenticators)) { throw new IllegalArgumentException("Crypto-based authentication is not supported for " + "device credential prior to API 30."); } authenticateInternal(info, crypto); } /** * Shows the biometric prompt to the user. The prompt survives lifecycle changes by default. To * cancel authentication and dismiss the prompt, use {@link #cancelAuthentication()}. * * @param info An object describing the appearance and behavior of the prompt. * * @see #authenticate(PromptInfo, CryptoObject) */ @SuppressWarnings("ConstantConditions") public void authenticate(@NonNull PromptInfo info) { if (info == null) { throw new IllegalArgumentException("PromptInfo cannot be null."); } authenticateInternal(info, null /* crypto */); } /** * Shows the biometric prompt to the user and begins authentication. * * @param info An object describing the appearance and behavior of the prompt. * @param crypto A crypto object to be associated with this authentication. */ private void authenticateInternal(@NonNull PromptInfo info, @Nullable CryptoObject crypto) { if (mClientFragmentManager == null) { Log.e(TAG, "Unable to start authentication. Client fragment manager was null."); return; } if (mClientFragmentManager.isStateSaved()) { Log.e(TAG, "Unable to start authentication. Called after onSaveInstanceState()."); return; } final BiometricFragment biometricFragment = findOrAddBiometricFragment(mClientFragmentManager); biometricFragment.authenticate(info, crypto); } /** * Cancels the ongoing authentication session and dismisses the prompt. * * <p>On versions prior to Android 10 (API 29), calling this method while the user is * authenticating with their device credential will NOT work as expected. See * {@link PromptInfo.Builder#setDeviceCredentialAllowed(boolean)} for more details. */ public void cancelAuthentication() { if (mClientFragmentManager == null) { Log.e(TAG, "Unable to start authentication. Client fragment manager was null."); return; } final BiometricFragment biometricFragment = findBiometricFragment(mClientFragmentManager); if (biometricFragment == null) { Log.e(TAG, "Unable to cancel authentication. BiometricFragment not found."); return; } biometricFragment.cancelAuthentication(BiometricFragment.CANCELED_FROM_CLIENT); } /** * Gets the biometric view model instance for the given context, creating one if necessary. * * @param context The client context that will (directly or indirectly) host the prompt. * @return A biometric view model tied to the lifecycle of the given activity. */ @Nullable static BiometricViewModel getViewModel(@Nullable Context context) { return context instanceof ViewModelStoreOwner ? new ViewModelProvider((ViewModelStoreOwner) context).get(BiometricViewModel.class) : null; } /** * Gets the host Activity or Context the given Fragment. * * @param fragment The fragment. * @return The Activity or Context that hosts the Fragment. */ @Nullable static Context getHostActivityOrContext(@NonNull Fragment fragment) { final FragmentActivity activity = fragment.getActivity(); if (activity != null) { return activity; } else { // If the host activity is null, return the host context instead return fragment.getContext(); } } /** * Adds the necessary lifecycle observers to the given fragment host. * * @param fragment The fragment of the client application that will host the prompt. * @param viewModel A biometric view model tied to the lifecycle of the client activity. */ private static void addObservers( @NonNull Fragment fragment, @Nullable BiometricViewModel viewModel) { if (viewModel != null) { // Ensure that the callback is reset to avoid leaking fragment instances (b/167014923). fragment.getLifecycle().addObserver(new ResetCallbackObserver(viewModel)); } } /** * Searches for a {@link BiometricFragment} instance that has been added to an activity or * fragment. * * @param fragmentManager The fragment manager that will be used to search for the fragment. * @return An instance of {@link BiometricFragment} found by the fragment manager, or * {@code null} if no such fragment is found. */ @Nullable private static BiometricFragment findBiometricFragment( @NonNull FragmentManager fragmentManager) { return (BiometricFragment) fragmentManager.findFragmentByTag( BiometricPrompt.BIOMETRIC_FRAGMENT_TAG); } /** * Returns a {@link BiometricFragment} instance that has been added to an activity or fragment, * adding one if necessary. * * @param fragmentManager The fragment manager used to search for and/or add the fragment. * @return An instance of {@link BiometricFragment} associated with the fragment manager. */ @NonNull private static BiometricFragment findOrAddBiometricFragment( @NonNull FragmentManager fragmentManager) { BiometricFragment biometricFragment = findBiometricFragment(fragmentManager); // If the fragment hasn't been added before, add it. if (biometricFragment == null) { biometricFragment = BiometricFragment.newInstance(); fragmentManager.beginTransaction() .add(biometricFragment, BiometricPrompt.BIOMETRIC_FRAGMENT_TAG) .commitAllowingStateLoss(); // For the case when onResume() is being called right after authenticate, // we need to make sure that all fragment transactions have been committed. fragmentManager.executePendingTransactions(); } return biometricFragment; } }
/** * Opensec OVAL - https://nakamura5akihito.github.io/ * Copyright (C) 2015 Akihito Nakamura * * 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.opensec.oval.model.windows; import io.opensec.oval.model.ComponentType; import io.opensec.oval.model.ElementRef; import io.opensec.oval.model.Family; import io.opensec.oval.model.definitions.EntityStateIntType; import io.opensec.oval.model.definitions.EntityStateStringType; import io.opensec.oval.model.definitions.StateType; import java.util.ArrayList; import java.util.Collection; /** * The process state defines the different metadata * associate with a Windows process. * * @author Akihito Nakamura, AIST * @see <a href="http://oval.mitre.org/language/">OVAL Language</a> * @deprecated Deprecated as of version 5.8: * Replaced by the process58 object and * will be removed in a future version of the language. */ @Deprecated public class ProcessState extends StateType { //{0..1} private EntityStateStringType command_line; private EntityStateIntType pid; private EntityStateIntType ppid; private EntityStateStringType priority; private EntityStateStringType image_path; private EntityStateStringType current_dir; /** * Constructor. */ public ProcessState() { this( null, 0 ); } public ProcessState( final String id, final int version ) { this( id, version, null ); } public ProcessState( final String id, final int version, final String comment ) { super( id, version, comment ); // _oval_platform_type = OvalPlatformType.windows; // _oval_component_type = OvalComponentType.process; _oval_family = Family.WINDOWS; _oval_component = ComponentType.PROCESS; } /** */ public void setCommandLine( final EntityStateStringType command_line ) { this.command_line = command_line; } public EntityStateStringType getCommandLine() { return command_line; } /** */ public void setPid( final EntityStateIntType pid ) { this.pid = pid; } public EntityStateIntType getPid() { return pid; } /** */ public void setPpid( final EntityStateIntType ppid ) { this.ppid = ppid; } public EntityStateIntType getPpid() { return ppid; } /** */ public void setPriority( final EntityStateStringType priority ) { this.priority = priority; } public EntityStateStringType getPriority() { return priority; } /** */ public void setImagePath( final EntityStateStringType image_path ) { this.image_path = image_path; } public EntityStateStringType getImagePath() { return image_path; } /** */ public void setCurrentDir( final EntityStateStringType current_dir ) { this.current_dir = current_dir; } public EntityStateStringType getCurrentDir() { return current_dir; } //********************************************************************* // DefinitionsElement //********************************************************************* @Override public Collection<ElementRef> ovalGetElementRef() { Collection<ElementRef> ref_list = new ArrayList<ElementRef>(); ref_list.add( getCommandLine() ); ref_list.add( getPid() ); ref_list.add( getPpid() ); ref_list.add( getPriority() ); ref_list.add( getImagePath() ); ref_list.add( getCurrentDir() ); return ref_list; } //************************************************************** // java.lang.Object //************************************************************** @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals( final Object obj ) { if (!(obj instanceof ProcessState)) { return false; } return super.equals( obj ); } @Override public String toString() { return "process_state[" + super.toString() + ", command_line=" + getCommandLine() + ", pid=" + getPid() + ", ppid=" + getPpid() + ", priority=" + getPriority() + ", image_path=" + getImagePath() + ", current_dir=" + getCurrentDir() + "]"; } } //ProcessState
/* * 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.kafka.connect.runtime; import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.utils.MockTime; import org.apache.kafka.common.utils.Time; import org.apache.kafka.connect.connector.ConnectRecord; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.errors.RetriableException; import org.apache.kafka.connect.json.JsonConverter; import org.apache.kafka.connect.runtime.distributed.ClusterConfigState; import org.apache.kafka.connect.runtime.errors.ErrorHandlingMetrics; import org.apache.kafka.connect.runtime.errors.LogReporter; import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator; import org.apache.kafka.connect.runtime.errors.ToleranceType; import org.apache.kafka.connect.runtime.isolation.PluginClassLoader; import org.apache.kafka.connect.runtime.isolation.Plugins; import org.apache.kafka.connect.runtime.standalone.StandaloneConfig; import org.apache.kafka.connect.sink.SinkConnector; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTask; import org.apache.kafka.connect.source.SourceRecord; import org.apache.kafka.connect.source.SourceTask; import org.apache.kafka.connect.storage.Converter; import org.apache.kafka.connect.storage.HeaderConverter; import org.apache.kafka.connect.storage.OffsetStorageReader; import org.apache.kafka.connect.storage.OffsetStorageWriter; import org.apache.kafka.connect.transforms.Transformation; import org.apache.kafka.connect.transforms.util.SimpleConfig; import org.apache.kafka.connect.util.ConnectorTaskId; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.api.easymock.annotation.Mock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static org.apache.kafka.common.utils.Time.SYSTEM; import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @PrepareForTest({WorkerSinkTask.class, WorkerSourceTask.class}) @PowerMockIgnore("javax.management.*") public class ErrorHandlingTaskTest { private static final String TOPIC = "test"; private static final int PARTITION1 = 12; private static final int PARTITION2 = 13; private static final long FIRST_OFFSET = 45; @Mock Plugins plugins; private static final Map<String, String> TASK_PROPS = new HashMap<>(); static { TASK_PROPS.put(SinkConnector.TOPICS_CONFIG, TOPIC); TASK_PROPS.put(TaskConfig.TASK_CLASS_CONFIG, TestSinkTask.class.getName()); } public static final long OPERATOR_RETRY_TIMEOUT_MILLIS = 60000; public static final long OPERATOR_RETRY_MAX_DELAY_MILLIS = 5000; public static final ToleranceType OPERATOR_TOLERANCE_TYPE = ToleranceType.ALL; private static final TaskConfig TASK_CONFIG = new TaskConfig(TASK_PROPS); private ConnectorTaskId taskId = new ConnectorTaskId("job", 0); private TargetState initialState = TargetState.STARTED; private Time time; private MockConnectMetrics metrics; @SuppressWarnings("unused") @Mock private SinkTask sinkTask; @SuppressWarnings("unused") @Mock private SourceTask sourceTask; private Capture<WorkerSinkTaskContext> sinkTaskContext = EasyMock.newCapture(); private WorkerConfig workerConfig; @Mock private PluginClassLoader pluginLoader; @SuppressWarnings("unused") @Mock private HeaderConverter headerConverter; private WorkerSinkTask workerSinkTask; private WorkerSourceTask workerSourceTask; @SuppressWarnings("unused") @Mock private KafkaConsumer<byte[], byte[]> consumer; @SuppressWarnings("unused") @Mock private KafkaProducer<byte[], byte[]> producer; @Mock OffsetStorageReader offsetReader; @Mock OffsetStorageWriter offsetWriter; private Capture<ConsumerRebalanceListener> rebalanceListener = EasyMock.newCapture(); @SuppressWarnings("unused") @Mock private TaskStatus.Listener statusListener; private ErrorHandlingMetrics errorHandlingMetrics; @Before public void setup() { time = new MockTime(0, 0, 0); metrics = new MockConnectMetrics(); Map<String, String> workerProps = new HashMap<>(); workerProps.put("key.converter", "org.apache.kafka.connect.json.JsonConverter"); workerProps.put("value.converter", "org.apache.kafka.connect.json.JsonConverter"); workerProps.put("internal.key.converter", "org.apache.kafka.connect.json.JsonConverter"); workerProps.put("internal.value.converter", "org.apache.kafka.connect.json.JsonConverter"); workerProps.put("internal.key.converter.schemas.enable", "false"); workerProps.put("internal.value.converter.schemas.enable", "false"); workerProps.put("offset.storage.file.filename", "/tmp/connect.offsets"); pluginLoader = PowerMock.createMock(PluginClassLoader.class); workerConfig = new StandaloneConfig(workerProps); errorHandlingMetrics = new ErrorHandlingMetrics(taskId, metrics); } @After public void tearDown() { if (metrics != null) { metrics.stop(); } } @Test public void testErrorHandlingInSinkTasks() throws Exception { Map<String, String> reportProps = new HashMap<>(); reportProps.put(ConnectorConfig.ERRORS_LOG_ENABLE_CONFIG, "true"); reportProps.put(ConnectorConfig.ERRORS_LOG_INCLUDE_MESSAGES_CONFIG, "true"); LogReporter reporter = new LogReporter(taskId, connConfig(reportProps)); reporter.metrics(errorHandlingMetrics); RetryWithToleranceOperator retryWithToleranceOperator = operator(); retryWithToleranceOperator.metrics(errorHandlingMetrics); retryWithToleranceOperator.reporters(singletonList(reporter)); createSinkTask(initialState, retryWithToleranceOperator); expectInitializeTask(); // valid json ConsumerRecord<byte[], byte[]> record1 = new ConsumerRecord<>(TOPIC, PARTITION1, FIRST_OFFSET, null, "{\"a\": 10}".getBytes()); // bad json ConsumerRecord<byte[], byte[]> record2 = new ConsumerRecord<>(TOPIC, PARTITION2, FIRST_OFFSET, null, "{\"a\" 10}".getBytes()); EasyMock.expect(consumer.poll(EasyMock.anyLong())).andReturn(records(record1)); EasyMock.expect(consumer.poll(EasyMock.anyLong())).andReturn(records(record2)); sinkTask.put(EasyMock.anyObject()); EasyMock.expectLastCall().times(2); PowerMock.replayAll(); workerSinkTask.initialize(TASK_CONFIG); workerSinkTask.initializeAndStart(); workerSinkTask.iteration(); workerSinkTask.iteration(); // two records were consumed from Kafka assertSinkMetricValue("sink-record-read-total", 2.0); // only one was written to the task assertSinkMetricValue("sink-record-send-total", 1.0); // one record completely failed (converter issues) assertErrorHandlingMetricValue("total-record-errors", 1.0); // 2 failures in the transformation, and 1 in the converter assertErrorHandlingMetricValue("total-record-failures", 3.0); // one record completely failed (converter issues), and thus was skipped assertErrorHandlingMetricValue("total-records-skipped", 1.0); PowerMock.verifyAll(); } private RetryWithToleranceOperator operator() { return new RetryWithToleranceOperator(OPERATOR_RETRY_TIMEOUT_MILLIS, OPERATOR_RETRY_MAX_DELAY_MILLIS, OPERATOR_TOLERANCE_TYPE, SYSTEM); } @Test public void testErrorHandlingInSourceTasks() throws Exception { Map<String, String> reportProps = new HashMap<>(); reportProps.put(ConnectorConfig.ERRORS_LOG_ENABLE_CONFIG, "true"); reportProps.put(ConnectorConfig.ERRORS_LOG_INCLUDE_MESSAGES_CONFIG, "true"); LogReporter reporter = new LogReporter(taskId, connConfig(reportProps)); reporter.metrics(errorHandlingMetrics); RetryWithToleranceOperator retryWithToleranceOperator = operator(); retryWithToleranceOperator.metrics(errorHandlingMetrics); retryWithToleranceOperator.reporters(singletonList(reporter)); createSourceTask(initialState, retryWithToleranceOperator); // valid json Schema valSchema = SchemaBuilder.struct().field("val", Schema.INT32_SCHEMA).build(); Struct struct1 = new Struct(valSchema).put("val", 1234); SourceRecord record1 = new SourceRecord(emptyMap(), emptyMap(), TOPIC, PARTITION1, valSchema, struct1); Struct struct2 = new Struct(valSchema).put("val", 6789); SourceRecord record2 = new SourceRecord(emptyMap(), emptyMap(), TOPIC, PARTITION1, valSchema, struct2); EasyMock.expect(workerSourceTask.isStopping()).andReturn(false); EasyMock.expect(workerSourceTask.isStopping()).andReturn(false); EasyMock.expect(workerSourceTask.isStopping()).andReturn(true); EasyMock.expect(workerSourceTask.commitOffsets()).andReturn(true); offsetWriter.offset(EasyMock.anyObject(), EasyMock.anyObject()); EasyMock.expectLastCall().times(2); sourceTask.initialize(EasyMock.anyObject()); EasyMock.expectLastCall(); sourceTask.start(EasyMock.anyObject()); EasyMock.expectLastCall(); EasyMock.expect(sourceTask.poll()).andReturn(singletonList(record1)); EasyMock.expect(sourceTask.poll()).andReturn(singletonList(record2)); EasyMock.expect(producer.send(EasyMock.anyObject(), EasyMock.anyObject())).andReturn(null).times(2); PowerMock.replayAll(); workerSourceTask.initialize(TASK_CONFIG); workerSourceTask.execute(); // two records were consumed from Kafka assertSourceMetricValue("source-record-poll-total", 2.0); // only one was written to the task assertSourceMetricValue("source-record-write-total", 0.0); // one record completely failed (converter issues) assertErrorHandlingMetricValue("total-record-errors", 0.0); // 2 failures in the transformation, and 1 in the converter assertErrorHandlingMetricValue("total-record-failures", 4.0); // one record completely failed (converter issues), and thus was skipped assertErrorHandlingMetricValue("total-records-skipped", 0.0); PowerMock.verifyAll(); } private ConnectorConfig connConfig(Map<String, String> connProps) { Map<String, String> props = new HashMap<>(); props.put(ConnectorConfig.NAME_CONFIG, "test"); props.put(ConnectorConfig.CONNECTOR_CLASS_CONFIG, SinkTask.class.getName()); props.putAll(connProps); return new ConnectorConfig(plugins, props); } @Test public void testErrorHandlingInSourceTasksWthBadConverter() throws Exception { Map<String, String> reportProps = new HashMap<>(); reportProps.put(ConnectorConfig.ERRORS_LOG_ENABLE_CONFIG, "true"); reportProps.put(ConnectorConfig.ERRORS_LOG_INCLUDE_MESSAGES_CONFIG, "true"); LogReporter reporter = new LogReporter(taskId, connConfig(reportProps)); reporter.metrics(errorHandlingMetrics); RetryWithToleranceOperator retryWithToleranceOperator = operator(); retryWithToleranceOperator.metrics(errorHandlingMetrics); retryWithToleranceOperator.reporters(singletonList(reporter)); createSourceTask(initialState, retryWithToleranceOperator, badConverter()); // valid json Schema valSchema = SchemaBuilder.struct().field("val", Schema.INT32_SCHEMA).build(); Struct struct1 = new Struct(valSchema).put("val", 1234); SourceRecord record1 = new SourceRecord(emptyMap(), emptyMap(), TOPIC, PARTITION1, valSchema, struct1); Struct struct2 = new Struct(valSchema).put("val", 6789); SourceRecord record2 = new SourceRecord(emptyMap(), emptyMap(), TOPIC, PARTITION1, valSchema, struct2); EasyMock.expect(workerSourceTask.isStopping()).andReturn(false); EasyMock.expect(workerSourceTask.isStopping()).andReturn(false); EasyMock.expect(workerSourceTask.isStopping()).andReturn(true); EasyMock.expect(workerSourceTask.commitOffsets()).andReturn(true); offsetWriter.offset(EasyMock.anyObject(), EasyMock.anyObject()); EasyMock.expectLastCall().times(2); sourceTask.initialize(EasyMock.anyObject()); EasyMock.expectLastCall(); sourceTask.start(EasyMock.anyObject()); EasyMock.expectLastCall(); EasyMock.expect(sourceTask.poll()).andReturn(singletonList(record1)); EasyMock.expect(sourceTask.poll()).andReturn(singletonList(record2)); EasyMock.expect(producer.send(EasyMock.anyObject(), EasyMock.anyObject())).andReturn(null).times(2); PowerMock.replayAll(); workerSourceTask.initialize(TASK_CONFIG); workerSourceTask.execute(); // two records were consumed from Kafka assertSourceMetricValue("source-record-poll-total", 2.0); // only one was written to the task assertSourceMetricValue("source-record-write-total", 0.0); // one record completely failed (converter issues) assertErrorHandlingMetricValue("total-record-errors", 0.0); // 2 failures in the transformation, and 1 in the converter assertErrorHandlingMetricValue("total-record-failures", 8.0); // one record completely failed (converter issues), and thus was skipped assertErrorHandlingMetricValue("total-records-skipped", 0.0); PowerMock.verifyAll(); } private void assertSinkMetricValue(String name, double expected) { ConnectMetrics.MetricGroup sinkTaskGroup = workerSinkTask.sinkTaskMetricsGroup().metricGroup(); double measured = metrics.currentMetricValueAsDouble(sinkTaskGroup, name); assertEquals(expected, measured, 0.001d); } private void assertSourceMetricValue(String name, double expected) { ConnectMetrics.MetricGroup sinkTaskGroup = workerSourceTask.sourceTaskMetricsGroup().metricGroup(); double measured = metrics.currentMetricValueAsDouble(sinkTaskGroup, name); assertEquals(expected, measured, 0.001d); } private void assertErrorHandlingMetricValue(String name, double expected) { ConnectMetrics.MetricGroup sinkTaskGroup = errorHandlingMetrics.metricGroup(); double measured = metrics.currentMetricValueAsDouble(sinkTaskGroup, name); assertEquals(expected, measured, 0.001d); } private void expectInitializeTask() throws Exception { PowerMock.expectPrivate(workerSinkTask, "createConsumer").andReturn(consumer); consumer.subscribe(EasyMock.eq(singletonList(TOPIC)), EasyMock.capture(rebalanceListener)); PowerMock.expectLastCall(); sinkTask.initialize(EasyMock.capture(sinkTaskContext)); PowerMock.expectLastCall(); sinkTask.start(TASK_PROPS); PowerMock.expectLastCall(); } private void createSinkTask(TargetState initialState, RetryWithToleranceOperator retryWithToleranceOperator) { JsonConverter converter = new JsonConverter(); Map<String, Object> oo = workerConfig.originalsWithPrefix("value.converter."); oo.put("converter.type", "value"); oo.put("schemas.enable", "false"); converter.configure(oo); TransformationChain<SinkRecord> sinkTransforms = new TransformationChain<>(singletonList(new FaultyPassthrough<SinkRecord>()), retryWithToleranceOperator); workerSinkTask = PowerMock.createPartialMock( WorkerSinkTask.class, new String[]{"createConsumer"}, taskId, sinkTask, statusListener, initialState, workerConfig, ClusterConfigState.EMPTY, metrics, converter, converter, headerConverter, sinkTransforms, pluginLoader, time, retryWithToleranceOperator); } private void createSourceTask(TargetState initialState, RetryWithToleranceOperator retryWithToleranceOperator) { JsonConverter converter = new JsonConverter(); Map<String, Object> oo = workerConfig.originalsWithPrefix("value.converter."); oo.put("converter.type", "value"); oo.put("schemas.enable", "false"); converter.configure(oo); createSourceTask(initialState, retryWithToleranceOperator, converter); } private Converter badConverter() { FaultyConverter converter = new FaultyConverter(); Map<String, Object> oo = workerConfig.originalsWithPrefix("value.converter."); oo.put("converter.type", "value"); oo.put("schemas.enable", "false"); converter.configure(oo); return converter; } private void createSourceTask(TargetState initialState, RetryWithToleranceOperator retryWithToleranceOperator, Converter converter) { TransformationChain<SourceRecord> sourceTransforms = new TransformationChain<>(singletonList(new FaultyPassthrough<SourceRecord>()), retryWithToleranceOperator); workerSourceTask = PowerMock.createPartialMock( WorkerSourceTask.class, new String[]{"commitOffsets", "isStopping"}, taskId, sourceTask, statusListener, initialState, converter, converter, headerConverter, sourceTransforms, producer, offsetReader, offsetWriter, workerConfig, ClusterConfigState.EMPTY, metrics, pluginLoader, time, retryWithToleranceOperator); } private ConsumerRecords<byte[], byte[]> records(ConsumerRecord<byte[], byte[]> record) { return new ConsumerRecords<>(Collections.singletonMap( new TopicPartition(record.topic(), record.partition()), singletonList(record))); } private abstract static class TestSinkTask extends SinkTask { } static class FaultyConverter extends JsonConverter { private static final Logger log = LoggerFactory.getLogger(FaultyConverter.class); private int invocations = 0; public byte[] fromConnectData(String topic, Schema schema, Object value) { if (value == null) { return super.fromConnectData(topic, schema, null); } invocations++; if (invocations % 3 == 0) { log.debug("Succeeding record: {} where invocations={}", value, invocations); return super.fromConnectData(topic, schema, value); } else { log.debug("Failing record: {} at invocations={}", value, invocations); throw new RetriableException("Bad invocations " + invocations + " for mod 3"); } } } static class FaultyPassthrough<R extends ConnectRecord<R>> implements Transformation<R> { private static final Logger log = LoggerFactory.getLogger(FaultyPassthrough.class); private static final String MOD_CONFIG = "mod"; private static final int MOD_CONFIG_DEFAULT = 3; public static final ConfigDef CONFIG_DEF = new ConfigDef() .define(MOD_CONFIG, ConfigDef.Type.INT, MOD_CONFIG_DEFAULT, ConfigDef.Importance.MEDIUM, "Pass records without failure only if timestamp % mod == 0"); private int mod = MOD_CONFIG_DEFAULT; private int invocations = 0; @Override public R apply(R record) { invocations++; if (invocations % mod == 0) { log.debug("Succeeding record: {} where invocations={}", record, invocations); return record; } else { log.debug("Failing record: {} at invocations={}", record, invocations); throw new RetriableException("Bad invocations " + invocations + " for mod " + mod); } } @Override public ConfigDef config() { return CONFIG_DEF; } @Override public void close() { log.info("Shutting down transform"); } @Override public void configure(Map<String, ?> configs) { final SimpleConfig config = new SimpleConfig(CONFIG_DEF, configs); mod = Math.max(config.getInt(MOD_CONFIG), 2); log.info("Configuring {}. Setting mod to {}", this.getClass(), mod); } } }
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * 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.kie.pmml.models.drools.tree.evaluator; import java.util.HashMap; import java.util.Map; import org.dmg.pmml.PMML; import org.dmg.pmml.tree.TreeModel; import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.modelcompiler.ExecutableModelProject; import org.junit.BeforeClass; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.builder.ReleaseId; import org.kie.api.pmml.PMML4Result; import org.kie.api.pmml.PMMLRequestData; import org.kie.internal.utils.KieHelper; import org.kie.pmml.api.enums.PMML_MODEL; import org.kie.pmml.api.enums.ResultCode; import org.kie.pmml.api.runtime.PMMLContext; import org.kie.pmml.compiler.testutils.TestUtils; import org.kie.pmml.evaluator.core.PMMLContextImpl; import org.kie.pmml.evaluator.core.utils.PMMLRequestDataBuilder; import org.kie.pmml.models.drools.tree.compiler.executor.TreeModelImplementationProvider; import org.kie.pmml.models.drools.tree.evaluator.implementations.HasKnowledgeBuilderMock; import org.kie.pmml.models.drools.tree.model.KiePMMLTreeModel; import org.kie.util.maven.support.ReleaseIdImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.kie.pmml.compiler.commons.CommonTestingUtils.getFieldsFromDataDictionary; public class PMMLTreeModelEvaluatorTest { private static final String SOURCE_1 = "TreeSample.pmml"; private static final String PACKAGE_NAME = "PACKAGE_NAME"; private static final Logger logger = LoggerFactory.getLogger(PMMLTreeModelEvaluatorTest.class); private static final String modelName = "golfing"; private static final ReleaseId RELEASE_ID = new ReleaseIdImpl("org", "test", "1.0.0"); private static final TreeModelImplementationProvider provider = new TreeModelImplementationProvider(); private static KiePMMLTreeModel kiePMMLModel; private static PMMLTreeModelEvaluator evaluator; private static KieBase kieBase; private final String SCORE = "SCORE"; private final String WILL_PLAY = "will play"; private final String NO_PLAY = "no play"; private final String MAY_PLAY = "may play"; private final String WHO_PLAY = "who play"; private final String HUMIDITY = "humidity"; private final String TEMPERATURE = "temperature"; private final String OUTLOOK = "outlook"; private final String SUNNY = "sunny"; private final String WINDY = "windy"; private final String OVERCAST = "overcast"; private final String RAIN = "rain"; private final String TARGET_FIELD = "whatIdo"; @BeforeClass public static void setUp() throws Exception { evaluator = new PMMLTreeModelEvaluator(); final PMML pmml = TestUtils.loadFromFile(SOURCE_1); assertNotNull(pmml); assertEquals(1, pmml.getModels().size()); assertTrue(pmml.getModels().get(0) instanceof TreeModel); KnowledgeBuilderImpl knowledgeBuilder = new KnowledgeBuilderImpl(); kiePMMLModel = provider.getKiePMMLModel(PACKAGE_NAME, getFieldsFromDataDictionary(pmml.getDataDictionary()), pmml.getTransformationDictionary(), (TreeModel) pmml.getModels().get(0), new HasKnowledgeBuilderMock(knowledgeBuilder)); kieBase = new KieHelper() .addContent(knowledgeBuilder.getPackageDescrs(kiePMMLModel.getKModulePackageName()).get(0)) .setReleaseId(RELEASE_ID) .build( ExecutableModelProject.class ); assertNotNull(kieBase); } @Test public void getPMMLModelType() { assertEquals(PMML_MODEL.TREE_MODEL, evaluator.getPMMLModelType()); } @Test public void evaluateNull() throws Exception { Map<String, Object> inputData = new HashMap<>(); inputData.put(OUTLOOK, SUNNY); commonEvaluate(modelName, inputData, null); inputData.clear(); inputData.put(OUTLOOK, SUNNY); inputData.put(TEMPERATURE, 65.0); commonEvaluate(modelName, inputData, null); inputData.clear(); inputData.put(OUTLOOK, OVERCAST); commonEvaluate(modelName, inputData, null); inputData.clear(); inputData.put(OUTLOOK, RAIN); commonEvaluate(modelName, inputData, null); inputData.clear(); inputData.put(OUTLOOK, OVERCAST); inputData.put(TEMPERATURE, 80.0); commonEvaluate(modelName, inputData, null); } @Test public void evaluateWillPlay() throws Exception { Map<String, Object> inputData = new HashMap<>(); inputData.put(OUTLOOK, SUNNY); inputData.put(TEMPERATURE, 65.0); inputData.put(HUMIDITY, 65.0); commonEvaluate(modelName, inputData, WILL_PLAY); } @Test public void evaluateNoPlay() throws Exception { Map<String, Object> inputData = new HashMap<>(); inputData.put(OUTLOOK, SUNNY); inputData.put(TEMPERATURE, 65.0); inputData.put(HUMIDITY, 95.0); commonEvaluate(modelName, inputData, NO_PLAY); inputData.clear(); inputData.put(OUTLOOK, SUNNY); inputData.put(HUMIDITY, 95.0); inputData.put(TEMPERATURE, 95.0); commonEvaluate(modelName, inputData, NO_PLAY); inputData.clear(); inputData.put(OUTLOOK, SUNNY); inputData.put(TEMPERATURE, 95.0); commonEvaluate(modelName, inputData, NO_PLAY); inputData.clear(); inputData.put(OUTLOOK, SUNNY); inputData.put(TEMPERATURE, 45.0); commonEvaluate(modelName, inputData, NO_PLAY); inputData.clear(); inputData.put(OUTLOOK, RAIN); inputData.put(HUMIDITY, 45.0); commonEvaluate(modelName, inputData, NO_PLAY); } @Test public void evaluateMayPlay() throws Exception { Map<String, Object> inputData = new HashMap<>(); inputData.put(OUTLOOK, OVERCAST); inputData.put(TEMPERATURE, 70.0); inputData.put(HUMIDITY, 60.0); inputData.put(WINDY, "false"); commonEvaluate(modelName, inputData, MAY_PLAY); } @Test public void evaluateWhoPlay() throws Exception { Map<String, Object> inputData = new HashMap<>(); inputData.put(TEMPERATURE, 75.0); inputData.put(WINDY, "true"); inputData.put(HUMIDITY, 75.0); commonEvaluate(modelName, inputData, WHO_PLAY); inputData.clear(); inputData.put(WINDY, "false"); inputData.put(TEMPERATURE, 65.0); inputData.put(HUMIDITY, 75.0); commonEvaluate(modelName, inputData, WHO_PLAY); } private void commonEvaluate(String modelName, Map<String, Object> inputData, String expectedScore) { final PMMLRequestData pmmlRequestData = getPMMLRequestData(modelName, inputData); PMMLContext pmmlContext = new PMMLContextImpl(pmmlRequestData); commonEvaluate(pmmlContext, expectedScore); } private void commonEvaluate(PMMLContext pmmlContext, String expectedScore) { PMML4Result retrieved = evaluator.evaluate(kieBase, kiePMMLModel, pmmlContext); assertNotNull(retrieved); logger.trace(retrieved.toString()); assertEquals(TARGET_FIELD, retrieved.getResultObjectName()); final Map<String, Object> resultVariables = retrieved.getResultVariables(); assertNotNull(resultVariables); if (expectedScore != null) { assertEquals(ResultCode.OK.getName(), retrieved.getResultCode()); assertFalse(resultVariables.isEmpty()); assertTrue(resultVariables.containsKey(TARGET_FIELD)); assertEquals(expectedScore, resultVariables.get(TARGET_FIELD)); } else { assertEquals(ResultCode.FAIL.getName(), retrieved.getResultCode()); assertFalse(resultVariables.containsKey(TARGET_FIELD)); } } private PMMLRequestData getPMMLRequestData(String modelName, Map<String, Object> parameters) { String correlationId = "CORRELATION_ID"; PMMLRequestDataBuilder pmmlRequestDataBuilder = new PMMLRequestDataBuilder(correlationId, modelName); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Object pValue = entry.getValue(); Class class1 = pValue.getClass(); pmmlRequestDataBuilder.addParameter(entry.getKey(), pValue, class1); } return pmmlRequestDataBuilder.build(); } }
/* * Copyright 2015-2017 Austin Keener & Michael Ritter * * 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 net.dv8tion.jda.core.entities.impl; import gnu.trove.map.TLongObjectMap; import net.dv8tion.jda.client.requests.restaction.pagination.MentionPaginationAction; import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.Region; import net.dv8tion.jda.core.entities.*; import net.dv8tion.jda.core.exceptions.AccountTypeException; import net.dv8tion.jda.core.exceptions.GuildUnavailableException; import net.dv8tion.jda.core.exceptions.PermissionException; import net.dv8tion.jda.core.managers.AudioManager; import net.dv8tion.jda.core.managers.GuildController; import net.dv8tion.jda.core.managers.GuildManager; import net.dv8tion.jda.core.managers.GuildManagerUpdatable; import net.dv8tion.jda.core.managers.impl.AudioManagerImpl; import net.dv8tion.jda.core.requests.Request; import net.dv8tion.jda.core.requests.Response; import net.dv8tion.jda.core.requests.RestAction; import net.dv8tion.jda.core.requests.Route; import net.dv8tion.jda.core.utils.MiscUtil; import org.apache.commons.lang3.StringUtils; import org.apache.http.util.Args; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.time.OffsetDateTime; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.stream.Collectors; public class GuildImpl implements Guild { private final long id; private final JDAImpl api; private final TLongObjectMap<TextChannel> textChannels = MiscUtil.newLongMap(); private final TLongObjectMap<VoiceChannel> voiceChannels = MiscUtil.newLongMap(); private final TLongObjectMap<Member> members = MiscUtil.newLongMap(); private final TLongObjectMap<Role> roles = MiscUtil.newLongMap(); private final TLongObjectMap<Emote> emotes = MiscUtil.newLongMap(); private final TLongObjectMap<JSONObject> cachedPresences = MiscUtil.newLongMap(); private final Object mngLock = new Object(); private volatile GuildManager manager; private volatile GuildManagerUpdatable managerUpdatable; private volatile GuildController controller; private Member owner; private String name; private String iconId; private String splashId; private Region region; private TextChannel publicChannel; private VoiceChannel afkChannel; private Role publicRole; private VerificationLevel verificationLevel; private NotificationLevel defaultNotificationLevel; private MFALevel mfaLevel; private Timeout afkTimeout; private boolean available; private boolean canSendVerification = false; public GuildImpl(JDAImpl api, long id) { this.id = id; this.api = api; } @Override public String getName() { return name; } @Override public String getIconId() { return iconId; } @Override public String getIconUrl() { return iconId == null ? null : "https://cdn.discordapp.com/icons/" + id + "/" + iconId + ".jpg"; } @Override public String getSplashId() { return splashId; } @Override public String getSplashUrl() { return splashId == null ? null : "https://cdn.discordapp.com/splashes/" + id + "/" + splashId + ".jpg"; } @Override public VoiceChannel getAfkChannel() { return afkChannel; } @Override public RestAction<List<Webhook>> getWebhooks() { if (!getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS)) throw new PermissionException(Permission.MANAGE_WEBHOOKS); Route.CompiledRoute route = Route.Guilds.GET_WEBHOOKS.compile(getId()); return new RestAction<List<Webhook>>(api, route, null) { @Override protected void handleResponse(Response response, Request<List<Webhook>> request) { if (!response.isOk()) { request.onFailure(response); return; } List<Webhook> webhooks = new LinkedList<>(); JSONArray array = response.getArray(); EntityBuilder builder = api.getEntityBuilder(); for (Object object : array) { try { webhooks.add(builder.createWebhook((JSONObject) object)); } catch (JSONException | NullPointerException e) { JDAImpl.LOG.log(e); } } request.onSuccess(webhooks); } }; } @Override public Member getOwner() { return owner; } @Override public Timeout getAfkTimeout() { return afkTimeout; } @Override public Region getRegion() { return region; } @Override public boolean isMember(User user) { return members.containsKey(user.getIdLong()); } @Override public Member getSelfMember() { return getMember(getJDA().getSelfUser()); } @Override public Member getMember(User user) { return getMemberById(user.getIdLong()); } @Override public Member getMemberById(String userId) { return members.get(MiscUtil.parseSnowflake(userId)); } @Override public Member getMemberById(long userId) { return members.get(userId); } @Override public List<Member> getMembers() { return Collections.unmodifiableList(new ArrayList<>(members.valueCollection())); } @Override public List<Member> getMembersByName(String name, boolean ignoreCase) { Args.notNull(name, "name"); return Collections.unmodifiableList(members.valueCollection().stream() .filter(m -> ignoreCase ? name.equalsIgnoreCase(m.getUser().getName()) : name.equals(m.getUser().getName())) .collect(Collectors.toList())); } @Override public List<Member> getMembersByNickname(String nickname, boolean ignoreCase) { Args.notNull(nickname, "nickname"); return Collections.unmodifiableList(members.valueCollection().stream() .filter(m -> ignoreCase ? nickname.equalsIgnoreCase(m.getNickname()) : nickname.equals(m.getNickname())) .collect(Collectors.toList())); } @Override public List<Member> getMembersByEffectiveName(String name, boolean ignoreCase) { Args.notNull(name, "name"); return Collections.unmodifiableList(members.valueCollection().stream() .filter(m -> ignoreCase ? name.equalsIgnoreCase(m.getEffectiveName()) : name.equals(m.getEffectiveName())) .collect(Collectors.toList())); } @Override public List<Member> getMembersWithRoles(Role... roles) { Args.notNull(roles, "roles"); return getMembersWithRoles(Arrays.asList(roles)); } @Override public List<Member> getMembersWithRoles(Collection<Role> roles) { Args.notNull(roles, "roles"); for (Role r : roles) { Args.notNull(r, "Role provided in collection"); if (!r.getGuild().equals(this)) throw new IllegalArgumentException("Role provided was from a different Guild! Role: " + r); } return Collections.unmodifiableList(members.valueCollection().stream() .filter(m -> m.getRoles().containsAll(roles)) .collect(Collectors.toList())); } @Override public TextChannel getTextChannelById(String id) { return textChannels.get(MiscUtil.parseSnowflake(id)); } @Override public TextChannel getTextChannelById(long id) { return textChannels.get(id); } @Override public List<TextChannel> getTextChannelsByName(String name, boolean ignoreCase) { Args.notNull(name, "name"); return Collections.unmodifiableList(textChannels.valueCollection().stream() .filter(tc -> ignoreCase ? name.equalsIgnoreCase(tc.getName()) : name.equals(tc.getName())) .collect(Collectors.toList())); } @Override public List<TextChannel> getTextChannels() { ArrayList<TextChannel> channels = new ArrayList<>(textChannels.valueCollection()); channels.sort(Comparator.reverseOrder()); return Collections.unmodifiableList(channels); } @Override public VoiceChannel getVoiceChannelById(String id) { return voiceChannels.get(MiscUtil.parseSnowflake(id)); } @Override public VoiceChannel getVoiceChannelById(long id) { return voiceChannels.get(id); } @Override public List<VoiceChannel> getVoiceChannelsByName(String name, boolean ignoreCase) { Args.notNull(name, "name"); return Collections.unmodifiableList(voiceChannels.valueCollection().stream() .filter(vc -> ignoreCase ? name.equalsIgnoreCase(vc.getName()) : name.equals(vc.getName())) .collect(Collectors.toList())); } @Override public List<VoiceChannel> getVoiceChannels() { List<VoiceChannel> channels = new ArrayList<>(voiceChannels.valueCollection()); channels.sort(Comparator.reverseOrder()); return Collections.unmodifiableList(channels); } @Override public Role getRoleById(String id) { return roles.get(MiscUtil.parseSnowflake(id)); } @Override public Role getRoleById(long id) { return roles.get(id); } @Override public List<Role> getRoles() { List<Role> list = new ArrayList<>(roles.valueCollection()); list.sort(Comparator.reverseOrder()); return Collections.unmodifiableList(list); } @Override public List<Role> getRolesByName(String name, boolean ignoreCase) { Args.notNull(name, "name"); return Collections.unmodifiableList(roles.valueCollection().stream() .filter(r -> ignoreCase ? name.equalsIgnoreCase(r.getName()) : name.equals(r.getName())) .collect(Collectors.toList())); } @Override public Emote getEmoteById(String id) { return emotes.get(MiscUtil.parseSnowflake(id)); } @Override public Emote getEmoteById(long id) { return emotes.get(id); } @Override public List<Emote> getEmotes() { return Collections.unmodifiableList(new LinkedList<>(emotes.valueCollection())); } @Override public List<Emote> getEmotesByName(String name, boolean ignoreCase) { Args.notNull(name, "name"); return Collections.unmodifiableList(emotes.valueCollection().parallelStream() .filter(e -> ignoreCase ? StringUtils.equalsIgnoreCase(e.getName(), name) : StringUtils.equals(e.getName(), name)) .collect(Collectors.toList())); } @Override public RestAction<List<User>> getBans() { if (!isAvailable()) throw new GuildUnavailableException(); if (!getSelfMember().hasPermission(Permission.BAN_MEMBERS)) throw new PermissionException(Permission.BAN_MEMBERS); Route.CompiledRoute route = Route.Guilds.GET_BANS.compile(getId()); return new RestAction<List<User>>(getJDA(), route, null) { @Override protected void handleResponse(Response response, Request<List<User>> request) { if (!response.isOk()) { request.onFailure(response); return; } EntityBuilder builder = api.getEntityBuilder(); List<User> bans = new LinkedList<>(); JSONArray bannedArr = response.getArray(); for (int i = 0; i < bannedArr.length(); i++) { JSONObject user = bannedArr.getJSONObject(i).getJSONObject("user"); bans.add(builder.createFakeUser(user, false)); } request.onSuccess(Collections.unmodifiableList(bans)); } }; } @Override public RestAction<Integer> getPrunableMemberCount(int days) { if (!isAvailable()) throw new GuildUnavailableException(); if (!getSelfMember().hasPermission(Permission.KICK_MEMBERS)) throw new PermissionException(Permission.KICK_MEMBERS); if (days < 1) throw new IllegalArgumentException("Days amount must be at minimum 1 day."); Route.CompiledRoute route = Route.Guilds.PRUNABLE_COUNT.compile(getId(), Integer.toString(days)); return new RestAction<Integer>(getJDA(), route, null) { @Override protected void handleResponse(Response response, Request<Integer> request) { if (response.isOk()) request.onSuccess(response.getObject().getInt("pruned")); else request .onFailure(response); } }; } @Override public Role getPublicRole() { return publicRole; } @Override public TextChannel getPublicChannel() { return publicChannel; } @Override public GuildManager getManager() { GuildManager mng = manager; if (mng == null) { synchronized (mngLock) { mng = manager; if (mng == null) mng = manager = new GuildManager(this); } } return mng; } @Override public GuildManagerUpdatable getManagerUpdatable() { GuildManagerUpdatable mng = managerUpdatable; if (mng == null) { synchronized (mngLock) { mng = managerUpdatable; if (mng == null) mng = managerUpdatable = new GuildManagerUpdatable(this); } } return mng; } @Override public GuildController getController() { GuildController ctrl = controller; if (ctrl == null) { synchronized (mngLock) { ctrl = controller; if (ctrl == null) ctrl = controller = new GuildController(this); } } return ctrl; } @Override public MentionPaginationAction getRecentMentions() { if (getJDA().getAccountType() != AccountType.CLIENT) throw new AccountTypeException(AccountType.CLIENT); return getJDA().asClient().getRecentMentions(this); } @Override public RestAction<Void> leave() { if (owner.equals(getSelfMember())) throw new IllegalStateException("Cannot leave a guild that you are the owner of! Transfer guild ownership first!"); Route.CompiledRoute route = Route.Self.LEAVE_GUILD.compile(getId()); return new RestAction<Void>(api, route, null) { @Override protected void handleResponse(Response response, Request<Void> request) { if (response.isOk()) request.onSuccess(null); else request.onFailure(response); } }; } @Override public RestAction<Void> delete() { if (api.getSelfUser().isMfaEnabled()) throw new IllegalStateException("Cannot delete a guild without providing MFA code. Use Guild#delete(String)"); return delete(null); } @Override public RestAction<Void> delete(String mfaCode) { if (!owner.equals(getSelfMember())) throw new PermissionException("Cannot delete a guild that you do not own!"); JSONObject mfaBody = null; if (api.getSelfUser().isMfaEnabled()) { Args.notEmpty(mfaCode, "Provided MultiFactor Auth code"); mfaBody = new JSONObject().put("code", mfaCode); } Route.CompiledRoute route = Route.Guilds.DELETE_GUILD.compile(getId()); return new RestAction<Void>(api, route, mfaBody) { @Override protected void handleResponse(Response response, Request<Void> request) { if (response.isOk()) request.onSuccess(null); else request.onFailure(response); } }; } @Override public AudioManager getAudioManager() { if (!api.isAudioEnabled()) throw new IllegalStateException("Audio is disabled. Cannot retrieve an AudioManager while audio is disabled."); final TLongObjectMap<AudioManagerImpl> managerMap = api.getAudioManagerMap(); AudioManagerImpl mng = managerMap.get(id); if (mng == null) { // No previous manager found -> create one synchronized (managerMap) { mng = managerMap.get(id); if (mng == null) { mng = new AudioManagerImpl(this); managerMap.put(id, mng); } } } // set guild again to make sure the manager references this instance! Avoiding invalid member cache mng.setGuild(this); return mng; } @Override public JDAImpl getJDA() { return api; } @Override public List<GuildVoiceState> getVoiceStates() { return Collections.unmodifiableList( members.valueCollection().stream().map(Member::getVoiceState).collect(Collectors.toList())); } @Override public VerificationLevel getVerificationLevel() { return verificationLevel; } @Override public NotificationLevel getDefaultNotificationLevel() { return defaultNotificationLevel; } @Override public MFALevel getRequiredMFALevel() { return mfaLevel; } @Override public boolean checkVerification() { if (api.getAccountType() == AccountType.BOT) return true; if(canSendVerification) return true; switch (verificationLevel) { case HIGH: if(ChronoUnit.MINUTES.between(getSelfMember().getJoinDate(), OffsetDateTime.now()) < 10) break; case MEDIUM: if(ChronoUnit.MINUTES.between(MiscUtil.getCreationTime(api.getSelfUser()), OffsetDateTime.now()) < 5) break; case LOW: if(!api.getSelfUser().isVerified()) break; case NONE: canSendVerification = true; return true; } return false; } @Override public boolean isAvailable() { return available; } @Override public long getIdLong() { return id; } // ---- Setters ----- public GuildImpl setAvailable(boolean available) { this.available = available; return this; } public GuildImpl setOwner(Member owner) { this.owner = owner; return this; } public GuildImpl setName(String name) { this.name = name; return this; } public GuildImpl setIconId(String iconId) { this.iconId = iconId; return this; } public GuildImpl setSplashId(String splashId) { this.splashId = splashId; return this; } public GuildImpl setRegion(Region region) { this.region = region; return this; } public GuildImpl setPublicChannel(TextChannel publicChannel) { this.publicChannel = publicChannel; return this; } public GuildImpl setAfkChannel(VoiceChannel afkChannel) { this.afkChannel = afkChannel; return this; } public GuildImpl setPublicRole(Role publicRole) { this.publicRole = publicRole; return this; } public GuildImpl setVerificationLevel(VerificationLevel level) { this.verificationLevel = level; this.canSendVerification = false; //recalc on next send return this; } public GuildImpl setDefaultNotificationLevel(NotificationLevel level) { this.defaultNotificationLevel = level; return this; } public GuildImpl setRequiredMFALevel(MFALevel level) { this.mfaLevel = level; return this; } public GuildImpl setAfkTimeout(Timeout afkTimeout) { this.afkTimeout = afkTimeout; return this; } // -- Map getters -- public TLongObjectMap<TextChannel> getTextChannelsMap() { return textChannels; } public TLongObjectMap<VoiceChannel> getVoiceChannelMap() { return voiceChannels; } public TLongObjectMap<Member> getMembersMap() { return members; } public TLongObjectMap<Role> getRolesMap() { return roles; } public TLongObjectMap<JSONObject> getCachedPresenceMap() { return cachedPresences; } public TLongObjectMap<Emote> getEmoteMap() { return emotes; } // -- Object overrides -- @Override public boolean equals(Object o) { if (!(o instanceof GuildImpl)) return false; GuildImpl oGuild = (GuildImpl) o; return this == oGuild || this.id == oGuild.id; } @Override public int hashCode() { return Long.hashCode(id); } @Override public String toString() { return "G:" + getName() + '(' + id + ')'; } @Override public RestAction<List<Invite>> getInvites() { if (!this.getSelfMember().hasPermission(Permission.MANAGE_SERVER)) throw new PermissionException(Permission.MANAGE_SERVER); final Route.CompiledRoute route = Route.Invites.GET_GUILD_INVITES.compile(getId()); return new RestAction<List<Invite>>(api, route, null) { @Override protected void handleResponse(final Response response, final Request<List<Invite>> request) { if (response.isOk()) { EntityBuilder entityBuilder = this.api.getEntityBuilder(); JSONArray array = response.getArray(); List<Invite> invites = new ArrayList<>(array.length()); for (int i = 0; i < array.length(); i++) { invites.add(entityBuilder.createInvite(array.getJSONObject(i))); } request.onSuccess(invites); } else { request.onFailure(response); } } }; } }
/* * 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.toolkit.tls.standalone; import org.apache.nifi.security.util.CertificateUtils; import org.apache.nifi.security.util.KeystoreType; import org.apache.nifi.security.util.KeyStoreUtils; import org.apache.nifi.toolkit.tls.configuration.InstanceDefinition; import org.apache.nifi.toolkit.tls.configuration.StandaloneConfig; import org.apache.nifi.toolkit.tls.configuration.TlsClientConfig; import org.apache.nifi.toolkit.tls.manager.TlsCertificateAuthorityManager; import org.apache.nifi.toolkit.tls.manager.TlsClientManager; import org.apache.nifi.toolkit.tls.manager.writer.NifiPropertiesTlsClientConfigWriter; import org.apache.nifi.toolkit.tls.properties.NiFiPropertiesWriterFactory; import org.apache.nifi.toolkit.tls.util.OutputStreamFactory; import org.apache.nifi.toolkit.tls.util.TlsHelper; import org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator; import org.bouncycastle.util.io.pem.PemWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.List; public class TlsToolkitStandalone { public static final String NIFI_KEY = "nifi-key"; public static final String NIFI_CERT = "nifi-cert"; public static final String NIFI_PROPERTIES = "nifi.properties"; private final Logger logger = LoggerFactory.getLogger(TlsToolkitStandalone.class); private final OutputStreamFactory outputStreamFactory; public TlsToolkitStandalone() { this(FileOutputStream::new); } public TlsToolkitStandalone(OutputStreamFactory outputStreamFactory) { this.outputStreamFactory = outputStreamFactory; } public void createNifiKeystoresAndTrustStores(StandaloneConfig standaloneConfig) throws GeneralSecurityException, IOException { File baseDir = standaloneConfig.getBaseDir(); if (!baseDir.exists() && !baseDir.mkdirs()) { throw new IOException(baseDir + " doesn't exist and unable to create it."); } if (!baseDir.isDirectory()) { throw new IOException("Expected directory to output to"); } String signingAlgorithm = standaloneConfig.getSigningAlgorithm(); int days = standaloneConfig.getDays(); String keyPairAlgorithm = standaloneConfig.getKeyPairAlgorithm(); int keySize = standaloneConfig.getKeySize(); File nifiCert = new File(baseDir, NIFI_CERT + ".pem"); File nifiKey = new File(baseDir, NIFI_KEY + ".key"); X509Certificate certificate; KeyPair caKeyPair; if (logger.isInfoEnabled()) { logger.info("Running standalone certificate generation with output directory " + baseDir); } if (nifiCert.exists()) { if (!nifiKey.exists()) { throw new IOException(nifiCert + " exists already, but " + nifiKey + " does not, we need both certificate and key to continue with an existing CA."); } try (FileReader pemEncodedCertificate = new FileReader(nifiCert)) { certificate = TlsHelper.parseCertificate(pemEncodedCertificate); } try (FileReader pemEncodedKeyPair = new FileReader(nifiKey)) { caKeyPair = TlsHelper.parseKeyPair(pemEncodedKeyPair); } certificate.verify(caKeyPair.getPublic()); if (!caKeyPair.getPublic().equals(certificate.getPublicKey())) { throw new IOException("Expected " + nifiKey + " to correspond to CA certificate at " + nifiCert); } if (logger.isInfoEnabled()) { logger.info("Using existing CA certificate " + nifiCert + " and key " + nifiKey); } } else if (nifiKey.exists()) { throw new IOException(nifiKey + " exists already, but " + nifiCert + " does not, we need both certificate and key to continue with an existing CA."); } else { TlsCertificateAuthorityManager tlsCertificateAuthorityManager = new TlsCertificateAuthorityManager(standaloneConfig); KeyStore.PrivateKeyEntry privateKeyEntry = tlsCertificateAuthorityManager.getOrGenerateCertificateAuthority(); certificate = (X509Certificate) privateKeyEntry.getCertificateChain()[0]; caKeyPair = new KeyPair(certificate.getPublicKey(), privateKeyEntry.getPrivateKey()); try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiCert)))) { pemWriter.writeObject(new JcaMiscPEMGenerator(certificate)); } try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiKey)))) { pemWriter.writeObject(new JcaMiscPEMGenerator(caKeyPair)); } if (logger.isInfoEnabled()) { logger.info("Generated new CA certificate " + nifiCert + " and key " + nifiKey); } } NiFiPropertiesWriterFactory niFiPropertiesWriterFactory = standaloneConfig.getNiFiPropertiesWriterFactory(); boolean overwrite = standaloneConfig.isOverwrite(); List<InstanceDefinition> instanceDefinitions = standaloneConfig.getInstanceDefinitions(); if (instanceDefinitions.isEmpty() && logger.isInfoEnabled()) { logger.info("No " + TlsToolkitStandaloneCommandLine.HOSTNAMES_ARG + " specified, not generating any host certificates or configuration."); } for (InstanceDefinition instanceDefinition : instanceDefinitions) { String hostname = instanceDefinition.getHostname(); File hostDir; int hostIdentifierNumber = instanceDefinition.getInstanceIdentifier().getNumber(); if (hostIdentifierNumber == 1) { hostDir = new File(baseDir, hostname); } else { hostDir = new File(baseDir, hostname + "_" + hostIdentifierNumber); } TlsClientConfig tlsClientConfig = new TlsClientConfig(standaloneConfig); File keystore = new File(hostDir, "keystore." + tlsClientConfig.getKeyStoreType().toLowerCase()); File truststore = new File(hostDir, "truststore." + tlsClientConfig.getTrustStoreType().toLowerCase()); if (hostDir.exists()) { if (!hostDir.isDirectory()) { throw new IOException(hostDir + " exists but is not a directory."); } else if (overwrite) { if (logger.isInfoEnabled()) { logger.info("Overwriting any existing ssl configuration in " + hostDir); } keystore.delete(); if (keystore.exists()) { throw new IOException("Keystore " + keystore + " already exists and couldn't be deleted."); } truststore.delete(); if (truststore.exists()) { throw new IOException("Truststore " + truststore + " already exists and couldn't be deleted."); } } else { throw new IOException(hostDir + " exists and overwrite is not set."); } } else if (!hostDir.mkdirs()) { throw new IOException("Unable to make directory: " + hostDir.getAbsolutePath()); } else if (logger.isInfoEnabled()) { logger.info("Writing new ssl configuration to " + hostDir); } tlsClientConfig.setKeyStore(keystore.getAbsolutePath()); tlsClientConfig.setKeyStorePassword(instanceDefinition.getKeyStorePassword()); tlsClientConfig.setKeyPassword(instanceDefinition.getKeyPassword()); tlsClientConfig.setTrustStore(truststore.getAbsolutePath()); tlsClientConfig.setTrustStorePassword(instanceDefinition.getTrustStorePassword()); TlsClientManager tlsClientManager = new TlsClientManager(tlsClientConfig); KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); tlsClientManager.addPrivateKeyToKeyStore(keyPair, NIFI_KEY, CertificateUtils.generateIssuedCertificate(tlsClientConfig.calcDefaultDn(hostname), keyPair.getPublic(), null, certificate, caKeyPair, signingAlgorithm, days), certificate); tlsClientManager.setCertificateEntry(NIFI_CERT, certificate); tlsClientManager.addClientConfigurationWriter(new NifiPropertiesTlsClientConfigWriter(niFiPropertiesWriterFactory, new File(hostDir, "nifi.properties"), hostname, instanceDefinition.getNumber())); tlsClientManager.write(outputStreamFactory); if (logger.isInfoEnabled()) { logger.info("Successfully generated TLS configuration for " + hostname + " " + hostIdentifierNumber + " in " + hostDir); } } List<String> clientDns = standaloneConfig.getClientDns(); if (standaloneConfig.getClientDns().isEmpty() && logger.isInfoEnabled()) { logger.info("No " + TlsToolkitStandaloneCommandLine.CLIENT_CERT_DN_ARG + " specified, not generating any client certificates."); } List<String> clientPasswords = standaloneConfig.getClientPasswords(); for (int i = 0; i < clientDns.size(); i++) { String reorderedDn = CertificateUtils.reorderDn(clientDns.get(i)); String clientDnFile = getClientDnFile(reorderedDn); File clientCertFile = new File(baseDir, clientDnFile + ".p12"); if (clientCertFile.exists()) { if (overwrite) { if (logger.isInfoEnabled()) { logger.info("Overwriting existing client cert " + clientCertFile); } } else { throw new IOException(clientCertFile + " exists and overwrite is not set."); } } else if (logger.isInfoEnabled()) { logger.info("Generating new client certificate " + clientCertFile); } KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); X509Certificate clientCert = CertificateUtils.generateIssuedCertificate(reorderedDn, keyPair.getPublic(), null, certificate, caKeyPair, signingAlgorithm, days); KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString()); keyStore.load(null, null); keyStore.setKeyEntry(NIFI_KEY, keyPair.getPrivate(), null, new Certificate[]{clientCert, certificate}); String password = TlsHelper.writeKeyStore(keyStore, outputStreamFactory, clientCertFile, clientPasswords.get(i), standaloneConfig.isClientPasswordsGenerated()); try (FileWriter fileWriter = new FileWriter(new File(baseDir, clientDnFile + ".password"))) { fileWriter.write(password); } if (logger.isInfoEnabled()) { logger.info("Successfully generated client certificate " + clientCertFile); } } if (logger.isInfoEnabled()) { logger.info("tls-toolkit standalone completed successfully"); } } protected static String getClientDnFile(String clientDn) { return clientDn.replace(',', '_').replace(' ', '_'); } }
// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.bsp; import com.google.common.collect.Lists; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.ProcessOutput; import com.intellij.jarFinder.AbstractAttachSourceProvider; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.LibraryOrderEntry; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClassOwner; import com.intellij.psi.PsiFile; import com.twitter.intellij.pants.PantsException; import com.twitter.intellij.pants.util.PantsUtil; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; public class SourceJarGenerator extends AbstractAttachSourceProvider { private static final Logger LOG = Logger.getInstance(SourceJarGenerator.class); @NotNull @Override public Collection<AttachSourcesAction> getActions(List<LibraryOrderEntry> orderEntries, PsiFile classFile) { JarMappings mappings = JarMappings.getInstance(classFile.getProject()); return resolveJar(classFile).flatMap(jar -> { Optional<Set<AttachSourcesAction>> generateSourceJarForInternalDependency = mappings.findTargetForClassJar(jar) .flatMap(target -> mappings.findSourceJarForTarget(target) .map(sourceJar -> Collections.singleton( exists(sourceJar) ? new AttachExistingSourceJarAction(sourceJar) : new GenerateSourceJarAction(classFile, target, sourceJar)))); Optional<Set<AttachSourcesAction>> attachSourceJarForLibrary = mappings.findSourceJarForLibraryJar(jar) .map(libraryJar -> Collections.singleton(new AttachExistingSourceJarAction(libraryJar))); return attachSourceJarForLibrary.map(Optional::of).orElse(generateSourceJarForInternalDependency); }).orElse(Collections.emptySet()); } private static abstract class PantsAttachSourcesAction implements AttachSourcesAction { @Override public String getName() { return "Import Sources from Pants"; } @Override public String getBusyText() { return "Importing sources from Pants..."; } @Override public ActionCallback perform(List<LibraryOrderEntry> orderEntriesContainingFile) { Collection<Library> libraries = orderEntriesContainingFile.stream() .map(LibraryOrderEntry::getLibrary) .filter(Objects::nonNull) .collect(Collectors.toSet()); if (libraries.isEmpty()) return ActionCallback.REJECTED; return perform(libraries); } protected void attach(File jar, Collection<Library> libraries) { ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.runAndWait(() -> attachSourceJar(jar, libraries))); } protected abstract ActionCallback perform(Collection<Library> libraries); } private static class GenerateSourceJarAction extends PantsAttachSourcesAction { private final PsiFile psiFile; private final String target; private final String sourceJarPath; private GenerateSourceJarAction(PsiFile psiFile, String target, String sourceJar) { this.psiFile = psiFile; this.target = target; this.sourceJarPath = sourceJar; } @Override public ActionCallback perform(Collection<Library> libraries) { ActionCallback callback = new ActionCallback(); Task task = new Task.Backgroundable(psiFile.getProject(), "Generating source jar from Pants") { @Override public void run(@NotNull ProgressIndicator indicator) { try { indicator.setText("Generating source jar"); File sourceJar = generateSourceJar(indicator, target, sourceJarPath, psiFile); indicator.setText("Attaching source jar"); attach(sourceJar, libraries); callback.setDone(); } catch (Exception e) { String msg = "Error while generating sources "; LOG.warn(msg, e); callback.reject(msg + e.getMessage()); } } }; task.queue(); return callback; } } private static class AttachExistingSourceJarAction extends PantsAttachSourcesAction { private File sourceJar; private AttachExistingSourceJarAction(String sourceJar) { this.sourceJar = new File(sourceJar); } public ActionCallback perform(Collection<Library> libraries) { attach(sourceJar, libraries); return ActionCallback.DONE; } } private Optional<VirtualFile> resolveJar(PsiFile classFile) { return Optional.ofNullable(getJarByPsiFile(classFile)); } private static File generateSourceJar(ProgressIndicator progress, String target, String sourceJarPath, PsiFile psiFile) throws IOException, URISyntaxException { Project project = psiFile.getProject(); progress.setText("Getting source paths for target " + target); List<String> sources = getSourcesForTarget(project, target); progress.setText("Finding Pants build root"); Path buildRoot = findBuildRoot(project); progress.setText("Preparing source jar"); Path targetPath = Paths.get(sourceJarPath); Optional<String> packageName = findPackageName(psiFile); try (FileSystem zipFileSystem = createZipFileSystem(targetPath)) { for (String source : sources) { progress.setText2("Processing " + source); String sourceRoot = findSourceRoot(source, packageName); Path pathInZip = zipFileSystem.getPath(source.substring(sourceRoot.length())); Files.createDirectories(pathInZip.getParent()); Path absoluteSourcePath = buildRoot.resolve(source); Files.copy(absoluteSourcePath, pathInZip, StandardCopyOption.REPLACE_EXISTING); } } return targetPath.toFile(); } @NotNull private static Path findBuildRoot(Project project) { return Paths.get(PantsUtil.findBuildRoot(project) .map(VirtualFile::getPath) .orElseThrow(() -> new PantsException("Could not find build root for " + project))); } private static FileSystem createZipFileSystem(Path targetPath) throws URISyntaxException, IOException { URI fileUri = targetPath.toUri(); URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null); return FileSystems.newFileSystem(zipUri, Collections.singletonMap("create", Files.notExists(targetPath))); } @NotNull private static String findSourceRoot(String source, Optional<String> packageName) { return packageName .map(pkg -> inferSourceRootFromPackage(source, pkg)) .orElseGet(() -> approximateSourceRoot(Paths.get(source)).map(p -> p.toString() + "/")) .orElse(""); } @NotNull private static Optional<String> inferSourceRootFromPackage(String source, String pkg) { String subpath = pkg.replace('.', '/'); int index = source.indexOf(subpath); return index >= 0 ? Optional.of(source.substring(0, index)) : Optional.empty(); } private static PathMatcher sourceRootPattern = FileSystems.getDefault().getPathMatcher( "glob:**/{main,test,tests,src,3rdparty,3rd_party,thirdparty,third_party}/{resources,scala,java,jvm,proto,python,protobuf,py}" ); private static PathMatcher defaultTestRootPattern = FileSystems.getDefault().getPathMatcher( "glob:**/{test,tests}" ); private static Optional<Path> approximateSourceRoot(Path path) { if (sourceRootPattern.matches(path)) { return Optional.of(path); } else if (defaultTestRootPattern.matches(path)) { return Optional.of(path); } else { Path parent = path.getParent(); if (parent != null) { return approximateSourceRoot(parent); } else { return Optional.empty(); } } } private static Optional<String> findPackageName(PsiFile psiFile) { if (psiFile instanceof PsiClassOwner) { String packageName = ((PsiClassOwner) psiFile).getPackageName(); if (!packageName.equals("")) return Optional.of(packageName); } return Optional.empty(); } private static List<String> getSourcesForTarget(Project project, String targetAddress) { GeneralCommandLine cmd = PantsUtil.defaultCommandLine(project); try { cmd.addParameters("filemap", targetAddress); final ProcessOutput processOutput = PantsUtil.getCmdOutput(cmd, null); if (processOutput.checkSuccess(LOG)) { String stdout = processOutput.getStdout(); return Arrays.stream(stdout.split("\n")) .map(String::trim) .filter(s -> !s.isEmpty()) .map(line -> line.split("\\s+")) .filter(s -> targetAddress.equals(s[1])) .map(s -> s[0]) .collect(Collectors.toList()); } else { List<String> errorLogs = Lists.newArrayList( String.format( "Could not list sources for target: Pants exited with status %d", processOutput.getExitCode() ), String.format("argv: '%s'", cmd.getCommandLineString()), "stdout:", processOutput.getStdout(), "stderr:", processOutput.getStderr() ); final String errorMessage = String.join("\n", errorLogs); LOG.warn(errorMessage); throw new PantsException(errorMessage); } } catch (ExecutionException e) { final String processCreationFailureMessage = String.format( "Could not execute command: '%s' due to error: '%s'", cmd.getCommandLineString(), e.getMessage() ); LOG.warn(processCreationFailureMessage, e); throw new PantsException(processCreationFailureMessage); } } public static void attachSourceJar(@NotNull File sourceJar, @NotNull Collection<? extends Library> libraries) { VirtualFile srcFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(sourceJar); if (srcFile == null) return; VirtualFile jarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(srcFile); if (jarRoot == null) return; WriteAction.run(() -> { for (Library library : libraries) { Library.ModifiableModel model = library.getModifiableModel(); List<VirtualFile> alreadyExistingFiles = Arrays.asList(model.getFiles(OrderRootType.SOURCES)); if (!alreadyExistingFiles.contains(jarRoot)) { model.addRoot(jarRoot, OrderRootType.SOURCES); } model.commit(); } }); } private boolean exists(String sourceJar) { VirtualFile path = LocalFileSystem.getInstance().findFileByPath(sourceJar); return path != null && path.exists(); } }
/** * 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.falcon.regression; import org.apache.falcon.entity.v0.Frequency; import org.apache.falcon.entity.v0.feed.ActionType; import org.apache.falcon.regression.Entities.FeedMerlin; import org.apache.falcon.regression.core.bundle.Bundle; import org.apache.falcon.regression.core.helpers.ColoHelper; import org.apache.falcon.regression.core.response.ServiceResponse; import org.apache.falcon.regression.core.util.AssertUtil; import org.apache.falcon.regression.core.util.BundleUtil; import org.apache.falcon.regression.core.util.TimeUtil; import org.apache.falcon.regression.core.util.Util; import org.apache.falcon.regression.testHelper.BaseTestClass; import org.apache.log4j.Logger; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Feed SLA tests. */ @Test(groups = { "distributed", "embedded", "sanity" }) public class FeedSLATest extends BaseTestClass { private ColoHelper cluster = servers.get(0); private String baseTestDir = cleanAndGetTestDir(); private String feedInputPath = baseTestDir + "/input" + MINUTE_DATE_PATTERN; private static final Logger LOGGER = Logger.getLogger(FeedSLATest.class); private FeedMerlin feedMerlin; private String startTime; private String endTime; @BeforeMethod(alwaysRun = true) public void setup() throws Exception { Bundle bundle = BundleUtil.readELBundle(); bundles[0] = new Bundle(bundle, cluster); bundles[0].generateUniqueBundle(this); bundles[0].setInputFeedDataPath(feedInputPath); startTime = TimeUtil.getTimeWrtSystemTime(0); endTime = TimeUtil.addMinsToTime(startTime, 120); LOGGER.info("Time range between : " + startTime + " and " + endTime); ServiceResponse response = prism.getClusterHelper().submitEntity(bundles[0].getClusters().get(0)); AssertUtil.assertSucceeded(response); feedMerlin = new FeedMerlin(bundles[0].getInputFeedFromBundle()); feedMerlin.setFrequency(new Frequency("1", Frequency.TimeUnit.hours)); } @AfterMethod(alwaysRun = true) public void tearDown() { removeTestClassEntities(); } /** * Submit feed with correctly adjusted sla. Response should reflect success. * */ @Test public void submitValidFeedSLA() throws Exception { feedMerlin.clearFeedClusters(); feedMerlin.addFeedCluster(new FeedMerlin.FeedClusterBuilder( Util.readEntityName(bundles[0].getClusters().get(0))) .withRetention("days(1000000)", ActionType.DELETE) .withValidity(startTime, endTime) .build()); //set slaLow and slaHigh feedMerlin.setSla(new Frequency("3", Frequency.TimeUnit.hours), new Frequency("6", Frequency.TimeUnit.hours)); final ServiceResponse serviceResponse = prism.getFeedHelper().submitEntity(feedMerlin.toString()); AssertUtil.assertSucceeded(serviceResponse); } /** * Submit feed with slaHigh greater than feed retention. Response should reflect failure. * */ @Test public void submitFeedWithSLAHigherThanRetention() throws Exception { feedMerlin.clearFeedClusters(); feedMerlin.addFeedCluster(new FeedMerlin.FeedClusterBuilder( Util.readEntityName(bundles[0].getClusters().get(0))) .withRetention((new Frequency("2", Frequency.TimeUnit.hours)).toString(), ActionType.DELETE) .withValidity(startTime, endTime) .build()); //set slaLow and slaHigh feedMerlin.setSla(new Frequency("3", Frequency.TimeUnit.hours), new Frequency("6", Frequency.TimeUnit.hours)); final ServiceResponse serviceResponse = prism.getFeedHelper().submitEntity(feedMerlin.toString()); String message = "Feed's retention limit: " + feedMerlin.getClusters().getClusters().get(0).getRetention().getLimit() + " of referenced cluster " + bundles[0].getClusterNames().get(0) + " should be more than feed's late arrival cut-off period: " + feedMerlin.getSla().getSlaHigh().getTimeUnit() + "(" + feedMerlin.getSla().getSlaHigh().getFrequency() + ")" + " for feed: " + bundles[0].getInputFeedNameFromBundle(); validate(serviceResponse, message); } /** * Submit feed with slaHigh less than slaLow. Response should reflect failure. * */ @Test public void submitFeedWithSLAHighLowerthanSLALow() throws Exception { feedMerlin.clearFeedClusters(); feedMerlin.addFeedCluster(new FeedMerlin.FeedClusterBuilder( Util.readEntityName(bundles[0].getClusters().get(0))) .withRetention((new Frequency("6", Frequency.TimeUnit.hours)).toString(), ActionType.DELETE) .withValidity(startTime, endTime) .build()); //set slaLow and slaHigh feedMerlin.setSla(new Frequency("4", Frequency.TimeUnit.hours), new Frequency("2", Frequency.TimeUnit.hours)); final ServiceResponse serviceResponse = prism.getFeedHelper().submitEntity(feedMerlin.toString()); String message = "slaLow of Feed: " + feedMerlin.getSla().getSlaLow().getTimeUnit() + "(" + feedMerlin.getSla().getSlaLow().getFrequency() + ")is greater than slaHigh: " + feedMerlin.getSla().getSlaHigh().getTimeUnit() + "(" + feedMerlin.getSla().getSlaHigh().getFrequency() + ") for cluster: " + bundles[0].getClusterNames().get(0); validate(serviceResponse, message); } /** * Submit feed with slaHigh and slaLow greater than feed retention. Response should reflect failure. * */ @Test public void submitFeedWithSLAHighSLALowHigherThanRetention() throws Exception { feedMerlin.clearFeedClusters(); feedMerlin.addFeedCluster(new FeedMerlin.FeedClusterBuilder( Util.readEntityName(bundles[0].getClusters().get(0))) .withRetention((new Frequency("4", Frequency.TimeUnit.hours)).toString(), ActionType.DELETE) .withValidity(startTime, endTime) .build()); //set slaLow and slaHigh feedMerlin.setSla(new Frequency("5", Frequency.TimeUnit.hours), new Frequency("6", Frequency.TimeUnit.hours)); final ServiceResponse serviceResponse = prism.getFeedHelper().submitEntity(feedMerlin.toString()); String message = "Feed's retention limit: " + feedMerlin.getClusters().getClusters().get(0).getRetention().getLimit() + " of referenced cluster " + bundles[0].getClusterNames().get(0) + " should be more than feed's late arrival cut-off period: " + feedMerlin.getSla().getSlaHigh().getTimeUnit() +"(" + feedMerlin.getSla().getSlaHigh().getFrequency() + ")" + " for feed: " + bundles[0].getInputFeedNameFromBundle(); validate(serviceResponse, message); } /** * Submit feed with slaHigh and slaLow having equal value. Response should reflect success. * */ @Test public void submitFeedWithSameSLAHighSLALow() throws Exception { feedMerlin.clearFeedClusters(); feedMerlin.addFeedCluster(new FeedMerlin.FeedClusterBuilder( Util.readEntityName(bundles[0].getClusters().get(0))) .withRetention((new Frequency("7", Frequency.TimeUnit.hours)).toString(), ActionType.DELETE) .withValidity(startTime, endTime) .build()); //set slaLow and slaHigh feedMerlin.setSla(new Frequency("3", Frequency.TimeUnit.hours), new Frequency("3", Frequency.TimeUnit.hours)); final ServiceResponse serviceResponse = prism.getFeedHelper().submitEntity(feedMerlin.toString()); AssertUtil.assertSucceeded(serviceResponse); } private void validate(ServiceResponse response, String message) throws Exception { AssertUtil.assertFailed(response); LOGGER.info("Expected message is : " + message); Assert.assertTrue(response.getMessage().contains(message), "Correct response was not present in feed schedule. Feed response is : " + response.getMessage()); } }
package org.json; /* Copyright (c) 2013 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Kim makes immutable eight bit Unicode strings. If the MSB of a byte is set, * then the next byte is a continuation byte. The last byte of a character never * has the MSB reset. Every byte that is not the last byte has the MSB set. Kim * stands for "Keep it minimal". A Unicode character is never longer than 3 * bytes. Every byte contributes 7 bits to the character. ASCII is unmodified. * * Kim UTF-8 one byte U+007F U+007F two bytes U+3FFF U+07FF three bytes U+10FFF * U+FFFF four bytes U+10FFFF * * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one * byte smaller when encoded in Kim compared to UTF-8. * * Kim is beneficial when using scripts such as Old South Arabian, Aramaic, * Avestan, Balinese, Batak, Bopomofo, Buginese, Buhid, Carian, Cherokee, * Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian, * Glagolitic, Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi, Kannada, * Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu, Lycian, Lydian, Malayalam, * Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue, Ol Chiki, Old * Turkic, Oriya, Osmanya, Pahlavi, Parthian, Phags-Pa, Phoenician, Samaritan, * Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa, Takri, Tai Le, Tai Tham, * Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS. * * A kim object can be constructed from an ordinary UTF-16 string, or from a * byte array. A kim object can produce a UTF-16 string. * * As with UTF-8, it is possible to detect character boundaries within a byte * sequence. UTF-8 is one of the world's great inventions. While Kim is more * efficient, it is not clear that it is worth the expense of transition. * * @version 2013-04-18 */ public class Kim { /** * The byte array containing the kim's content. */ private byte[] bytes = null; /** * The kim's hashcode, conforming to Java's hashcode conventions. */ private int hashcode = 0; /** * The number of bytes in the kim. The number of bytes can be as much as * three times the number of characters. */ public int length = 0; /** * The memoization of toString(). */ private String string = null; /** * Make a kim from a portion of a byte array. * * @param bytes * A byte array. * @param from * The index of the first byte. * @param thru * The index of the last byte plus one. */ public Kim(byte[] bytes, int from, int thru) { // As the bytes are copied into the new kim, a hashcode is computed // using a // modified Fletcher code. int sum = 1; int value; this.hashcode = 0; this.length = thru - from; if (this.length > 0) { this.bytes = new byte[this.length]; for (int at = 0; at < this.length; at += 1) { value = bytes[at + from] & 0xFF; sum += value; this.hashcode += sum; this.bytes[at] = (byte) value; } this.hashcode += sum << 16; } } /** * Make a kim from a byte array. * * @param bytes * The byte array. * @param length * The number of bytes. */ public Kim(byte[] bytes, int length) { this(bytes, 0, length); } /** * Make a new kim from a substring of an existing kim. The coordinates are * in byte units, not character units. * * @param kim * The source of bytes. * @param from * The point at which to take bytes. * @param thru * The point at which to stop taking bytes. * @return the substring */ public Kim(Kim kim, int from, int thru) { this(kim.bytes, from, thru); } /** * Make a kim from a string. * * @param string * The string. * @throws JSONException * if surrogate pair mismatch. */ public Kim(String string) throws JSONException { int stringLength = string.length(); this.hashcode = 0; this.length = 0; // First pass: Determine the length of the kim, allowing for the UTF-16 // to UTF-32 conversion, and then the UTF-32 to Kim conversion. if (stringLength > 0) { for (int i = 0; i < stringLength; i += 1) { int c = string.charAt(i); if (c <= 0x7F) { this.length += 1; } else if (c <= 0x3FFF) { this.length += 2; } else { if (c >= 0xD800 && c <= 0xDFFF) { i += 1; int d = string.charAt(i); if (c > 0xDBFF || d < 0xDC00 || d > 0xDFFF) { throw new JSONException("Bad UTF16"); } } this.length += 3; } } // Second pass: Allocate a byte array and fill that array with the // conversion // while computing the hashcode. this.bytes = new byte[length]; int at = 0; int b; int sum = 1; for (int i = 0; i < stringLength; i += 1) { int character = string.charAt(i); if (character <= 0x7F) { bytes[at] = (byte) character; sum += character; this.hashcode += sum; at += 1; } else if (character <= 0x3FFF) { b = 0x80 | (character >>> 7); bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; b = character & 0x7F; bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; } else { if (character >= 0xD800 && character <= 0xDBFF) { i += 1; character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; } b = 0x80 | (character >>> 14); bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; b = 0x80 | ((character >>> 7) & 0xFF); bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; b = character & 0x7F; bytes[at] = (byte) b; sum += b; this.hashcode += sum; at += 1; } } this.hashcode += sum << 16; } } /** * Returns the character at the specified index. The index refers to byte * values and ranges from 0 to length - 1. The index of the next character * is at index + Kim.characterSize(kim.characterAt(index)). * * @param at * the index of the char value. The first character is at 0. * @returns a Unicode character between 0 and 0x10FFFF. * @throws JSONException * if at does not point to a valid character. */ public int characterAt(int at) throws JSONException { int c = get(at); if ((c & 0x80) == 0) { return c; } int character; int c1 = get(at + 1); if ((c1 & 0x80) == 0) { character = ((c & 0x7F) << 7) | c1; if (character > 0x7F) { return character; } } else { int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF && (character < 0xD800 || character > 0xDFFF)) { return character; } } throw new JSONException("Bad character at " + at); } /** * Returns the number of bytes needed to contain the character in Kim * format. * * @param character * a Unicode character between 0 and 0x10FFFF. * @return 1, 2, or 3 * @throws JSONException * if the character is not representable in a kim. */ public static int characterSize(int character) throws JSONException { if (character < 0 || character > 0x10FFFF) { throw new JSONException("Bad character " + character); } return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; } /** * Copy the contents of this kim to a byte array. * * @param bytes * A byte array of sufficient size. * @param at * The position within the byte array to take the byes. * @return The position immediately after the copy. */ public int copy(byte[] bytes, int at) { System.arraycopy(this.bytes, 0, bytes, at, this.length); return at + this.length; } /** * Two kim objects containing exactly the same bytes in the same order are * equal to each other. * * @param obj * the other kim with which to compare. * @returns true if this and obj are both kim objects containing identical * byte sequences. */ @Override public boolean equals(Object obj) { if (!(obj instanceof Kim)) { return false; } Kim that = (Kim) obj; if (this == that) { return true; } if (this.hashcode != that.hashcode) { return false; } return java.util.Arrays.equals(this.bytes, that.bytes); } /** * Get a byte from a kim. * * @param at * The position of the byte. The first byte is at 0. * @return The byte. * @throws JSONException * if there is no byte at that position. */ public int get(int at) throws JSONException { if (at < 0 || at > this.length) { throw new JSONException("Bad character at " + at); } return (this.bytes[at]) & 0xFF; } /** * Returns a hash code value for the kim. */ @Override public int hashCode() { return this.hashcode; } /** * Produce a UTF-16 String from this kim. The number of codepoints in the * string will not be greater than the number of bytes in the kim, although * it could be less. * * @return The string. A kim memoizes its string representation. * @throws JSONException * if the kim is not valid. */ @Override public String toString() throws JSONException { if (this.string == null) { int c; int length = 0; char chars[] = new char[this.length]; for (int at = 0; at < this.length; at += characterSize(c)) { c = this.characterAt(at); if (c < 0x10000) { chars[length] = (char) c; length += 1; } else { chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10)); length += 1; chars[length] = (char) (0xDC00 | (c & 0x03FF)); length += 1; } } this.string = new String(chars, 0, length); } return this.string; } }
/* * 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.servicecatalog.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ExecuteProvisionedProductServiceAction" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ExecuteProvisionedProductServiceActionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The identifier of the provisioned product. * </p> */ private String provisionedProductId; /** * <p> * The self-service action identifier. For example, <code>act-fs7abcd89wxyz</code>. * </p> */ private String serviceActionId; /** * <p> * An idempotency token that uniquely identifies the execute request. * </p> */ private String executeToken; /** * <p> * The language code. * </p> * <ul> * <li> * <p> * <code>en</code> - English (default) * </p> * </li> * <li> * <p> * <code>jp</code> - Japanese * </p> * </li> * <li> * <p> * <code>zh</code> - Chinese * </p> * </li> * </ul> */ private String acceptLanguage; /** * <p> * A map of all self-service action parameters and their values. If a provided parameter is of a special type, such * as <code>TARGET</code>, the provided value will override the default value generated by AWS Service Catalog. If * the parameters field is not provided, no additional parameters are passed and default values will be used for any * special parameters such as <code>TARGET</code>. * </p> */ private java.util.Map<String, java.util.List<String>> parameters; /** * <p> * The identifier of the provisioned product. * </p> * * @param provisionedProductId * The identifier of the provisioned product. */ public void setProvisionedProductId(String provisionedProductId) { this.provisionedProductId = provisionedProductId; } /** * <p> * The identifier of the provisioned product. * </p> * * @return The identifier of the provisioned product. */ public String getProvisionedProductId() { return this.provisionedProductId; } /** * <p> * The identifier of the provisioned product. * </p> * * @param provisionedProductId * The identifier of the provisioned product. * @return Returns a reference to this object so that method calls can be chained together. */ public ExecuteProvisionedProductServiceActionRequest withProvisionedProductId(String provisionedProductId) { setProvisionedProductId(provisionedProductId); return this; } /** * <p> * The self-service action identifier. For example, <code>act-fs7abcd89wxyz</code>. * </p> * * @param serviceActionId * The self-service action identifier. For example, <code>act-fs7abcd89wxyz</code>. */ public void setServiceActionId(String serviceActionId) { this.serviceActionId = serviceActionId; } /** * <p> * The self-service action identifier. For example, <code>act-fs7abcd89wxyz</code>. * </p> * * @return The self-service action identifier. For example, <code>act-fs7abcd89wxyz</code>. */ public String getServiceActionId() { return this.serviceActionId; } /** * <p> * The self-service action identifier. For example, <code>act-fs7abcd89wxyz</code>. * </p> * * @param serviceActionId * The self-service action identifier. For example, <code>act-fs7abcd89wxyz</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public ExecuteProvisionedProductServiceActionRequest withServiceActionId(String serviceActionId) { setServiceActionId(serviceActionId); return this; } /** * <p> * An idempotency token that uniquely identifies the execute request. * </p> * * @param executeToken * An idempotency token that uniquely identifies the execute request. */ public void setExecuteToken(String executeToken) { this.executeToken = executeToken; } /** * <p> * An idempotency token that uniquely identifies the execute request. * </p> * * @return An idempotency token that uniquely identifies the execute request. */ public String getExecuteToken() { return this.executeToken; } /** * <p> * An idempotency token that uniquely identifies the execute request. * </p> * * @param executeToken * An idempotency token that uniquely identifies the execute request. * @return Returns a reference to this object so that method calls can be chained together. */ public ExecuteProvisionedProductServiceActionRequest withExecuteToken(String executeToken) { setExecuteToken(executeToken); return this; } /** * <p> * The language code. * </p> * <ul> * <li> * <p> * <code>en</code> - English (default) * </p> * </li> * <li> * <p> * <code>jp</code> - Japanese * </p> * </li> * <li> * <p> * <code>zh</code> - Chinese * </p> * </li> * </ul> * * @param acceptLanguage * The language code.</p> * <ul> * <li> * <p> * <code>en</code> - English (default) * </p> * </li> * <li> * <p> * <code>jp</code> - Japanese * </p> * </li> * <li> * <p> * <code>zh</code> - Chinese * </p> * </li> */ public void setAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; } /** * <p> * The language code. * </p> * <ul> * <li> * <p> * <code>en</code> - English (default) * </p> * </li> * <li> * <p> * <code>jp</code> - Japanese * </p> * </li> * <li> * <p> * <code>zh</code> - Chinese * </p> * </li> * </ul> * * @return The language code.</p> * <ul> * <li> * <p> * <code>en</code> - English (default) * </p> * </li> * <li> * <p> * <code>jp</code> - Japanese * </p> * </li> * <li> * <p> * <code>zh</code> - Chinese * </p> * </li> */ public String getAcceptLanguage() { return this.acceptLanguage; } /** * <p> * The language code. * </p> * <ul> * <li> * <p> * <code>en</code> - English (default) * </p> * </li> * <li> * <p> * <code>jp</code> - Japanese * </p> * </li> * <li> * <p> * <code>zh</code> - Chinese * </p> * </li> * </ul> * * @param acceptLanguage * The language code.</p> * <ul> * <li> * <p> * <code>en</code> - English (default) * </p> * </li> * <li> * <p> * <code>jp</code> - Japanese * </p> * </li> * <li> * <p> * <code>zh</code> - Chinese * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public ExecuteProvisionedProductServiceActionRequest withAcceptLanguage(String acceptLanguage) { setAcceptLanguage(acceptLanguage); return this; } /** * <p> * A map of all self-service action parameters and their values. If a provided parameter is of a special type, such * as <code>TARGET</code>, the provided value will override the default value generated by AWS Service Catalog. If * the parameters field is not provided, no additional parameters are passed and default values will be used for any * special parameters such as <code>TARGET</code>. * </p> * * @return A map of all self-service action parameters and their values. If a provided parameter is of a special * type, such as <code>TARGET</code>, the provided value will override the default value generated by AWS * Service Catalog. If the parameters field is not provided, no additional parameters are passed and default * values will be used for any special parameters such as <code>TARGET</code>. */ public java.util.Map<String, java.util.List<String>> getParameters() { return parameters; } /** * <p> * A map of all self-service action parameters and their values. If a provided parameter is of a special type, such * as <code>TARGET</code>, the provided value will override the default value generated by AWS Service Catalog. If * the parameters field is not provided, no additional parameters are passed and default values will be used for any * special parameters such as <code>TARGET</code>. * </p> * * @param parameters * A map of all self-service action parameters and their values. If a provided parameter is of a special * type, such as <code>TARGET</code>, the provided value will override the default value generated by AWS * Service Catalog. If the parameters field is not provided, no additional parameters are passed and default * values will be used for any special parameters such as <code>TARGET</code>. */ public void setParameters(java.util.Map<String, java.util.List<String>> parameters) { this.parameters = parameters; } /** * <p> * A map of all self-service action parameters and their values. If a provided parameter is of a special type, such * as <code>TARGET</code>, the provided value will override the default value generated by AWS Service Catalog. If * the parameters field is not provided, no additional parameters are passed and default values will be used for any * special parameters such as <code>TARGET</code>. * </p> * * @param parameters * A map of all self-service action parameters and their values. If a provided parameter is of a special * type, such as <code>TARGET</code>, the provided value will override the default value generated by AWS * Service Catalog. If the parameters field is not provided, no additional parameters are passed and default * values will be used for any special parameters such as <code>TARGET</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public ExecuteProvisionedProductServiceActionRequest withParameters(java.util.Map<String, java.util.List<String>> parameters) { setParameters(parameters); return this; } /** * Add a single Parameters entry * * @see ExecuteProvisionedProductServiceActionRequest#withParameters * @returns a reference to this object so that method calls can be chained together. */ public ExecuteProvisionedProductServiceActionRequest addParametersEntry(String key, java.util.List<String> value) { if (null == this.parameters) { this.parameters = new java.util.HashMap<String, java.util.List<String>>(); } if (this.parameters.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.parameters.put(key, value); return this; } /** * Removes all the entries added into Parameters. * * @return Returns a reference to this object so that method calls can be chained together. */ public ExecuteProvisionedProductServiceActionRequest clearParametersEntries() { this.parameters = null; 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 (getProvisionedProductId() != null) sb.append("ProvisionedProductId: ").append(getProvisionedProductId()).append(","); if (getServiceActionId() != null) sb.append("ServiceActionId: ").append(getServiceActionId()).append(","); if (getExecuteToken() != null) sb.append("ExecuteToken: ").append(getExecuteToken()).append(","); if (getAcceptLanguage() != null) sb.append("AcceptLanguage: ").append(getAcceptLanguage()).append(","); if (getParameters() != null) sb.append("Parameters: ").append(getParameters()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ExecuteProvisionedProductServiceActionRequest == false) return false; ExecuteProvisionedProductServiceActionRequest other = (ExecuteProvisionedProductServiceActionRequest) obj; if (other.getProvisionedProductId() == null ^ this.getProvisionedProductId() == null) return false; if (other.getProvisionedProductId() != null && other.getProvisionedProductId().equals(this.getProvisionedProductId()) == false) return false; if (other.getServiceActionId() == null ^ this.getServiceActionId() == null) return false; if (other.getServiceActionId() != null && other.getServiceActionId().equals(this.getServiceActionId()) == false) return false; if (other.getExecuteToken() == null ^ this.getExecuteToken() == null) return false; if (other.getExecuteToken() != null && other.getExecuteToken().equals(this.getExecuteToken()) == false) return false; if (other.getAcceptLanguage() == null ^ this.getAcceptLanguage() == null) return false; if (other.getAcceptLanguage() != null && other.getAcceptLanguage().equals(this.getAcceptLanguage()) == false) return false; if (other.getParameters() == null ^ this.getParameters() == null) return false; if (other.getParameters() != null && other.getParameters().equals(this.getParameters()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getProvisionedProductId() == null) ? 0 : getProvisionedProductId().hashCode()); hashCode = prime * hashCode + ((getServiceActionId() == null) ? 0 : getServiceActionId().hashCode()); hashCode = prime * hashCode + ((getExecuteToken() == null) ? 0 : getExecuteToken().hashCode()); hashCode = prime * hashCode + ((getAcceptLanguage() == null) ? 0 : getAcceptLanguage().hashCode()); hashCode = prime * hashCode + ((getParameters() == null) ? 0 : getParameters().hashCode()); return hashCode; } @Override public ExecuteProvisionedProductServiceActionRequest clone() { return (ExecuteProvisionedProductServiceActionRequest) super.clone(); } }
/* * Copyright 2015 Ben Manes. 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 com.github.benmanes.caffeine.cache.simulator.policy.linked; import static com.github.benmanes.caffeine.cache.simulator.policy.Policy.Characteristic.WEIGHTED; import static java.util.Locale.US; import static java.util.stream.Collectors.toSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import com.github.benmanes.caffeine.cache.simulator.BasicSettings; import com.github.benmanes.caffeine.cache.simulator.admission.Admission; import com.github.benmanes.caffeine.cache.simulator.admission.Admittor; import com.github.benmanes.caffeine.cache.simulator.policy.AccessEvent; import com.github.benmanes.caffeine.cache.simulator.policy.Policy; import com.github.benmanes.caffeine.cache.simulator.policy.Policy.PolicySpec; import com.github.benmanes.caffeine.cache.simulator.policy.PolicyStats; import com.google.common.base.MoreObjects; import com.typesafe.config.Config; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; /** * A cache that uses a linked list, in either insertion or access order, to implement simple * page replacement algorithms. * * @author ben.manes@gmail.com (Ben Manes) */ @PolicySpec(characteristics = WEIGHTED) public final class LinkedPolicy implements Policy { final Long2ObjectMap<Node> data; final PolicyStats policyStats; final EvictionPolicy policy; final Admittor admittor; final long maximumSize; final boolean weighted; final Node sentinel; long currentSize; public LinkedPolicy(Config config, Set<Characteristic> characteristics, Admission admission, EvictionPolicy policy) { this.policyStats = new PolicyStats(admission.format(policy.label())); this.admittor = admission.from(config, policyStats); this.weighted = characteristics.contains(WEIGHTED); BasicSettings settings = new BasicSettings(config); this.data = new Long2ObjectOpenHashMap<>(); this.maximumSize = settings.maximumSize(); this.sentinel = new Node(); this.policy = policy; } /** Returns all variations of this policy based on the configuration parameters. */ public static Set<Policy> policies(Config config, Set<Characteristic> characteristics, EvictionPolicy policy) { BasicSettings settings = new BasicSettings(config); return settings.admission().stream().map(admission -> new LinkedPolicy(config, characteristics, admission, policy) ).collect(toSet()); } @Override public PolicyStats stats() { return policyStats; } @Override public void record(AccessEvent event) { final int weight = weighted ? event.weight() : 1; final long key = event.key(); Node old = data.get(key); admittor.record(key); if (old == null) { policyStats.recordWeightedMiss(weight); if (weight > maximumSize) { policyStats.recordOperation(); return; } Node node = new Node(key, weight, sentinel); data.put(key, node); currentSize += node.weight; node.appendToTail(); evict(node); } else { policyStats.recordWeightedHit(weight); currentSize += (weight - old.weight); old.weight = weight; policy.onAccess(old, policyStats); evict(old); } } /** Evicts while the map exceeds the maximum capacity. */ private void evict(Node candidate) { if (currentSize > maximumSize) { while (currentSize > maximumSize) { if (candidate.weight > maximumSize) { evictEntry(candidate); continue; } Node victim = policy.findVictim(sentinel, policyStats); boolean admit = admittor.admit(candidate.key, victim.key); if (admit) { evictEntry(victim); } else { evictEntry(candidate); } } } else { policyStats.recordOperation(); } } private void evictEntry(Node node) { policyStats.recordEviction(); currentSize -= node.weight; data.remove(node.key); node.remove(); } /** The replacement policy. */ public enum EvictionPolicy { /** Evicts entries based on insertion order. */ FIFO { @Override void onAccess(Node node, PolicyStats policyStats) { policyStats.recordOperation(); // do nothing } @Override Node findVictim(Node sentinel, PolicyStats policyStats) { policyStats.recordOperation(); return sentinel.next; } }, /** * Evicts entries based on insertion order, but gives an entry a "second chance" if it has been * requested recently. */ CLOCK { @Override void onAccess(Node node, PolicyStats policyStats) { policyStats.recordOperation(); node.marked = true; } @Override Node findVictim(Node sentinel, PolicyStats policyStats) { for (;;) { policyStats.recordOperation(); Node node = sentinel.next; if (node.marked) { node.moveToTail(); node.marked = false; } else { return node; } } } }, /** Evicts entries based on how recently they are used, with the most recent evicted first. */ MRU { @Override void onAccess(Node node, PolicyStats policyStats) { policyStats.recordOperation(); node.moveToTail(); } @Override Node findVictim(Node sentinel, PolicyStats policyStats) { policyStats.recordOperation(); // Skip over the added entry return sentinel.prev.prev; } }, /** Evicts entries based on how recently they are used, with the least recent evicted first. */ LRU { @Override void onAccess(Node node, PolicyStats policyStats) { policyStats.recordOperation(); node.moveToTail(); } @Override Node findVictim(Node sentinel, PolicyStats policyStats) { policyStats.recordOperation(); return sentinel.next; } }; public String label() { return "linked." + StringUtils.capitalize(name().toLowerCase(US)); } /** Performs any operations required by the policy after a node was successfully retrieved. */ abstract void onAccess(Node node, PolicyStats policyStats); /** Returns the victim entry to evict. */ abstract Node findVictim(Node sentinel, PolicyStats policyStats); } /** A node on the double-linked list. */ static final class Node { final Node sentinel; boolean marked; Node prev; Node next; long key; int weight; /** Creates a new sentinel node. */ public Node() { this.key = Long.MIN_VALUE; this.sentinel = this; this.prev = this; this.next = this; } /** Creates a new, unlinked node. */ public Node(long key, int weight, Node sentinel) { this.sentinel = sentinel; this.key = key; this.weight = weight; } /** Appends the node to the tail of the list. */ public void appendToTail() { Node tail = sentinel.prev; sentinel.prev = this; tail.next = this; next = sentinel; prev = tail; } /** Removes the node from the list. */ public void remove() { prev.next = next; next.prev = prev; prev = next = null; key = Long.MIN_VALUE; } /** Moves the node to the tail. */ public void moveToTail() { // unlink prev.next = next; next.prev = prev; // link next = sentinel; prev = sentinel.prev; sentinel.prev = this; prev.next = this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("key", key) .add("weight", weight) .add("marked", marked) .toString(); } } }
/* * 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.forecast.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <note> * <p> * This object belongs to the <a>CreatePredictor</a> operation. If you created your predictor with * <a>CreateAutoPredictor</a>, see <a>AttributeConfig</a>. * </p> * </note> * <p> * Provides featurization (transformation) information for a dataset field. This object is part of the * <a>FeaturizationConfig</a> object. * </p> * <p> * For example: * </p> * <p> * <code>{</code> * </p> * <p> * <code>"AttributeName": "demand",</code> * </p> * <p> * <code>FeaturizationPipeline [ {</code> * </p> * <p> * <code>"FeaturizationMethodName": "filling",</code> * </p> * <p> * <code>"FeaturizationMethodParameters": {"aggregation": "avg", "backfill": "nan"}</code> * </p> * <p> * <code>} ]</code> * </p> * <p> * <code>}</code> * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/Featurization" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Featurization implements Serializable, Cloneable, StructuredPojo { /** * <p> * The name of the schema attribute that specifies the data field to be featurized. Amazon Forecast supports the * target field of the <code>TARGET_TIME_SERIES</code> and the <code>RELATED_TIME_SERIES</code> datasets. For * example, for the <code>RETAIL</code> domain, the target is <code>demand</code>, and for the <code>CUSTOM</code> * domain, the target is <code>target_value</code>. For more information, see <a>howitworks-missing-values</a>. * </p> */ private String attributeName; /** * <p> * An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. * </p> */ private java.util.List<FeaturizationMethod> featurizationPipeline; /** * <p> * The name of the schema attribute that specifies the data field to be featurized. Amazon Forecast supports the * target field of the <code>TARGET_TIME_SERIES</code> and the <code>RELATED_TIME_SERIES</code> datasets. For * example, for the <code>RETAIL</code> domain, the target is <code>demand</code>, and for the <code>CUSTOM</code> * domain, the target is <code>target_value</code>. For more information, see <a>howitworks-missing-values</a>. * </p> * * @param attributeName * The name of the schema attribute that specifies the data field to be featurized. Amazon Forecast supports * the target field of the <code>TARGET_TIME_SERIES</code> and the <code>RELATED_TIME_SERIES</code> datasets. * For example, for the <code>RETAIL</code> domain, the target is <code>demand</code>, and for the * <code>CUSTOM</code> domain, the target is <code>target_value</code>. For more information, see * <a>howitworks-missing-values</a>. */ public void setAttributeName(String attributeName) { this.attributeName = attributeName; } /** * <p> * The name of the schema attribute that specifies the data field to be featurized. Amazon Forecast supports the * target field of the <code>TARGET_TIME_SERIES</code> and the <code>RELATED_TIME_SERIES</code> datasets. For * example, for the <code>RETAIL</code> domain, the target is <code>demand</code>, and for the <code>CUSTOM</code> * domain, the target is <code>target_value</code>. For more information, see <a>howitworks-missing-values</a>. * </p> * * @return The name of the schema attribute that specifies the data field to be featurized. Amazon Forecast supports * the target field of the <code>TARGET_TIME_SERIES</code> and the <code>RELATED_TIME_SERIES</code> * datasets. For example, for the <code>RETAIL</code> domain, the target is <code>demand</code>, and for the * <code>CUSTOM</code> domain, the target is <code>target_value</code>. For more information, see * <a>howitworks-missing-values</a>. */ public String getAttributeName() { return this.attributeName; } /** * <p> * The name of the schema attribute that specifies the data field to be featurized. Amazon Forecast supports the * target field of the <code>TARGET_TIME_SERIES</code> and the <code>RELATED_TIME_SERIES</code> datasets. For * example, for the <code>RETAIL</code> domain, the target is <code>demand</code>, and for the <code>CUSTOM</code> * domain, the target is <code>target_value</code>. For more information, see <a>howitworks-missing-values</a>. * </p> * * @param attributeName * The name of the schema attribute that specifies the data field to be featurized. Amazon Forecast supports * the target field of the <code>TARGET_TIME_SERIES</code> and the <code>RELATED_TIME_SERIES</code> datasets. * For example, for the <code>RETAIL</code> domain, the target is <code>demand</code>, and for the * <code>CUSTOM</code> domain, the target is <code>target_value</code>. For more information, see * <a>howitworks-missing-values</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public Featurization withAttributeName(String attributeName) { setAttributeName(attributeName); return this; } /** * <p> * An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. * </p> * * @return An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. */ public java.util.List<FeaturizationMethod> getFeaturizationPipeline() { return featurizationPipeline; } /** * <p> * An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. * </p> * * @param featurizationPipeline * An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. */ public void setFeaturizationPipeline(java.util.Collection<FeaturizationMethod> featurizationPipeline) { if (featurizationPipeline == null) { this.featurizationPipeline = null; return; } this.featurizationPipeline = new java.util.ArrayList<FeaturizationMethod>(featurizationPipeline); } /** * <p> * An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setFeaturizationPipeline(java.util.Collection)} or * {@link #withFeaturizationPipeline(java.util.Collection)} if you want to override the existing values. * </p> * * @param featurizationPipeline * An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. * @return Returns a reference to this object so that method calls can be chained together. */ public Featurization withFeaturizationPipeline(FeaturizationMethod... featurizationPipeline) { if (this.featurizationPipeline == null) { setFeaturizationPipeline(new java.util.ArrayList<FeaturizationMethod>(featurizationPipeline.length)); } for (FeaturizationMethod ele : featurizationPipeline) { this.featurizationPipeline.add(ele); } return this; } /** * <p> * An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. * </p> * * @param featurizationPipeline * An array of one <code>FeaturizationMethod</code> object that specifies the feature transformation method. * @return Returns a reference to this object so that method calls can be chained together. */ public Featurization withFeaturizationPipeline(java.util.Collection<FeaturizationMethod> featurizationPipeline) { setFeaturizationPipeline(featurizationPipeline); 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 (getAttributeName() != null) sb.append("AttributeName: ").append(getAttributeName()).append(","); if (getFeaturizationPipeline() != null) sb.append("FeaturizationPipeline: ").append(getFeaturizationPipeline()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Featurization == false) return false; Featurization other = (Featurization) obj; if (other.getAttributeName() == null ^ this.getAttributeName() == null) return false; if (other.getAttributeName() != null && other.getAttributeName().equals(this.getAttributeName()) == false) return false; if (other.getFeaturizationPipeline() == null ^ this.getFeaturizationPipeline() == null) return false; if (other.getFeaturizationPipeline() != null && other.getFeaturizationPipeline().equals(this.getFeaturizationPipeline()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAttributeName() == null) ? 0 : getAttributeName().hashCode()); hashCode = prime * hashCode + ((getFeaturizationPipeline() == null) ? 0 : getFeaturizationPipeline().hashCode()); return hashCode; } @Override public Featurization clone() { try { return (Featurization) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.forecast.model.transform.FeaturizationMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package session; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import javax.jms.BytesMessage; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Queue; import javax.jms.QueueBrowser; import javax.jms.Session; import javax.jms.StreamMessage; import javax.jms.TemporaryQueue; import javax.jms.TemporaryTopic; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicSubscriber; import connection.MyConnectionSendMessage; import messages.MessageAckSession; import messages.MyBytesMessage; import messages.MyMessage; import messages.MyMessageConsumer; import messages.MyMessageProducer; import messages.MyObjectMessage; import topic.MyTopic; import utils.Utils; public class MySession implements Session, SessionMessageReceiverListener, SessionConsumerOperations, MessageAckSession,MySessionMessageSend{ MyConnectionSendMessage connection; boolean transacted; int acknowledgeMode; MessageListener messageListener; ConcurrentHashMap<String, List<MessageListener>> subscribedList; boolean closed; boolean isClosing; public MySession(boolean trans, int ack, MyConnectionSendMessage connection){ this.transacted = trans; this.acknowledgeMode = ack; this.connection = connection; this.subscribedList = new ConcurrentHashMap<String, List<MessageListener>>(); closed = false; isClosing = false; } public void isOpen() throws JMSException{ if(closed){ throw new JMSException("Consumer closed"); } } @Override public void close() throws JMSException { synchronized (this) { isClosing = true; if(!closed){ closed = true; connection.closeSession(this); for(String d : subscribedList.keySet()){ List<MessageListener> arr = this.subscribedList.get(d); for(MessageListener msg : arr){ if(msg instanceof MessageConsumer){ MessageConsumer msgC = (MessageConsumer) msg; msgC.close(); } } } } } } @Override public void commit() throws JMSException { throw new IllegalStateException("this JMS implementation does not implement transacted Sessions"); } @Override public QueueBrowser createBrowser(Queue arg0) throws JMSException { throw new JMSException("Not Implemented method"); } @Override public QueueBrowser createBrowser(Queue arg0, String arg1) throws JMSException { throw new JMSException("Not Implemented method"); } @Override public BytesMessage createBytesMessage() throws JMSException { BytesMessage bmsg = new MyBytesMessage(); return bmsg; } @Override public MessageConsumer createConsumer(Destination destination) throws JMSException { return createConsumer(destination, null, false); } @Override public MessageConsumer createConsumer(Destination destination, String selector) throws JMSException { return createConsumer(destination, selector, false); } @Override public MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal) throws JMSException { isOpen(); try { MyMessageConsumer msgConsumer = new MyMessageConsumer(destination, selector,noLocal,this); this.connection.subscribe(destination, this); Topic topic = (Topic) destination; synchronized (this) { List<MessageListener> list = this.subscribedList.get(topic.getTopicName()); if( list == null){ list = Collections.synchronizedList(new ArrayList<MessageListener>());; } list.add(msgConsumer); this.subscribedList.put(topic.getTopicName(), list); } return msgConsumer; } catch (IOException e) { Utils.raise(e); } return null; } @Override public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1) throws JMSException { throw new JMSException("Not Implemented method"); } @Override public TopicSubscriber createDurableSubscriber(Topic topic, String name, String messageSelector, boolean noLocal) throws JMSException { throw new JMSException("Not Implemented method"); } @Override public MapMessage createMapMessage() throws JMSException { throw new JMSException("Not Implemented method"); } @Override public Message createMessage() throws JMSException { return new MyMessage(); } @Override public ObjectMessage createObjectMessage() throws JMSException { return new MyObjectMessage(); } @Override public ObjectMessage createObjectMessage(Serializable arg0) throws JMSException { return new MyObjectMessage(arg0); } @Override public MessageProducer createProducer(Destination arg0) throws JMSException { isOpen(); MessageProducer msgProducer = new MyMessageProducer(arg0,this); return msgProducer; } @Override public Queue createQueue(String arg0) throws JMSException { throw new JMSException("Not Implemented method"); } @Override public StreamMessage createStreamMessage() throws JMSException { throw new JMSException("Not Implemented method"); } @Override public TemporaryQueue createTemporaryQueue() throws JMSException { throw new JMSException("Not Implemented method"); } @Override public TemporaryTopic createTemporaryTopic() throws JMSException { throw new JMSException("Not Implemented method"); } @Override public TextMessage createTextMessage() throws JMSException { throw new JMSException("Not Implemented method"); } @Override public TextMessage createTextMessage(String arg0) throws JMSException { throw new JMSException("Not Implemented method"); } @Override public Topic createTopic(String arg0) throws JMSException { Topic topic = new MyTopic(arg0); try { connection.createTopic(topic); } catch (IOException e) { Utils.raise(e); } return topic; } @Override public int getAcknowledgeMode() throws JMSException { return this.acknowledgeMode; } @Override public MessageListener getMessageListener() throws JMSException { return this.messageListener; } @Override public boolean getTransacted() throws JMSException { throw new IllegalStateException("this JMS implementation does not implement transacted Sessions"); } @Override public void recover() throws JMSException { // TODO Auto-generated method stub } @Override public void rollback() throws JMSException { throw new IllegalStateException("this JMS implementation does not implement transacted Sessions"); } @Override public void run() { // TODO Auto-generated method stub } @Override public void setMessageListener(MessageListener arg0) throws JMSException { this.messageListener = arg0; } @Override public void unsubscribe(String arg0) throws JMSException { try { this.connection.unsubscribe(arg0, this); } catch (IOException e) { Utils.raise(e); } } @Override public void onMessageReceived(Message message) { Topic destination; MyMessage msg = (MyMessage)message; msg.setSessionAck(this); try { destination = (Topic)msg.getJMSDestination(); synchronized (this) { List<MessageListener> consumers = this.subscribedList.get(destination.getTopicName()); for(MessageListener consumer : consumers ){ consumer.onMessage(msg); } } } catch (JMSException e) { e.printStackTrace(); } } @Override public void ack(Message message) throws JMSException { try { this.connection.acknowledgeMessage(message,this); } catch (IOException e) { Utils.raise(e); } } @Override public void send(Message message) throws IOException, JMSException { connection.sendMessage(message); } @Override public void closeConsumer(MyMessageConsumer consumer) throws JMSException { Topic topic = (Topic)consumer.getDestination(); synchronized (this) { if(!isClosing){ List<MessageListener> arr = this.subscribedList.get(topic.getTopicName()); arr.remove(consumer); if(arr.isEmpty()){ unsubscribe(topic.getTopicName()); } } } } @Override public void received(Message message) throws JMSException { if(this.acknowledgeMode == Session.AUTO_ACKNOWLEDGE){ message.acknowledge(); } } }
/* MIT License Copyright (c) 2017 Alexander Stephen Cameron (http://stephencamerondataservices.com.au/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package au.com.scds.agric.dom.demo.data; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.jdo.annotations.Column; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.Inheritance; import javax.jdo.annotations.InheritanceStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.Queries; import javax.jdo.annotations.Query; import javax.jdo.annotations.Order; 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.XmlTransient; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.apache.isis.applib.annotation.DomainObject; /** * A batch of product, efficiently created in bulk for subdivision into * product-item lots. * * * <p> * Java class for Batch complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name="Batch"> * &lt;complexContent> * &lt;extension base="{http://www.example.org/AgricProducerSchema}Sampled"> * &lt;sequence> * &lt;element name="created-on" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;element name="created-by" type="{http://www.example.org/AgricProducerSchema}Person"/> * &lt;element name="scheduled-for" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;element name="completed-on" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;element name="completed-by" type="{http://www.example.org/AgricProducerSchema}Person" minOccurs="0"/> * &lt;element name="formulation" type="{http://www.example.org/AgricProducerSchema}Formulation"/> * &lt;element name="product-item" type="{http://www.example.org/AgricProducerSchema}ProductItem" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Batch", propOrder = { "productLine", "createdOn", "createdBy", "scheduledFor", "completedOn", "completedBy", "formulation","specification","batchComponents", "productItems" }) @DomainObject(objectType = "Batch") @PersistenceCapable(identityType = IdentityType.DATASTORE) @Inheritance(strategy = InheritanceStrategy.NEW_TABLE) @Queries({ @Query(name = "findById", language = "JDOQL", value = "SELECT FROM au.com.scds.agric.dom.demo.data.Batch WHERE batch_id_OID == :id ") }) public class Batch extends Sampled { @XmlElement(name = "product-line", required = true) @Column(allowsNull = "false") protected ProductLine productLine; @XmlElement(name = "created-on", required = true, type = String.class) @XmlJavaTypeAdapter(Adapter1.class) @XmlSchemaType(name = "dateTime") @Column(allowsNull = "true") protected Date createdOn; @XmlElement(name = "created-by", required = true) @Column(allowsNull = "true") protected Person createdBy; @XmlElement(name = "scheduled-for", type = String.class) @XmlJavaTypeAdapter(Adapter1.class) @XmlSchemaType(name = "dateTime") @Column(allowsNull = "true") protected Date scheduledFor; @XmlElement(name = "completed-on", type = String.class) @XmlJavaTypeAdapter(Adapter1.class) @XmlSchemaType(name = "dateTime") @Column(allowsNull = "true") protected Date completedOn; @XmlElement(name = "completed-by") @Column(allowsNull = "true") protected Person completedBy; @XmlElement() @Column(allowsNull = "true") protected Formulation formulation; @XmlElement() @Column(allowsNull = "true") protected Specification specification; @XmlElement(name = "batch-component") @Persistent(mappedBy = "batch") @Order(column="batchorder_idx") protected List<BatchComponent> batchComponents = new ArrayList<>(); @XmlElement(name = "product-item") @Persistent(mappedBy = "batch") @Order(column="batchorder_idx") protected List<ProductItem> productItems = new ArrayList<>(); @XmlTransient @Persistent(mappedBy = "batch") @Order(column="batchorder_idx") protected List<OrderLineBatch> batchOrderLines = new ArrayList<>(); public ProductLine getProductLine() { return productLine; } public void setProductLine(ProductLine productLine) { this.productLine = productLine; } /** * Gets the value of the createdOn property. * * @return possible object is {@link String } * */ public Date getCreatedOn() { return createdOn; } /** * Sets the value of the createdOn property. * * @param value * allowed object is {@link String } * */ public void setCreatedOn(Date value) { this.createdOn = value; } /** * Gets the value of the createdBy property. * * @return possible object is {@link Person } * */ public Person getCreatedBy() { return createdBy; } /** * Sets the value of the createdBy property. * * @param value * allowed object is {@link Person } * */ public void setCreatedBy(Person value) { this.createdBy = value; } /** * Gets the value of the scheduledFor property. * * @return possible object is {@link String } * */ public Date getScheduledFor() { return scheduledFor; } /** * Sets the value of the scheduledFor property. * * @param value * allowed object is {@link String } * */ public void setScheduledFor(Date value) { this.scheduledFor = value; } /** * Gets the value of the completedOn property. * * @return possible object is {@link String } * */ public Date getCompletedOn() { return completedOn; } /** * Sets the value of the completedOn property. * * @param value * allowed object is {@link String } * */ public void setCompletedOn(Date value) { this.completedOn = value; } /** * Gets the value of the completedBy property. * * @return possible object is {@link Person } * */ public Person getCompletedBy() { return completedBy; } /** * Sets the value of the completedBy property. * * @param value * allowed object is {@link Person } * */ public void setCompletedBy(Person value) { this.completedBy = value; } /** * Gets the value of the formulation property. * * @return possible object is {@link Formulation } * */ public Formulation getFormulation() { return formulation; } /** * Sets the value of the formulation property. * * @param value * allowed object is {@link Formulation } * */ public void setFormulation(Formulation value) { this.formulation = value; } /** * Gets the value of the specification property. * * @return * possible object is * {@link Specification } * */ public Specification getSpecification() { return specification; } /** * Sets the value of the specification property. * * @param value * allowed object is * {@link Specification } * */ public void setSpecification(Specification value) { this.specification = value; } /** * Gets the value of the batchComponent 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 batchComponent property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBatchComponent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BatchComponent } * * */ public List<BatchComponent> getBatchComponents() { return this.batchComponents; } /** * Gets the value of the productItem 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 productItem property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getProductItem().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProductItem } * * */ public List<ProductItem> getProductItems() { return this.productItems; } public List<OrderLineBatch> getBatchOrderLines() { return this.batchOrderLines; } }
package net.crowdweather.droid; import static android.location.LocationManager.GPS_PROVIDER; import static android.location.LocationManager.NETWORK_PROVIDER; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; Location location; // location double latitude; // latitude double longitude; // longitude // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; public GPSTracker(Context context) { this.mContext = context; getLocation(); } @Override public void onLocationChanged(Location location) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void onStatusChanged(String provider, int status, Bundle extras) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void onProviderEnabled(String provider) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void onProviderDisabled(String provider) { //To change body of implemented methods use File | Settings | File Templates. } @Override public IBinder onBind(Intent intent) { return null; //To change body of implemented methods use File | Settings | File Templates. } public Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager .isProviderEnabled(GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; // First get location from Network Provider if (isNetworkEnabled) { locationManager.requestLocationUpdates( NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will lauch Settings Options * */ public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title alertDialog.setTitle("GPS is settings"); // Setting Dialog Message alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); // On pressing Settings button alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }); // on pressing cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } }
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/logging/v2/logging_config.proto package com.google.logging.v2; /** * * * <pre> * The response from ListBuckets. * </pre> * * Protobuf type {@code google.logging.v2.ListBucketsResponse} */ public final class ListBucketsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.logging.v2.ListBucketsResponse) ListBucketsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListBucketsResponse.newBuilder() to construct. private ListBucketsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListBucketsResponse() { buckets_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListBucketsResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ListBucketsResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; 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: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { buckets_ = new java.util.ArrayList<com.google.logging.v2.LogBucket>(); mutable_bitField0_ |= 0x00000001; } buckets_.add( input.readMessage(com.google.logging.v2.LogBucket.parser(), extensionRegistry)); break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); nextPageToken_ = 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 { if (((mutable_bitField0_ & 0x00000001) != 0)) { buckets_ = java.util.Collections.unmodifiableList(buckets_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.logging.v2.LoggingConfigProto .internal_static_google_logging_v2_ListBucketsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.logging.v2.LoggingConfigProto .internal_static_google_logging_v2_ListBucketsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.logging.v2.ListBucketsResponse.class, com.google.logging.v2.ListBucketsResponse.Builder.class); } public static final int BUCKETS_FIELD_NUMBER = 1; private java.util.List<com.google.logging.v2.LogBucket> buckets_; /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ @java.lang.Override public java.util.List<com.google.logging.v2.LogBucket> getBucketsList() { return buckets_; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.logging.v2.LogBucketOrBuilder> getBucketsOrBuilderList() { return buckets_; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ @java.lang.Override public int getBucketsCount() { return buckets_.size(); } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ @java.lang.Override public com.google.logging.v2.LogBucket getBuckets(int index) { return buckets_.get(index); } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ @java.lang.Override public com.google.logging.v2.LogBucketOrBuilder getBucketsOrBuilder(int index) { return buckets_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; private volatile java.lang.Object nextPageToken_; /** * * * <pre> * If there might be more results than appear in this response, then * `nextPageToken` is included. To get the next set of results, call the same * method again using the value of `nextPageToken` as `pageToken`. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; 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(); nextPageToken_ = s; return s; } } /** * * * <pre> * If there might be more results than appear in this response, then * `nextPageToken` is included. To get the next set of results, call the same * method again using the value of `nextPageToken` as `pageToken`. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = 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 { for (int i = 0; i < buckets_.size(); i++) { output.writeMessage(1, buckets_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < buckets_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, buckets_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } 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.logging.v2.ListBucketsResponse)) { return super.equals(obj); } com.google.logging.v2.ListBucketsResponse other = (com.google.logging.v2.ListBucketsResponse) obj; if (!getBucketsList().equals(other.getBucketsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) 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(); if (getBucketsCount() > 0) { hash = (37 * hash) + BUCKETS_FIELD_NUMBER; hash = (53 * hash) + getBucketsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.logging.v2.ListBucketsResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.logging.v2.ListBucketsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.logging.v2.ListBucketsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.logging.v2.ListBucketsResponse 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.logging.v2.ListBucketsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.logging.v2.ListBucketsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.logging.v2.ListBucketsResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.logging.v2.ListBucketsResponse 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.logging.v2.ListBucketsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.logging.v2.ListBucketsResponse 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.logging.v2.ListBucketsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.logging.v2.ListBucketsResponse 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.logging.v2.ListBucketsResponse 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 response from ListBuckets. * </pre> * * Protobuf type {@code google.logging.v2.ListBucketsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.logging.v2.ListBucketsResponse) com.google.logging.v2.ListBucketsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.logging.v2.LoggingConfigProto .internal_static_google_logging_v2_ListBucketsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.logging.v2.LoggingConfigProto .internal_static_google_logging_v2_ListBucketsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.logging.v2.ListBucketsResponse.class, com.google.logging.v2.ListBucketsResponse.Builder.class); } // Construct using com.google.logging.v2.ListBucketsResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getBucketsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (bucketsBuilder_ == null) { buckets_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { bucketsBuilder_.clear(); } nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.logging.v2.LoggingConfigProto .internal_static_google_logging_v2_ListBucketsResponse_descriptor; } @java.lang.Override public com.google.logging.v2.ListBucketsResponse getDefaultInstanceForType() { return com.google.logging.v2.ListBucketsResponse.getDefaultInstance(); } @java.lang.Override public com.google.logging.v2.ListBucketsResponse build() { com.google.logging.v2.ListBucketsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.logging.v2.ListBucketsResponse buildPartial() { com.google.logging.v2.ListBucketsResponse result = new com.google.logging.v2.ListBucketsResponse(this); int from_bitField0_ = bitField0_; if (bucketsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { buckets_ = java.util.Collections.unmodifiableList(buckets_); bitField0_ = (bitField0_ & ~0x00000001); } result.buckets_ = buckets_; } else { result.buckets_ = bucketsBuilder_.build(); } result.nextPageToken_ = nextPageToken_; 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.logging.v2.ListBucketsResponse) { return mergeFrom((com.google.logging.v2.ListBucketsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.logging.v2.ListBucketsResponse other) { if (other == com.google.logging.v2.ListBucketsResponse.getDefaultInstance()) return this; if (bucketsBuilder_ == null) { if (!other.buckets_.isEmpty()) { if (buckets_.isEmpty()) { buckets_ = other.buckets_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureBucketsIsMutable(); buckets_.addAll(other.buckets_); } onChanged(); } } else { if (!other.buckets_.isEmpty()) { if (bucketsBuilder_.isEmpty()) { bucketsBuilder_.dispose(); bucketsBuilder_ = null; buckets_ = other.buckets_; bitField0_ = (bitField0_ & ~0x00000001); bucketsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getBucketsFieldBuilder() : null; } else { bucketsBuilder_.addAllMessages(other.buckets_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; 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.logging.v2.ListBucketsResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.logging.v2.ListBucketsResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.logging.v2.LogBucket> buckets_ = java.util.Collections.emptyList(); private void ensureBucketsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { buckets_ = new java.util.ArrayList<com.google.logging.v2.LogBucket>(buckets_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.logging.v2.LogBucket, com.google.logging.v2.LogBucket.Builder, com.google.logging.v2.LogBucketOrBuilder> bucketsBuilder_; /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public java.util.List<com.google.logging.v2.LogBucket> getBucketsList() { if (bucketsBuilder_ == null) { return java.util.Collections.unmodifiableList(buckets_); } else { return bucketsBuilder_.getMessageList(); } } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public int getBucketsCount() { if (bucketsBuilder_ == null) { return buckets_.size(); } else { return bucketsBuilder_.getCount(); } } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public com.google.logging.v2.LogBucket getBuckets(int index) { if (bucketsBuilder_ == null) { return buckets_.get(index); } else { return bucketsBuilder_.getMessage(index); } } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder setBuckets(int index, com.google.logging.v2.LogBucket value) { if (bucketsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBucketsIsMutable(); buckets_.set(index, value); onChanged(); } else { bucketsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder setBuckets(int index, com.google.logging.v2.LogBucket.Builder builderForValue) { if (bucketsBuilder_ == null) { ensureBucketsIsMutable(); buckets_.set(index, builderForValue.build()); onChanged(); } else { bucketsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder addBuckets(com.google.logging.v2.LogBucket value) { if (bucketsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBucketsIsMutable(); buckets_.add(value); onChanged(); } else { bucketsBuilder_.addMessage(value); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder addBuckets(int index, com.google.logging.v2.LogBucket value) { if (bucketsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBucketsIsMutable(); buckets_.add(index, value); onChanged(); } else { bucketsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder addBuckets(com.google.logging.v2.LogBucket.Builder builderForValue) { if (bucketsBuilder_ == null) { ensureBucketsIsMutable(); buckets_.add(builderForValue.build()); onChanged(); } else { bucketsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder addBuckets(int index, com.google.logging.v2.LogBucket.Builder builderForValue) { if (bucketsBuilder_ == null) { ensureBucketsIsMutable(); buckets_.add(index, builderForValue.build()); onChanged(); } else { bucketsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder addAllBuckets( java.lang.Iterable<? extends com.google.logging.v2.LogBucket> values) { if (bucketsBuilder_ == null) { ensureBucketsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, buckets_); onChanged(); } else { bucketsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder clearBuckets() { if (bucketsBuilder_ == null) { buckets_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { bucketsBuilder_.clear(); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public Builder removeBuckets(int index) { if (bucketsBuilder_ == null) { ensureBucketsIsMutable(); buckets_.remove(index); onChanged(); } else { bucketsBuilder_.remove(index); } return this; } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public com.google.logging.v2.LogBucket.Builder getBucketsBuilder(int index) { return getBucketsFieldBuilder().getBuilder(index); } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public com.google.logging.v2.LogBucketOrBuilder getBucketsOrBuilder(int index) { if (bucketsBuilder_ == null) { return buckets_.get(index); } else { return bucketsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public java.util.List<? extends com.google.logging.v2.LogBucketOrBuilder> getBucketsOrBuilderList() { if (bucketsBuilder_ != null) { return bucketsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(buckets_); } } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public com.google.logging.v2.LogBucket.Builder addBucketsBuilder() { return getBucketsFieldBuilder() .addBuilder(com.google.logging.v2.LogBucket.getDefaultInstance()); } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public com.google.logging.v2.LogBucket.Builder addBucketsBuilder(int index) { return getBucketsFieldBuilder() .addBuilder(index, com.google.logging.v2.LogBucket.getDefaultInstance()); } /** * * * <pre> * A list of buckets. * </pre> * * <code>repeated .google.logging.v2.LogBucket buckets = 1;</code> */ public java.util.List<com.google.logging.v2.LogBucket.Builder> getBucketsBuilderList() { return getBucketsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.logging.v2.LogBucket, com.google.logging.v2.LogBucket.Builder, com.google.logging.v2.LogBucketOrBuilder> getBucketsFieldBuilder() { if (bucketsBuilder_ == null) { bucketsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.logging.v2.LogBucket, com.google.logging.v2.LogBucket.Builder, com.google.logging.v2.LogBucketOrBuilder>( buckets_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); buckets_ = null; } return bucketsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * If there might be more results than appear in this response, then * `nextPageToken` is included. To get the next set of results, call the same * method again using the value of `nextPageToken` as `pageToken`. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * If there might be more results than appear in this response, then * `nextPageToken` is included. To get the next set of results, call the same * method again using the value of `nextPageToken` as `pageToken`. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * If there might be more results than appear in this response, then * `nextPageToken` is included. To get the next set of results, call the same * method again using the value of `nextPageToken` as `pageToken`. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; onChanged(); return this; } /** * * * <pre> * If there might be more results than appear in this response, then * `nextPageToken` is included. To get the next set of results, call the same * method again using the value of `nextPageToken` as `pageToken`. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); onChanged(); return this; } /** * * * <pre> * If there might be more results than appear in this response, then * `nextPageToken` is included. To get the next set of results, call the same * method again using the value of `nextPageToken` as `pageToken`. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = 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.logging.v2.ListBucketsResponse) } // @@protoc_insertion_point(class_scope:google.logging.v2.ListBucketsResponse) private static final com.google.logging.v2.ListBucketsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.logging.v2.ListBucketsResponse(); } public static com.google.logging.v2.ListBucketsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListBucketsResponse> PARSER = new com.google.protobuf.AbstractParser<ListBucketsResponse>() { @java.lang.Override public ListBucketsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ListBucketsResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ListBucketsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListBucketsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.logging.v2.ListBucketsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright 2016 Tyler Wong * * 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 me.tylerbwong.pokebase.gui.activities; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.media.MediaPlayer; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Pair; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.animation.AlphaAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.r0adkll.slidr.Slidr; import com.r0adkll.slidr.model.SlidrConfig; import com.yarolegovich.lovelydialog.LovelyChoiceDialog; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import me.tylerbwong.pokebase.R; import me.tylerbwong.pokebase.gui.views.PokemonInfoView; import me.tylerbwong.pokebase.model.database.DatabaseOpenHelper; /** * @author Tyler Wong */ public class PokemonProfileActivity extends AppCompatActivity implements AppBarLayout.OnOffsetChangedListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.profile_image) ImageView profileImg; @BindView(R.id.pokemon_name) TextView title; @BindView(R.id.main_title) TextView mainTitle; @BindView(R.id.previous_label) TextView previousLabel; @BindView(R.id.next_label) TextView nextLabel; @BindView(R.id.previous_image) ImageView previousImage; @BindView(R.id.next_image) ImageView nextImage; @BindView(R.id.layout) CoordinatorLayout layout; @BindView(R.id.title_layout) LinearLayout titleContainer; @BindView(R.id.app_bar) AppBarLayout appBar; @BindView(R.id.info_view) PokemonInfoView infoView; private ActionBar actionBar; private DatabaseOpenHelper databaseHelper; private int pokemonId; private String pokemonName; private List<Pair<Integer, String>> pokemonTeams; private boolean isTitleVisible = false; private boolean isTitleContainerVisible = true; private static final String ICON = "icon_"; private static final String SPRITE = "sprites_"; private static final String AUDIO = "audio_"; private static final String DRAWABLE = "drawable"; private static final String RAW = "raw"; private static final String UNDO = "UNDO"; private static final String PROFILE = "profile"; private static final int PROFILE_IMG_ELEVATION = 40; private static final int DEFAULT_LEVEL = 1; private static final int DEFAULT_MOVE = 0; private static final int FIRST_POKEMON = 1; private static final int LAST_POKEMON = 721; private static final int TEN = 10; private static final int HUNDRED = 100; private static final String DOUBLE_ZERO = "00"; private static final String ZERO = "0"; private static final float PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR = 0.9f; private static final float PERCENTAGE_TO_HIDE_TITLE_DETAILS = 0.3f; private static final int ALPHA_ANIMATIONS_DURATION = 200; public static final String POKEMON_ID_KEY = "pokemon_id"; public static final String POKEMON_NAME_KEY = "pokemon_name"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); ButterKnife.bind(this); databaseHelper = DatabaseOpenHelper.getInstance(this); profileImg.setClipToOutline(true); profileImg.setElevation(PROFILE_IMG_ELEVATION); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } appBar.addOnOffsetChangedListener(this); startAlphaAnimation(title, 0, View.INVISIBLE); SlidrConfig config = new SlidrConfig.Builder() .sensitivity(1f) .scrimColor(Color.BLACK) .scrimStartAlpha(0.8f) .scrimEndAlpha(0f) .velocityThreshold(2400) .distanceThreshold(0.25f) .edge(true) .edgeSize(0.18f) .build(); Slidr.attach(this, config); Bundle extras = getIntent().getExtras(); pokemonId = extras.getInt(POKEMON_ID_KEY); pokemonName = extras.getString(POKEMON_NAME_KEY); infoView.setButtonsVisible(true); infoView.loadPokemonInfo(pokemonId); loadNextPrevious(); Glide.with(PokemonProfileActivity.this) .load(String.format(getString(R.string.sprite_url), databaseHelper.queryPokemonNameById(pokemonId).toLowerCase())) .into(profileImg); String formattedName = String.format(getString(R.string.pokemon_name), formatId(pokemonId), pokemonName); title.setText(formattedName); mainTitle.setText(formattedName); } @OnClick(R.id.previous) public void onPrevious() { if (pokemonId == FIRST_POKEMON) { switchPokemon(LAST_POKEMON); } else { switchPokemon(pokemonId - 1); } } @OnClick(R.id.next) public void onNext() { if (pokemonId == LAST_POKEMON) { switchPokemon(FIRST_POKEMON); } else { switchPokemon(pokemonId + 1); } } public void closeEvolutionsDialog() { infoView.closeEvolutionsDialog(); } public static String formatId(int id) { String result; if (id < TEN) { result = DOUBLE_ZERO + String.valueOf(id); } else if (id >= TEN && id < HUNDRED) { result = ZERO + String.valueOf(id); } else { result = String.valueOf(id); } return result; } private void switchPokemon(int pokemonId) { Intent intent = getIntent(); Bundle extras = new Bundle(); extras.putInt(POKEMON_ID_KEY, pokemonId); extras.putString(POKEMON_NAME_KEY, databaseHelper.queryPokemonNameById(pokemonId)); intent.putExtras(extras); startActivity(intent); finish(); } private void loadNextPrevious() { int nextPokemonId, previousPokemonId; if (pokemonId == FIRST_POKEMON) { previousPokemonId = LAST_POKEMON; nextPokemonId = pokemonId + 1; } else if (pokemonId == LAST_POKEMON) { previousPokemonId = pokemonId - 1; nextPokemonId = FIRST_POKEMON; } else { previousPokemonId = pokemonId - 1; nextPokemonId = pokemonId + 1; } previousLabel.setText(String.format(getString(R.string.hashtag_format), formatId(previousPokemonId))); Glide.with(this) .load(String.format(getString(R.string.icon_url), databaseHelper.queryPokemonNameById(previousPokemonId).toLowerCase())) .into(previousImage); nextLabel.setText(String.format(getString(R.string.hashtag_format), formatId(nextPokemonId))); Glide.with(this) .load(String.format(getString(R.string.icon_url), databaseHelper.queryPokemonNameById(nextPokemonId).toLowerCase())) .into(nextImage); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; case R.id.audio_action: playAudio(); break; case R.id.add_action: showAddToTeamDialog(); break; default: break; } return true; } private void playAudio() { final MediaPlayer player = MediaPlayer.create(this, getResources().getIdentifier( AUDIO + pokemonId, RAW, getPackageName())); player.setOnCompletionListener(mediaPlayer -> player.release()); player.start(); Toast.makeText(this, getString(R.string.sound_played), Toast.LENGTH_SHORT).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_audio, menu); inflater.inflate(R.menu.menu_add, menu); return true; } private void showAddToTeamDialog() { databaseHelper.queryTeamIdsAndNames() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(teams -> { String[] teamNames = new String[teams.size()]; for (int index = 0; index < teams.size(); index++) { teamNames[index] = teams.get(index).second; } if (!teams.isEmpty()) { new LovelyChoiceDialog(PokemonProfileActivity.this) .setTopColorRes(R.color.colorPrimary) .setTitle(String.format(getString(R.string.add_team_title), pokemonName)) .setIcon(R.drawable.ic_add_circle_outline_white_24dp) .setItems(teamNames, (position, item) -> databaseHelper.insertTeamPokemon(teams.get(position).first, pokemonId, pokemonName, DEFAULT_LEVEL, DEFAULT_MOVE, DEFAULT_MOVE, DEFAULT_MOVE, DEFAULT_MOVE) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(() -> { Snackbar snackbar = Snackbar.make(layout, String.format( getString(R.string.add_success), pokemonName, item), Snackbar.LENGTH_LONG) .setAction(UNDO, view -> databaseHelper.deleteLastAddedPokemon()); snackbar.setActionTextColor(ContextCompat.getColor( getApplicationContext(), R.color.colorPrimary)); snackbar.show(); }) ) .show(); } else { new LovelyChoiceDialog(PokemonProfileActivity.this) .setTopColorRes(R.color.colorPrimary) .setTitle(getString(R.string.no_teams_title)) .setMessage(String.format(getString(R.string.no_teams), pokemonName)) .setIcon(R.drawable.ic_add_circle_outline_white_24dp) .show(); } }); } @Override public void onOffsetChanged(AppBarLayout appBarLayout, int offset) { int maxScroll = appBarLayout.getTotalScrollRange(); float percentage = (float) Math.abs(offset) / (float) maxScroll; handleAlphaOnTitle(percentage); handleToolbarTitleVisibility(percentage); if (Math.abs(offset) >= appBar.getHeight() - getResources().getDimension(R.dimen.toolbar_margin_top)) { actionBar.setElevation(getResources().getDimension(R.dimen.toolbar_elevation)); actionBar.setBackgroundDrawable(new ColorDrawable( ContextCompat.getColor(this, R.color.colorPrimary))); } else { actionBar.setElevation(0); actionBar.setBackgroundDrawable(null); } } private void handleToolbarTitleVisibility(float percentage) { if (percentage >= PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR) { if (!isTitleVisible) { startAlphaAnimation(title, ALPHA_ANIMATIONS_DURATION, View.VISIBLE); isTitleVisible = true; } } else { if (isTitleVisible) { startAlphaAnimation(title, ALPHA_ANIMATIONS_DURATION, View.INVISIBLE); isTitleVisible = false; } } } private void handleAlphaOnTitle(float percentage) { if (percentage >= PERCENTAGE_TO_HIDE_TITLE_DETAILS) { if (isTitleContainerVisible) { startAlphaAnimation(titleContainer, ALPHA_ANIMATIONS_DURATION, View.INVISIBLE); isTitleContainerVisible = false; } } else { if (!isTitleContainerVisible) { startAlphaAnimation(titleContainer, ALPHA_ANIMATIONS_DURATION, View.VISIBLE); isTitleContainerVisible = true; } } } public static void startAlphaAnimation(View view, long duration, int visibility) { AlphaAnimation alphaAnimation = (visibility == View.VISIBLE) ? new AlphaAnimation(0f, 1f) : new AlphaAnimation(1f, 0f); alphaAnimation.setDuration(duration); alphaAnimation.setFillAfter(true); view.startAnimation(alphaAnimation); } }
/* * 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.controller.repository; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; public class RingBufferEventRepository implements FlowFileEventRepository { private final int numMinutes; private final ConcurrentMap<String, EventContainer> componentEventMap = new ConcurrentHashMap<>(); public RingBufferEventRepository(final int numMinutes) { this.numMinutes = numMinutes; } @Override public void close() throws IOException { } @Override public void updateRepository(final FlowFileEvent event) { final String componentId = event.getComponentIdentifier(); EventContainer eventContainer = componentEventMap.get(componentId); if (eventContainer == null) { eventContainer = new SecondPrecisionEventContainer(numMinutes); final EventContainer oldEventContainer = componentEventMap.putIfAbsent(componentId, eventContainer); if (oldEventContainer != null) { eventContainer = oldEventContainer; } } eventContainer.addEvent(event); } @Override public StandardRepositoryStatusReport reportTransferEvents(final long sinceEpochMillis) { final StandardRepositoryStatusReport report = new StandardRepositoryStatusReport(); for (final Map.Entry<String, EventContainer> entry : componentEventMap.entrySet()) { final String consumerId = entry.getKey(); final EventContainer container = entry.getValue(); final FlowFileEvent reportEntry = container.generateReport(consumerId, sinceEpochMillis); report.addReportEntry(reportEntry); } return report; } @Override public void purgeTransferEvents(final long cutoffEpochMilliseconds) { // This is done so that if a processor is removed from the graph, its events // will be removed rather than being kept in memory for (final EventContainer container : componentEventMap.values()) { container.purgeEvents(cutoffEpochMilliseconds); } } private static interface EventContainer { public void addEvent(FlowFileEvent event); public void purgeEvents(long cutoffEpochMillis); public FlowFileEvent generateReport(String consumerId, long sinceEpochMillis); } private class EventSum { private final AtomicReference<EventSumValue> ref = new AtomicReference<>(new EventSumValue()); private void add(final FlowFileEvent event) { EventSumValue newValue; EventSumValue value; do { value = ref.get(); newValue = new EventSumValue(value, event.getFlowFilesIn(), event.getFlowFilesOut(), event.getFlowFilesRemoved(), event.getContentSizeIn(), event.getContentSizeOut(), event.getContentSizeRemoved(), event.getBytesRead(), event.getBytesWritten(), event.getFlowFilesReceived(), event.getBytesReceived(), event.getFlowFilesSent(), event.getBytesSent(), event.getProcessingNanoseconds(), event.getInvocations(), event.getAggregateLineageMillis()); } while (!ref.compareAndSet(value, newValue)); } public EventSumValue getValue() { return ref.get(); } public void addOrReset(final FlowFileEvent event) { final long expectedMinute = System.currentTimeMillis() / 60000; final EventSumValue curValue = ref.get(); if (curValue.getMinuteTimestamp() != expectedMinute) { ref.compareAndSet(curValue, new EventSumValue()); } add(event); } } private static class EventSumValue { private final int flowFilesIn, flowFilesOut, flowFilesRemoved; private final long contentSizeIn, contentSizeOut, contentSizeRemoved; private final long bytesRead, bytesWritten; private final int flowFilesReceived, flowFilesSent; private final long bytesReceived, bytesSent; private final long processingNanos; private final long aggregateLineageMillis; private final int invocations; private final long minuteTimestamp; private final long millisecondTimestamp; public EventSumValue() { flowFilesIn = flowFilesOut = flowFilesRemoved = 0; contentSizeIn = contentSizeOut = contentSizeRemoved = 0; bytesRead = bytesWritten = 0; flowFilesReceived = flowFilesSent = 0; bytesReceived = bytesSent = 0L; processingNanos = invocations = 0; aggregateLineageMillis = 0L; this.millisecondTimestamp = System.currentTimeMillis(); this.minuteTimestamp = millisecondTimestamp / 60000; } public EventSumValue(final EventSumValue base, final int flowFilesIn, final int flowFilesOut, final int flowFilesRemoved, final long contentSizeIn, final long contentSizeOut, final long contentSizeRemoved, final long bytesRead, final long bytesWritten, final int flowFilesReceived, final long bytesReceived, final int flowFilesSent, final long bytesSent, final long processingNanos, final int invocations, final long aggregateLineageMillis) { this.flowFilesIn = base.flowFilesIn + flowFilesIn; this.flowFilesOut = base.flowFilesOut + flowFilesOut; this.flowFilesRemoved = base.flowFilesRemoved + flowFilesRemoved; this.contentSizeIn = base.contentSizeIn + contentSizeIn; this.contentSizeOut = base.contentSizeOut + contentSizeOut; this.contentSizeRemoved = base.contentSizeRemoved + contentSizeRemoved; this.bytesRead = base.bytesRead + bytesRead; this.bytesWritten = base.bytesWritten + bytesWritten; this.flowFilesReceived = base.flowFilesReceived + flowFilesReceived; this.bytesReceived = base.bytesReceived + bytesReceived; this.flowFilesSent = base.flowFilesSent + flowFilesSent; this.bytesSent = base.bytesSent + bytesSent; this.processingNanos = base.processingNanos + processingNanos; this.invocations = base.invocations + invocations; this.aggregateLineageMillis = base.aggregateLineageMillis + aggregateLineageMillis; this.millisecondTimestamp = System.currentTimeMillis(); this.minuteTimestamp = millisecondTimestamp / 60000; } public long getTimestamp() { return millisecondTimestamp; } public long getMinuteTimestamp() { return minuteTimestamp; } public long getBytesRead() { return bytesRead; } public long getBytesWritten() { return bytesWritten; } public int getFlowFilesIn() { return flowFilesIn; } public int getFlowFilesOut() { return flowFilesOut; } public long getContentSizeIn() { return contentSizeIn; } public long getContentSizeOut() { return contentSizeOut; } public int getFlowFilesRemoved() { return flowFilesRemoved; } public long getContentSizeRemoved() { return contentSizeRemoved; } public long getProcessingNanoseconds() { return processingNanos; } public int getInvocations() { return invocations; } public long getAggregateLineageMillis() { return aggregateLineageMillis; } public int getFlowFilesReceived() { return flowFilesReceived; } public int getFlowFilesSent() { return flowFilesSent; } public long getBytesReceived() { return bytesReceived; } public long getBytesSent() { return bytesSent; } } private class SecondPrecisionEventContainer implements EventContainer { private final int numBins; private final EventSum[] sums; public SecondPrecisionEventContainer(final int numMinutes) { numBins = 1 + numMinutes * 60; sums = new EventSum[numBins]; for (int i = 0; i < numBins; i++) { sums[i] = new EventSum(); } } @Override public void addEvent(final FlowFileEvent event) { final int second = (int) (System.currentTimeMillis() / 1000); final int binIdx = (int) (second % numBins); final EventSum sum = sums[binIdx]; sum.addOrReset(event); } @Override public void purgeEvents(final long cutoffEpochMilliseconds) { // no need to do anything } @Override public FlowFileEvent generateReport(final String consumerId, final long sinceEpochMillis) { int flowFilesIn = 0, flowFilesOut = 0, flowFilesRemoved = 0; long contentSizeIn = 0L, contentSizeOut = 0L, contentSizeRemoved = 0L; long bytesRead = 0L, bytesWritten = 0L; int invocations = 0; long processingNanos = 0L; long aggregateLineageMillis = 0L; int flowFilesReceived = 0, flowFilesSent = 0; long bytesReceived = 0L, bytesSent = 0L; final long second = sinceEpochMillis / 1000; final int startBinIdx = (int) (second % numBins); for (int i = 0; i < numBins; i++) { int binIdx = (startBinIdx + i) % numBins; final EventSum sum = sums[binIdx]; final EventSumValue sumValue = sum.getValue(); if (sumValue.getTimestamp() >= sinceEpochMillis) { flowFilesIn += sumValue.getFlowFilesIn(); flowFilesOut += sumValue.getFlowFilesOut(); flowFilesRemoved += sumValue.getFlowFilesRemoved(); contentSizeIn += sumValue.getContentSizeIn(); contentSizeOut += sumValue.getContentSizeOut(); contentSizeRemoved += sumValue.getContentSizeRemoved(); bytesRead += sumValue.getBytesRead(); bytesWritten += sumValue.getBytesWritten(); flowFilesReceived += sumValue.getFlowFilesReceived(); bytesReceived += sumValue.getBytesReceived(); flowFilesSent += sumValue.getFlowFilesSent(); bytesSent += sumValue.getBytesSent(); invocations += sumValue.getInvocations(); processingNanos += sumValue.getProcessingNanoseconds(); aggregateLineageMillis += sumValue.getAggregateLineageMillis(); } } return new StandardFlowFileEvent(consumerId, flowFilesIn, contentSizeIn, flowFilesOut, contentSizeOut, flowFilesRemoved, contentSizeRemoved, bytesRead, bytesWritten, flowFilesReceived, bytesReceived, flowFilesSent, bytesSent, invocations, aggregateLineageMillis, processingNanos); } } }
package graph; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class BuildGraph { public static ResultatBuildGraph buildGraph(String fileName, int nbMaxEdgesPerNode, double minEdgeWeight) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(fileName)); String line = null; int N = 100; String[] lineSplit = new String[4]; Map<Integer,String> nodesMapItoS = new HashMap<Integer,String>(); Map<String,Integer> nodesMapStoI = new HashMap<String,Integer>(); Map<Integer,Integer> nbEdgesFromNode = new HashMap<Integer,Integer>(); Graph<Integer, Float> g = new ArrayBackedGraph<Float>(N, 1); br.readLine(); int i = 0; int root = 0; //root word of each cluster,line int linectr=0,linectr2 = 0; while ( (line = br.readLine()) != null){ linectr++; if (linectr==10000){ linectr2 +=linectr; System.out.println("line " + linectr2); linectr=0; } lineSplit = line.split("\t"); //System.out.println(lineSplit[0]); String word = lineSplit[0]; if (nodesMapStoI.containsKey(word)){ root = nodesMapStoI.get(word); }else{ //if (!freqMap.containsKey(lineSplit[0]) || (freqMap.containsKey(lineSplit[0]) && freqMap.get(lineSplit[0]) > freqThreshold)){ root = i; i++; g.addNode(root); nbEdgesFromNode.put(root, 0); if (nodesMapItoS.containsKey(root)) System.out.println("duplicated node for root = "+root); nodesMapItoS.put(Integer.valueOf(root), word); nodesMapStoI.put(word, Integer.valueOf(root)); //}else{ //System.out.println("node " + lineSplit[0]+ "not added due to low freq"); //} } if (lineSplit.length>1){ //System.out.println(lineSplit[2]); ArrayList<String> neighboursSplit = new ArrayList<String>(Arrays.asList(lineSplit[1].split(","))); for (String neighbourSp : neighboursSplit){ //neighbours.add(neighbourSp.split(":")[0]); // if node already added if (neighbourSp.split(":").length>1){ if (nodesMapStoI.containsKey(neighbourSp.split(":")[0])){ int node = nodesMapStoI.get(neighbourSp.split(":")[0]); if (nbEdgesFromNode.get(root) < nbMaxEdgesPerNode && nbEdgesFromNode.get(node) < nbMaxEdgesPerNode && Float.valueOf(neighbourSp.split(":")[1]) > minEdgeWeight){ g.addEdgeUndirected(root, node, Float.valueOf(neighbourSp.split(":")[1])); nbEdgesFromNode.put(root,nbEdgesFromNode.get(root)+1); nbEdgesFromNode.put(node,nbEdgesFromNode.get(node)+1); } }else{ g.addNode(i); nbEdgesFromNode.put(i, 0); nodesMapItoS.put(Integer.valueOf(i), neighbourSp.split(":")[0]); nodesMapStoI.put(neighbourSp.split(":")[0] , Integer.valueOf(i)); if (nbEdgesFromNode.get(root) < nbMaxEdgesPerNode && Float.valueOf(neighbourSp.split(":")[1]) > minEdgeWeight){ g.addEdgeUndirected(root, i, Float.valueOf(neighbourSp.split(":")[1])); nbEdgesFromNode.put(root,nbEdgesFromNode.get(root)+1); nbEdgesFromNode.put(i,1); } i++; } } } } } System.out.println("graph built with a limit of "+nbMaxEdgesPerNode+" edges from each node."); ResultatBuildGraph res = new ResultatBuildGraph(g,nodesMapItoS,nodesMapStoI); return res; } public static ResultatBuildGraph buildGraph(String fileName, int nbMaxEdgesPerNode) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(fileName)); String line = null; int N = 100; String[] lineSplit = new String[4]; Map<Integer,String> nodesMapItoS = new HashMap<Integer,String>(); Map<String,Integer> nodesMapStoI = new HashMap<String,Integer>(); Map<Integer,Integer> nbEdgesFromNode = new HashMap<Integer,Integer>(); Graph<Integer, Float> g = new ArrayBackedGraph<Float>(N, 1); br.readLine(); int i = 0; int root = 0; //root word of each cluster,line int linectr=0,linectr2 = 0; while ( (line = br.readLine()) != null){ linectr++; if (linectr==10000){ linectr2 +=linectr; System.out.println("line " + linectr2); linectr=0; } lineSplit = line.split("\t"); //System.out.println(lineSplit[0]); String word = lineSplit[0]; if (nodesMapStoI.containsKey(word)){ root = nodesMapStoI.get(word); }else{ //if (!freqMap.containsKey(lineSplit[0]) || (freqMap.containsKey(lineSplit[0]) && freqMap.get(lineSplit[0]) > freqThreshold)){ root = i; i++; g.addNode(root); nbEdgesFromNode.put(root, 0); if (nodesMapItoS.containsKey(root)) System.out.println("duplicated node for root = "+root); nodesMapItoS.put(Integer.valueOf(root), word); nodesMapStoI.put(word, Integer.valueOf(root)); //}else{ //System.out.println("node " + lineSplit[0]+ "not added due to low freq"); //} } if (lineSplit.length>1){ //System.out.println(lineSplit[2]); ArrayList<String> neighboursSplit = new ArrayList<String>(Arrays.asList(lineSplit[1].split(","))); for (String neighbourSp : neighboursSplit){ //neighbours.add(neighbourSp.split(":")[0]); // if node already added if (neighbourSp.split(":").length>1){ if (nodesMapStoI.containsKey(neighbourSp.split(":")[0])){ int node = nodesMapStoI.get(neighbourSp.split(":")[0]); if (nbEdgesFromNode.get(root) < nbMaxEdgesPerNode || nbEdgesFromNode.get(node) < nbMaxEdgesPerNode){ g.addEdgeUndirected(root, node, Float.valueOf(neighbourSp.split(":")[1])); nbEdgesFromNode.put(root,nbEdgesFromNode.get(root)+1); nbEdgesFromNode.put(node,nbEdgesFromNode.get(node)+1); } }else{ g.addNode(i); nbEdgesFromNode.put(i, 0); nodesMapItoS.put(Integer.valueOf(i), neighbourSp.split(":")[0]); nodesMapStoI.put(neighbourSp.split(":")[0] , Integer.valueOf(i)); if (nbEdgesFromNode.get(root) < nbMaxEdgesPerNode){ g.addEdgeUndirected(root, i, Float.valueOf(neighbourSp.split(":")[1])); nbEdgesFromNode.put(root,nbEdgesFromNode.get(root)+1); nbEdgesFromNode.put(i,1); } i++; } } } } } System.out.println("graph built with a limit of "+nbMaxEdgesPerNode+" edges from each node."); ResultatBuildGraph res = new ResultatBuildGraph(g,nodesMapItoS,nodesMapStoI); return res; } public static ResultatBuildGraph buildGraph(String fileName) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(fileName)); String line = null; int N = 100; String[] lineSplit = new String[4]; Map<Integer,String> nodesMapItoS = new HashMap<Integer,String>(); Map<String,Integer> nodesMapStoI = new HashMap<String,Integer>(); Graph<Integer, Float> g = new ArrayBackedGraph<Float>(N, 1); br.readLine(); int i = 0; int root = 0; //root word of each cluster,line int linectr=0,linectr2 = 0; while ( (line = br.readLine()) != null){ linectr++; if (linectr==10000){ linectr2 +=linectr; System.out.println("line " + linectr2); linectr=0; } lineSplit = line.split("\t"); //System.out.println(lineSplit[0]); String word = lineSplit[0]; if (nodesMapStoI.containsKey(word)){ root = nodesMapStoI.get(word); }else{ //if (!freqMap.containsKey(lineSplit[0]) || (freqMap.containsKey(lineSplit[0]) && freqMap.get(lineSplit[0]) > freqThreshold)){ root = i; i++; g.addNode(root); if (nodesMapItoS.containsKey(root)) System.out.println("duplicated node for root = "+root); nodesMapItoS.put(Integer.valueOf(root), word); nodesMapStoI.put(word, Integer.valueOf(root)); //}else{ //System.out.println("node " + lineSplit[0]+ "not added due to low freq"); //} } if (lineSplit.length>1){ //System.out.println(lineSplit[2]); ArrayList<String> neighboursSplit = new ArrayList<String>(Arrays.asList(lineSplit[1].split(","))); for (String neighbourSp : neighboursSplit){ //neighbours.add(neighbourSp.split(":")[0]); // if node already added if (neighbourSp.split(":").length>1){ if (nodesMapStoI.containsKey(neighbourSp.split(":")[0])){ int node = nodesMapStoI.get(neighbourSp.split(":")[0]); g.addEdgeUndirected(root, node, Float.valueOf(neighbourSp.split(":")[1])); }else{ g.addNode(i); nodesMapItoS.put(Integer.valueOf(i), neighbourSp.split(":")[0]); nodesMapStoI.put(neighbourSp.split(":")[0] , Integer.valueOf(i)); g.addEdgeUndirected(root, i, Float.valueOf(neighbourSp.split(":")[1])); i++; } } } } } System.out.println("graph built"); ResultatBuildGraph res = new ResultatBuildGraph(g,nodesMapItoS,nodesMapStoI); return res; } }
/* * Copyright 2014-2019 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.lakeformation.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The AWS Lake Formation principal. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lakeformation-2017-03-31/DataLakeSettings" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DataLakeSettings implements Serializable, Cloneable, StructuredPojo { /** * <p> * A list of AWS Lake Formation principals. * </p> */ private java.util.List<DataLakePrincipal> dataLakeAdmins; /** * <p> * A list of up to three principal permissions entries for default create database permissions. * </p> */ private java.util.List<PrincipalPermissions> createDatabaseDefaultPermissions; /** * <p> * A list of up to three principal permissions entries for default create table permissions. * </p> */ private java.util.List<PrincipalPermissions> createTableDefaultPermissions; /** * <p> * A list of AWS Lake Formation principals. * </p> * * @return A list of AWS Lake Formation principals. */ public java.util.List<DataLakePrincipal> getDataLakeAdmins() { return dataLakeAdmins; } /** * <p> * A list of AWS Lake Formation principals. * </p> * * @param dataLakeAdmins * A list of AWS Lake Formation principals. */ public void setDataLakeAdmins(java.util.Collection<DataLakePrincipal> dataLakeAdmins) { if (dataLakeAdmins == null) { this.dataLakeAdmins = null; return; } this.dataLakeAdmins = new java.util.ArrayList<DataLakePrincipal>(dataLakeAdmins); } /** * <p> * A list of AWS Lake Formation principals. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setDataLakeAdmins(java.util.Collection)} or {@link #withDataLakeAdmins(java.util.Collection)} if you want * to override the existing values. * </p> * * @param dataLakeAdmins * A list of AWS Lake Formation principals. * @return Returns a reference to this object so that method calls can be chained together. */ public DataLakeSettings withDataLakeAdmins(DataLakePrincipal... dataLakeAdmins) { if (this.dataLakeAdmins == null) { setDataLakeAdmins(new java.util.ArrayList<DataLakePrincipal>(dataLakeAdmins.length)); } for (DataLakePrincipal ele : dataLakeAdmins) { this.dataLakeAdmins.add(ele); } return this; } /** * <p> * A list of AWS Lake Formation principals. * </p> * * @param dataLakeAdmins * A list of AWS Lake Formation principals. * @return Returns a reference to this object so that method calls can be chained together. */ public DataLakeSettings withDataLakeAdmins(java.util.Collection<DataLakePrincipal> dataLakeAdmins) { setDataLakeAdmins(dataLakeAdmins); return this; } /** * <p> * A list of up to three principal permissions entries for default create database permissions. * </p> * * @return A list of up to three principal permissions entries for default create database permissions. */ public java.util.List<PrincipalPermissions> getCreateDatabaseDefaultPermissions() { return createDatabaseDefaultPermissions; } /** * <p> * A list of up to three principal permissions entries for default create database permissions. * </p> * * @param createDatabaseDefaultPermissions * A list of up to three principal permissions entries for default create database permissions. */ public void setCreateDatabaseDefaultPermissions(java.util.Collection<PrincipalPermissions> createDatabaseDefaultPermissions) { if (createDatabaseDefaultPermissions == null) { this.createDatabaseDefaultPermissions = null; return; } this.createDatabaseDefaultPermissions = new java.util.ArrayList<PrincipalPermissions>(createDatabaseDefaultPermissions); } /** * <p> * A list of up to three principal permissions entries for default create database permissions. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setCreateDatabaseDefaultPermissions(java.util.Collection)} or * {@link #withCreateDatabaseDefaultPermissions(java.util.Collection)} if you want to override the existing values. * </p> * * @param createDatabaseDefaultPermissions * A list of up to three principal permissions entries for default create database permissions. * @return Returns a reference to this object so that method calls can be chained together. */ public DataLakeSettings withCreateDatabaseDefaultPermissions(PrincipalPermissions... createDatabaseDefaultPermissions) { if (this.createDatabaseDefaultPermissions == null) { setCreateDatabaseDefaultPermissions(new java.util.ArrayList<PrincipalPermissions>(createDatabaseDefaultPermissions.length)); } for (PrincipalPermissions ele : createDatabaseDefaultPermissions) { this.createDatabaseDefaultPermissions.add(ele); } return this; } /** * <p> * A list of up to three principal permissions entries for default create database permissions. * </p> * * @param createDatabaseDefaultPermissions * A list of up to three principal permissions entries for default create database permissions. * @return Returns a reference to this object so that method calls can be chained together. */ public DataLakeSettings withCreateDatabaseDefaultPermissions(java.util.Collection<PrincipalPermissions> createDatabaseDefaultPermissions) { setCreateDatabaseDefaultPermissions(createDatabaseDefaultPermissions); return this; } /** * <p> * A list of up to three principal permissions entries for default create table permissions. * </p> * * @return A list of up to three principal permissions entries for default create table permissions. */ public java.util.List<PrincipalPermissions> getCreateTableDefaultPermissions() { return createTableDefaultPermissions; } /** * <p> * A list of up to three principal permissions entries for default create table permissions. * </p> * * @param createTableDefaultPermissions * A list of up to three principal permissions entries for default create table permissions. */ public void setCreateTableDefaultPermissions(java.util.Collection<PrincipalPermissions> createTableDefaultPermissions) { if (createTableDefaultPermissions == null) { this.createTableDefaultPermissions = null; return; } this.createTableDefaultPermissions = new java.util.ArrayList<PrincipalPermissions>(createTableDefaultPermissions); } /** * <p> * A list of up to three principal permissions entries for default create table permissions. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setCreateTableDefaultPermissions(java.util.Collection)} or * {@link #withCreateTableDefaultPermissions(java.util.Collection)} if you want to override the existing values. * </p> * * @param createTableDefaultPermissions * A list of up to three principal permissions entries for default create table permissions. * @return Returns a reference to this object so that method calls can be chained together. */ public DataLakeSettings withCreateTableDefaultPermissions(PrincipalPermissions... createTableDefaultPermissions) { if (this.createTableDefaultPermissions == null) { setCreateTableDefaultPermissions(new java.util.ArrayList<PrincipalPermissions>(createTableDefaultPermissions.length)); } for (PrincipalPermissions ele : createTableDefaultPermissions) { this.createTableDefaultPermissions.add(ele); } return this; } /** * <p> * A list of up to three principal permissions entries for default create table permissions. * </p> * * @param createTableDefaultPermissions * A list of up to three principal permissions entries for default create table permissions. * @return Returns a reference to this object so that method calls can be chained together. */ public DataLakeSettings withCreateTableDefaultPermissions(java.util.Collection<PrincipalPermissions> createTableDefaultPermissions) { setCreateTableDefaultPermissions(createTableDefaultPermissions); 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 (getDataLakeAdmins() != null) sb.append("DataLakeAdmins: ").append(getDataLakeAdmins()).append(","); if (getCreateDatabaseDefaultPermissions() != null) sb.append("CreateDatabaseDefaultPermissions: ").append(getCreateDatabaseDefaultPermissions()).append(","); if (getCreateTableDefaultPermissions() != null) sb.append("CreateTableDefaultPermissions: ").append(getCreateTableDefaultPermissions()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DataLakeSettings == false) return false; DataLakeSettings other = (DataLakeSettings) obj; if (other.getDataLakeAdmins() == null ^ this.getDataLakeAdmins() == null) return false; if (other.getDataLakeAdmins() != null && other.getDataLakeAdmins().equals(this.getDataLakeAdmins()) == false) return false; if (other.getCreateDatabaseDefaultPermissions() == null ^ this.getCreateDatabaseDefaultPermissions() == null) return false; if (other.getCreateDatabaseDefaultPermissions() != null && other.getCreateDatabaseDefaultPermissions().equals(this.getCreateDatabaseDefaultPermissions()) == false) return false; if (other.getCreateTableDefaultPermissions() == null ^ this.getCreateTableDefaultPermissions() == null) return false; if (other.getCreateTableDefaultPermissions() != null && other.getCreateTableDefaultPermissions().equals(this.getCreateTableDefaultPermissions()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDataLakeAdmins() == null) ? 0 : getDataLakeAdmins().hashCode()); hashCode = prime * hashCode + ((getCreateDatabaseDefaultPermissions() == null) ? 0 : getCreateDatabaseDefaultPermissions().hashCode()); hashCode = prime * hashCode + ((getCreateTableDefaultPermissions() == null) ? 0 : getCreateTableDefaultPermissions().hashCode()); return hashCode; } @Override public DataLakeSettings clone() { try { return (DataLakeSettings) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.lakeformation.model.transform.DataLakeSettingsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package twilightforest.structures.icetower; import java.util.List; import java.util.Random; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; import net.minecraft.world.gen.structure.StructureBoundingBox; import net.minecraft.world.gen.structure.StructureComponent; import twilightforest.TFTreasure; import twilightforest.structures.StructureTFComponent; import twilightforest.structures.StructureTFDecorator; import twilightforest.structures.lichtower.ComponentTFTowerWing; public class ComponentTFIceTowerWing extends ComponentTFTowerWing { protected static final int SIZE = 11; private static final int RANGE = 17; boolean hasBase = false; protected int treasureFloor = -1; public ComponentTFIceTowerWing() {} protected ComponentTFIceTowerWing(int i, int x, int y, int z, int pSize, int pHeight, int direction) { super(i, x, y, z, pSize, pHeight, direction); } protected void func_143012_a(NBTTagCompound par1NBTTagCompound) { super.func_143012_a(par1NBTTagCompound); par1NBTTagCompound.func_74757_a("hasBase", hasBase); par1NBTTagCompound.func_74768_a("treasureFloor", treasureFloor); } protected void func_143011_b(NBTTagCompound par1NBTTagCompound) { super.func_143011_b(par1NBTTagCompound); hasBase = par1NBTTagCompound.func_74767_n("hasBase"); treasureFloor = par1NBTTagCompound.func_74762_e("treasureFloor"); } public void func_74861_a(StructureComponent parent, List list, Random rand) { if ((parent != null) && ((parent instanceof StructureTFComponent))) { deco = deco; } addOpening(0, 1, size / 2, 2); hasBase = shouldHaveBase(rand); if (func_74877_c() < 5) { int dirOffset = rand.nextInt(4); for (int i = 0; i < 4; i++) { int dir = (dirOffset + i) % 4; int[] dest = getValidOpening(rand, dir); if ((func_74877_c() == 4) && ((parent instanceof ComponentTFIceTowerMain)) && (!hasBossWing)) { boolean hasBoss = makeBossTowerWing(list, rand, func_74877_c() + 1, dest[0], dest[1], dest[2], 15, 41, dir); hasBossWing = hasBoss; } else { int childHeight = (rand.nextInt(2) + rand.nextInt(2) + 2) * 10 + 1; makeTowerWing(list, rand, func_74877_c() + 1, dest[0], dest[1], dest[2], 11, childHeight, dir); } } } int floors = height / 10; if ((treasureFloor == -1) && (floors > 1)) { treasureFloor = rand.nextInt(floors - 1); } makeARoof(parent, list, rand); if (!hasBase) { makeABeard(parent, list, rand); } } protected boolean shouldHaveBase(Random rand) { return (func_74877_c() == 0) || (rand.nextBoolean()); } private boolean isOutOfRange(StructureComponent parent, int nx, int ny, int nz, int range) { return (Math.abs(nx - parent.func_74874_b().func_78881_e()) > range) || (Math.abs(nz - parent.func_74874_b().func_78891_g()) > range); } public boolean makeTowerWing(List<StructureComponent> list, Random rand, int index, int x, int y, int z, int wingSize, int wingHeight, int rotation) { int direction = (getCoordBaseMode() + rotation) % 4; int[] dx = offsetTowerCoords(x, y, z, wingSize, direction); if (isOutOfRange((StructureComponent)list.get(0), dx[0], dx[1], dx[2], 17)) { return false; } ComponentTFIceTowerWing wing = new ComponentTFIceTowerWing(index, dx[0], dx[1], dx[2], wingSize, wingHeight, direction); StructureComponent intersect = StructureComponent.func_74883_a(list, wing.func_74874_b()); if ((intersect == null) || (intersect == this)) { list.add(wing); wing.func_74861_a((StructureComponent)list.get(0), list, rand); addOpening(x, y, z, rotation); return true; } return false; } public boolean makeBossTowerWing(List<StructureComponent> list, Random rand, int index, int x, int y, int z, int wingSize, int wingHeight, int rotation) { int direction = (getCoordBaseMode() + rotation) % 4; int[] dx = offsetTowerCoords(x, y, z, wingSize, direction); ComponentTFIceTowerWing wing = new ComponentTFIceTowerBossWing(index, dx[0], dx[1], dx[2], wingSize, wingHeight, direction); StructureComponent intersect = StructureComponent.func_74883_a(list, wing.func_74874_b()); if ((intersect == null) || (intersect == this)) { list.add(wing); wing.func_74861_a((StructureComponent)list.get(0), list, rand); addOpening(x, y, z, rotation); return true; } return false; } protected int getYByStairs(int rx, Random rand, int direction) { int floors = height / 10; return 11 + rand.nextInt(floors - 1) * 10; } public boolean func_74875_a(World world, Random rand, StructureBoundingBox sbb) { Random decoRNG = new Random(world.func_72905_C() + field_74887_e.field_78897_a * 321534781 ^ field_74887_e.field_78896_c * 756839); func_74882_a(world, sbb, 0, 0, 0, size - 1, height - 1, size - 1, false, rand, deco.randomBlocks); func_74878_a(world, sbb, 1, 1, 1, size - 2, height - 2, size - 2); if (hasBase) { for (int x = 0; x < size; x++) { for (int z = 0; z < size; z++) { func_151554_b(world, deco.blockID, deco.blockMeta, x, -1, z, sbb); } } } nullifySkyLightForBoundingBox(world); makeFloorsForTower(world, decoRNG, sbb); makeOpenings(world, sbb); return true; } public void nullifySkyLightForBoundingBox(World world) { nullifySkyLight(world, field_74887_e.field_78897_a + 1, field_74887_e.field_78895_b + 1, field_74887_e.field_78896_c + 1, field_74887_e.field_78893_d - 1, field_74887_e.field_78894_e - 1, field_74887_e.field_78892_f - 1); } protected void makeFloorsForTower(World world, Random decoRNG, StructureBoundingBox sbb) { int floors = height / 10; int ladderDir = 3; int downLadderDir = -1; int floorHeight = 10; for (int i = 0; i < floors - 1; i++) { placeFloor(world, decoRNG, sbb, floorHeight, i); downLadderDir = ladderDir; ladderDir++; ladderDir %= 4; decorateFloor(world, decoRNG, i, i * floorHeight, i * floorHeight + floorHeight, ladderDir, downLadderDir, sbb); } int topFloor = floors - 1; decorateTopFloor(world, decoRNG, topFloor, topFloor * floorHeight, topFloor * floorHeight + floorHeight, ladderDir, downLadderDir, sbb); } protected void placeFloor(World world, Random rand, StructureBoundingBox sbb, int floorHeight, int floor) { for (int x = 1; x < size - 1; x++) { for (int z = 1; z < size - 1; z++) { func_151550_a(world, deco.floorID, deco.floorMeta, x, floor * floorHeight + floorHeight, z, sbb); } } } protected void makeDoorOpening(World world, int dx, int dy, int dz, StructureBoundingBox sbb) { super.makeDoorOpening(world, dx, dy, dz, sbb); if (func_151548_a(world, dx, dy + 2, dz, sbb) != Blocks.field_150350_a) { func_151550_a(world, deco.accentID, deco.accentMeta, dx, dy + 2, dz, sbb); } } protected void decorateFloor(World world, Random rand, int floor, int bottom, int top, int ladderUpDir, int ladderDownDir, StructureBoundingBox sbb) { boolean hasTreasure = treasureFloor == floor; switch (rand.nextInt(8)) { case 0: if (isNoDoorAreaRotated(9, bottom + 5, 1, 10, top + 1, 7, ladderUpDir)) decorateWraparoundWallSteps(world, rand, bottom, top, ladderUpDir, ladderDownDir, hasTreasure, sbb); break; case 1: if (isNoDoorAreaRotated(7, bottom, 0, 10, top + 1, 10, ladderUpDir)) decorateFarWallSteps(world, rand, bottom, top, ladderUpDir, ladderDownDir, hasTreasure, sbb); break; case 2: if (isNoDoorAreaRotated(9, bottom + 5, 1, 10, top + 1, 7, ladderUpDir)) decorateWraparoundWallStepsPillars(world, rand, bottom, top, ladderUpDir, ladderDownDir, hasTreasure, sbb); break; case 3: decoratePlatform(world, rand, bottom, top, ladderUpDir, ladderDownDir, hasTreasure, sbb); break; case 4: decoratePillarParkour(world, rand, bottom, top, ladderUpDir, ladderDownDir, hasTreasure, sbb); break; case 5: decoratePillarPlatforms(world, rand, bottom, top, ladderUpDir, ladderDownDir, hasTreasure, sbb); break; case 6: decoratePillarPlatformsOutside(world, rand, bottom, top, ladderUpDir, ladderDownDir, hasTreasure, sbb); break; } decorateQuadPillarStairs(world, rand, bottom, top, ladderUpDir, ladderDownDir, hasTreasure, sbb); } private boolean isNoDoorAreaRotated(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int rotation) { boolean isClear = true; StructureBoundingBox exclusionBox; switch (rotation) { case 0: default: exclusionBox = new StructureBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); break; case 1: exclusionBox = new StructureBoundingBox(size - 1 - maxZ, minY, minX, size - 1 - minZ, maxY, maxX); break; case 2: exclusionBox = new StructureBoundingBox(size - 1 - maxX, minY, size - 1 - maxZ, size - 1 - minX, maxY, size - 1 - minZ); break; case 3: exclusionBox = new StructureBoundingBox(minZ, minY, size - 1 - maxX, maxZ, maxY, size - 1 - minX); } for (ChunkCoordinates door : openings) { if (exclusionBox.func_78890_b(field_71574_a, field_71572_b, field_71573_c)) { isClear = false; } } return isClear; } protected void decorateTopFloor(World world, Random rand, int floor, int bottom, int top, int ladderUpDir, int ladderDownDir, StructureBoundingBox sbb) { if (rand.nextBoolean()) { decoratePillarsCorners(world, rand, bottom, top, ladderDownDir, sbb); } else { decoratePillarsGrid(world, rand, bottom, top, ladderDownDir, sbb); } if (isDeadEnd()) { decorateTopFloorTreasure(world, rand, bottom, top, ladderDownDir, sbb); } } private void decorateTopFloorTreasure(World world, Random rand, int bottom, int top, int rotation, StructureBoundingBox sbb) { fillBlocksRotated(world, sbb, 5, bottom + 1, 5, 5, bottom + 4, 5, deco.pillarID, deco.pillarMeta, rotation); placeTreasureAtCurrentPosition(world, null, 5, bottom + 5, 5, TFTreasure.aurora_room, sbb); } private void decoratePillars(World world, Random rand, int bottom, int top, int rotation, StructureBoundingBox sbb) { fillBlocksRotated(world, sbb, 3, bottom + 1, 3, 3, top - 1, 3, deco.pillarID, deco.pillarMeta, rotation); fillBlocksRotated(world, sbb, 7, bottom + 1, 3, 7, top - 1, 3, deco.pillarID, deco.pillarMeta, rotation); fillBlocksRotated(world, sbb, 3, bottom + 1, 7, 3, top - 1, 7, deco.pillarID, deco.pillarMeta, rotation); fillBlocksRotated(world, sbb, 7, bottom + 1, 7, 7, top - 1, 7, deco.pillarID, deco.pillarMeta, rotation); } private void decoratePillarsGrid(World world, Random rand, int bottom, int top, int rotation, StructureBoundingBox sbb) { int beamMetaNS = (field_74885_f + rotation) % 2 == 0 ? 4 : 8; int beamMetaEW = beamMetaNS == 4 ? 8 : 4; fillBlocksRotated(world, sbb, 3, bottom + 5, 1, 3, bottom + 5, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 7, bottom + 5, 1, 7, bottom + 5, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 1, bottom + 5, 3, 9, bottom + 5, 3, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 1, bottom + 5, 7, 9, bottom + 5, 7, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); decoratePillars(world, rand, bottom, top, rotation, sbb); } private void decoratePillarsCorners(World world, Random rand, int bottom, int top, int rotation, StructureBoundingBox sbb) { int beamMetaNS = (field_74885_f + rotation) % 2 == 0 ? 4 : 8; int beamMetaEW = beamMetaNS == 4 ? 8 : 4; fillBlocksRotated(world, sbb, 3, bottom + 5, 1, 3, bottom + 5, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 7, bottom + 5, 1, 7, bottom + 5, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 1, bottom + 5, 3, 9, bottom + 5, 3, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 1, bottom + 5, 7, 9, bottom + 5, 7, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillAirRotated(world, sbb, 3, bottom + 5, 3, 7, bottom + 5, 7, rotation); decoratePillars(world, rand, bottom, top, rotation, sbb); } private void decorateFarWallSteps(World world, Random rand, int bottom, int top, int ladderUpDir, int ladderDownDir, boolean hasTreasure, StructureBoundingBox sbb) { for (int z = 1; z < 10; z++) { int y = bottom + 10 - z / 2; placeBlockRotated(world, z % 2 == 0 ? deco.pillarID : deco.platformID, z % 2 == 0 ? deco.pillarMeta : deco.platformMeta, 9, y, z, ladderUpDir, sbb); for (int by = bottom + 1; by < y; by++) { placeBlockRotated(world, deco.pillarID, deco.pillarMeta, 9, by, z, ladderUpDir, sbb); } } for (int z = 1; z < 10; z++) { int y = bottom + 1 + z / 2; placeBlockRotated(world, z % 2 == 0 ? deco.platformID : deco.pillarID, z % 2 == 0 ? deco.platformMeta : deco.pillarMeta, 8, y, z, ladderUpDir, sbb); for (int by = bottom + 1; by < y; by++) { placeBlockRotated(world, deco.pillarID, deco.pillarMeta, 8, by, z, ladderUpDir, sbb); } } placeBlockRotated(world, deco.platformID, deco.platformMeta, 7, bottom + 1, 1, ladderUpDir, sbb); for (int z = 2; z < 7; z++) { placeBlockRotated(world, Blocks.field_150350_a, 0, 9, top, z, ladderUpDir, sbb); } if (hasTreasure) { placeTreasureRotated(world, 1, bottom + 8, 5, ladderUpDir, TFTreasure.aurora_cache, false, sbb); int beamMetaNS = (field_74885_f + ladderUpDir) % 2 == 0 ? 4 : 8; placeBlockRotated(world, deco.pillarID, deco.pillarMeta + beamMetaNS, 1, bottom + 7, 5, ladderUpDir, sbb); } } private void decorateWraparoundWallSteps(World world, Random rand, int bottom, int top, int ladderUpDir, int ladderDownDir, boolean hasTreasure, StructureBoundingBox sbb) { for (int z = 1; z < 10; z++) { int y = bottom + 10 - z / 2; placeBlockRotated(world, deco.platformID, deco.platformMeta + (z % 2 == 0 ? 8 : 0), 9, y, z, ladderUpDir, sbb); } for (int x = 1; x < 9; x++) { int y = bottom + 2 + (x - 1) / 2; placeBlockRotated(world, deco.platformID, deco.platformMeta + (x % 2 == 0 ? 8 : 0), x, y, 9, ladderUpDir, sbb); } placeBlockRotated(world, deco.platformID, deco.platformMeta + 8, 1, bottom + 1, 8, ladderUpDir, sbb); placeBlockRotated(world, deco.platformID, deco.platformMeta, 1, bottom + 1, 7, ladderUpDir, sbb); for (int z = 2; z < 7; z++) { placeBlockRotated(world, Blocks.field_150350_a, 0, 9, top, z, ladderUpDir, sbb); } if (hasTreasure) { placeTreasureRotated(world, 1, bottom + 5, 5, ladderUpDir, TFTreasure.aurora_cache, false, sbb); int beamMetaNS = (field_74885_f + ladderUpDir) % 2 == 0 ? 4 : 8; placeBlockRotated(world, deco.pillarID, deco.pillarMeta + beamMetaNS, 1, bottom + 4, 5, ladderUpDir, sbb); } } private void decorateWraparoundWallStepsPillars(World world, Random rand, int bottom, int top, int ladderUpDir, int ladderDownDir, boolean hasTreasure, StructureBoundingBox sbb) { int rotation = ladderDownDir; int beamMetaNS = (field_74885_f + rotation) % 2 == 0 ? 4 : 8; int beamMetaEW = beamMetaNS == 4 ? 8 : 4; decorateWraparoundWallSteps(world, rand, bottom, top, ladderUpDir, ladderDownDir, false, sbb); decoratePillars(world, rand, bottom, top, rotation, sbb); fillBlocksRotated(world, sbb, 3, bottom + 5, 1, 3, bottom + 5, 2, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 7, bottom + 5, 1, 7, bottom + 5, 2, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 8, bottom + 5, 3, 9, bottom + 5, 3, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 8, bottom + 5, 7, 9, bottom + 5, 7, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 1, bottom + 2, 3, 2, bottom + 2, 3, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 1, bottom + 6, 3, 2, bottom + 6, 3, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 1, bottom + 4, 7, 2, bottom + 4, 7, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 1, bottom + 8, 7, 2, bottom + 8, 7, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 3, bottom + 6, 8, 3, bottom + 6, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 7, bottom + 8, 8, 7, bottom + 8, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); if (hasTreasure) { placeTreasureRotated(world, 7, bottom + 6, 1, ladderUpDir, TFTreasure.aurora_cache, false, sbb); } } private void decoratePlatform(World world, Random rand, int bottom, int top, int ladderUpDir, int ladderDownDir, boolean hasTreasure, StructureBoundingBox sbb) { decoratePillars(world, rand, bottom, top, ladderDownDir, sbb); fillBlocksRotated(world, sbb, 3, bottom + 5, 3, 7, bottom + 5, 7, deco.floorID, deco.floorMeta, ladderDownDir); for (int z = 6; z < 10; z++) { int y = bottom - 2 + z / 2; placeBlockRotated(world, deco.platformID, deco.platformMeta + (z % 2 == 1 ? 8 : 0), 1, y, z, ladderDownDir, sbb); } for (int x = 2; x < 6; x++) { int y = bottom + 2 + x / 2; placeBlockRotated(world, deco.platformID, deco.platformMeta + (x % 2 == 1 ? 8 : 0), x, y, 9, ladderDownDir, sbb); } placeBlockRotated(world, deco.platformID, deco.platformMeta, 5, bottom + 5, 8, ladderDownDir, sbb); placeBlockRotated(world, deco.platformID, deco.platformMeta, 5, bottom + 6, 2, ladderUpDir, sbb); for (int x = 5; x < 10; x++) { int y = bottom + 4 + x / 2; placeBlockRotated(world, deco.platformID, deco.platformMeta + (x % 2 == 1 ? 8 : 0), x, y, 1, ladderUpDir, sbb); if (x > 6) { placeBlockRotated(world, Blocks.field_150350_a, 0, x, top, 1, ladderUpDir, sbb); } } for (int z = 2; z < 5; z++) { int y = bottom + 8 + z / 2; placeBlockRotated(world, Blocks.field_150350_a, 0, 9, top, z, ladderUpDir, sbb); placeBlockRotated(world, deco.platformID, deco.platformMeta + (z % 2 == 1 ? 8 : 0), 9, y, z, ladderUpDir, sbb); } if (hasTreasure) { placeTreasureRotated(world, 3, bottom + 6, 5, ladderDownDir, TFTreasure.aurora_cache, false, sbb); } } private void decorateQuadPillarStairs(World world, Random rand, int bottom, int top, int ladderUpDir, int ladderDownDir, boolean hasTreasure, StructureBoundingBox sbb) { decoratePillars(world, rand, bottom, top, ladderDownDir, sbb); for (int z = 6; z < 9; z++) { int y = bottom - 2 + z / 2; placeBlockRotated(world, deco.platformID, deco.platformMeta + (z % 2 == 1 ? 8 : 0), 2, y, z, ladderDownDir, sbb); } for (int x = 3; x < 9; x++) { int y = bottom + 1 + x / 2; placeBlockRotated(world, deco.platformID, deco.platformMeta + (x % 2 == 1 ? 8 : 0), x, y, 8, ladderDownDir, sbb); } for (int z = 7; z > 1; z--) { int y = top - 2 - (z - 1) / 2; if (z < 4) { placeBlockRotated(world, Blocks.field_150350_a, 0, 8, top, z, ladderDownDir, sbb); } placeBlockRotated(world, deco.platformID, deco.platformMeta + (z % 2 == 1 ? 8 : 0), 8, y, z, ladderDownDir, sbb); } for (int x = 7; x > 3; x--) { int y = top + 1 - (x - 1) / 2; placeBlockRotated(world, Blocks.field_150350_a, 0, x, top, 2, ladderDownDir, sbb); placeBlockRotated(world, deco.platformID, deco.platformMeta + (x % 2 == 1 ? 8 : 0), x, y, 2, ladderDownDir, sbb); } if (hasTreasure) { placeTreasureRotated(world, 3, bottom + 7, 7, ladderUpDir, TFTreasure.aurora_cache, false, sbb); } } private void decoratePillarPlatforms(World world, Random rand, int bottom, int top, int ladderUpDir, int ladderDownDir, boolean hasTreasure, StructureBoundingBox sbb) { for (int i = 1; i < 10; i++) { int rotation = (ladderUpDir + i) % 4; fillBlocksRotated(world, sbb, 2, bottom + i, 2, 4, bottom + i, 4, deco.floorID, deco.floorMeta, rotation); } fillAirRotated(world, sbb, 2, top, 2, 8, top, 4, ladderUpDir); fillAirRotated(world, sbb, 2, top, 2, 4, top, 6, ladderUpDir); placeBlockRotated(world, deco.pillarID, deco.pillarMeta, 7, top, 3, ladderUpDir, sbb); placeBlockRotated(world, deco.pillarID, deco.pillarMeta, 3, top, 3, ladderUpDir, sbb); decoratePillars(world, rand, bottom, top, ladderUpDir, sbb); if (hasTreasure) { placeTreasureRotated(world, 3, bottom + 5, 2, ladderUpDir, TFTreasure.aurora_cache, false, sbb); } } private void decoratePillarPlatformsOutside(World world, Random rand, int bottom, int top, int ladderUpDir, int ladderDownDir, boolean hasTreasure, StructureBoundingBox sbb) { for (int i = 1; i < 8; i++) { int rotation = (ladderUpDir + i) % 4; fillBlocksRotated(world, sbb, 1, bottom + i, 1, 3, bottom + i, 3, deco.platformID, deco.platformMeta, rotation); fillBlocksRotated(world, sbb, 4, bottom + i, 1, 6, bottom + i, 3, deco.floorID, deco.floorMeta, rotation); } int rotation = (ladderUpDir + 2) % 4; fillAirRotated(world, sbb, 5, top, 8, 9, top, 9, rotation); fillAirRotated(world, sbb, 8, top, 6, 9, top, 9, rotation); fillBlocksRotated(world, sbb, 8, top - 2, 7, 9, top - 2, 7, deco.platformID, deco.platformMeta, rotation); fillBlocksRotated(world, sbb, 8, top - 2, 8, 9, top - 2, 9, deco.floorID, deco.floorMeta, rotation); fillBlocksRotated(world, sbb, 7, top - 1, 8, 7, top - 1, 9, deco.platformID, deco.platformMeta, rotation); fillBlocksRotated(world, sbb, 6, top - 1, 8, 6, top - 1, 9, deco.platformID, deco.platformMeta | 0x8, rotation); fillBlocksRotated(world, sbb, 5, top - 0, 8, 5, top - 0, 9, deco.platformID, deco.platformMeta, rotation); decoratePillars(world, rand, bottom, top, ladderUpDir, sbb); if (hasTreasure) { placeTreasureRotated(world, 3, bottom + 5, 2, ladderUpDir, TFTreasure.aurora_cache, false, sbb); } } private void decoratePillarParkour(World world, Random rand, int bottom, int top, int ladderUpDir, int ladderDownDir, boolean hasTreasure, StructureBoundingBox sbb) { int rotation = ladderDownDir; int beamMetaNS = (field_74885_f + rotation) % 2 == 0 ? 4 : 8; int beamMetaEW = beamMetaNS == 4 ? 8 : 4; decoratePillars(world, rand, bottom, top, rotation, sbb); placeBlockRotated(world, deco.pillarID, deco.pillarMeta, 5, bottom + 1, 5, rotation, sbb); fillBlocksRotated(world, sbb, 5, bottom + 2, 7, 5, bottom + 2, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 1, bottom + 3, 7, 2, bottom + 3, 7, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 3, bottom + 3, 8, 3, bottom + 3, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 1, bottom + 7, 7, 2, bottom + 7, 7, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 3, bottom + 7, 8, 3, bottom + 7, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillAirRotated(world, sbb, 3, bottom + 4, 7, 3, bottom + 6, 7, rotation); fillBlocksRotated(world, sbb, 1, bottom + 4, 5, 2, bottom + 4, 5, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 3, bottom + 5, 1, 3, bottom + 5, 2, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 1, bottom + 5, 3, 2, bottom + 5, 3, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillAirRotated(world, sbb, 3, bottom + 6, 3, 3, bottom + 8, 3, rotation); fillBlocksRotated(world, sbb, 5, bottom + 6, 1, 5, bottom + 6, 2, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillAirRotated(world, sbb, 7, bottom + 8, 3, 7, bottom + 10, 3, rotation); fillBlocksRotated(world, sbb, 7, bottom + 7, 1, 7, bottom + 7, 2, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillBlocksRotated(world, sbb, 8, bottom + 7, 3, 9, bottom + 7, 3, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 8, bottom + 8, 5, 9, bottom + 8, 5, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 8, bottom + 9, 7, 9, bottom + 9, 7, deco.pillarID, deco.pillarMeta + beamMetaNS, rotation); fillBlocksRotated(world, sbb, 7, bottom + 9, 8, 7, bottom + 9, 9, deco.pillarID, deco.pillarMeta + beamMetaEW, rotation); fillAirRotated(world, sbb, 2, top, 2, 8, top, 4, ladderUpDir); fillAirRotated(world, sbb, 2, top, 2, 4, top, 6, ladderUpDir); if (hasTreasure) { placeTreasureRotated(world, 8, bottom + 8, 7, ladderUpDir, TFTreasure.aurora_cache, false, sbb); } } public void makeARoof(StructureComponent parent, List<StructureComponent> list, Random rand) { int index = func_74877_c(); tryToFitRoof(list, rand, new ComponentTFIceTowerRoof(index + 1, this)); } public void makeABeard(StructureComponent parent, List<StructureComponent> list, Random rand) { int index = func_74877_c(); ComponentTFIceTowerBeard beard = new ComponentTFIceTowerBeard(index + 1, this); list.add(beard); beard.func_74861_a(this, list, rand); } }
package org.pageseeder.berlioz.flint.model; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.pageseeder.berlioz.flint.util.FileFilters; import org.pageseeder.xmlwriter.XMLWritable; import org.pageseeder.xmlwriter.XMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Contains the definition of an index as loaded from Berlioz config file. */ public class IndexDefinition implements XMLWritable { /** To know what's going on */ private static final Logger LOGGER = LoggerFactory.getLogger(IndexDefinition.class); /** * The definition name (or type in berlioz config) */ private final String _name; /** * The index name (static or dynamic) */ private final String _indexName; /** * The content paths to include (static or dynamic) */ private final String _path; /** * The content paths to exclude (static or dynamic) */ private final List<String> _pathExcludes = new ArrayList<String>(); /** * A regex matching the files to include when indexing */ private String includeFilesRegex = null; /** * A regex matching the files to exclude when indexing */ private String excludeFilesRegex = null; /** * the iXML template */ private final File _template; /** * if there was an error with the template */ private String templateError = null; /** * if there was an error with the template */ private Map<String, AutoSuggestDefinition> _autosuggests = new HashMap<>(); /** * @param name the index name * @param path the content path * @param template the iXML template * * @throws InvalidIndexDefinitionException if template deos not exist or path and name don't match */ public IndexDefinition(String name, String indexname, String path, Collection<String> excludes, File template) throws InvalidIndexDefinitionException { if (name == null) throw new NullPointerException("name"); if (indexname == null) throw new NullPointerException("indexname"); if (path == null) throw new NullPointerException("path"); if (template == null) throw new NullPointerException("name"); this._name = name; this._indexName = indexname; this._path = path; if (excludes != null) { for (String exclude : excludes) { this._pathExcludes.add(exclude.replaceFirst("/$", "")); //remove trailing '/' } } this._template = template; if (!template.exists() || !template.isFile()) throw new InvalidIndexDefinitionException("invalid template file "+template.getAbsolutePath()); // validate definition if (staticIndex() != staticToken(this._path)) throw new InvalidIndexDefinitionException("name and path must be both dynamic or both static"); } public String getName() { return this._name; } public void addAutoSuggest(String name, String fields, String terms, String returnFields, Map<String, Float> weights) { assert name != null; assert fields != null; assert terms != null; AutoSuggestDefinition def = new AutoSuggestDefinition(name, fields, Boolean.valueOf(terms), returnFields, weights); this._autosuggests.put(name, def); } public AutoSuggestDefinition addAutoSuggest(String name, List<String> fields, boolean terms, List<String> returnFields, Map<String, Float> weights) { assert name != null; assert fields != null; AutoSuggestDefinition asd = new AutoSuggestDefinition(name, fields, terms, returnFields, weights); this._autosuggests.put(name, asd); return asd; } public void setIndexingFilesRegex(final String regexInclude, final String regexExclude) { this.includeFilesRegex = regexInclude; this.excludeFilesRegex = regexExclude; } public Collection<String> listAutoSuggestNames() { return this._autosuggests.keySet(); } public AutoSuggestDefinition getAutoSuggest(String name) { assert name != null; return this._autosuggests.get(name); } public FileFilter buildFileFilter(final File root) { // no regex ? just match PSML files then if (this.includeFilesRegex != null || this.excludeFilesRegex != null) { return new FileFilter() { @Override public boolean accept(File file) { String path = org.pageseeder.berlioz.flint.util.Files.path(root, file); // can't compute the path? means they are not related, don't index if (path == null) return false; // include if (includeFilesRegex != null && !path.matches(includeFilesRegex)) return false; // exclude if (excludeFilesRegex != null && path.matches(excludeFilesRegex)) return false; return true; } }; } // default is all PSML files return FileFilters.getPSMLFiles(); } public boolean indexNameClash(IndexDefinition other) { // static if (staticIndex()) { if (other.staticIndex()) return this._indexName.equals(other._indexName); Pattern pattern = Pattern.compile(other._indexName.replaceAll("\\{name\\}", "([\\\\w\\\\-]+)")); return pattern.matcher(this._indexName).matches(); } // dynamic if (other.staticIndex()) { Pattern pattern = Pattern.compile(this._indexName.replaceAll("\\{name\\}", "([\\\\w\\\\-]+)")); return pattern.matcher(other._indexName).matches(); } // both dynamic: first check if one starts with duynamic and the other one ends with it -> clash if (other._indexName.startsWith("{name}") && this._indexName.endsWith("{name}")) return true; if (this._indexName.startsWith("{name}") && other._indexName.endsWith("{name}")) return true; // then turn patterns to string with '*' and match against the other pattern Pattern otherpattern = Pattern.compile(other._indexName.replaceAll("\\{name\\}", "([\\\\*\\\\w\\\\-]+)")); String myStaticPath = this._indexName.replaceAll("\\{name\\}", "*"); if (otherpattern.matcher(myStaticPath).matches()) return true; Pattern mypattern = Pattern.compile(this._indexName.replaceAll("\\{name\\}", "([\\\\*\\\\w\\\\-]+)")); String otherStaticPath = other._indexName.replaceAll("\\{name\\}", "*"); if (mypattern.matcher(otherStaticPath).matches()) return true; return false; } /** * @param error new error message */ public void setTemplateError(String templateError) { this.templateError = templateError; } /** * @return the iXML template. */ public File getTemplate() { return this._template; } /** * @param name an index name * * @return <code>true</code> if the name provided matches this index definition's pattern (or static name) */ public boolean indexNameMatches(String name) { if (name == null) return false; // dynamic name? if (staticIndex()) return this._indexName.equals(name); // create pattern return name.matches(this._indexName.replaceAll("\\{name\\}", "(.*)")); } /** * Build the root folder for the content using the root and the index name provided. * * @param root the root folder * @param name the index name * * @return the file */ public Collection<File> findContentRoots(final File root) { final List<File> candidates = new ArrayList<>(); // static path? if (staticIndex()) { File onlyOne = new File(root, this._path); if (onlyOne.exists() && onlyOne.isDirectory()) candidates.add(onlyOne); } else { // build pattern final Pattern pattern = Pattern.compile(this._path.replaceAll("\\{name\\}", "([\\\\w\\\\-]+)")); // go through root's descendants try { Files.walkFileTree(root.toPath(), new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { String path = org.pageseeder.berlioz.flint.util.Files.path(root, dir.toFile()); if (path != null) { // check include if (!pattern.matcher('/' + path).matches()) return FileVisitResult.CONTINUE; // check exclude if (isExcluded('/' + path, false)) return FileVisitResult.CONTINUE; candidates.add(dir.toFile()); return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException ex) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException ex) { return FileVisitResult.CONTINUE; } }); } catch (IOException ex) { LOGGER.error("Failed to parse root for content root candidates", ex); } } return candidates; } /** * Build the root folder for the content using the root and the index name provided. * * @param root the root folder * @param name the index name * * @return the file */ public File buildContentRoot(File root, String name) { return new File(root, buildContentPath(name)); } /** * Build the root folder path for the content using the index name provided. * * @param name the index name * * @return the resolved path */ public String buildContentPath(String name) { // build name bit from name // i.e. if indexname=book-{name} and name=book-001 namebit=001 String nameBit; if (staticIndex()) { nameBit = name; } else { Matcher matcher = Pattern.compile(this._indexName.replaceAll("\\{name\\}", "(.+)")).matcher(name); if (!matcher.matches()) throw new IllegalArgumentException("Name provided "+name+": does not match pattern "+this._name); nameBit = matcher.group(1); } // change pattern {name} return this._path.replaceAll("\\{name\\}", nameBit); } /** * Extract an index name from a full path if the path matches this definition's path. * For example: * def name def path file path --> extracted name * myindex /a/b/c /a/b/c/d/e/f myindex * myindex /a/b/c /a/b/d/e null * {name} /a/{name} /a/b/c/d/e/f b * idx-{name} /a/b/{name}/d /a/b/c/d/e/f idx-c * idx-{name} /a/b/c/d/{name} /a/b/c/d/e/f idx-e * idx-{name} /a/b/d/{name}/e /a/b/c/d/e/f null * index-{name} /a/b/files-{name} /a/b/files-001c/d/e/f index-001 * * @param path * @return */ public String findIndexName(String path) { if (path == null) return null; // static? if (staticIndex()) { // descendant or same folder if (path.startsWith(this._path+'/') || path.equals(this._path)) return this._indexName; return null; } // create pattern Matcher matcher = Pattern.compile(this._path.replaceAll("\\{name\\}", "([\\\\w\\\\-]+)") + "(/.+)?").matcher(path); if (matcher.matches()) { // check exclude if (!isExcluded(path, true)) return this._indexName.replaceAll("\\{name\\}", matcher.group(1)); } return null; } @Override public void toXML(XMLWriter xml) throws IOException { toXML(xml, true); } public void toXML(XMLWriter xml, boolean close) throws IOException { xml.openElement("definition"); xml.attribute("name", this._name); xml.attribute("index-name", this._indexName); xml.attribute("path", this._path); xml.attribute("template", this._template.getName()); if (this.templateError != null) xml.attribute("template-error", this.templateError); // autosuggests for (AutoSuggestDefinition as : this._autosuggests.values()) { as.toXML(xml); } if (close) xml.closeElement(); } public boolean hasTemplateError() { return this.templateError != null; } /** * @return <code>true</code> if this index has a static name. */ private boolean staticIndex() { return staticToken(this._indexName); } /** * @param token the token to check if it's static (does not contain {name}) * * @return <code>true</code> if the token is static. */ private boolean staticToken(String token) { return token.indexOf("{name}") == -1; } /** * @param path the path to check * * @return <code>true</code> if the path matches an exclude pattern */ private boolean isExcluded(String path, boolean startsWith) { // check exclude for (String exclude : IndexDefinition.this._pathExcludes) { // static? if (exclude.indexOf("*") == -1) { if ((path.equals(exclude) && !startsWith) || (path.startsWith(exclude+'/') && startsWith)) return true; } else { Pattern exPat = Pattern.compile(exclude.replaceAll("\\*", "(.*?)") + (startsWith ? "(/.+)?" : "")); if (exPat.matcher(path).matches()) return true; } } return false; } /** * An exception used when creating a definition. */ public static class InvalidIndexDefinitionException extends IllegalArgumentException { private static final long serialVersionUID = 1L; public InvalidIndexDefinitionException(String msg) { super(msg); } } /** * An exception used when creating a definition. */ public static class AutoSuggestDefinition implements XMLWritable { private final String _name; private final List<String> _fields; private final List<String> _resultFields; private final boolean _terms; private final Map<String, Float> _weights; private int min = 2; public AutoSuggestDefinition(String name, List<String> fields, boolean terms, List<String> resultFields, Map<String, Float> weights) { this._name = name; this._fields = fields; this._terms = terms; this._resultFields = resultFields; this._weights = weights; } public AutoSuggestDefinition(String name, String fields, boolean terms, String resultFields, Map<String, Float> weights) { this._name = name; this._fields = fields == null ? null : Arrays.asList(fields.split(",")); this._terms = terms; this._resultFields = resultFields == null ? null : Arrays.asList(resultFields.split(",")); this._weights = weights; } public Collection<String> getSearchFields() { return this._fields; } public Collection<String> getResultFields() { return this._resultFields; } public boolean useTerms() { return this._terms; } public String getName() { return this._name; } public Map<String, Float> getWeights() { return this._weights; } public int minChars() { return this.min; } public void setMinChars(int m) { this.min = m; } @Override public void toXML(XMLWriter xml) throws IOException { xml.openElement("autosuggest"); xml.attribute("name", this._name); xml.attribute("min-chars", this.min); xml.attribute("terms", Boolean.toString(this._terms)); if (this._weights != null) { StringBuilder weights = new StringBuilder(); for (Entry<String, Float> weight: this._weights.entrySet()) { weights.append(weights.length() == 0 ? "" : ",").append(weight.getKey()).append(':').append(weight.getValue()); } xml.attribute("weight", weights.toString()); } if (this._fields != null) { StringBuilder fields = new StringBuilder(); for (int i = 0; i < this._fields.size(); i++) { fields.append(i == 0 ? "" : ",").append(this._fields.get(i)); } xml.attribute("fields", fields.toString()); } if (this._resultFields != null && !this._resultFields.isEmpty()) { StringBuilder fields = new StringBuilder(); for (int i = 0; i < this._resultFields.size(); i++) { fields.append(i == 0 ? "" : ",").append(this._resultFields.get(i)); } xml.attribute("result-fields", fields.toString()); } xml.closeElement(); } } }
package com.xero.api.client; import com.xero.api.ApiClient; import com.xero.models.assets.Asset; import com.xero.models.assets.AssetStatusQueryParam; import com.xero.models.assets.AssetType; import com.xero.models.assets.Assets; import com.xero.models.assets.Setting; import java.util.UUID; import com.xero.api.XeroApiExceptionHandler; import com.fasterxml.jackson.core.type.TypeReference; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.Credential; import javax.ws.rs.core.UriBuilder; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayInputStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.List; import org.apache.commons.io.IOUtils; import org.slf4j.LoggerFactory; import org.slf4j.Logger; public class AssetApi { private ApiClient apiClient; private static AssetApi instance = null; private String userAgent = "Default"; private String version = "4.1.1"; static final Logger logger = LoggerFactory.getLogger(AssetApi.class); public AssetApi() { this(new ApiClient()); } public static AssetApi getInstance(ApiClient apiClient) { if (instance == null) { instance = new AssetApi(apiClient); } return instance; } public AssetApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public String getUserAgent() { return this.userAgent + " [Xero-Java-" + this.version + "]"; } /** * adds a fixed asset Adds an asset to the system * * <p><b>200</b> - return single object - create new asset * * <p><b>400</b> - invalid input, object invalid * * @param xeroTenantId Xero identifier for Tenant * @param asset Fixed asset you are creating * @param accessToken Authorization token for user set in header of each request * @return Asset * @throws IOException if an error occurs while attempting to invoke the API */ public Asset createAsset(String accessToken, String xeroTenantId, Asset asset) throws IOException { try { TypeReference<Asset> typeRef = new TypeReference<Asset>() {}; HttpResponse response = createAssetForHttpResponse(accessToken, xeroTenantId, asset); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug( "------------------ HttpResponseException " + e.getStatusCode() + " : createAsset -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400) { TypeReference<com.xero.models.assets.Error> errorTypeRef = new TypeReference<com.xero.models.assets.Error>() {}; com.xero.models.assets.Error assetError = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("Asset", assetError); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; } public HttpResponse createAssetForHttpResponse( String accessToken, String xeroTenantId, Asset asset) throws IOException { // verify the required parameter 'xeroTenantId' is set if (xeroTenantId == null) { throw new IllegalArgumentException( "Missing the required parameter 'xeroTenantId' when calling createAsset"); } // verify the required parameter 'asset' is set if (asset == null) { throw new IllegalArgumentException( "Missing the required parameter 'asset' when calling createAsset"); } if (accessToken == null) { throw new IllegalArgumentException( "Missing the required parameter 'accessToken' when calling createAsset"); } HttpHeaders headers = new HttpHeaders(); headers.set("Xero-Tenant-Id", xeroTenantId); headers.setAccept("application/json"); headers.setUserAgent(this.getUserAgent()); UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Assets"); String url = uriBuilder.build().toString(); GenericUrl genericUrl = new GenericUrl(url); if (logger.isDebugEnabled()) { logger.debug("POST " + genericUrl.toString()); } HttpContent content = null; content = apiClient.new JacksonJsonHttpContent(asset); Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken); HttpTransport transport = apiClient.getHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); return requestFactory .buildRequest(HttpMethods.POST, genericUrl, content) .setHeaders(headers) .setConnectTimeout(apiClient.getConnectionTimeout()) .setReadTimeout(apiClient.getReadTimeout()) .execute(); } /** * adds a fixed asset type Adds an fixed asset type to the system * * <p><b>200</b> - results single object - created fixed type * * <p><b>400</b> - invalid input, object invalid * * <p><b>409</b> - a type already exists * * @param xeroTenantId Xero identifier for Tenant * @param assetType Asset type to add * @param accessToken Authorization token for user set in header of each request * @return AssetType * @throws IOException if an error occurs while attempting to invoke the API */ public AssetType createAssetType(String accessToken, String xeroTenantId, AssetType assetType) throws IOException { try { TypeReference<AssetType> typeRef = new TypeReference<AssetType>() {}; HttpResponse response = createAssetTypeForHttpResponse(accessToken, xeroTenantId, assetType); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug( "------------------ HttpResponseException " + e.getStatusCode() + " : createAssetType -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); if (e.getStatusCode() == 400) { TypeReference<com.xero.models.assets.Error> errorTypeRef = new TypeReference<com.xero.models.assets.Error>() {}; com.xero.models.assets.Error assetError = apiClient.getObjectMapper().readValue(e.getContent(), errorTypeRef); handler.validationError("AssetType", assetError); } else { handler.execute(e); } } catch (IOException ioe) { throw ioe; } return null; } public HttpResponse createAssetTypeForHttpResponse( String accessToken, String xeroTenantId, AssetType assetType) throws IOException { // verify the required parameter 'xeroTenantId' is set if (xeroTenantId == null) { throw new IllegalArgumentException( "Missing the required parameter 'xeroTenantId' when calling createAssetType"); } if (accessToken == null) { throw new IllegalArgumentException( "Missing the required parameter 'accessToken' when calling createAssetType"); } HttpHeaders headers = new HttpHeaders(); headers.set("Xero-Tenant-Id", xeroTenantId); headers.setAccept("application/json"); headers.setUserAgent(this.getUserAgent()); UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/AssetTypes"); String url = uriBuilder.build().toString(); GenericUrl genericUrl = new GenericUrl(url); if (logger.isDebugEnabled()) { logger.debug("POST " + genericUrl.toString()); } HttpContent content = null; content = apiClient.new JacksonJsonHttpContent(assetType); Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken); HttpTransport transport = apiClient.getHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); return requestFactory .buildRequest(HttpMethods.POST, genericUrl, content) .setHeaders(headers) .setConnectTimeout(apiClient.getConnectionTimeout()) .setReadTimeout(apiClient.getReadTimeout()) .execute(); } /** * retrieves fixed asset by id By passing in the appropriate asset id, you can search for a * specific fixed asset in the system * * <p><b>200</b> - search results matching criteria * * <p><b>400</b> - bad input parameter * * @param xeroTenantId Xero identifier for Tenant * @param id fixed asset id for single object * @param accessToken Authorization token for user set in header of each request * @return Asset * @throws IOException if an error occurs while attempting to invoke the API */ public Asset getAssetById(String accessToken, String xeroTenantId, UUID id) throws IOException { try { TypeReference<Asset> typeRef = new TypeReference<Asset>() {}; HttpResponse response = getAssetByIdForHttpResponse(accessToken, xeroTenantId, id); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug( "------------------ HttpResponseException " + e.getStatusCode() + " : getAssetById -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); handler.execute(e); } catch (IOException ioe) { throw ioe; } return null; } public HttpResponse getAssetByIdForHttpResponse(String accessToken, String xeroTenantId, UUID id) throws IOException { // verify the required parameter 'xeroTenantId' is set if (xeroTenantId == null) { throw new IllegalArgumentException( "Missing the required parameter 'xeroTenantId' when calling getAssetById"); } // verify the required parameter 'id' is set if (id == null) { throw new IllegalArgumentException( "Missing the required parameter 'id' when calling getAssetById"); } if (accessToken == null) { throw new IllegalArgumentException( "Missing the required parameter 'accessToken' when calling getAssetById"); } HttpHeaders headers = new HttpHeaders(); headers.set("Xero-Tenant-Id", xeroTenantId); headers.setAccept("application/json"); headers.setUserAgent(this.getUserAgent()); // create a map of path variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("id", id); UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Assets/{id}"); String url = uriBuilder.buildFromMap(uriVariables).toString(); GenericUrl genericUrl = new GenericUrl(url); if (logger.isDebugEnabled()) { logger.debug("GET " + genericUrl.toString()); } HttpContent content = null; Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken); HttpTransport transport = apiClient.getHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); return requestFactory .buildRequest(HttpMethods.GET, genericUrl, content) .setHeaders(headers) .setConnectTimeout(apiClient.getConnectionTimeout()) .setReadTimeout(apiClient.getReadTimeout()) .execute(); } /** * searches fixed asset settings By passing in the appropriate options, you can search for * available fixed asset types in the system * * <p><b>200</b> - search results matching criteria * * <p><b>400</b> - bad input parameter * * @param xeroTenantId Xero identifier for Tenant * @param accessToken Authorization token for user set in header of each request * @return Setting * @throws IOException if an error occurs while attempting to invoke the API */ public Setting getAssetSettings(String accessToken, String xeroTenantId) throws IOException { try { TypeReference<Setting> typeRef = new TypeReference<Setting>() {}; HttpResponse response = getAssetSettingsForHttpResponse(accessToken, xeroTenantId); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug( "------------------ HttpResponseException " + e.getStatusCode() + " : getAssetSettings -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); handler.execute(e); } catch (IOException ioe) { throw ioe; } return null; } public HttpResponse getAssetSettingsForHttpResponse(String accessToken, String xeroTenantId) throws IOException { // verify the required parameter 'xeroTenantId' is set if (xeroTenantId == null) { throw new IllegalArgumentException( "Missing the required parameter 'xeroTenantId' when calling getAssetSettings"); } if (accessToken == null) { throw new IllegalArgumentException( "Missing the required parameter 'accessToken' when calling getAssetSettings"); } HttpHeaders headers = new HttpHeaders(); headers.set("Xero-Tenant-Id", xeroTenantId); headers.setAccept("application/json"); headers.setUserAgent(this.getUserAgent()); UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Settings"); String url = uriBuilder.build().toString(); GenericUrl genericUrl = new GenericUrl(url); if (logger.isDebugEnabled()) { logger.debug("GET " + genericUrl.toString()); } HttpContent content = null; Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken); HttpTransport transport = apiClient.getHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); return requestFactory .buildRequest(HttpMethods.GET, genericUrl, content) .setHeaders(headers) .setConnectTimeout(apiClient.getConnectionTimeout()) .setReadTimeout(apiClient.getReadTimeout()) .execute(); } /** * searches fixed asset types By passing in the appropriate options, you can search for available * fixed asset types in the system * * <p><b>200</b> - search results matching criteria * * <p><b>400</b> - bad input parameter * * @param xeroTenantId Xero identifier for Tenant * @param accessToken Authorization token for user set in header of each request * @return List&lt;AssetType&gt; * @throws IOException if an error occurs while attempting to invoke the API */ public List<AssetType> getAssetTypes(String accessToken, String xeroTenantId) throws IOException { try { TypeReference<List<AssetType>> typeRef = new TypeReference<List<AssetType>>() {}; HttpResponse response = getAssetTypesForHttpResponse(accessToken, xeroTenantId); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug( "------------------ HttpResponseException " + e.getStatusCode() + " : getAssetTypes -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); handler.execute(e); } catch (IOException ioe) { throw ioe; } return null; } public HttpResponse getAssetTypesForHttpResponse(String accessToken, String xeroTenantId) throws IOException { // verify the required parameter 'xeroTenantId' is set if (xeroTenantId == null) { throw new IllegalArgumentException( "Missing the required parameter 'xeroTenantId' when calling getAssetTypes"); } if (accessToken == null) { throw new IllegalArgumentException( "Missing the required parameter 'accessToken' when calling getAssetTypes"); } HttpHeaders headers = new HttpHeaders(); headers.set("Xero-Tenant-Id", xeroTenantId); headers.setAccept("application/json"); headers.setUserAgent(this.getUserAgent()); UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/AssetTypes"); String url = uriBuilder.build().toString(); GenericUrl genericUrl = new GenericUrl(url); if (logger.isDebugEnabled()) { logger.debug("GET " + genericUrl.toString()); } HttpContent content = null; Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken); HttpTransport transport = apiClient.getHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); return requestFactory .buildRequest(HttpMethods.GET, genericUrl, content) .setHeaders(headers) .setConnectTimeout(apiClient.getConnectionTimeout()) .setReadTimeout(apiClient.getReadTimeout()) .execute(); } /** * searches fixed asset By passing in the appropriate options, you can search for available fixed * asset in the system * * <p><b>200</b> - search results matching criteria * * <p><b>400</b> - bad input parameter * * @param xeroTenantId Xero identifier for Tenant * @param status Required when retrieving a collection of assets. See Asset Status Codes * @param page Results are paged. This specifies which page of the results to return. The default * page is 1. * @param pageSize The number of records returned per page. By default the number of records * returned is 10. * @param orderBy Requests can be ordered by AssetType, AssetName, AssetNumber, PurchaseDate and * PurchasePrice. If the asset status is DISPOSED it also allows DisposalDate and * DisposalPrice. * @param sortDirection ASC or DESC * @param filterBy A string that can be used to filter the list to only return assets containing * the text. Checks it against the AssetName, AssetNumber, Description and AssetTypeName * fields. * @param accessToken Authorization token for user set in header of each request * @return Assets * @throws IOException if an error occurs while attempting to invoke the API */ public Assets getAssets( String accessToken, String xeroTenantId, AssetStatusQueryParam status, Integer page, Integer pageSize, String orderBy, String sortDirection, String filterBy) throws IOException { try { TypeReference<Assets> typeRef = new TypeReference<Assets>() {}; HttpResponse response = getAssetsForHttpResponse( accessToken, xeroTenantId, status, page, pageSize, orderBy, sortDirection, filterBy); return apiClient.getObjectMapper().readValue(response.getContent(), typeRef); } catch (HttpResponseException e) { if (logger.isDebugEnabled()) { logger.debug( "------------------ HttpResponseException " + e.getStatusCode() + " : getAssets -------------------"); logger.debug(e.toString()); } XeroApiExceptionHandler handler = new XeroApiExceptionHandler(); handler.execute(e); } catch (IOException ioe) { throw ioe; } return null; } public HttpResponse getAssetsForHttpResponse( String accessToken, String xeroTenantId, AssetStatusQueryParam status, Integer page, Integer pageSize, String orderBy, String sortDirection, String filterBy) throws IOException { // verify the required parameter 'xeroTenantId' is set if (xeroTenantId == null) { throw new IllegalArgumentException( "Missing the required parameter 'xeroTenantId' when calling getAssets"); } // verify the required parameter 'status' is set if (status == null) { throw new IllegalArgumentException( "Missing the required parameter 'status' when calling getAssets"); } if (accessToken == null) { throw new IllegalArgumentException( "Missing the required parameter 'accessToken' when calling getAssets"); } HttpHeaders headers = new HttpHeaders(); headers.set("Xero-Tenant-Id", xeroTenantId); headers.setAccept("application/json"); headers.setUserAgent(this.getUserAgent()); UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/Assets"); if (status != null) { String key = "status"; Object value = status; if (value instanceof Collection) { uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); } else if (value instanceof Object[]) { uriBuilder = uriBuilder.queryParam(key, (Object[]) value); } else { uriBuilder = uriBuilder.queryParam(key, value); } } if (page != null) { String key = "page"; Object value = page; if (value instanceof Collection) { uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); } else if (value instanceof Object[]) { uriBuilder = uriBuilder.queryParam(key, (Object[]) value); } else { uriBuilder = uriBuilder.queryParam(key, value); } } if (pageSize != null) { String key = "pageSize"; Object value = pageSize; if (value instanceof Collection) { uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); } else if (value instanceof Object[]) { uriBuilder = uriBuilder.queryParam(key, (Object[]) value); } else { uriBuilder = uriBuilder.queryParam(key, value); } } if (orderBy != null) { String key = "orderBy"; Object value = orderBy; if (value instanceof Collection) { uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); } else if (value instanceof Object[]) { uriBuilder = uriBuilder.queryParam(key, (Object[]) value); } else { uriBuilder = uriBuilder.queryParam(key, value); } } if (sortDirection != null) { String key = "sortDirection"; Object value = sortDirection; if (value instanceof Collection) { uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); } else if (value instanceof Object[]) { uriBuilder = uriBuilder.queryParam(key, (Object[]) value); } else { uriBuilder = uriBuilder.queryParam(key, value); } } if (filterBy != null) { String key = "filterBy"; Object value = filterBy; if (value instanceof Collection) { uriBuilder = uriBuilder.queryParam(key, ((Collection) value).toArray()); } else if (value instanceof Object[]) { uriBuilder = uriBuilder.queryParam(key, (Object[]) value); } else { uriBuilder = uriBuilder.queryParam(key, value); } } String url = uriBuilder.build().toString(); GenericUrl genericUrl = new GenericUrl(url); if (logger.isDebugEnabled()) { logger.debug("GET " + genericUrl.toString()); } HttpContent content = null; Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken); HttpTransport transport = apiClient.getHttpTransport(); HttpRequestFactory requestFactory = transport.createRequestFactory(credential); return requestFactory .buildRequest(HttpMethods.GET, genericUrl, content) .setHeaders(headers) .setConnectTimeout(apiClient.getConnectionTimeout()) .setReadTimeout(apiClient.getReadTimeout()) .execute(); } public ByteArrayInputStream convertInputToByteArray(InputStream is) throws IOException { byte[] bytes = IOUtils.toByteArray(is); try { // Process the input stream.. ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); return byteArrayInputStream; } finally { is.close(); } } }
/* * Copyright 2020 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 androidx.car.app.model; import static com.google.common.truth.Truth.assertThat; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.internal.DoNotInstrument; import java.util.ArrayList; import java.util.List; /** Tests for {@link CarText}. */ @RunWith(RobolectricTestRunner.class) @DoNotInstrument public class CarTextTest { @Test public void toCharSequence_noSpans() { String text = ""; CarText carText = CarText.create(text); assertThat(carText.toCharSequence().toString()).isEqualTo(text); text = "Test string"; carText = CarText.create(text); assertThat(carText.toCharSequence().toString()).isEqualTo(text); } @Test public void toCharSequence_withSpans() { String text = "Part of this text is red"; SpannableString spannable = new SpannableString(text); // Add a foreground car color span. ForegroundCarColorSpan foregroundCarColorSpan = ForegroundCarColorSpan.create(CarColor.RED); spannable.setSpan(foregroundCarColorSpan, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // Add a duration span DurationSpan durationSpan = DurationSpan.create(46); spannable.setSpan(durationSpan, 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // Add a span that will be filtered out. ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(0xffff00); spannable.setSpan(foregroundColorSpan, 2, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // Create the car text from the spannable and verify it. CarText carText = CarText.create(spannable); CharSequence charSequence = carText.toCharSequence(); assertThat(charSequence.toString()).isEqualTo(text); List<CarSpanInfo> carSpans = getCarSpans(charSequence); assertThat(carSpans).hasSize(2); CarSpanInfo carSpan = carSpans.get(0); assertThat(carSpan.mCarSpan instanceof ForegroundCarColorSpan).isTrue(); assertThat(carSpan.mCarSpan).isEqualTo(foregroundCarColorSpan); assertThat(carSpan.mStart).isEqualTo(0); assertThat(carSpan.mEnd).isEqualTo(5); assertThat(carSpan.mFlags).isEqualTo(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); carSpan = carSpans.get(1); assertThat(carSpan.mCarSpan instanceof DurationSpan).isTrue(); assertThat(carSpan.mCarSpan).isEqualTo(durationSpan); assertThat(carSpan.mStart).isEqualTo(10); assertThat(carSpan.mEnd).isEqualTo(12); assertThat(carSpan.mFlags).isEqualTo(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } @Test public void variants_toCharSequence_withSpans() { String text1 = "Part of this text is red"; SpannableString spannable1 = new SpannableString(text1); ForegroundCarColorSpan foregroundCarColorSpan1 = ForegroundCarColorSpan.create(CarColor.RED); spannable1.setSpan(foregroundCarColorSpan1, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); DurationSpan durationSpan1 = DurationSpan.create(46); spannable1.setSpan(durationSpan1, 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // Create a text where the string is different String text2 = "Part of this text is blue"; SpannableString spannable2 = new SpannableString(text2); ForegroundCarColorSpan foregroundCarColorSpan2 = ForegroundCarColorSpan.create(CarColor.RED); spannable2.setSpan(foregroundCarColorSpan2, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); DurationSpan durationSpan2 = DurationSpan.create(46); spannable2.setSpan(durationSpan2, 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // Create the car text from the spannables and verify it. CarText carText = new CarText.Builder(spannable1).addVariant(spannable2).build(); // Check that we have two variants. assertThat(carText.toCharSequence()).isNotNull(); assertThat(carText.getVariants()).hasSize(1); // Check the first variant. CharSequence charSequence1 = carText.toCharSequence(); assertThat(charSequence1.toString()).isEqualTo(text1); List<CarSpanInfo> carSpans1 = getCarSpans(charSequence1); assertThat(carSpans1).hasSize(2); CarSpanInfo carSpan = carSpans1.get(0); assertThat(carSpan.mCarSpan instanceof ForegroundCarColorSpan).isTrue(); assertThat(carSpan.mCarSpan).isEqualTo(foregroundCarColorSpan1); assertThat(carSpan.mStart).isEqualTo(0); assertThat(carSpan.mEnd).isEqualTo(5); assertThat(carSpan.mFlags).isEqualTo(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); carSpan = carSpans1.get(1); assertThat(carSpan.mCarSpan instanceof DurationSpan).isTrue(); assertThat(carSpan.mCarSpan).isEqualTo(durationSpan1); assertThat(carSpan.mStart).isEqualTo(10); assertThat(carSpan.mEnd).isEqualTo(12); assertThat(carSpan.mFlags).isEqualTo(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // Check the second variant. CharSequence charSequence2 = carText.getVariants().get(0); assertThat(charSequence2.toString()).isEqualTo(text2); List<CarSpanInfo> carSpans = getCarSpans(charSequence2); assertThat(carSpans).hasSize(2); carSpan = carSpans.get(0); assertThat(carSpan.mCarSpan instanceof ForegroundCarColorSpan).isTrue(); assertThat(carSpan.mCarSpan).isEqualTo(foregroundCarColorSpan2); assertThat(carSpan.mStart).isEqualTo(0); assertThat(carSpan.mEnd).isEqualTo(5); assertThat(carSpan.mFlags).isEqualTo(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); carSpan = carSpans.get(1); assertThat(carSpan.mCarSpan instanceof DurationSpan).isTrue(); assertThat(carSpan.mCarSpan).isEqualTo(durationSpan2); assertThat(carSpan.mStart).isEqualTo(10); assertThat(carSpan.mEnd).isEqualTo(12); assertThat(carSpan.mFlags).isEqualTo(Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } @Test public void equals_and_hashCode() { String text = "Part of this text is red"; SpannableString spannable = new SpannableString(text); ForegroundCarColorSpan foregroundCarColorSpan = ForegroundCarColorSpan.create(CarColor.RED); spannable.setSpan(foregroundCarColorSpan, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); DurationSpan durationSpan = DurationSpan.create(46); spannable.setSpan(durationSpan, 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); CarText carText1 = CarText.create(spannable); text = "Part of this text is red"; spannable = new SpannableString(text); foregroundCarColorSpan = ForegroundCarColorSpan.create(CarColor.RED); spannable.setSpan(foregroundCarColorSpan, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); durationSpan = DurationSpan.create(46); spannable.setSpan(durationSpan, 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); CarText carText2 = CarText.create(spannable); // Create a text where the string is different text = "Part of this text is blue"; spannable = new SpannableString(text); foregroundCarColorSpan = ForegroundCarColorSpan.create(CarColor.RED); spannable.setSpan(foregroundCarColorSpan, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); durationSpan = DurationSpan.create(46); spannable.setSpan(durationSpan, 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); CarText carText3 = CarText.create(spannable); // Create a text where the spans change text = "Part of this text is red"; spannable = new SpannableString(text); foregroundCarColorSpan = ForegroundCarColorSpan.create(CarColor.RED); spannable.setSpan(foregroundCarColorSpan, 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); CarText carText4 = CarText.create(spannable); assertThat(carText1).isEqualTo(carText2); assertThat(carText1.hashCode()).isEqualTo(carText2.hashCode()); assertThat(carText1).isEqualTo(carText1); assertThat(carText1.hashCode()).isEqualTo(carText1.hashCode()); assertThat(carText1).isNotEqualTo(carText3); assertThat(carText1.hashCode()).isNotEqualTo(carText3.hashCode()); assertThat(carText2).isNotEqualTo(carText4); assertThat(carText2.hashCode()).isNotEqualTo(carText4.hashCode()); assertThat(carText3).isNotEqualTo(carText4); assertThat(carText3.hashCode()).isNotEqualTo(carText4.hashCode()); } private static List<CarSpanInfo> getCarSpans(CharSequence charSequence) { Spanned spanned = (Spanned) charSequence; List<CarSpanInfo> carSpans = new ArrayList<>(); for (Object span : spanned.getSpans(0, charSequence.length(), Object.class)) { assertThat(span instanceof CarSpan).isTrue(); CarSpanInfo info = new CarSpanInfo(); info.mCarSpan = (CarSpan) span; info.mStart = spanned.getSpanStart(span); info.mEnd = spanned.getSpanEnd(span); info.mFlags = spanned.getSpanFlags(span); carSpans.add(info); } return carSpans; } private static class CarSpanInfo { CarSpan mCarSpan; int mStart; int mEnd; int mFlags; } }
package org.avmframework.examples.testoptimization.behaviourpair; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Transition { /** * 0. Source state 1. Target state 2. Trigger-Event Trigger {user operations, network environment * parameters} 3. Conditions - Guard Conditions - Network Environment related {} 4. Effect-ignore * for now {} */ private HashMap<String, ValueSet> conditions; private List<String> triggers; private State sourceState; private State targetState; /** Construct methods. */ public Transition() { this.conditions = new HashMap<String, ValueSet>(); this.triggers = new ArrayList<String>(); this.sourceState = new State(); this.targetState = new State(); } public Transition(State sourceState, State targetState) { this.conditions = new HashMap<String, ValueSet>(); this.triggers = new ArrayList<String>(); this.sourceState = sourceState; this.targetState = targetState; } public Transition(NetworkEnvironment ne) { this.conditions = new HashMap<String, ValueSet>(); this.triggers = new ArrayList<String>(); this.sourceState = new State(); this.targetState = new State(); // this.triggers.add(ne.getPacketDelayName()); // this.triggers.add(ne.getPacketLossName()); // this.triggers.add(ne.getPacketCorruptionName()); // this.triggers.add(ne.getPacketDuplicationName()); } /** * Functional Methods setTriggerByNetworkEnvironment Set the trigger of the transition by network * environment. * * <p>Haven't been used! */ public static void setTriggerByNetworkEnvironment( Transition transition, NetworkEnvironment networkEnvironment) { String delay = "PacketDelay == "; double varDelay = networkEnvironment.getPacketDelay(); delay = delay + varDelay; String loss = "PacketLoss == "; double varLoss = networkEnvironment.getPacketLoss(); loss = loss + varLoss; String corrupt = "PacketCorruption == "; double varCorrupt = networkEnvironment.getPacketCorruption(); corrupt = corrupt + varCorrupt; String duplicate = "PacketDuplication == "; double varDuplicate = networkEnvironment.getPacketDuplication(); duplicate = duplicate + varDuplicate; transition.addTriggers(delay); transition.addTriggers(loss); transition.addTriggers(corrupt); transition.addTriggers(duplicate); } /** * ABANDONED. Functional Methods setTransitionByNetworkEnvironment: actually set the guard. * conditions */ public static void setTransitionByNetworkEnvironment( Transition transition, NetworkEnvironment networkEnvironment) { /* String delay = "PacketDelay == "; double varDelay = networkEnvironment.getPacketDelay(); delay = delay + varDelay; String loss = "PacketLoss == "; double varLoss = networkEnvironment.getPacketLoss(); loss = loss + varLoss; String corrupt = "PacketCorruption == "; double varCorrupt = networkEnvironment.getPacketCorruption(); corrupt = corrupt + varCorrupt; String duplicate = "PacketDuplication == "; double varDuplicate = networkEnvironment.getPacketDuplication(); duplicate = duplicate + varDuplicate; transition.addConditions(delay); transition.addConditions(loss); transition.addConditions(corrupt); transition.addConditions(duplicate); */ System.out.println("Method setTransitionByNetworkEnvironment has been out of time!"); } // This method is only used in state to set(remove) the transitions of one specific state. // Only compare source state, target state, and triggers. public boolean isequal(Transition transition) { if (!this.sourceState.isequal(transition.sourceState)) { return false; } if (!this.targetState.isequal(transition.targetState)) { return false; } int length = this.triggers.size(); if (length == transition.getTriggers().size()) { for (int i = 0; i < length; i++) { String tempTriggers = this.triggers.get(i); boolean temp = false; // This means one condition has the same condition in the other transition. for (int j = 0; j < length; j++) { if (tempTriggers.equals(transition.getTriggers().get(j))) { temp = true; } } if (temp == false) { return false; } } } else { return false; } return true; } public boolean isequalTriggerAndCondition(Transition transition) { // Notice! if (!this.sourceState.isEqualValueSet(transition.sourceState)) { return false; } // only use trigger's index 0 if (!transition.triggers.get(0).equals(this.triggers.get(0))) { return false; } // conditions if (transition.getConditions().size() == this.getConditions().size()) { HashMap<String, ValueSet> vals = this.conditions; Iterator it = vals.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, ValueSet> entry = (Map.Entry<String, ValueSet>) it.next(); String key = entry.getKey(); ValueSet val = entry.getValue(); if (transition.getConditions().get(key) != null) { if (transition.getConditions().get(key).isequal(val)) { // do nothing } else { return false; } } else { return false; } } } else { return false; } return true; } /** Set and Get this class's members Methods. */ public State getSourceState() { return this.sourceState; } public void setSourceState(State state) { this.sourceState = state; } public State getTargetState() { return this.targetState; } public void setTargetState(State state) { this.targetState = state; } public void setConditions(HashMap<String, ValueSet> gc) { this.conditions = gc; } public void addOneCondition(String var, String condition) { this.conditions.get(var).getValueSet().add(condition); } public void addConditions(String var, ValueSet valueSet) { this.conditions.put(var, valueSet); } public HashMap<String, ValueSet> getConditions() { return this.conditions; } public void addTriggers(String trigger) { this.triggers.add(trigger); } public List<String> getTriggers() { return this.triggers; } public static void main(String[] args) {} }
/* * The MIT License * * Copyright (c) 2012, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.model.lazy; import hudson.model.Job; import hudson.model.Run; import hudson.model.RunMap; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.lang.ref.Reference; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; import static jenkins.model.lazy.AbstractLazyLoadRunMap.Direction.*; import static jenkins.model.lazy.Boundary.*; import org.apache.commons.collections.keyvalue.DefaultMapEntry; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * {@link SortedMap} that keeps build records by their build numbers, in the descending order * (newer ones first.) * * <p> * The main thing about this class is that it encapsulates the lazy loading logic. * That is, while this class looks and feels like a normal {@link SortedMap} from outside, * it actually doesn't have every item in the map instantiated yet. As items in the map get * requested, this class {@link #retrieve(File) retrieves them} on demand, one by one. * * <p> * The lookup is primarily done by using the build number as the key (hence the key type is {@link Integer}), * but this class also provides look up based on {@linkplain #getIdOf(Object) the build ID}. * * <p> * This class makes the following assumption about the on-disk layout of the data: * * <ul> * <li>Every build is stored in a directory, named after its ID. * <li>ID and build number are in the consistent order. That is, * if there are two builds #M and #N, {@code M>N <=> M.id > N.id}. * </ul> * * <p> * On certain platforms, there are symbolic links named after build numbers that link to the build ID. * If these are available, they are used as a hint to speed up the lookup. Otherwise * we rely on the assumption above and perform a binary search to locate the build. * (notice that we'll have to do linear search if we don't have the consistent ordering assumption, * which robs the whole point of doing lazy loading.) * * <p> * Some of the {@link SortedMap} operations are weakly implemented. For example, * {@link #size()} may be inaccurate because we only count the number of directories that look like * build records, without checking if they are loadable. But these weaknesses aren't distinguishable * from concurrent modifications, where another thread deletes a build while one thread iterates them. * * <p> * Some of the {@link SortedMap} operations are inefficiently implemented, by * {@linkplain #all() loading all the build records eagerly}. We hope to replace * these implementations by more efficient lazy-loading ones as we go. * * <p> * Object lock of {@code this} is used to make sure mutation occurs sequentially. * That is, ensure that only one thread is actually calling {@link #retrieve(File)} and * updating {@link jenkins.model.lazy.AbstractLazyLoadRunMap.Index#byNumber} and {@link jenkins.model.lazy.AbstractLazyLoadRunMap.Index#byId}. * * @author Kohsuke Kawaguchi * @since 1.485 */ public abstract class AbstractLazyLoadRunMap<R> extends AbstractMap<Integer,R> implements SortedMap<Integer,R> { /** * Used in {@link #all()} to quickly determine if we've already loaded everything. */ private boolean fullyLoaded; /** * Currently visible index. * Updated atomically. Once set to this field, the index object may not be modified. */ private volatile Index index = new Index(); /** * Pair of two maps into a single class, so that the changes can be made visible atomically, * and updates can happen concurrently to read. * * The idiom is that you put yourself in a synchronized block, {@linkplain #copy() make a copy of this}, * update the copy, then set it to {@link #index}. */ private class Index { /** * Stores the mapping from build number to build, for builds that are already loaded. */ private final TreeMap<Integer,BuildReference<R>> byNumber; /** * Stores the build ID to build number for builds that we already know. * * If we have known load failure of the given ID, we record that in the map * by using the null value (not to be confused with a non-null {@link BuildReference} * with null referent, which just means the record was GCed.) */ private final TreeMap<String,BuildReference<R>> byId; private Index() { byId = new TreeMap<String,BuildReference<R>>(); byNumber = new TreeMap<Integer,BuildReference<R>>(COMPARATOR); } private Index(Index rhs) { byId = new TreeMap<String, BuildReference<R>>(rhs.byId); byNumber = new TreeMap<Integer,BuildReference<R>>(rhs.byNumber); } /** * Returns the build record #M (<=n) */ private Map.Entry<Integer,BuildReference<R>> ceilingEntry(int n) { // switch to this once we depend on JDK6 // return byNumber.ceilingEntry(n); Set<Entry<Integer, BuildReference<R>>> s = byNumber.tailMap(n).entrySet(); if (s.isEmpty()) return null; else return s.iterator().next(); } /** * Returns the build record #M (>=n) */ // >= and not <= because byNumber is in the descending order private Map.Entry<Integer,BuildReference<R>> floorEntry(int n) { // switch to this once we depend on JDK6 // return byNumber.floorEntry(n); SortedMap<Integer, BuildReference<R>> sub = byNumber.headMap(n); if (sub.isEmpty()) return null; Integer k = sub.lastKey(); return new DefaultMapEntry(k,sub.get(k)); } } /** * Build IDs found as directories, in the ascending order. */ // copy on write private volatile SortedList<String> idOnDisk = new SortedList<String>(Collections.<String>emptyList()); /** * Build number shortcuts found on disk, in the ascending order. */ // copy on write private volatile SortedIntList numberOnDisk = new SortedIntList(0); /** * Base directory for data. * In effect this is treated as a final field, but can't mark it final * because the compatibility requires that we make it settable * in the first call after the constructor. */ private File dir; protected AbstractLazyLoadRunMap(File dir) { initBaseDir(dir); } @Restricted(NoExternalUse.class) protected void initBaseDir(File dir) { assert this.dir==null; this.dir = dir; if (dir!=null) loadIdOnDisk(); } /** * @return true if {@link AbstractLazyLoadRunMap#AbstractLazyLoadRunMap} was called with a non-null param, or {@link RunMap#load(Job, RunMap.Constructor)} was called */ @Restricted(NoExternalUse.class) public final boolean baseDirInitialized() { return dir != null; } /** * Updates base directory location after directory changes. * This method should be used on jobs renaming, etc. * @param dir Directory location * @since 1.546 */ public final void updateBaseDir(File dir) { this.dir = dir; } /** * Let go of all the loaded references. * * This is a bit more sophisticated version of forcing GC. * Primarily for debugging and testing lazy loading behaviour. * @since 1.507 */ public void purgeCache() { index = new Index(); fullyLoaded = false; loadIdOnDisk(); } private void loadIdOnDisk() { String[] kids = dir.list(); if (kids == null) { // the job may have just been created kids = EMPTY_STRING_ARRAY; } List<String> buildDirs = new ArrayList<String>(); FilenameFilter buildDirFilter = createDirectoryFilter(); SortedIntList list = new SortedIntList(kids.length / 2); for (String s : kids) { if (buildDirFilter.accept(dir, s)) { buildDirs.add(s); } else { try { list.add(Integer.parseInt(s)); } catch (NumberFormatException e) { // this isn't a shortcut } } } Collections.sort(buildDirs); idOnDisk = new SortedList<String>(buildDirs); list.sort(); numberOnDisk = list; } public Comparator<? super Integer> comparator() { return COMPARATOR; } /** * If we have non-zero R in memory, we can return false right away. * If we have zero R in memory, try loading one and see if we can find something. */ @Override public boolean isEmpty() { return index.byId.isEmpty() && search(Integer.MAX_VALUE, DESC)==null; } @Override public Set<Entry<Integer, R>> entrySet() { assert baseDirInitialized(); return Collections.unmodifiableSet(new BuildReferenceMapAdapter<R>(this,all()).entrySet()); } /** * Returns a read-only view of records that has already been loaded. */ public SortedMap<Integer,R> getLoadedBuilds() { return Collections.unmodifiableSortedMap(new BuildReferenceMapAdapter<R>(this, index.byNumber)); } /** * @param fromKey * Biggest build number to be in the returned set. * @param toKey * Smallest build number-1 to be in the returned set (-1 because this is exclusive) */ public SortedMap<Integer, R> subMap(Integer fromKey, Integer toKey) { // TODO: if this method can produce a lazy map, that'd be wonderful // because due to the lack of floor/ceil/higher/lower kind of methods // to look up keys in SortedMap, various places of Jenkins rely on // subMap+firstKey/lastKey combo. R start = search(fromKey, DESC); if (start==null) return EMPTY_SORTED_MAP; R end = search(toKey, ASC); if (end==null) return EMPTY_SORTED_MAP; for (R i=start; i!=end; ) { i = search(getNumberOf(i)-1,DESC); assert i!=null; } return Collections.unmodifiableSortedMap(new BuildReferenceMapAdapter<R>(this, index.byNumber.subMap(fromKey, toKey))); } public SortedMap<Integer, R> headMap(Integer toKey) { return subMap(Integer.MAX_VALUE, toKey); } public SortedMap<Integer, R> tailMap(Integer fromKey) { return subMap(fromKey, Integer.MIN_VALUE); } public Integer firstKey() { R r = newestBuild(); if (r==null) throw new NoSuchElementException(); return getNumberOf(r); } public Integer lastKey() { R r = oldestBuild(); if (r==null) throw new NoSuchElementException(); return getNumberOf(r); } public R newestBuild() { return search(Integer.MAX_VALUE, DESC); } public R oldestBuild() { return search(Integer.MIN_VALUE, ASC); } @Override public R get(Object key) { if (key instanceof Integer) { int n = (Integer) key; return get(n); } return super.get(key); } public R get(int n) { return search(n,Direction.EXACT); } /** * Finds the build #M where M is nearby the given 'n'. * * <p> * * * @param n * the index to start the search from * @param d * defines what we mean by "nearby" above. * If EXACT, find #N or return null. * If ASC, finds the closest #M that satisfies M>=N. * If DESC, finds the closest #M that satisfies M&lt;=N. */ public @CheckForNull R search(final int n, final Direction d) { Entry<Integer, BuildReference<R>> c = index.ceilingEntry(n); if (c!=null && c.getKey()== n) { R r = c.getValue().get(); if (r!=null) return r; // found the exact #n } // at this point we know that we don't have #n loaded yet {// check numberOnDisk as a cache to see if we can find it there int npos = numberOnDisk.find(n); if (npos>=0) {// found exact match R r = load(numberOnDisk.get(npos), null); if (r!=null) return r; } switch (d) { case ASC: case DESC: // didn't find the exact match, but what's the nearest ascending value in the cache? int neighbor = (d==ASC?HIGHER:LOWER).apply(npos); if (numberOnDisk.isInRange(neighbor)) { R r = getByNumber(numberOnDisk.get(neighbor)); if (r!=null) { // make sure that the cache is accurate by looking at the previous ID // and it actually satisfies the constraint int prev = (d==ASC?LOWER:HIGHER).apply(idOnDisk.find(getIdOf(r))); if (idOnDisk.isInRange(prev)) { R pr = getById(idOnDisk.get(prev)); // sign*sign is making sure that #pr and #r sandwiches #n. if (pr!=null && signOfCompare(getNumberOf(pr),n)*signOfCompare(n,getNumberOf(r))>0) return r; else { // cache is lying. there's something fishy. // ignore the cache and do the slow search } } else { // r is the build with youngest ID return r; } } else { // cache says we should have a build but we didn't. // ignore the cache and do the slow search } } break; case EXACT: // fall through } // didn't find it in the cache, but don't give up yet // maybe the cache just doesn't exist. // so fall back to the slow search } // capture the snapshot and work off with it since it can be overwritten by other threads SortedList<String> idOnDisk = this.idOnDisk; boolean clonedIdOnDisk = false; // if we modify idOnDisk we need to write it back. this flag is set to true when we overwrit idOnDisk local var // slow path: we have to find the build from idOnDisk by guessing ID of the build. // first, narrow down the candidate IDs to try by using two known number-to-ID mapping if (idOnDisk.isEmpty()) return null; Entry<Integer, BuildReference<R>> f = index.floorEntry(n); // if bound is null, use a sentinel value String cid = c==null ? "\u0000" : c.getValue().id; String fid = f==null ? "\uFFFF" : f.getValue().id; // at this point, #n must be in (cid,fid) // We know that the build we are looking for exists in [lo,hi) --- it's "hi)" and not "hi]" because we do +1. // we will narrow this down via binary search final int initialSize = idOnDisk.size(); int lo = idOnDisk.higher(cid); int hi = idOnDisk.lower(fid)+1; final int initialLo = lo, initialHi = hi; if (!(0<=lo && lo<=hi && hi<=idOnDisk.size())) { // assertion error, but we are so far unable to get to the bottom of this bug. // but don't let this kill the loading the hard way String msg = String.format( "JENKINS-15652 Assertion error #1: failing to load %s #%d %s: lo=%d,hi=%d,size=%d,size2=%d", dir, n, d, lo, hi, idOnDisk.size(), initialSize); LOGGER.log(Level.WARNING, msg); return null; } while (lo<hi) { final int pivot = (lo+hi)/2; if (!(0<=lo && lo<=pivot && pivot<hi && hi<=idOnDisk.size())) { // assertion error, but we are so far unable to get to the bottom of this bug. // but don't let this kill the loading the hard way String msg = String.format( "JENKINS-15652 Assertion error #2: failing to load %s #%d %s: lo=%d,hi=%d,pivot=%d,size=%d (initial:lo=%d,hi=%d,size=%d)", dir, n, d, lo, hi, pivot, idOnDisk.size(), initialLo, initialHi, initialSize); LOGGER.log(Level.WARNING, msg); return null; } R r = load(idOnDisk.get(pivot), null); if (r==null) { // this ID isn't valid. get rid of that and retry pivot hi--; if (!clonedIdOnDisk) {// if we are making an edit, we need to own a copy idOnDisk = new SortedList<String>(idOnDisk); clonedIdOnDisk = true; } idOnDisk.remove(pivot); continue; } int found = getNumberOf(r); if (found==n) return r; // exact match if (found<n) lo = pivot+1; // the pivot was too small. look in the upper half else hi = pivot; // the pivot was too big. look in the lower half } if (clonedIdOnDisk) this.idOnDisk = idOnDisk; // feedback the modified result atomically assert lo==hi; // didn't find the exact match // both lo and hi point to the insertion point on idOnDisk switch (d) { case ASC: if (hi==idOnDisk.size()) return null; return getById(idOnDisk.get(hi)); case DESC: if (lo<=0) return null; if (lo-1>=idOnDisk.size()) { // assertion error, but we are so far unable to get to the bottom of this bug. // but don't let this kill the loading the hard way LOGGER.log(Level.WARNING, String.format( "JENKINS-15652 Assertion error #3: failing to load %s #%d %s: lo=%d,hi=%d,size=%d (initial:lo=%d,hi=%d,size=%d)", dir, n,d,lo,hi,idOnDisk.size(), initialLo,initialHi,initialSize)); return null; } return getById(idOnDisk.get(lo-1)); case EXACT: if (hi<=0) return null; R r = load(idOnDisk.get(hi-1), null); if (r==null) return null; int found = getNumberOf(r); if (found==n) return r; // exact match return null; default: throw new AssertionError(); } } /** * sign of (a-b). */ private static int signOfCompare(int a, int b) { if (a>b) return 1; if (a<b) return -1; return 0; } public R getById(String id) { Index snapshot = index; if (snapshot.byId.containsKey(id)) { BuildReference<R> ref = snapshot.byId.get(id); if (ref==null) return null; // known failure R v = unwrap(ref); if (v!=null) return v; // already in memory // otherwise fall through to load } return load(id,null); } public R getByNumber(int n) { return search(n,Direction.EXACT); } public R put(R value) { return _put(value); } protected R _put(R value) { return put(getNumberOf(value),value); } @Override public synchronized R put(Integer key, R r) { String id = getIdOf(r); int n = getNumberOf(r); Index copy = copy(); BuildReference<R> ref = createReference(r); BuildReference<R> old = copy.byId.put(id,ref); copy.byNumber.put(n,ref); index = copy; /* search relies on the fact that every object added via put() method be available in the xyzOnDisk index, so I'm adding them here however, this is awfully inefficient. I wonder if there's any better way to do this? */ if (!idOnDisk.contains(id)) { ArrayList<String> a = new ArrayList<String>(idOnDisk); a.add(id); Collections.sort(a); idOnDisk = new SortedList<String>(a); } if (!numberOnDisk.contains(n)) { SortedIntList a = new SortedIntList(numberOnDisk); a.add(n); a.sort(); numberOnDisk = a; } return unwrap(old); } private R unwrap(Reference<R> ref) { return ref!=null ? ref.get() : null; } @Override public synchronized void putAll(Map<? extends Integer,? extends R> rhs) { Index copy = copy(); for (R r : rhs.values()) { String id = getIdOf(r); BuildReference<R> ref = createReference(r); copy.byId.put(id,ref); copy.byNumber.put(getNumberOf(r),ref); } index = copy; } /** * Loads all the build records to fully populate the map. * Calling this method results in eager loading everything, * so the whole point of this class is to avoid this call as much as possible * for typical code path. * * @return * fully populated map. */ private TreeMap<Integer,BuildReference<R>> all() { if (!fullyLoaded) { synchronized (this) { if (!fullyLoaded) { Index copy = copy(); for (String id : idOnDisk) { if (!copy.byId.containsKey(id)) load(id,copy); } index = copy; fullyLoaded = true; } } } return index.byNumber; } /** * Creates a duplicate for the COW data structure in preparation for mutation. */ private Index copy() { return new Index(index); } /** * Tries to load the record #N by using the shortcut. * * @return null if the data failed to load. */ protected R load(int n, Index editInPlace) { R r = null; File shortcut = new File(dir,String.valueOf(n)); if (shortcut.isDirectory()) { synchronized (this) { r = load(shortcut,editInPlace); // make sure what we actually loaded is #n, // because the shortcuts can lie. if (r!=null && getNumberOf(r)!=n) r = null; if (r==null) { // if failed to locate, record that fact SortedIntList update = new SortedIntList(numberOnDisk); update.removeValue(n); numberOnDisk = update; } } } return r; } protected R load(String id, Index editInPlace) { assert dir != null; R v = load(new File(dir, id), editInPlace); if (v==null && editInPlace!=null) { // remember the failure. // if editInPlace==null, we can create a new copy for this, but not sure if it's worth doing, // given that we also update idOnDisk anyway. editInPlace.byId.put(id,null); } return v; } /** * @param editInPlace * If non-null, update this data structure. * Otherwise do a copy-on-write of {@link #index} */ protected synchronized R load(File dataDir, Index editInPlace) { try { R r = retrieve(dataDir); if (r==null) return null; Index copy = editInPlace!=null ? editInPlace : new Index(index); String id = getIdOf(r); BuildReference<R> ref = createReference(r); copy.byId.put(id,ref); copy.byNumber.put(getNumberOf(r),ref); if (editInPlace==null) index = copy; return r; } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+dataDir,e); } return null; } /** * Subtype to provide {@link Run#getNumber()} so that this class doesn't have to depend on it. */ protected abstract int getNumberOf(R r); /** * Subtype to provide {@link Run#getId()} so that this class doesn't have to depend on it. */ protected abstract String getIdOf(R r); /** * Allow subtype to capture a reference. */ protected BuildReference<R> createReference(R r) { return new BuildReference<R>(getIdOf(r),r); } /** * Parses {@code R} instance from data in the specified directory. * * @return * null if the parsing failed. * @throws IOException * if the parsing failed. This is just like returning null * except the caller will catch the exception and report it. */ protected abstract R retrieve(File dir) throws IOException; public synchronized boolean removeValue(R run) { Index copy = copy(); int n = getNumberOf(run); copy.byNumber.remove(n); SortedIntList a = new SortedIntList(numberOnDisk); a.removeValue(n); numberOnDisk = a; BuildReference<R> old = copy.byId.remove(getIdOf(run)); this.index = copy; return unwrap(old)!=null; } /** * Replaces all the current loaded Rs with the given ones. */ public synchronized void reset(TreeMap<Integer,R> builds) { Index index = new Index(); for (R r : builds.values()) { String id = getIdOf(r); BuildReference<R> ref = createReference(r); index.byId.put(id,ref); index.byNumber.put(getNumberOf(r),ref); } this.index = index; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object o) { return o==this; } /** * Lists the actual data directory */ protected abstract FilenameFilter createDirectoryFilter(); private static final Comparator<Comparable> COMPARATOR = new Comparator<Comparable>() { public int compare(Comparable o1, Comparable o2) { return -o1.compareTo(o2); } }; public enum Direction { ASC, DESC, EXACT } private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final SortedMap EMPTY_SORTED_MAP = Collections.unmodifiableSortedMap(new TreeMap()); static final Logger LOGGER = Logger.getLogger(AbstractLazyLoadRunMap.class.getName()); }
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ package com.sun.org.apache.bcel.internal.classfile; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This 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/>. */ import java.util.Stack; /** * Traverses a JavaClass with another Visitor object 'piggy-backed' * that is applied to all components of a JavaClass object. I.e. this * class supplies the traversal strategy, other classes can make use * of it. * * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A> */ public class DescendingVisitor implements Visitor { private JavaClass clazz; private Visitor visitor; private Stack stack = new Stack(); /** @return container of current entitity, i.e., predecessor during traversal */ public Object predecessor() { return predecessor(0); } /** * @param level nesting level, i.e., 0 returns the direct predecessor * @return container of current entitity, i.e., predecessor during traversal */ public Object predecessor(int level) { int size = stack.size(); if((size < 2) || (level < 0)) return null; else return stack.elementAt(size - (level + 2)); // size - 1 == current } /** @return current object */ public Object current() { return stack.peek(); } /** * @param clazz Class to traverse * @param visitor visitor object to apply to all components */ public DescendingVisitor(JavaClass clazz, Visitor visitor) { this.clazz = clazz; this.visitor = visitor; } /** * Start traversal. */ public void visit() { clazz.accept(this); } public void visitJavaClass(JavaClass clazz) { stack.push(clazz); clazz.accept(visitor); Field[] fields = clazz.getFields(); for(int i=0; i < fields.length; i++) fields[i].accept(this); Method[] methods = clazz.getMethods(); for(int i=0; i < methods.length; i++) methods[i].accept(this); Attribute[] attributes = clazz.getAttributes(); for(int i=0; i < attributes.length; i++) attributes[i].accept(this); clazz.getConstantPool().accept(this); stack.pop(); } public void visitField(Field field) { stack.push(field); field.accept(visitor); Attribute[] attributes = field.getAttributes(); for(int i=0; i < attributes.length; i++) attributes[i].accept(this); stack.pop(); } public void visitConstantValue(ConstantValue cv) { stack.push(cv); cv.accept(visitor); stack.pop(); } public void visitMethod(Method method) { stack.push(method); method.accept(visitor); Attribute[] attributes = method.getAttributes(); for(int i=0; i < attributes.length; i++) attributes[i].accept(this); stack.pop(); } public void visitExceptionTable(ExceptionTable table) { stack.push(table); table.accept(visitor); stack.pop(); } public void visitCode(Code code) { stack.push(code); code.accept(visitor); CodeException[] table = code.getExceptionTable(); for(int i=0; i < table.length; i++) table[i].accept(this); Attribute[] attributes = code.getAttributes(); for(int i=0; i < attributes.length; i++) attributes[i].accept(this); stack.pop(); } public void visitCodeException(CodeException ce) { stack.push(ce); ce.accept(visitor); stack.pop(); } public void visitLineNumberTable(LineNumberTable table) { stack.push(table); table.accept(visitor); LineNumber[] numbers = table.getLineNumberTable(); for(int i=0; i < numbers.length; i++) numbers[i].accept(this); stack.pop(); } public void visitLineNumber(LineNumber number) { stack.push(number); number.accept(visitor); stack.pop(); } public void visitLocalVariableTable(LocalVariableTable table) { stack.push(table); table.accept(visitor); LocalVariable[] vars = table.getLocalVariableTable(); for(int i=0; i < vars.length; i++) vars[i].accept(this); stack.pop(); } public void visitLocalVariableTypeTable(LocalVariableTypeTable obj) { stack.push(obj); obj.accept(visitor); stack.pop(); } public void visitStackMap(StackMap table) { stack.push(table); table.accept(visitor); StackMapEntry[] vars = table.getStackMap(); for(int i=0; i < vars.length; i++) vars[i].accept(this); stack.pop(); } public void visitStackMapEntry(StackMapEntry var) { stack.push(var); var.accept(visitor); stack.pop(); } public void visitLocalVariable(LocalVariable var) { stack.push(var); var.accept(visitor); stack.pop(); } public void visitConstantPool(ConstantPool cp) { stack.push(cp); cp.accept(visitor); Constant[] constants = cp.getConstantPool(); for(int i=1; i < constants.length; i++) { if(constants[i] != null) constants[i].accept(this); } stack.pop(); } public void visitConstantClass(ConstantClass constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantDouble(ConstantDouble constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantFieldref(ConstantFieldref constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantFloat(ConstantFloat constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantInteger(ConstantInteger constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantInterfaceMethodref(ConstantInterfaceMethodref constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantLong(ConstantLong constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantMethodref(ConstantMethodref constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantNameAndType(ConstantNameAndType constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantString(ConstantString constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitConstantUtf8(ConstantUtf8 constant) { stack.push(constant); constant.accept(visitor); stack.pop(); } public void visitInnerClasses(InnerClasses ic) { stack.push(ic); ic.accept(visitor); InnerClass[] ics = ic.getInnerClasses(); for(int i=0; i < ics.length; i++) ics[i].accept(this); stack.pop(); } public void visitInnerClass(InnerClass inner) { stack.push(inner); inner.accept(visitor); stack.pop(); } public void visitDeprecated(Deprecated attribute) { stack.push(attribute); attribute.accept(visitor); stack.pop(); } public void visitSignature(Signature attribute) { stack.push(attribute); attribute.accept(visitor); stack.pop(); } public void visitSourceFile(SourceFile attribute) { stack.push(attribute); attribute.accept(visitor); stack.pop(); } public void visitSynthetic(Synthetic attribute) { stack.push(attribute); attribute.accept(visitor); stack.pop(); } public void visitUnknown(Unknown attribute) { stack.push(attribute); attribute.accept(visitor); stack.pop(); } }
/* * 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.catalina.servlets; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import static org.apache.catalina.startup.SimpleHttpClient.CRLF; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; public class TestDefaultServlet extends TomcatBaseTest { /** * Test attempting to access special paths (WEB-INF/META-INF) using * DefaultServlet. */ @Test public void testGetSpecials() throws Exception { Tomcat tomcat = getTomcatInstance(); String contextPath = "/examples"; File appDir = new File(getBuildDirectory(), "webapps" + contextPath); // app dir is relative to server home tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); tomcat.start(); final ByteChunk res = new ByteChunk(); int rc =getUrl("http://localhost:" + getPort() + contextPath + "/WEB-INF/web.xml", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/WEB-INF/doesntexistanywhere", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/WEB-INF/", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/META-INF/MANIFEST.MF", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/META-INF/doesntexistanywhere", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); } /** * Test https://issues.apache.org/bugzilla/show_bug.cgi?id=50026 * Verify serving of resources from context root with subpath mapping. */ @Test public void testGetWithSubpathmount() throws Exception { Tomcat tomcat = getTomcatInstance(); String contextPath = "/examples"; File appDir = new File(getBuildDirectory(), "webapps" + contextPath); // app dir is relative to server home org.apache.catalina.Context ctx = tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); // Override the default servlet with our own mappings Tomcat.addServlet(ctx, "default2", new DefaultServlet()); ctx.addServletMapping("/", "default2"); ctx.addServletMapping("/servlets/*", "default2"); ctx.addServletMapping("/static/*", "default2"); tomcat.start(); final ByteChunk res = new ByteChunk(); // Make sure DefaultServlet isn't exposing special directories // by remounting the webapp under a sub-path int rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/WEB-INF/web.xml", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/WEB-INF/doesntexistanywhere", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/WEB-INF/", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/META-INF/MANIFEST.MF", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/META-INF/doesntexistanywhere", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); // Make sure DefaultServlet is serving resources relative to the // context root regardless of where the it is mapped final ByteChunk rootResource = new ByteChunk(); rc =getUrl("http://localhost:" + getPort() + contextPath + "/index.html", rootResource, null); assertEquals(HttpServletResponse.SC_OK, rc); final ByteChunk subpathResource = new ByteChunk(); rc =getUrl("http://localhost:" + getPort() + contextPath + "/servlets/index.html", subpathResource, null); assertEquals(HttpServletResponse.SC_OK, rc); assertFalse(rootResource.toString().equals(subpathResource.toString())); rc =getUrl("http://localhost:" + getPort() + contextPath + "/static/index.html", res, null); assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); } /** * Test https://issues.apache.org/bugzilla/show_bug.cgi?id=50413 Serving a * custom error page */ @Test public void testCustomErrorPage() throws Exception { File appDir = new File(getTemporaryDirectory(), "MyApp"); File webInf = new File(appDir, "WEB-INF"); addDeleteOnTearDown(appDir); if (!webInf.mkdirs() && !webInf.isDirectory()) { fail("Unable to create directory [" + webInf + "]"); } Writer w = new OutputStreamWriter(new FileOutputStream(new File(appDir, "WEB-INF/web.xml")), "UTF-8"); try { w.write("<?xml version='1.0' encoding='UTF-8'?>\n" + "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' " + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee " + " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'" + " version='2.4'>\n" + "<error-page>\n<error-code>404</error-code>\n" + "<location>/404.html</location>\n</error-page>\n" + "</web-app>\n"); w.flush(); } finally { w.close(); } w = new OutputStreamWriter(new FileOutputStream(new File(appDir, "404.html")), "ISO-8859-1"); try { w.write("It is 404.html"); w.flush(); } finally { w.close(); } Tomcat tomcat = getTomcatInstance(); String contextPath = "/MyApp"; tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath()); tomcat.start(); TestCustomErrorClient client = new TestCustomErrorClient(tomcat.getConnector().getLocalPort()); client.reset(); client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.0" +CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse404()); assertEquals("It is 404.html", client.getResponseBody()); SimpleDateFormat format = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); String tomorrow = format.format(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)); // https://issues.apache.org/bugzilla/show_bug.cgi?id=50413 // client.reset(); client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: close" + CRLF + "If-Modified-Since: " + tomorrow + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse404()); assertEquals("It is 404.html", client.getResponseBody()); // https://issues.apache.org/bugzilla/show_bug.cgi?id=50413#c6 // client.reset(); client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: close" + CRLF + "Range: bytes=0-100" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse404()); assertEquals("It is 404.html", client.getResponseBody()); } /** * Test what happens if a custom 404 page is configured, * but its file is actually missing. */ @Test public void testCustomErrorPageMissing() throws Exception { File appDir = new File(getTemporaryDirectory(), "MyApp"); File webInf = new File(appDir, "WEB-INF"); addDeleteOnTearDown(appDir); if (!webInf.mkdirs() && !webInf.isDirectory()) { fail("Unable to create directory [" + webInf + "]"); } Writer w = new OutputStreamWriter(new FileOutputStream(new File(appDir, "WEB-INF/web.xml")), "UTF-8"); try { w.write("<?xml version='1.0' encoding='UTF-8'?>\n" + "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' " + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee " + " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'" + " version='2.4'>\n" + "<error-page>\n<error-code>404</error-code>\n" + "<location>/404-absent.html</location>\n</error-page>\n" + "</web-app>\n"); w.flush(); } finally { w.close(); } Tomcat tomcat = getTomcatInstance(); String contextPath = "/MyApp"; tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath()); tomcat.start(); TestCustomErrorClient client = new TestCustomErrorClient(tomcat.getConnector().getLocalPort()); client.reset(); client.setRequest(new String[] { "GET /MyApp/missing HTTP/1.0" + CRLF + CRLF }); client.connect(); client.processRequest(); assertTrue(client.isResponse404()); } public static int getUrl(String path, ByteChunk out, Map<String, List<String>> resHead) throws IOException { out.recycle(); return TomcatBaseTest.getUrl(path, out, resHead); } private static class TestCustomErrorClient extends SimpleHttpClient { public TestCustomErrorClient(int port) { setPort(port); } @Override public boolean isResponseBodyOK() { return true; } } }
/* * Copyright 2015-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.provider.of.meter.impl; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalCause; import com.google.common.cache.RemovalNotification; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.onlab.util.ItemNotFoundException; import org.onosproject.core.CoreService; import org.onosproject.net.driver.Driver; import org.onosproject.net.driver.DriverService; import org.onosproject.net.meter.Band; import org.onosproject.net.meter.DefaultBand; import org.onosproject.net.meter.DefaultMeter; import org.onosproject.net.meter.Meter; import org.onosproject.net.meter.MeterFailReason; import org.onosproject.net.meter.MeterFeatures; import org.onosproject.net.meter.MeterId; import org.onosproject.net.meter.MeterOperation; import org.onosproject.net.meter.MeterOperations; import org.onosproject.net.meter.MeterProvider; import org.onosproject.net.meter.MeterProviderRegistry; import org.onosproject.net.meter.MeterProviderService; import org.onosproject.net.meter.MeterState; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.provider.AbstractProvider; import org.onosproject.net.provider.ProviderId; import org.onosproject.openflow.controller.Dpid; import org.onosproject.openflow.controller.OpenFlowController; import org.onosproject.openflow.controller.OpenFlowEventListener; import org.onosproject.openflow.controller.OpenFlowSwitch; import org.onosproject.openflow.controller.OpenFlowSwitchListener; import org.onosproject.openflow.controller.RoleState; import org.onosproject.provider.of.meter.util.MeterFeaturesBuilder; import org.projectfloodlight.openflow.protocol.OFErrorMsg; import org.projectfloodlight.openflow.protocol.OFErrorType; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFMeterBandStats; import org.projectfloodlight.openflow.protocol.OFMeterConfigStatsReply; import org.projectfloodlight.openflow.protocol.OFMeterFeatures; import org.projectfloodlight.openflow.protocol.OFMeterStats; import org.projectfloodlight.openflow.protocol.OFMeterStatsReply; import org.projectfloodlight.openflow.protocol.OFPortStatus; import org.projectfloodlight.openflow.protocol.OFStatsReply; import org.projectfloodlight.openflow.protocol.OFStatsType; import org.projectfloodlight.openflow.protocol.OFVersion; import org.projectfloodlight.openflow.protocol.errormsg.OFMeterModFailedErrorMsg; import org.slf4j.Logger; import java.util.Collection; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static org.onosproject.net.DeviceId.deviceId; import static org.onosproject.openflow.controller.Dpid.uri; import static org.slf4j.LoggerFactory.getLogger; /** * Provider which uses an OpenFlow controller to handle meters. */ @Component(immediate = true, enabled = true) public class OpenFlowMeterProvider extends AbstractProvider implements MeterProvider { private final Logger log = getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY) protected OpenFlowController controller; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected MeterProviderRegistry providerRegistry; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected DriverService driverService; private MeterProviderService providerService; private static final AtomicLong XID_COUNTER = new AtomicLong(1); static final int POLL_INTERVAL = 10; static final long TIMEOUT = 30; private Cache<Long, MeterOperation> pendingOperations; private InternalMeterListener listener = new InternalMeterListener(); private Map<Dpid, MeterStatsCollector> collectors = Maps.newHashMap(); private static final Set<Device.Type> NO_METER_SUPPORT = ImmutableSet.copyOf(EnumSet.of(Device.Type.ROADM, Device.Type.ROADM_OTN, Device.Type.FIBER_SWITCH, Device.Type.OTN)); /** * Creates a OpenFlow meter provider. */ public OpenFlowMeterProvider() { super(new ProviderId("of", "org.onosproject.provider.meter")); } @Activate public void activate() { providerService = providerRegistry.register(this); pendingOperations = CacheBuilder.newBuilder() .expireAfterWrite(TIMEOUT, TimeUnit.SECONDS) .removalListener((RemovalNotification<Long, MeterOperation> notification) -> { if (notification.getCause() == RemovalCause.EXPIRED) { providerService.meterOperationFailed(notification.getValue(), MeterFailReason.TIMEOUT); } }).build(); controller.addEventListener(listener); controller.addListener(listener); controller.getSwitches().forEach((sw -> createStatsCollection(sw))); } @Deactivate public void deactivate() { providerRegistry.unregister(this); collectors.values().forEach(MeterStatsCollector::stop); collectors.clear(); controller.removeEventListener(listener); controller.removeListener(listener); providerService = null; } @Override public void performMeterOperation(DeviceId deviceId, MeterOperations meterOps) { Dpid dpid = Dpid.dpid(deviceId.uri()); OpenFlowSwitch sw = controller.getSwitch(dpid); if (sw == null) { log.error("Unknown device {}", deviceId); meterOps.operations().forEach(op -> providerService.meterOperationFailed(op, MeterFailReason.UNKNOWN_DEVICE) ); return; } meterOps.operations().forEach(op -> performOperation(sw, op)); } @Override public void performMeterOperation(DeviceId deviceId, MeterOperation meterOp) { Dpid dpid = Dpid.dpid(deviceId.uri()); OpenFlowSwitch sw = controller.getSwitch(dpid); if (sw == null) { log.error("Unknown device {}", deviceId); providerService.meterOperationFailed(meterOp, MeterFailReason.UNKNOWN_DEVICE); return; } performOperation(sw, meterOp); if (meterOp.type().equals(MeterOperation.Type.REMOVE)) { forceMeterStats(deviceId); } } private void forceMeterStats(DeviceId deviceId) { Dpid dpid = Dpid.dpid(deviceId.uri()); OpenFlowSwitch sw = controller.getSwitch(dpid); MeterStatsCollector once = new MeterStatsCollector(sw, 1); once.sendMeterStatisticRequest(); } private void performOperation(OpenFlowSwitch sw, MeterOperation op) { pendingOperations.put(op.meter().id().id(), op); Meter meter = op.meter(); MeterModBuilder builder = MeterModBuilder.builder(meter.id().id(), sw.factory()); if (meter.isBurst()) { builder.burst(); } builder.withBands(meter.bands()) .withId(meter.id()) .withRateUnit(meter.unit()); switch (op.type()) { case ADD: sw.sendMsg(builder.add()); break; case REMOVE: sw.sendMsg(builder.remove()); break; case MODIFY: sw.sendMsg(builder.modify()); break; default: log.warn("Unknown Meter command {}; not sending anything", op.type()); providerService.meterOperationFailed(op, MeterFailReason.UNKNOWN_COMMAND); } } private void createStatsCollection(OpenFlowSwitch sw) { if (sw != null && isMeterSupported(sw)) { MeterStatsCollector msc = new MeterStatsCollector(sw, POLL_INTERVAL); stopCollectorIfNeeded(collectors.put(new Dpid(sw.getId()), msc)); msc.start(); } } private void stopCollectorIfNeeded(MeterStatsCollector collector) { if (collector != null) { collector.stop(); } } // TODO: ONOS-3546 Support per device enabling/disabling via network config private boolean isMeterSupported(OpenFlowSwitch sw) { if (sw.factory().getVersion() == OFVersion.OF_10 || sw.factory().getVersion() == OFVersion.OF_11 || sw.factory().getVersion() == OFVersion.OF_12 || NO_METER_SUPPORT.contains(sw.deviceType()) || !isMeterCapable(sw)) { log.debug("{} does not support Meter.\n", sw.getDpid()); return false; } return true; } /** * Determine whether the given switch is meter-capable. * * @param sw switch * @return the boolean value of meterCapable property, or true if it is not configured. */ private boolean isMeterCapable(OpenFlowSwitch sw) { Driver driver; try { driver = driverService.getDriver(DeviceId.deviceId(Dpid.uri(sw.getDpid()))); } catch (ItemNotFoundException e) { driver = driverService.getDriver(sw.manufacturerDescription(), sw.hardwareDescription(), sw.softwareDescription()); } String isMeterCapable = driver.getProperty(METER_CAPABLE); return isMeterCapable == null || Boolean.parseBoolean(isMeterCapable); } private void pushMeterStats(Dpid dpid, OFStatsReply msg) { DeviceId deviceId = DeviceId.deviceId(Dpid.uri(dpid)); if (msg.getStatsType() == OFStatsType.METER) { OFMeterStatsReply reply = (OFMeterStatsReply) msg; Collection<Meter> meters = buildMeters(deviceId, reply.getEntries()); //TODO do meter accounting here. providerService.pushMeterMetrics(deviceId, meters); } else if (msg.getStatsType() == OFStatsType.METER_CONFIG) { OFMeterConfigStatsReply reply = (OFMeterConfigStatsReply) msg; // FIXME: Map<Long, Meter> meters = collectMeters(deviceId, reply); } } private MeterFeatures buildMeterFeatures(Dpid dpid, OFMeterFeatures mf) { if (mf != null) { return new MeterFeaturesBuilder(mf, deviceId(uri(dpid))) .build(); } else { // This will usually happen for OpenFlow devices prior to 1.3 return MeterFeaturesBuilder.noMeterFeatures(deviceId(uri(dpid))); } } private void pushMeterFeatures(Dpid dpid, OFMeterFeatures meterFeatures) { providerService.pushMeterFeatures(deviceId(uri(dpid)), buildMeterFeatures(dpid, meterFeatures)); } private void destroyMeterFeatures(Dpid dpid) { providerService.deleteMeterFeatures(deviceId(uri(dpid))); } private Map<Long, Meter> collectMeters(DeviceId deviceId, OFMeterConfigStatsReply reply) { return Maps.newHashMap(); //TODO: Needs a fix to be applied to loxi MeterConfig stat is incorrect } private Collection<Meter> buildMeters(DeviceId deviceId, List<OFMeterStats> entries) { return entries.stream().map(stat -> { DefaultMeter.Builder builder = DefaultMeter.builder(); Collection<Band> bands = buildBands(stat.getBandStats()); builder.forDevice(deviceId) .withId(MeterId.meterId(stat.getMeterId())) //FIXME: need to encode appId in meter id, but that makes // things a little annoying for debugging .fromApp(coreService.getAppId("org.onosproject.core")) .withBands(bands); DefaultMeter meter = builder.build(); meter.setState(MeterState.ADDED); meter.setLife(stat.getDurationSec()); meter.setProcessedBytes(stat.getByteInCount().getValue()); meter.setProcessedPackets(stat.getPacketInCount().getValue()); if (stat.getVersion().getWireVersion() < OFVersion.OF_15.getWireVersion()) { meter.setReferenceCount(stat.getFlowCount()); } // marks the meter as seen on the dataplane pendingOperations.invalidate(stat.getMeterId()); return meter; }).collect(Collectors.toSet()); } private Collection<Band> buildBands(List<OFMeterBandStats> bandStats) { return bandStats.stream().map(stat -> { DefaultBand band = ((DefaultBand.Builder) DefaultBand.builder().ofType(DefaultBand.Type.DROP)).build(); band.setBytes(stat.getByteBandCount().getValue()); band.setPackets(stat.getPacketBandCount().getValue()); return band; }).collect(Collectors.toList()); } private void signalMeterError(OFMeterModFailedErrorMsg meterError, MeterOperation op) { switch (meterError.getCode()) { case UNKNOWN: providerService.meterOperationFailed(op, MeterFailReason.UNKNOWN_DEVICE); break; case METER_EXISTS: providerService.meterOperationFailed(op, MeterFailReason.EXISTING_METER); break; case INVALID_METER: providerService.meterOperationFailed(op, MeterFailReason.INVALID_METER); break; case UNKNOWN_METER: providerService.meterOperationFailed(op, MeterFailReason.UNKNOWN); break; case BAD_COMMAND: providerService.meterOperationFailed(op, MeterFailReason.UNKNOWN_COMMAND); break; case BAD_FLAGS: providerService.meterOperationFailed(op, MeterFailReason.UNKNOWN_FLAGS); break; case BAD_RATE: providerService.meterOperationFailed(op, MeterFailReason.BAD_RATE); break; case BAD_BURST: providerService.meterOperationFailed(op, MeterFailReason.BAD_BURST); break; case BAD_BAND: providerService.meterOperationFailed(op, MeterFailReason.BAD_BAND); break; case BAD_BAND_VALUE: providerService.meterOperationFailed(op, MeterFailReason.BAD_BAND_VALUE); break; case OUT_OF_METERS: providerService.meterOperationFailed(op, MeterFailReason.OUT_OF_METERS); break; case OUT_OF_BANDS: providerService.meterOperationFailed(op, MeterFailReason.OUT_OF_BANDS); break; default: providerService.meterOperationFailed(op, MeterFailReason.UNKNOWN); } } private class InternalMeterListener implements OpenFlowSwitchListener, OpenFlowEventListener { @Override public void handleMessage(Dpid dpid, OFMessage msg) { switch (msg.getType()) { case STATS_REPLY: pushMeterStats(dpid, (OFStatsReply) msg); break; case ERROR: OFErrorMsg error = (OFErrorMsg) msg; if (error.getErrType() == OFErrorType.METER_MOD_FAILED) { MeterOperation op = pendingOperations.getIfPresent(error.getXid()); pendingOperations.invalidate(error.getXid()); if (op == null) { log.warn("Unknown Meter operation failed {}", error); } else { OFMeterModFailedErrorMsg meterError = (OFMeterModFailedErrorMsg) error; signalMeterError(meterError, op); } } break; default: break; } } @Override public void switchAdded(Dpid dpid) { createStatsCollection(controller.getSwitch(dpid)); pushMeterFeatures(dpid, controller.getSwitch(dpid).getMeterFeatures()); } @Override public void switchRemoved(Dpid dpid) { stopCollectorIfNeeded(collectors.remove(dpid)); destroyMeterFeatures(dpid); } @Override public void switchChanged(Dpid dpid) { } @Override public void portChanged(Dpid dpid, OFPortStatus status) { } @Override public void receivedRoleReply(Dpid dpid, RoleState requested, RoleState response) { } } }
/* * Copyright (C) 2014 Indeed 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.indeed.lsmtree.core; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Ordering; import com.google.common.io.ByteStreams; import com.indeed.util.core.io.Closeables2; import com.indeed.util.core.reference.SharedReference; import com.indeed.util.io.BufferedFileDataOutputStream; import com.indeed.util.serialization.Serializer; import org.apache.log4j.Logger; import javax.annotation.Nullable; import java.io.BufferedInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; /** * @author jplaisance */ public final class VolatileGeneration<K, V> implements Generation<K,V> { private static final Logger log = Logger.getLogger(VolatileGeneration.class); private final TransactionLog.Writer transactionLog; private final Object deleted; private final ConcurrentSkipListMap<K, Object> map; private final File logPath; private final Serializer<K> keySerializer; private final Serializer<V> valueSerializer; private final Ordering<K> ordering; private final SharedReference<Closeable> stuffToClose; public VolatileGeneration(File logPath, Serializer<K> keySerializer, Serializer<V> valueSerializer, Comparator<K> comparator) throws IOException { this(logPath, keySerializer, valueSerializer, comparator, false); } public VolatileGeneration(File logPath, Serializer<K> keySerializer, Serializer<V> valueSerializer, Comparator<K> comparator, boolean loadExistingReadOnly) throws IOException { this.ordering = Ordering.from(comparator); map = new ConcurrentSkipListMap(comparator); this.logPath = logPath; this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; deleted = new Object(); if (loadExistingReadOnly) { if (!logPath.exists()) throw new IllegalArgumentException(logPath.getAbsolutePath()+" does not exist"); transactionLog = null; replayTransactionLog(logPath, true); } else { if (logPath.exists()) throw new IllegalArgumentException("to load existing logs set loadExistingReadOnly to true or create a new log and use replayTransactionLog"); transactionLog = new TransactionLog.Writer(logPath, keySerializer, valueSerializer, false); } stuffToClose = SharedReference.create((Closeable)new Closeable() { public void close() throws IOException { closeWriter(); } }); } public void replayTransactionLog(File path) throws IOException { replayTransactionLog(path, false); } private void replayTransactionLog(File path, boolean readOnly) throws IOException { final TransactionLog.Reader<K, V> reader = new TransactionLog.Reader(path, keySerializer, valueSerializer); try { while (reader.next()) { final K key = reader.getKey(); switch (reader.getType()) { case PUT: final V value = reader.getValue(); if (!readOnly) transactionLog.put(key, value); map.put(key, value); break; case DELETE: if (!readOnly) transactionLog.delete(key); map.put(key, deleted); break; } } } catch (TransactionLog.LogClosedException e) { //shouldn't happen here ever log.error("log is closed and it shouldn't be", e); throw new IOException(e); } finally { reader.close(); if (!readOnly) transactionLog.sync(); } } public void put(K key, V value) throws IOException, TransactionLog.LogClosedException { transactionLog.put(key, value); map.put(key, value); } public void delete(K key) throws IOException, TransactionLog.LogClosedException { transactionLog.delete(key); map.put(key, deleted); } @Override public Entry<K, V> get(final K key) { final Object value = map.get(key); if (value == null) return null; if (value == deleted) return Entry.createDeleted(key); return Entry.create(key, (V)value); } @Override public Boolean isDeleted(final K key) { final Entry<K, V> result = get(key); return result == null ? null : (result.isDeleted() ? Boolean.TRUE : Boolean.FALSE); } @Override public Generation<K, V> head(K endKey, boolean inclusive) { return new FilteredGeneration<K, V>(this, stuffToClose.copy(), null, false, endKey, inclusive); } @Override public Generation<K, V> tail(K startKey, boolean inclusive) { return new FilteredGeneration<K, V>(this, stuffToClose.copy(), startKey, inclusive, null, false); } @Override public Generation<K, V> slice(K start, boolean startInclusive, K end, boolean endInclusive) { return new FilteredGeneration<K, V>(this, stuffToClose.copy(), start, startInclusive, end, endInclusive); } @Override public Generation<K, V> reverse() { return new ReverseGeneration<K, V>(this, stuffToClose.copy()); } @Override public long size() { return map.size(); } @Override public long sizeInBytes() throws IOException { return transactionLog == null ? 0 : transactionLog.sizeInBytes(); } @Override public boolean hasDeletions() { return true; } @Override public Iterator<Entry<K, V>> iterator() { return iterator(null, false); } @Override public Iterator<Entry<K, V>> iterator(final @Nullable K start, final boolean startInclusive) { return new AbstractIterator<Entry<K, V>>() { boolean initialized = false; K key; @Override protected Entry<K, V> computeNext() { final Map.Entry<K, Object> entry; if (!initialized) { initialized = true; if (start == null) { entry = map.firstEntry(); } else if (startInclusive) { entry = map.ceilingEntry(start); } else { entry = map.higherEntry(start); } } else { entry = map.higherEntry(key); } if (entry == null) { return endOfData(); } key = entry.getKey(); final Object value = entry.getValue(); if (value == deleted) return Entry.createDeleted(key); return Entry.create(key, (V)value); } }; } @Override public Iterator<Entry<K, V>> reverseIterator() { return reverseIterator(null, false); } @Override public Iterator<Entry<K, V>> reverseIterator(final @Nullable K start, final boolean startInclusive) { return new AbstractIterator<Entry<K, V>>() { boolean initialized = false; K key; @Override protected Entry<K, V> computeNext() { final Map.Entry<K, Object> entry; if (!initialized) { initialized = true; if (start == null) { entry = map.lastEntry(); } else if (startInclusive) { entry = map.floorEntry(start); } else { entry = map.lowerEntry(start); } } else { entry = map.lowerEntry(key); } if (entry == null) { return endOfData(); } key = entry.getKey(); final Object value = entry.getValue(); if (value == deleted) return Entry.createDeleted(key); return Entry.create(key, (V)value); } }; } @Override public Comparator<K> getComparator() { return ordering; } public void sync() throws IOException { if (transactionLog != null) transactionLog.sync(); } public void closeWriter() throws IOException { if (transactionLog != null) { transactionLog.close(); } } @Override public void close() throws IOException { stuffToClose.close(); } @Override public void delete() throws IOException { log.info("deleting "+getPath()); getPath().delete(); } @Override public File getPath() { return logPath; } @Override public void checkpoint(final File checkpointPath) throws IOException { BufferedFileDataOutputStream out = null; InputStream in = null; try { out = new BufferedFileDataOutputStream(new File(checkpointPath, logPath.getName())); in = new BufferedInputStream(new FileInputStream(logPath), 65536); ByteStreams.copy(in, out); out.sync(); } finally { if (out != null) out.close(); if (in != null) in.close(); } } }
package gov.nist.javax.sip.clientauthutils; import gov.nist.core.StackLogger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * The class takes standard Http Authentication details and returns a response according to the * MD5 algorithm * * @author Emil Ivov */ public class MessageDigestAlgorithm { /** * Calculates an http authentication response in accordance with rfc2617. * <p> * * @param algorithm a string indicating a pair of algorithms (MD5 (default), or MD5-sess) used * to produce the digest and a checksum. * @param hashUserNameRealmPasswd MD5 hash of (username:realm:password) * @param nonce_value A server-specified data string provided in the challenge. * @param cnonce_value an optional client-chosen value whose purpose is to foil chosen * plaintext attacks. * @param method the SIP method of the request being challenged. * @param digest_uri_value the value of the "uri" directive on the Authorization header in the * request. * @param entity_body the entity-body * @param qop_value Indicates what "quality of protection" the client has applied to the * message. * @param nc_value the hexadecimal count of the number of requests (including the current * request) that the client has sent with the nonce value in this request. * @return a digest response as defined in rfc2617 * @throws NullPointerException in case of incorrectly null parameters. */ static String calculateResponse(String algorithm, String hashUserNameRealmPasswd, String nonce_value, String nc_value, String cnonce_value, String method, String digest_uri_value, String entity_body, String qop_value, StackLogger stackLogger) { if (stackLogger.isLoggingEnabled()) { stackLogger.logDebug("trying to authenticate using : " + algorithm + ", "+ hashUserNameRealmPasswd + ", " + nonce_value + ", " + nc_value + ", " + cnonce_value + ", " + method + ", " + digest_uri_value + ", " + entity_body + ", " + qop_value); } if (hashUserNameRealmPasswd == null || method == null || digest_uri_value == null || nonce_value == null) throw new NullPointerException( "Null parameter to MessageDigestAlgorithm.calculateResponse()"); // The following follows closely the algorithm for generating a response // digest as specified by rfc2617 if (cnonce_value == null || cnonce_value.length() == 0) throw new NullPointerException( "cnonce_value may not be absent for MD5-Sess algorithm."); String A2 = null; if (qop_value == null || qop_value.trim().length() == 0 || qop_value.trim().equalsIgnoreCase("auth")) { A2 = method + ":" + digest_uri_value; } else { if (entity_body == null) entity_body = ""; A2 = method + ":" + digest_uri_value + ":" + H(entity_body); } String request_digest = null; if (cnonce_value != null && qop_value != null && nc_value != null && (qop_value.equalsIgnoreCase("auth") || qop_value.equalsIgnoreCase("auth-int"))) { request_digest = KD(hashUserNameRealmPasswd, nonce_value + ":" + nc_value + ":" + cnonce_value + ":" + qop_value + ":" + H(A2)); } else { request_digest = KD(hashUserNameRealmPasswd, nonce_value + ":" + H(A2)); } return request_digest; } /** * Calculates an http authentication response in accordance with rfc2617. * <p> * * @param algorithm a string indicating a pair of algorithms (MD5 (default), or MD5-sess) used * to produce the digest and a checksum. * @param username_value username_value (see rfc2617) * @param realm_value A string that has been displayed to the user in order to determine the * context of the username and password to use. * @param passwd the password to encode in the challenge response. * @param nonce_value A server-specified data string provided in the challenge. * @param cnonce_value an optional client-chosen value whose purpose is to foil chosen * plaintext attacks. * @param method the SIP method of the request being challenged. * @param digest_uri_value the value of the "uri" directive on the Authorization header in the * request. * @param entity_body the entity-body * @param qop_value Indicates what "quality of protection" the client has applied to the * message. * @param nc_value the hexadecimal count of the number of requests (including the current * request) that the client has sent with the nonce value in this request. * @return a digest response as defined in rfc2617 * @throws NullPointerException in case of incorrectly null parameters. */ static String calculateResponse(String algorithm, String username_value, String realm_value, String passwd, String nonce_value, String nc_value, String cnonce_value, String method, String digest_uri_value, String entity_body, String qop_value, StackLogger stackLogger) { if (stackLogger.isLoggingEnabled()) { stackLogger.logDebug("trying to authenticate using : " + algorithm + ", " + username_value + ", " + realm_value + ", " + (passwd != null && passwd.trim().length() > 0) + ", " + nonce_value + ", " + nc_value + ", " + cnonce_value + ", " + method + ", " + digest_uri_value + ", " + entity_body + ", " + qop_value); } if (username_value == null || realm_value == null || passwd == null || method == null || digest_uri_value == null || nonce_value == null) throw new NullPointerException( "Null parameter to MessageDigestAlgorithm.calculateResponse()"); // The following follows closely the algorithm for generating a response // digest as specified by rfc2617 String A1 = null; if (algorithm == null || algorithm.trim().length() == 0 || algorithm.trim().equalsIgnoreCase("MD5")) { A1 = username_value + ":" + realm_value + ":" + passwd; } else { if (cnonce_value == null || cnonce_value.length() == 0) throw new NullPointerException( "cnonce_value may not be absent for MD5-Sess algorithm."); A1 = H(username_value + ":" + realm_value + ":" + passwd) + ":" + nonce_value + ":" + cnonce_value; } String A2 = null; if (qop_value == null || qop_value.trim().length() == 0 || qop_value.trim().equalsIgnoreCase("auth")) { A2 = method + ":" + digest_uri_value; } else { if (entity_body == null) entity_body = ""; A2 = method + ":" + digest_uri_value + ":" + H(entity_body); } String request_digest = null; if (cnonce_value != null && qop_value != null && nc_value != null && (qop_value.equalsIgnoreCase("auth") || qop_value.equalsIgnoreCase("auth-int"))) { request_digest = KD(H(A1), nonce_value + ":" + nc_value + ":" + cnonce_value + ":" + qop_value + ":" + H(A2)); } else { request_digest = KD(H(A1), nonce_value + ":" + H(A2)); } return request_digest; } /** * Defined in rfc 2617 as H(data) = MD5(data); * * @param data data * @return MD5(data) */ private static String H(String data) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); return toHexString(digest.digest(data.getBytes())); } catch (NoSuchAlgorithmException ex) { // shouldn't happen throw new RuntimeException("Failed to instantiate an MD5 algorithm", ex); } } /** * Defined in rfc 2617 as KD(secret, data) = H(concat(secret, ":", data)) * * @param data data * @param secret secret * @return H(concat(secret, ":", data)); */ private static String KD(String secret, String data) { return H(secret + ":" + data); } // the following code was copied from the NIST-SIP instant // messenger (its author is Olivier Deruelle). Thanks for making it public! /** * to hex converter */ private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * Converts b[] to hex string. * * @param b the bte array to convert * @return a Hex representation of b. */ private static String toHexString(byte b[]) { int pos = 0; char[] c = new char[b.length * 2]; for (int i = 0; i < b.length; i++) { c[pos++] = toHex[(b[i] >> 4) & 0x0F]; c[pos++] = toHex[b[i] & 0x0f]; } return new String(c); } }
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.arrow.vector; import io.netty.buffer.ArrowBuf; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.vector.complex.impl.DecimalReaderImpl; import org.apache.arrow.vector.complex.reader.FieldReader; import org.apache.arrow.vector.holders.DecimalHolder; import org.apache.arrow.vector.holders.NullableDecimalHolder; import org.apache.arrow.vector.types.Types; import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.util.DecimalUtility; import org.apache.arrow.vector.util.TransferPair; import java.math.BigDecimal; /** * DecimalVector implements a fixed width vector (16 bytes) of * decimal values which could be null. A validity buffer (bit vector) is * maintained to track which elements in the vector are null. */ public class DecimalVector extends BaseFixedWidthVector { public static final byte TYPE_WIDTH = 16; private final FieldReader reader; private final int precision; private final int scale; /** * Instantiate a DecimalVector. This doesn't allocate any memory for * the data in vector. * @param name name of the vector * @param allocator allocator for memory management. */ public DecimalVector(String name, BufferAllocator allocator, int precision, int scale) { this(name, FieldType.nullable(new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(precision, scale)), allocator); } /** * Instantiate a DecimalVector. This doesn't allocate any memory for * the data in vector. * @param name name of the vector * @param fieldType type of Field materialized by this vector * @param allocator allocator for memory management. */ public DecimalVector(String name, FieldType fieldType, BufferAllocator allocator) { super(name, allocator, fieldType, TYPE_WIDTH); org.apache.arrow.vector.types.pojo.ArrowType.Decimal arrowType = (org.apache.arrow.vector.types.pojo.ArrowType.Decimal) fieldType.getType(); reader = new DecimalReaderImpl(DecimalVector.this); this.precision = arrowType.getPrecision(); this.scale = arrowType.getScale(); } /** * Get a reader that supports reading values from this vector * @return Field Reader for this vector */ @Override public FieldReader getReader() { return reader; } /** * Get minor type for this vector. The vector holds values belonging * to a particular type. * @return {@link org.apache.arrow.vector.types.Types.MinorType} */ @Override public Types.MinorType getMinorType() { return Types.MinorType.DECIMAL; } /****************************************************************** * * * vector value retrieval methods * * * ******************************************************************/ /** * Get the element at the given index from the vector. * * @param index position of element * @return element at given index */ public ArrowBuf get(int index) throws IllegalStateException { if (isSet(index) == 0) { throw new IllegalStateException("Value at index is null"); } return valueBuffer.slice(index * TYPE_WIDTH, TYPE_WIDTH); } /** * Get the element at the given index from the vector and * sets the state in holder. If element at given index * is null, holder.isSet will be zero. * * @param index position of element */ public void get(int index, NullableDecimalHolder holder) { if (isSet(index) == 0) { holder.isSet = 0; return; } holder.isSet = 1; holder.buffer = valueBuffer; holder.precision = precision; holder.scale = scale; holder.start = index * TYPE_WIDTH; } /** * Same as {@link #get(int)}. * * @param index position of element * @return element at given index */ public BigDecimal getObject(int index) { if (isSet(index) == 0) { return null; } else { return DecimalUtility.getBigDecimalFromArrowBuf(valueBuffer, index, scale); } } /** * Copy a cell value from a particular index in source vector to a particular * position in this vector * @param fromIndex position to copy from in source vector * @param thisIndex position to copy to in this vector * @param from source vector */ public void copyFrom(int fromIndex, int thisIndex, DecimalVector from) { BitVectorHelper.setValidityBit(validityBuffer, thisIndex, from.isSet(fromIndex)); from.valueBuffer.getBytes(fromIndex * TYPE_WIDTH, valueBuffer, thisIndex * TYPE_WIDTH, TYPE_WIDTH); } /** * Same as {@link #copyFrom(int, int, DecimalVector)} except that * it handles the case when the capacity of the vector needs to be expanded * before copy. * @param fromIndex position to copy from in source vector * @param thisIndex position to copy to in this vector * @param from source vector */ public void copyFromSafe(int fromIndex, int thisIndex, DecimalVector from) { handleSafe(thisIndex); copyFrom(fromIndex, thisIndex, from); } /** * Return scale for the decimal value */ public int getScale() { return scale; } /****************************************************************** * * * vector value setter methods * * * ******************************************************************/ /** * Set the element at the given index to the given value. * * @param index position of element * @param buffer ArrowBuf containing decimal value. */ public void set(int index, ArrowBuf buffer) { BitVectorHelper.setValidityBitToOne(validityBuffer, index); valueBuffer.setBytes(index * TYPE_WIDTH, buffer, 0, TYPE_WIDTH); } /** * Set the decimal element at given index to the provided array of bytes. * Decimal is now implemented as Little Endian. This API allows the user * to pass a decimal value in the form of byte array in BE byte order. * * Consumers of Arrow code can use this API instead of first swapping * the source bytes (doing a write and read) and then finally writing to * ArrowBuf of decimal vector. * * This method takes care of adding the necessary padding if the length * of byte array is less then 16 (length of decimal type). * * @param index position of element * @param value array of bytes containing decimal in big endian byte order. */ public void setBigEndian(int index, byte[] value) { assert value.length <= TYPE_WIDTH; BitVectorHelper.setValidityBitToOne(validityBuffer, index); final int length = value.length; int startIndex = index * TYPE_WIDTH; if (length == TYPE_WIDTH) { for (int i = TYPE_WIDTH - 1; i >= 3; i-=4) { valueBuffer.setByte(startIndex, value[i]); valueBuffer.setByte(startIndex + 1, value[i-1]); valueBuffer.setByte(startIndex + 2, value[i-2]); valueBuffer.setByte(startIndex + 3, value[i-3]); startIndex += 4; } } else { for (int i = length - 1; i >= 0; i--) { valueBuffer.setByte(startIndex, value[i]); startIndex++; } valueBuffer.setZero(startIndex, TYPE_WIDTH - length); } } /** * Set the element at the given index to the given value. * * @param index position of element * @param start start index of data in the buffer * @param buffer ArrowBuf containing decimal value. */ public void set(int index, int start, ArrowBuf buffer) { BitVectorHelper.setValidityBitToOne(validityBuffer, index); valueBuffer.setBytes(index * TYPE_WIDTH, buffer, start, TYPE_WIDTH); } /** * Set the element at the given index to the given value. * * @param index position of element * @param value BigDecimal containing decimal value. */ public void set(int index, BigDecimal value) { BitVectorHelper.setValidityBitToOne(validityBuffer, index); DecimalUtility.checkPrecisionAndScale(value, precision, scale); DecimalUtility.writeBigDecimalToArrowBuf(value, valueBuffer, index); } /** * Set the element at the given index to the value set in data holder. * If the value in holder is not indicated as set, element in the * at the given index will be null. * * @param index position of element * @param holder nullable data holder for value of element */ public void set(int index, NullableDecimalHolder holder) throws IllegalArgumentException { if (holder.isSet < 0) { throw new IllegalArgumentException(); } else if (holder.isSet > 0) { BitVectorHelper.setValidityBitToOne(validityBuffer, index); valueBuffer.setBytes(index * TYPE_WIDTH, holder.buffer, holder.start, TYPE_WIDTH); } else { BitVectorHelper.setValidityBit(validityBuffer, index, 0); } } /** * Set the element at the given index to the value set in data holder. * * @param index position of element * @param holder data holder for value of element */ public void set(int index, DecimalHolder holder) { BitVectorHelper.setValidityBitToOne(validityBuffer, index); valueBuffer.setBytes(index * TYPE_WIDTH, holder.buffer, holder.start, TYPE_WIDTH); } /** * Same as {@link #set(int, ArrowBuf)} except that it handles the * case when index is greater than or equal to existing * value capacity {@link #getValueCapacity()}. * * @param index position of element * @param buffer ArrowBuf containing decimal value. */ public void setSafe(int index, ArrowBuf buffer) { handleSafe(index); set(index, buffer); } /** * Same as {@link #setBigEndian(int, byte[])} except that it handles the * case when index is greater than or equal to existing * value capacity {@link #getValueCapacity()}. */ public void setBigEndianSafe(int index, byte[] value) { handleSafe(index); setBigEndian(index, value); } /** * Same as {@link #set(int, int, ArrowBuf)} except that it handles the * case when index is greater than or equal to existing * value capacity {@link #getValueCapacity()}. * * @param index position of element * @param start start index of data in the buffer * @param buffer ArrowBuf containing decimal value. */ public void setSafe(int index, int start, ArrowBuf buffer) { handleSafe(index); set(index, start, buffer); } /** * Same as {@link #set(int, BigDecimal)} except that it handles the * case when index is greater than or equal to existing * value capacity {@link #getValueCapacity()}. * * @param index position of element * @param value BigDecimal containing decimal value. */ public void setSafe(int index, BigDecimal value) { handleSafe(index); set(index, value); } /** * Same as {@link #set(int, NullableDecimalHolder)} except that it handles the * case when index is greater than or equal to existing * value capacity {@link #getValueCapacity()}. * * @param index position of element * @param holder nullable data holder for value of element */ public void setSafe(int index, NullableDecimalHolder holder) throws IllegalArgumentException { handleSafe(index); set(index, holder); } /** * Same as {@link #set(int, DecimalHolder)} except that it handles the * case when index is greater than or equal to existing * value capacity {@link #getValueCapacity()}. * * @param index position of element * @param holder data holder for value of element */ public void setSafe(int index, DecimalHolder holder) { handleSafe(index); set(index, holder); } /** * Set the element at the given index to null. * * @param index position of element */ public void setNull(int index) { handleSafe(index); /* not really needed to set the bit to 0 as long as * the buffer always starts from 0. */ BitVectorHelper.setValidityBit(validityBuffer, index, 0); } /** * Store the given value at a particular position in the vector. isSet indicates * whether the value is NULL or not. * @param index position of the new value * @param isSet 0 for NULL value, 1 otherwise * @param start start position of the value in the buffer * @param buffer buffer containing the value to be stored in the vector */ public void set(int index, int isSet, int start, ArrowBuf buffer) { if (isSet > 0) { set(index, start, buffer); } else { BitVectorHelper.setValidityBit(validityBuffer, index, 0); } } /** * Same as {@link #setSafe(int, int, int, ArrowBuf)} except that it handles * the case when the position of new value is beyond the current value * capacity of the vector. * @param index position of the new value * @param isSet 0 for NULL value, 1 otherwise * @param start start position of the value in the buffer * @param buffer buffer containing the value to be stored in the vector */ public void setSafe(int index, int isSet, int start, ArrowBuf buffer) { handleSafe(index); set(index, isSet, start, buffer); } /****************************************************************** * * * vector transfer * * * ******************************************************************/ /** * Construct a TransferPair comprising of this and and a target vector of * the same type. * @param ref name of the target vector * @param allocator allocator for the target vector * @return {@link TransferPair} */ @Override public TransferPair getTransferPair(String ref, BufferAllocator allocator) { return new TransferImpl(ref, allocator); } /** * Construct a TransferPair with a desired target vector of the same type. * @param to target vector * @return {@link TransferPair} */ @Override public TransferPair makeTransferPair(ValueVector to) { return new TransferImpl((DecimalVector) to); } private class TransferImpl implements TransferPair { DecimalVector to; public TransferImpl(String ref, BufferAllocator allocator) { to = new DecimalVector(ref, allocator, DecimalVector.this.precision, DecimalVector.this.scale); } public TransferImpl(DecimalVector to) { this.to = to; } @Override public DecimalVector getTo() { return to; } @Override public void transfer() { transferTo(to); } @Override public void splitAndTransfer(int startIndex, int length) { splitAndTransferTo(startIndex, length, to); } @Override public void copyValueSafe(int fromIndex, int toIndex) { to.copyFromSafe(fromIndex, toIndex, DecimalVector.this); } } }
/******************************************************************************* * * Copyright (c) 2004-2010 Oracle Corporation. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Kohsuke Kawaguchi * * *******************************************************************************/ package hudson.util; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.converters.collections.MapConverter; import com.thoughtworks.xstream.converters.collections.TreeMapConverter; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.mapper.Mapper; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * {@link Map} that has copy-on-write semantics. * * <p> This class is suitable where highly concurrent access is needed, yet the * write operation is relatively uncommon. * * @author Kohsuke Kawaguchi */ public abstract class CopyOnWriteMap<K, V> implements Map<K, V> { protected volatile Map<K, V> core; /** * Read-only view of {@link #core}. */ private volatile Map<K, V> view; protected CopyOnWriteMap(Map<K, V> core) { update(core); } protected CopyOnWriteMap() { update(Collections.<K, V>emptyMap()); } protected void update(Map<K, V> m) { core = m; view = Collections.unmodifiableMap(core); } public int size() { return core.size(); } public boolean isEmpty() { return core.isEmpty(); } public boolean containsKey(Object key) { return core.containsKey(key); } public boolean containsValue(Object value) { return core.containsValue(value); } public V get(Object key) { return core.get(key); } public synchronized V put(K key, V value) { Map<K, V> m = copy(); V r = m.put(key, value); update(m); return r; } public synchronized V remove(Object key) { Map<K, V> m = copy(); V r = m.remove(key); update(m); return r; } public synchronized void putAll(Map<? extends K, ? extends V> t) { Map<K, V> m = copy(); m.putAll(t); update(m); } protected abstract Map<K, V> copy(); public synchronized void clear() { update(Collections.<K, V>emptyMap()); } /** * This method will return a read-only {@link Set}. */ public Set<K> keySet() { return view.keySet(); } /** * This method will return a read-only {@link Collection}. */ public Collection<V> values() { return view.values(); } /** * This method will return a read-only {@link Set}. */ public Set<Entry<K, V>> entrySet() { return view.entrySet(); } /** * {@link CopyOnWriteMap} backed by {@link HashMap}. */ public static final class Hash<K, V> extends CopyOnWriteMap<K, V> { public Hash(Map<K, V> core) { super(new LinkedHashMap<K, V>(core)); } public Hash() { } protected Map<K, V> copy() { return new LinkedHashMap<K, V>(core); } public static class ConverterImpl extends MapConverter { public ConverterImpl(Mapper mapper) { super(mapper); } @Override public boolean canConvert(Class type) { return type == Hash.class; } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { return new Hash((Map) super.unmarshal(reader, context)); } @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { super.marshal(((Hash) source).core, writer, context); } } } /** * {@link CopyOnWriteMap} backed by {@link TreeMap}. */ public static final class Tree<K, V> extends CopyOnWriteMap<K, V> { private final Comparator<K> comparator; public Tree(Map<K, V> core, Comparator<K> comparator) { this(comparator); putAll(core); } public Tree(Comparator<K> comparator) { super(new TreeMap<K, V>(comparator)); this.comparator = comparator; } public Tree() { this(null); } protected Map<K, V> copy() { TreeMap<K, V> m = new TreeMap<K, V>(comparator); m.putAll(core); return m; } @Override public synchronized void clear() { update(new TreeMap<K, V>(comparator)); } public static class ConverterImpl extends TreeMapConverter { public ConverterImpl(Mapper mapper) { super(mapper); } @Override public boolean canConvert(Class type) { return type == Tree.class; } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { TreeMap tm = (TreeMap) super.unmarshal(reader, context); return new Tree(tm, tm.comparator()); } @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { super.marshal(((Tree) source).core, writer, context); } } } }
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.support.ui; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriverException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; /** * An implementation of the {@link Wait} interface that may have its timeout and polling interval * configured on the fly. * * <p> * Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as * the frequency with which to check the condition. Furthermore, the user may configure the wait to * ignore specific types of exceptions whilst waiting, such as * {@link org.openqa.selenium.NoSuchElementException NoSuchElementExceptions} when searching for an * element on the page. * * <p> * Sample usage: <pre> * // Waiting 30 seconds for an element to be present on the page, checking * // for its presence once every 5 seconds. * Wait&lt;WebDriver&gt; wait = new FluentWait&lt;WebDriver&gt;(driver) * .withTimeout(30, SECONDS) * .pollingEvery(5, SECONDS) * .ignoring(NoSuchElementException.class); * * WebElement foo = wait.until(new Function&lt;WebDriver, WebElement&gt;() { * public WebElement apply(WebDriver driver) { * return driver.findElement(By.id("foo")); * } * }); * </pre> * * <p> * <em>This class makes no thread safety guarantees.</em> * * @param <T> The input type for each condition used with this instance. */ public class FluentWait<T> implements Wait<T> { protected final static long DEFAULT_SLEEP_TIMEOUT = 500; /** * @deprecated use {@link #DEFAULT_WAIT_DURATION} */ @Deprecated public static final Duration FIVE_HUNDRED_MILLIS = new Duration(DEFAULT_SLEEP_TIMEOUT, MILLISECONDS); private static final java.time.Duration DEFAULT_WAIT_DURATION = java.time.Duration.ofMillis(DEFAULT_SLEEP_TIMEOUT); private final T input; private final java.time.Clock clock; private final Sleeper sleeper; private java.time.Duration timeout = DEFAULT_WAIT_DURATION; private java.time.Duration interval = DEFAULT_WAIT_DURATION; private Supplier<String> messageSupplier = () -> null; private List<Class<? extends Throwable>> ignoredExceptions = new ArrayList<>(); /** * @param input The input value to pass to the evaluated conditions. */ public FluentWait(T input) { this(input, new SystemClock(), Sleeper.SYSTEM_SLEEPER); } /** * @param input The input value to pass to the evaluated conditions. * @param clock The clock to use when measuring the timeout. * @param sleeper Used to put the thread to sleep between evaluation loops. */ @Deprecated public FluentWait(T input, Clock clock, Sleeper sleeper) { this(input, clock.asJreClock(), sleeper); } /** * @param input The input value to pass to the evaluated conditions. * @param clock The clock to use when measuring the timeout. * @param sleeper Used to put the thread to sleep between evaluation loops. */ public FluentWait(T input, java.time.Clock clock, Sleeper sleeper) { this.input = requireNonNull(input); this.clock = requireNonNull(clock); this.sleeper = requireNonNull(sleeper); } /** * Sets how long to wait for the evaluated condition to be true. The default timeout is * {@link #FIVE_HUNDRED_MILLIS}. * * @deprecated use {@link #withTimeout(java.time.Duration)} * * @param duration The timeout duration. * @param unit The unit of time. * @return A self reference. */ @Deprecated public FluentWait<T> withTimeout(long duration, TimeUnit unit) { return withTimeout(java.time.Duration.of(duration, toChronoUnit(unit))); } /** * Sets how long to wait for the evaluated condition to be true. The default timeout is * {@link #DEFAULT_WAIT_DURATION}. * * @param timeout The timeout duration. * @return A self reference. */ public FluentWait<T> withTimeout(java.time.Duration timeout) { this.timeout = timeout; return this; } /** * Sets the message to be displayed when time expires. * * @param message to be appended to default. * @return A self reference. */ public FluentWait<T> withMessage(final String message) { this.messageSupplier = () -> message; return this; } /** * Sets the message to be evaluated and displayed when time expires. * * @param messageSupplier to be evaluated on failure and appended to default. * @return A self reference. */ public FluentWait<T> withMessage(Supplier<String> messageSupplier) { this.messageSupplier = messageSupplier; return this; } /** * Sets how often the condition should be evaluated. * * <p> * In reality, the interval may be greater as the cost of actually evaluating a condition function * is not factored in. The default polling interval is {@link #FIVE_HUNDRED_MILLIS}. * * @deprecated use {@link #pollingEvery(java.time.Duration)} * * @param duration The timeout duration. * @param unit The unit of time. * @return A self reference. */ @Deprecated public FluentWait<T> pollingEvery(long duration, TimeUnit unit) { return pollingEvery(java.time.Duration.of(duration, toChronoUnit(unit))); } /** * Sets how often the condition should be evaluated. * * <p> * In reality, the interval may be greater as the cost of actually evaluating a condition function * is not factored in. The default polling interval is {@link #DEFAULT_WAIT_DURATION}. * * @param interval The timeout duration. * @return A self reference. */ public FluentWait<T> pollingEvery(java.time.Duration interval) { this.interval = interval; return this; } /** * Configures this instance to ignore specific types of exceptions while waiting for a condition. * Any exceptions not whitelisted will be allowed to propagate, terminating the wait. * * @param types The types of exceptions to ignore. * @param <K> an Exception that extends Throwable * @return A self reference. */ public <K extends Throwable> FluentWait<T> ignoreAll(Collection<Class<? extends K>> types) { ignoredExceptions.addAll(types); return this; } /** * @see #ignoreAll(Collection) * @param exceptionType exception to ignore * @return a self reference */ public FluentWait<T> ignoring(Class<? extends Throwable> exceptionType) { return this.ignoreAll(ImmutableList.<Class<? extends Throwable>>of(exceptionType)); } /** * @see #ignoreAll(Collection) * @param firstType exception to ignore * @param secondType another exception to ignore * @return a self reference */ public FluentWait<T> ignoring(Class<? extends Throwable> firstType, Class<? extends Throwable> secondType) { return this.ignoreAll(ImmutableList.of(firstType, secondType)); } /** * Repeatedly applies this instance's input value to the given function until one of the following * occurs: * <ol> * <li>the function returns neither null nor false</li> * <li>the function throws an unignored exception</li> * <li>the timeout expires</li> * <li>the current thread is interrupted</li> * </ol> * * @param isTrue the parameter to pass to the {@link ExpectedCondition} * @param <V> The function's expected return type. * @return The function's return value if the function returned something different * from null or false before the timeout expired. * @throws TimeoutException If the timeout expires. */ @Override public <V> V until(Function<? super T, V> isTrue) { Instant end = clock.instant().plus(timeout); Throwable lastException; while (true) { try { V value = isTrue.apply(input); if (value != null && (Boolean.class != value.getClass() || Boolean.TRUE.equals(value))) { return value; } // Clear the last exception; if another retry or timeout exception would // be caused by a false or null value, the last exception is not the // cause of the timeout. lastException = null; } catch (Throwable e) { lastException = propagateIfNotIgnored(e); } // Check the timeout after evaluating the function to ensure conditions // with a zero timeout can succeed. if (end.isBefore(clock.instant())) { String message = messageSupplier != null ? messageSupplier.get() : null; String timeoutMessage = String.format( "Expected condition failed: %s (tried for %d second(s) with %d milliseconds interval)", message == null ? "waiting for " + isTrue : message, timeout.getSeconds(), interval.toMillis()); throw timeoutException(timeoutMessage, lastException); } try { sleeper.sleep(interval); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new WebDriverException(e); } } } private Throwable propagateIfNotIgnored(Throwable e) { for (Class<? extends Throwable> ignoredException : ignoredExceptions) { if (ignoredException.isInstance(e)) { return e; } } Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } /** * Throws a timeout exception. This method may be overridden to throw an exception that is * idiomatic for a particular test infrastructure, such as an AssertionError in JUnit4. * * @param message The timeout message. * @param lastException The last exception to be thrown and subsequently suppressed while waiting * on a function. * @return Nothing will ever be returned; this return type is only specified as a convenience. */ protected RuntimeException timeoutException(String message, Throwable lastException) { throw new TimeoutException(message, lastException); } /** * Converts the {@code TimeUnit} to the equivalent {@code ChronoUnit}. * * This is a backport from Java 9, see https://bugs.openjdk.java.net/browse/JDK-8141452. * * @param timeUnit the TimeUnit to convert * @return the converted equivalent ChronoUnit */ private ChronoUnit toChronoUnit(TimeUnit timeUnit) { switch (timeUnit) { case NANOSECONDS: return ChronoUnit.NANOS; case MICROSECONDS: return ChronoUnit.MICROS; case MILLISECONDS: return ChronoUnit.MILLIS; case SECONDS: return ChronoUnit.SECONDS; case MINUTES: return ChronoUnit.MINUTES; case HOURS: return ChronoUnit.HOURS; case DAYS: return ChronoUnit.DAYS; default: throw new IllegalArgumentException("No ChronoUnit equivalent for " + timeUnit); } } }
/** * 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.websocket; import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.io.Closeable; import java.io.IOException; import java.net.MalformedURLException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.websocket.DeploymentException; import org.apache.bookkeeper.common.util.OrderedScheduler; import org.apache.pulsar.broker.PulsarServerException; import org.apache.pulsar.broker.ServiceConfiguration; import org.apache.pulsar.broker.authentication.AuthenticationService; import org.apache.pulsar.broker.authorization.AuthorizationService; import org.apache.pulsar.broker.cache.ConfigurationCacheService; import org.apache.pulsar.client.api.ClientBuilder; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.PulsarClientException; import org.apache.pulsar.common.configuration.PulsarConfigurationLoader; import org.apache.pulsar.common.policies.data.ClusterData; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap; import org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet; import org.apache.pulsar.websocket.service.WebSocketProxyConfiguration; import org.apache.pulsar.websocket.stats.ProxyStats; import org.apache.pulsar.zookeeper.GlobalZooKeeperCache; import org.apache.pulsar.zookeeper.ZooKeeperCache; import org.apache.pulsar.zookeeper.ZooKeeperClientFactory; import org.apache.pulsar.zookeeper.ZookeeperClientFactoryImpl; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.util.concurrent.DefaultThreadFactory; /** * Socket proxy server which initializes other dependent services and starts server by opening web-socket end-point url. * */ public class WebSocketService implements Closeable { public static final int MaxTextFrameSize = 1024 * 1024; AuthenticationService authenticationService; AuthorizationService authorizationService; PulsarClient pulsarClient; private final ScheduledExecutorService executor = Executors .newScheduledThreadPool(WebSocketProxyConfiguration.WEBSOCKET_SERVICE_THREADS, new DefaultThreadFactory("pulsar-websocket")); private final OrderedScheduler orderedExecutor = OrderedScheduler.newSchedulerBuilder() .numThreads(WebSocketProxyConfiguration.GLOBAL_ZK_THREADS).name("pulsar-websocket-ordered").build(); private GlobalZooKeeperCache globalZkCache; private ZooKeeperClientFactory zkClientFactory; private ServiceConfiguration config; private ConfigurationCacheService configurationCacheService; private ClusterData localCluster; private final ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<ProducerHandler>> topicProducerMap; private final ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<ConsumerHandler>> topicConsumerMap; private final ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<ReaderHandler>> topicReaderMap; private final ProxyStats proxyStats; public WebSocketService(WebSocketProxyConfiguration config) { this(createClusterData(config), PulsarConfigurationLoader.convertFrom(config)); } public WebSocketService(ClusterData localCluster, ServiceConfiguration config) { this.config = config; this.localCluster = localCluster; this.topicProducerMap = new ConcurrentOpenHashMap<>(); this.topicConsumerMap = new ConcurrentOpenHashMap<>(); this.topicReaderMap = new ConcurrentOpenHashMap<>(); this.proxyStats = new ProxyStats(this); } public void start() throws PulsarServerException, PulsarClientException, MalformedURLException, ServletException, DeploymentException { if (isNotBlank(config.getConfigurationStoreServers())) { this.globalZkCache = new GlobalZooKeeperCache(getZooKeeperClientFactory(), (int) config.getZooKeeperSessionTimeoutMillis(), config.getConfigurationStoreServers(), this.orderedExecutor, this.executor); try { this.globalZkCache.start(); } catch (IOException e) { throw new PulsarServerException(e); } this.configurationCacheService = new ConfigurationCacheService(getGlobalZkCache()); log.info("Global Zookeeper cache started"); } // start authorizationService if (config.isAuthorizationEnabled()) { if (configurationCacheService == null) { throw new PulsarServerException( "Failed to initialize authorization manager due to empty ConfigurationStoreServers"); } authorizationService = new AuthorizationService(this.config, configurationCacheService); } // start authentication service authenticationService = new AuthenticationService(this.config); log.info("Pulsar WebSocket Service started"); } @Override public void close() throws IOException { if (pulsarClient != null) { pulsarClient.close(); } if (authenticationService != null) { authenticationService.close(); } if (globalZkCache != null) { globalZkCache.close(); } executor.shutdown(); orderedExecutor.shutdown(); } public AuthenticationService getAuthenticationService() { return authenticationService; } public AuthorizationService getAuthorizationService() { return authorizationService; } public ZooKeeperCache getGlobalZkCache() { return globalZkCache; } public ZooKeeperClientFactory getZooKeeperClientFactory() { if (zkClientFactory == null) { zkClientFactory = new ZookeeperClientFactoryImpl(); } // Return default factory return zkClientFactory; } public synchronized PulsarClient getPulsarClient() throws IOException { // Do lazy initialization of client if (pulsarClient == null) { if (localCluster == null) { // If not explicitly set, read clusters data from ZK localCluster = retrieveClusterData(); } pulsarClient = createClientInstance(localCluster); } return pulsarClient; } private PulsarClient createClientInstance(ClusterData clusterData) throws IOException { ClientBuilder clientBuilder = PulsarClient.builder() // .statsInterval(0, TimeUnit.SECONDS) // .enableTls(config.isTlsEnabled()) // .allowTlsInsecureConnection(config.isTlsAllowInsecureConnection()) // .tlsTrustCertsFilePath(config.getBrokerClientTrustCertsFilePath()) // .ioThreads(config.getWebSocketNumIoThreads()) // .connectionsPerBroker(config.getWebSocketConnectionsPerBroker()); if (isNotBlank(config.getBrokerClientAuthenticationPlugin()) && isNotBlank(config.getBrokerClientAuthenticationParameters())) { clientBuilder.authentication(config.getBrokerClientAuthenticationPlugin(), config.getBrokerClientAuthenticationParameters()); } if (config.isBrokerClientTlsEnabled()) { if (isNotBlank(clusterData.getBrokerServiceUrlTls())) { clientBuilder.serviceUrl(clusterData.getBrokerServiceUrlTls()); } else if (isNotBlank(clusterData.getServiceUrlTls())) { clientBuilder.serviceUrl(clusterData.getServiceUrlTls()); } } else if (isNotBlank(clusterData.getBrokerServiceUrl())) { clientBuilder.serviceUrl(clusterData.getBrokerServiceUrl()); } else { clientBuilder.serviceUrl(clusterData.getServiceUrl()); } return clientBuilder.build(); } private static ClusterData createClusterData(WebSocketProxyConfiguration config) { if (isNotBlank(config.getBrokerServiceUrl()) || isNotBlank(config.getBrokerServiceUrlTls())) { return new ClusterData(config.getServiceUrl(), config.getServiceUrlTls(), config.getBrokerServiceUrl(), config.getBrokerServiceUrlTls()); } else if (isNotBlank(config.getServiceUrl()) || isNotBlank(config.getServiceUrlTls())) { return new ClusterData(config.getServiceUrl(), config.getServiceUrlTls()); } else { return null; } } private ClusterData retrieveClusterData() throws PulsarServerException { if (configurationCacheService == null) { throw new PulsarServerException( "Failed to retrieve Cluster data due to empty ConfigurationStoreServers"); } try { String path = "/admin/clusters/" + config.getClusterName(); return localCluster = configurationCacheService.clustersCache().get(path) .orElseThrow(() -> new KeeperException.NoNodeException(path)); } catch (Exception e) { throw new PulsarServerException(e); } } public ProxyStats getProxyStats() { return proxyStats; } public ConfigurationCacheService getConfigurationCache() { return configurationCacheService; } public ScheduledExecutorService getExecutor() { return executor; } public boolean isAuthenticationEnabled() { if (this.config == null) return false; return this.config.isAuthenticationEnabled(); } public boolean isAuthorizationEnabled() { if (this.config == null) return false; return this.config.isAuthorizationEnabled(); } public boolean addProducer(ProducerHandler producer) { return topicProducerMap .computeIfAbsent(producer.getProducer().getTopic(), topic -> new ConcurrentOpenHashSet<>()) .add(producer); } public ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<ProducerHandler>> getProducers() { return topicProducerMap; } public boolean removeProducer(ProducerHandler producer) { final String topicName = producer.getProducer().getTopic(); if (topicProducerMap.containsKey(topicName)) { return topicProducerMap.get(topicName).remove(producer); } return false; } public boolean addConsumer(ConsumerHandler consumer) { return topicConsumerMap .computeIfAbsent(consumer.getConsumer().getTopic(), topic -> new ConcurrentOpenHashSet<>()) .add(consumer); } public ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<ConsumerHandler>> getConsumers() { return topicConsumerMap; } public boolean removeConsumer(ConsumerHandler consumer) { final String topicName = consumer.getConsumer().getTopic(); if (topicConsumerMap.containsKey(topicName)) { return topicConsumerMap.get(topicName).remove(consumer); } return false; } public boolean addReader(ReaderHandler reader) { return topicReaderMap.computeIfAbsent(reader.getConsumer().getTopic(), topic -> new ConcurrentOpenHashSet<>()) .add(reader); } public ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<ReaderHandler>> getReaders() { return topicReaderMap; } public boolean removeReader(ReaderHandler reader) { final String topicName = reader.getConsumer().getTopic(); if (topicReaderMap.containsKey(topicName)) { return topicReaderMap.get(topicName).remove(reader); } return false; } public ServiceConfiguration getConfig() { return config; } private static final Logger log = LoggerFactory.getLogger(WebSocketService.class); }
package game.menu; import game.graphics.GameGraphics; import game.graphics.Images; import game.graphics.SpriteSheet; import game.graphics.WindowBorderRenderer; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Transparency; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; /** * Handles Popup Messages that appear above a character or item in the game. * * TODO look into this * http://docs.oracle.com/javase/7/docs/api/java/awt/font/TextLayout.html * * @author Aaron Carson * @version Jul 19, 2015 */ public class MultiLineMessage implements Message { private String[] text; private Color color; private int alignment; private boolean drawBorder; private SpriteSheet spriteSheet; /** * Create a message to be rendered to the screen. * * @param text The text to render. * @param color the color of the text to render. */ public MultiLineMessage(String text, Color color, int alignment, boolean border) { this.text = text.split("\n"); this.color = color; this.alignment = alignment; this.drawBorder = border; this.spriteSheet = new SpriteSheet(Images.MENU_BORDER, 8); } /** * Create a new Text that renders in white, centered, with a border. * * @param text */ public MultiLineMessage(String text) { this(text, DEFAULT_COLOR, CENTER, true); } public boolean rendered = false; public BufferedImage windowImage; /** * Render the given text to the screen. * * @param g The text to render. * @param x The x coordinate. * @param y The y coordinate. * @param transparency the alpha value to render at. */ public void render(Graphics2D g, int x, int y, float transparency) { g.setFont(FONT); TextLayout[] layouts = new TextLayout[text.length]; TextLayout tl = new TextLayout(text[0], FONT, g.getFontRenderContext()); layouts[0] = tl; Rectangle2D bounds = tl.getBounds(); for(int i = 1; i < text.length; i++){ TextLayout next = new TextLayout(text[i], FONT, g.getFontRenderContext()); layouts[i] = next; Rectangle2D nBounds = next.getBounds(); if (nBounds.getWidth() > bounds.getWidth()){ tl = next; bounds = nBounds; } } float xOff; switch (alignment) { case RIGHT: xOff = (float)bounds.getWidth(); break; case CENTER: xOff = (float)bounds.getWidth() / 2; break; case LEFT: default: xOff = 0; break; } int xPadding = 8; int yPadding = 8; int lineSpacing = 4; /* bounds.setRect(bounds.getX() + x,// - xOff, bounds.getY() + y,//+ yOff, bounds.getWidth(), bounds.getHeight() ); */ if(!rendered){ rendered = true; float tHeight = tl.getAscent() + tl.getDescent() + lineSpacing; System.out.printf("boundsHeight: %f text.length: %d\n", bounds.getHeight(), text.length); windowImage = createBorderImage((int)bounds.getWidth(), (int) tHeight * text.length - lineSpacing, xPadding, yPadding); Graphics2D wg = windowImage.createGraphics(); int xPad = spriteSheet.getTileWidth(); int yPad = spriteSheet.getTileHeight(); wg.setColor(Color.BLACK); wg.fillRect(xPad, yPad, windowImage.getWidth() - xPad * 2, windowImage.getHeight() - yPad * 2); int cwx = windowImage.getWidth() / 2; int cwy = windowImage.getHeight() / 2; wg.setColor(color); for(int i = 0; i < layouts.length; i++){ //Rectangle2D nBounds = layouts[i].getBounds(); layouts[i].draw(wg, cwx - xOff, 8 + yPadding + tl.getAscent() + tHeight * i ); } wg.dispose(); } //g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency)); g.drawImage(windowImage, x - windowImage.getWidth() / 2, y - windowImage.getHeight() / 2, null); //g.setColor(Color.BLACK); //g.fill(bounds); //g.setColor(Color.WHITE); //tl.draw(g, x - xOff, y + yOff); } /** * Create a BufferedImage bordered by this WindowBorder, that encloses * the given width and height, and has the given padding. * @param w The width to enclose * @param h The height to enclose * @param xPadding * @param yPadding * @return */ public BufferedImage createBorderImage(int w, int h, int xPadding, int yPadding) { GraphicsConfiguration gc = GameGraphics.getGraphicsConfiguration(); int tileWidth = spriteSheet.getTileWidth(); int tileHeight = spriteSheet.getTileWidth(); // calculate the dimensions of the image. int width = (xPadding + tileWidth) * 2 + w; int height = (yPadding + tileHeight) * 2 + h; BufferedImage image = gc.createCompatibleImage(width, height,Transparency.TRANSLUCENT); Graphics2D g = image.createGraphics(); WindowBorderRenderer windowBorder = new WindowBorderRenderer(); windowBorder.render(g, 0,0, width, height); /* //g.setColor(Color.PINK); //g.fillRect(0, 0, width, height); int top = 1; int bottom = 1 + spriteSheet.getWidth() * 2; int left = 0 + spriteSheet.getWidth() * 1; int right = 2 + spriteSheet.getWidth() * 1; int topLeft = 0; int topRight = 2; int bottomLeft = 0 + spriteSheet.getWidth() * 2; int bottomRight = 2 + spriteSheet.getWidth() * 2; // draw the edges. //int widthInTiles = image.getWidth() / tileWidth; //int heightInTiles = image.getHeight() / tileHeight; int x, y; int xMax = width - tileWidth; int yMax = height - tileHeight; // draw along the top and bottom. for (x = tileWidth; x < width - tileWidth; x += tileWidth) { y = 0; spriteSheet.render(g, top, x, y); y = yMax; spriteSheet.render(g, bottom, x, y); } // draw along the left and right. for (y = tileWidth; y < height - tileHeight; y += tileHeight) { x = 0; spriteSheet.render(g, left, x, y); x = xMax; spriteSheet.render(g, right, x, y); } // draw the four corners. spriteSheet.render(g, topLeft, 0, 0); spriteSheet.render(g, topRight, xMax, 0); spriteSheet.render(g, bottomLeft, 0, yMax); spriteSheet.render(g, bottomRight, xMax, yMax); */ g.dispose(); return image; } }
/* * Copyright 2016 ThoughtWorks, 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.thoughtworks.go.helper; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.materials.*; import com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig; import com.thoughtworks.go.config.materials.git.GitMaterialConfig; import com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig; import com.thoughtworks.go.config.materials.perforce.P4MaterialConfig; import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig; import com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig; import com.thoughtworks.go.domain.config.Configuration; import com.thoughtworks.go.domain.config.ConfigurationKey; import com.thoughtworks.go.domain.config.ConfigurationProperty; import com.thoughtworks.go.domain.config.ConfigurationValue; import com.thoughtworks.go.domain.packagerepository.ConfigurationPropertyMother; import com.thoughtworks.go.domain.packagerepository.PackageDefinition; import com.thoughtworks.go.domain.packagerepository.PackageDefinitionMother; import com.thoughtworks.go.domain.packagerepository.PackageRepository; import com.thoughtworks.go.domain.packagerepository.PackageRepositoryMother; import com.thoughtworks.go.domain.scm.SCM; import com.thoughtworks.go.domain.scm.SCMMother; import com.thoughtworks.go.security.GoCipher; import com.thoughtworks.go.util.command.HgUrlArgument; import com.thoughtworks.go.util.command.UrlArgument; import static com.thoughtworks.go.util.DataStructureUtils.m; public class MaterialConfigsMother { public static MaterialConfigs defaultMaterialConfigs() { return defaultSvnMaterialConfigsWithUrl("http://some/svn/url"); } public static MaterialConfigs defaultSvnMaterialConfigsWithUrl(String svnUrl) { return new MaterialConfigs(svnMaterialConfig(svnUrl, "svnDir", null, null, false, null)); } public static MaterialConfigs multipleMaterialConfigs() { MaterialConfigs materialConfigs = new MaterialConfigs(); materialConfigs.add(svnMaterialConfig("http://svnurl", null)); materialConfigs.add(hgMaterialConfig("http://hgurl", "hgdir")); materialConfigs.add(dependencyMaterialConfig("cruise", "dev")); return materialConfigs; } public static PackageMaterialConfig packageMaterialConfig(){ return packageMaterialConfig("repo-name", "package-name"); } public static PackageMaterialConfig packageMaterialConfig(String repoName, String packageName) { PackageMaterialConfig material = new PackageMaterialConfig("p-id"); PackageRepository repository = PackageRepositoryMother.create("repo-id", repoName, "pluginid", "version", new Configuration(ConfigurationPropertyMother.create("k1", false, "repo-v1"), ConfigurationPropertyMother.create("k2", false, "repo-v2"))); PackageDefinition packageDefinition = PackageDefinitionMother.create("p-id", packageName, new Configuration(ConfigurationPropertyMother.create("k3", false, "package-v1")), repository); material.setPackageDefinition(packageDefinition); repository.getPackages().add(packageDefinition); return material; } public static PluggableSCMMaterialConfig pluggableSCMMaterialConfig() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); return pluggableSCMMaterialConfig("scm-id", "des-folder", filter); } public static PluggableSCMMaterialConfig pluggableSCMMaterialConfigWithConfigProperties(String... properties) { SCM scmConfig = SCMMother.create("scm-id"); Configuration configuration = new Configuration(); for (String property : properties) { ConfigurationProperty configurationProperty = new ConfigurationProperty(new ConfigurationKey(property), new ConfigurationValue(property+"-value")); configuration.add(configurationProperty); } scmConfig.setConfiguration(configuration); return new PluggableSCMMaterialConfig(null, scmConfig, "des-folder", null); } public static PluggableSCMMaterialConfig pluggableSCMMaterialConfig(String scmId, String destinationFolder, Filter filter) { return new PluggableSCMMaterialConfig(null, SCMMother.create(scmId), destinationFolder, filter); } public static DependencyMaterialConfig dependencyMaterialConfig(String pipelineName, String stageName) { return new DependencyMaterialConfig(new CaseInsensitiveString(pipelineName), new CaseInsensitiveString(stageName)); } public static DependencyMaterialConfig dependencyMaterialConfig() { return new DependencyMaterialConfig(new CaseInsensitiveString("pipeline-name"), new CaseInsensitiveString("stage-name")); } public static HgMaterialConfig hgMaterialConfigFull() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); return new HgMaterialConfig(new HgUrlArgument("http://user:pass@domain/path##branch"),true, filter, false, "dest-folder", new CaseInsensitiveString("hg-material") ); } public static HgMaterialConfig hgMaterialConfig() { return hgMaterialConfig("hg-url"); } public static HgMaterialConfig hgMaterialConfig(String url) { return hgMaterialConfig(url, null); } public static HgMaterialConfig hgMaterialConfig(String url, String folder) { return new HgMaterialConfig(url, folder); } public static GitMaterialConfig gitMaterialConfig(String url, String submoduleFolder, String branch, boolean shallowClone) { GitMaterialConfig gitMaterialConfig = new GitMaterialConfig(url, branch); gitMaterialConfig.setShallowClone(shallowClone); gitMaterialConfig.setSubmoduleFolder(submoduleFolder); return gitMaterialConfig; } public static GitMaterialConfig gitMaterialConfig() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); return new GitMaterialConfig(new UrlArgument("http://user:password@funk.com/blank"), "branch", "sub_module_folder", false, filter, false, "destination", new CaseInsensitiveString("AwesomeGitMaterial"), true); } public static GitMaterialConfig gitMaterialConfig(String url) { return new GitMaterialConfig(url); } public static P4MaterialConfig p4MaterialConfig() { return p4MaterialConfig("serverAndPort", null, null, "view", false); } public static P4MaterialConfig p4MaterialConfigFull() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); P4MaterialConfig config = p4MaterialConfig("host:9876", "user", "password", "view", true); config.setFolder("dest-folder"); config.setFilter(filter); config.setName(new CaseInsensitiveString("p4-material")); return config; } public static P4MaterialConfig p4MaterialConfig(String serverAndPort, String userName, String password, String view, boolean useTickets) { final P4MaterialConfig material = new P4MaterialConfig(serverAndPort, view); material.setConfigAttributes(m(P4MaterialConfig.USERNAME, userName, P4MaterialConfig.AUTO_UPDATE, "true")); material.setPassword(password); material.setUseTickets(useTickets); return material; } public static SvnMaterialConfig svnMaterialConfig() { return svnMaterialConfig("url", "svnDir"); } public static SvnMaterialConfig svnMaterialConfig(String svnUrl, String folder, CaseInsensitiveString name) { SvnMaterialConfig svnMaterialConfig = svnMaterialConfig(svnUrl, folder); svnMaterialConfig.setName(name); return svnMaterialConfig; } public static SvnMaterialConfig svnMaterialConfig(String svnUrl, String folder) { return svnMaterialConfig(svnUrl, folder, false); } public static SvnMaterialConfig svnMaterialConfig(String svnUrl, String folder, boolean autoUpdate) { SvnMaterialConfig materialConfig = new SvnMaterialConfig(new UrlArgument(svnUrl), "user", "pass", true, new GoCipher(), autoUpdate, new Filter(new IgnoredFiles("*.doc")), false, folder, new CaseInsensitiveString("svn-material")); materialConfig.setPassword("pass"); return materialConfig; } public static SvnMaterialConfig svnMaterialConfig(String svnUrl, String folder, String userName, String password, boolean checkExternals, String filterPattern) { SvnMaterialConfig svnMaterial = new SvnMaterialConfig(svnUrl, userName, password, checkExternals, folder); if (filterPattern != null) svnMaterial.setFilter(new Filter(new IgnoredFiles(filterPattern))); String name = svnUrl.replaceAll("/", "_"); name = name.replaceAll(":", "_"); svnMaterial.setName(new CaseInsensitiveString(name)); return svnMaterial; } public static HgMaterialConfig filteredHgMaterialConfig(String pattern) { HgMaterialConfig materialConfig = hgMaterialConfig(); materialConfig.setFilter(new Filter(new IgnoredFiles(pattern))); return materialConfig; } public static MaterialConfigs mockMaterialConfigs(String url) { return new MaterialConfigs(new SvnMaterialConfig(url, null, null, false)); } public static TfsMaterialConfig tfsMaterialConfig(){ Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); TfsMaterialConfig tfsMaterialConfig= new TfsMaterialConfig(new GoCipher(), new UrlArgument("http://10.4.4.101:8080/tfs/Sample"), "loser", "some_domain", "passwd", "walk_this_path"); tfsMaterialConfig.setFilter(filter); tfsMaterialConfig.setName(new CaseInsensitiveString("tfs-material")); tfsMaterialConfig.setFolder("dest-folder"); return tfsMaterialConfig; } }
package com.baoyz.swipemenulistview; import android.content.Context; import android.support.v4.view.GestureDetectorCompat; import android.support.v4.widget.ScrollerCompat; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector.OnGestureListener; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.animation.Interpolator; import android.widget.AbsListView; import android.widget.FrameLayout; /** * * @author baoyz * @date 2014-8-23 * */ public class SwipeMenuLayout extends FrameLayout { private static final int CONTENT_VIEW_ID = 1; private static final int MENU_VIEW_ID = 2; private static final int STATE_CLOSE = 0; private static final int STATE_OPEN = 1; private View mContentView; private SwipeMenuView mMenuView; private int mDownX; private int state = STATE_CLOSE; private GestureDetectorCompat mGestureDetector; private OnGestureListener mGestureListener; private boolean isFling; private int MIN_FLING = dp2px(15); private int MAX_VELOCITYX = -dp2px(500); private ScrollerCompat mOpenScroller; private ScrollerCompat mCloseScroller; private int mBaseX; private int position; private Interpolator mCloseInterpolator; private Interpolator mOpenInterpolator; public SwipeMenuLayout(View contentView, SwipeMenuView menuView) { this(contentView, menuView, null, null); } public SwipeMenuLayout(View contentView, SwipeMenuView menuView, Interpolator closeInterpolator, Interpolator openInterpolator) { super(contentView.getContext()); mCloseInterpolator = closeInterpolator; mOpenInterpolator = openInterpolator; mContentView = contentView; mMenuView = menuView; mMenuView.setLayout(this); init(); } // private SwipeMenuLayout(Context context, AttributeSet attrs, int // defStyle) { // super(context, attrs, defStyle); // } private SwipeMenuLayout(Context context, AttributeSet attrs) { super(context, attrs); } private SwipeMenuLayout(Context context) { super(context); } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; mMenuView.setPosition(position); } private void init() { setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mGestureListener = new SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { isFling = false; return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO if ((e1.getX() - e2.getX()) > MIN_FLING && velocityX < MAX_VELOCITYX) { isFling = true; } // Log.i("byz", MAX_VELOCITYX + ", velocityX = " + velocityX); return super.onFling(e1, e2, velocityX, velocityY); } }; mGestureDetector = new GestureDetectorCompat(getContext(), mGestureListener); // mScroller = ScrollerCompat.create(getContext(), new // BounceInterpolator()); if (mCloseInterpolator != null) { mCloseScroller = ScrollerCompat.create(getContext(), mCloseInterpolator); } else { mCloseScroller = ScrollerCompat.create(getContext()); } if (mOpenInterpolator != null) { mOpenScroller = ScrollerCompat.create(getContext(), mOpenInterpolator); } else { mOpenScroller = ScrollerCompat.create(getContext()); } LayoutParams contentParams = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); mContentView.setLayoutParams(contentParams); if (mContentView.getId() < 1) { mContentView.setId(CONTENT_VIEW_ID); } mMenuView.setId(MENU_VIEW_ID); mMenuView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); addView(mContentView); addView(mMenuView); // if (mContentView.getBackground() == null) { // mContentView.setBackgroundColor(Color.WHITE); // } // in android 2.x, MenuView height is MATCH_PARENT is not work. // getViewTreeObserver().addOnGlobalLayoutListener( // new OnGlobalLayoutListener() { // @Override // public void onGlobalLayout() { // setMenuHeight(mContentView.getHeight()); // // getViewTreeObserver() // // .removeGlobalOnLayoutListener(this); // } // }); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } public boolean onSwipe(MotionEvent event) { mGestureDetector.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mDownX = (int) event.getX(); isFling = false; break; case MotionEvent.ACTION_MOVE: // Log.i("byz", "downX = " + mDownX + ", moveX = " + event.getX()); int dis = (int) (mDownX - event.getX()); if (state == STATE_OPEN) { dis += mMenuView.getWidth(); } swipe(dis); break; case MotionEvent.ACTION_UP: if (isFling || (mDownX - event.getX()) > (mMenuView.getWidth() / 2)) { // open smoothOpenMenu(); } else { // close smoothCloseMenu(); return false; } break; } return true; } public boolean isOpen() { return state == STATE_OPEN; } @Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); } private void swipe(int dis) { if (dis > mMenuView.getWidth()) { dis = mMenuView.getWidth(); } if (dis < 0) { dis = 0; } mContentView.layout(-dis, mContentView.getTop(), mContentView.getWidth() - dis, getMeasuredHeight()); mMenuView.layout(mContentView.getWidth() - dis, mMenuView.getTop(), mContentView.getWidth() + mMenuView.getWidth() - dis, mMenuView.getBottom()); } @Override public void computeScroll() { if (state == STATE_OPEN) { if (mOpenScroller.computeScrollOffset()) { swipe(mOpenScroller.getCurrX()); postInvalidate(); } } else { if (mCloseScroller.computeScrollOffset()) { swipe(mBaseX - mCloseScroller.getCurrX()); postInvalidate(); } } } public void smoothCloseMenu() { state = STATE_CLOSE; mBaseX = -mContentView.getLeft(); mCloseScroller.startScroll(0, 0, mBaseX, 0, 350); postInvalidate(); } public void smoothOpenMenu() { state = STATE_OPEN; mOpenScroller.startScroll(-mContentView.getLeft(), 0, mMenuView.getWidth(), 0, 350); postInvalidate(); } public void closeMenu() { if (mCloseScroller.computeScrollOffset()) { mCloseScroller.abortAnimation(); } if (state == STATE_OPEN) { state = STATE_CLOSE; swipe(0); } } public void openMenu() { if (state == STATE_CLOSE) { state = STATE_OPEN; swipe(mMenuView.getWidth()); } } public View getContentView() { return mContentView; } public SwipeMenuView getMenuView() { return mMenuView; } private int dp2px(int dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources().getDisplayMetrics()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mMenuView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec( getMeasuredHeight(), MeasureSpec.EXACTLY)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mContentView.layout(0, 0, getMeasuredWidth(), mContentView.getMeasuredHeight()); mMenuView.layout(getMeasuredWidth(), 0, getMeasuredWidth() + mMenuView.getMeasuredWidth(), mContentView.getMeasuredHeight()); // setMenuHeight(mContentView.getMeasuredHeight()); // bringChildToFront(mContentView); } public void setMenuHeight(int measuredHeight) { Log.i("byz", "pos = " + position + ", height = " + measuredHeight); LayoutParams params = (LayoutParams) mMenuView.getLayoutParams(); if (params.height != measuredHeight) { params.height = measuredHeight; mMenuView.setLayoutParams(mMenuView.getLayoutParams()); } } }
package com.sequenceiq.mock.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.sequenceiq.mock.swagger.model.ApiMetricData; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.*; /** * A metric represents a specific metric monitored by the Cloudera Management Services, and a list of values matching a user query. &lt;p&gt; These fields are available only in the \&quot;full\&quot; view: &lt;ul&gt; &lt;li&gt;displayName&lt;/li&gt; &lt;li&gt;description&lt;/li&gt; &lt;/ul&gt; */ @ApiModel(description = "A metric represents a specific metric monitored by the Cloudera Management Services, and a list of values matching a user query. <p> These fields are available only in the \"full\" view: <ul> <li>displayName</li> <li>description</li> </ul>") @Validated @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2021-12-10T21:24:30.629+01:00") public class ApiMetric { @JsonProperty("name") private String name = null; @JsonProperty("context") private String context = null; @JsonProperty("unit") private String unit = null; @JsonProperty("data") @Valid private List<ApiMetricData> data = null; @JsonProperty("displayName") private String displayName = null; @JsonProperty("description") private String description = null; public ApiMetric name(String name) { this.name = name; return this; } /** * Name of the metric. * @return name **/ @ApiModelProperty(value = "Name of the metric.") public String getName() { return name; } public void setName(String name) { this.name = name; } public ApiMetric context(String context) { this.context = context; return this; } /** * Context the metric is associated with. * @return context **/ @ApiModelProperty(value = "Context the metric is associated with.") public String getContext() { return context; } public void setContext(String context) { this.context = context; } public ApiMetric unit(String unit) { this.unit = unit; return this; } /** * Unit of the metric values. * @return unit **/ @ApiModelProperty(value = "Unit of the metric values.") public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public ApiMetric data(List<ApiMetricData> data) { this.data = data; return this; } public ApiMetric addDataItem(ApiMetricData dataItem) { if (this.data == null) { this.data = new ArrayList<>(); } this.data.add(dataItem); return this; } /** * List of readings retrieved from the monitors. * @return data **/ @ApiModelProperty(value = "List of readings retrieved from the monitors.") @Valid public List<ApiMetricData> getData() { return data; } public void setData(List<ApiMetricData> data) { this.data = data; } public ApiMetric displayName(String displayName) { this.displayName = displayName; return this; } /** * Requires \"full\" view. User-friendly display name for the metric. * @return displayName **/ @ApiModelProperty(value = "Requires \"full\" view. User-friendly display name for the metric.") public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public ApiMetric description(String description) { this.description = description; return this; } /** * Requires \"full\" view. Description of the metric. * @return description **/ @ApiModelProperty(value = "Requires \"full\" view. Description of the metric.") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiMetric apiMetric = (ApiMetric) o; return Objects.equals(this.name, apiMetric.name) && Objects.equals(this.context, apiMetric.context) && Objects.equals(this.unit, apiMetric.unit) && Objects.equals(this.data, apiMetric.data) && Objects.equals(this.displayName, apiMetric.displayName) && Objects.equals(this.description, apiMetric.description); } @Override public int hashCode() { return Objects.hash(name, context, unit, data, displayName, description); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ApiMetric {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" context: ").append(toIndentedString(context)).append("\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" data: ").append(toIndentedString(data)).append("\n"); sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
// $ANTLR 3.2 Sep 23, 2009 12:02:23 Formula.g 2010-11-23 21:34:54 package folf; import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; public class FormulaLexer extends Lexer { public static final int GE=21; public static final int LT=18; public static final int EXPONENT=23; public static final int UNICODE_ESC=26; public static final int OCTAL_ESC=25; public static final int NUMBER=22; public static final int FORALL=10; public static final int WHITESPACE=29; public static final int HEX_DIGIT=27; public static final int NOT=15; public static final int AND=14; public static final int ID=6; public static final int EOF=-1; public static final int LPAREN=4; public static final int T__30=30; public static final int T__31=31; public static final int RPAREN=5; public static final int T__32=32; public static final int T__33=33; public static final int ESC_SEQ=24; public static final int IN=9; public static final int T__34=34; public static final int T__35=35; public static final int T__36=36; public static final int T__37=37; public static final int T__38=38; public static final int EQUIVALENCE=7; public static final int OR=13; public static final int GT=20; public static final int IMPLICATION=12; public static final int EXISTS=11; public static final int EQ=16; public static final int COMMENT=28; public static final int LE=19; public static final int STRING=8; public static final int NE=17; folf.Parser owner; public void emitErrorMessage(String msg) { owner.appendErrorMessage(msg); } // delegates // delegators public FormulaLexer() {;} public FormulaLexer(CharStream input) { this(input, new RecognizerSharedState()); } public FormulaLexer(CharStream input, RecognizerSharedState state) { super(input,state); } public String getGrammarFileName() { return "Formula.g"; } // $ANTLR start "LPAREN" public final void mLPAREN() throws RecognitionException { try { int _type = LPAREN; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:19:8: ( '(' ) // Formula.g:19:10: '(' { match('('); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "LPAREN" // $ANTLR start "RPAREN" public final void mRPAREN() throws RecognitionException { try { int _type = RPAREN; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:20:8: ( ')' ) // Formula.g:20:10: ')' { match(')'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "RPAREN" // $ANTLR start "T__30" public final void mT__30() throws RecognitionException { try { int _type = T__30; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:21:7: ( ';' ) // Formula.g:21:9: ';' { match(';'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__30" // $ANTLR start "T__31" public final void mT__31() throws RecognitionException { try { int _type = T__31; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:22:7: ( ',' ) // Formula.g:22:9: ',' { match(','); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__31" // $ANTLR start "T__32" public final void mT__32() throws RecognitionException { try { int _type = T__32; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:23:7: ( 'success_msg' ) // Formula.g:23:9: 'success_msg' { match("success_msg"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__32" // $ANTLR start "T__33" public final void mT__33() throws RecognitionException { try { int _type = T__33; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:24:7: ( 'failure_msg' ) // Formula.g:24:9: 'failure_msg' { match("failure_msg"); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__33" // $ANTLR start "T__34" public final void mT__34() throws RecognitionException { try { int _type = T__34; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:25:7: ( ':' ) // Formula.g:25:9: ':' { match(':'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__34" // $ANTLR start "T__35" public final void mT__35() throws RecognitionException { try { int _type = T__35; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:26:7: ( '+' ) // Formula.g:26:9: '+' { match('+'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__35" // $ANTLR start "T__36" public final void mT__36() throws RecognitionException { try { int _type = T__36; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:27:7: ( '-' ) // Formula.g:27:9: '-' { match('-'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__36" // $ANTLR start "T__37" public final void mT__37() throws RecognitionException { try { int _type = T__37; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:28:7: ( '*' ) // Formula.g:28:9: '*' { match('*'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__37" // $ANTLR start "T__38" public final void mT__38() throws RecognitionException { try { int _type = T__38; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:29:7: ( '/' ) // Formula.g:29:9: '/' { match('/'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "T__38" // $ANTLR start "FORALL" public final void mFORALL() throws RecognitionException { try { int _type = FORALL; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:562:8: ( 'forall' | '\\\\forall' | '\\u2200' ) int alt1=3; switch ( input.LA(1) ) { case 'f': { alt1=1; } break; case '\\': { alt1=2; } break; case '\u2200': { alt1=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 1, 0, input); throw nvae; } switch (alt1) { case 1 : // Formula.g:562:10: 'forall' { match("forall"); } break; case 2 : // Formula.g:562:21: '\\\\forall' { match("\\forall"); } break; case 3 : // Formula.g:562:34: '\\u2200' { match('\u2200'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "FORALL" // $ANTLR start "EXISTS" public final void mEXISTS() throws RecognitionException { try { int _type = EXISTS; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:564:8: ( 'exists' | '\\\\exists' | '\\u2203' ) int alt2=3; switch ( input.LA(1) ) { case 'e': { alt2=1; } break; case '\\': { alt2=2; } break; case '\u2203': { alt2=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 2, 0, input); throw nvae; } switch (alt2) { case 1 : // Formula.g:564:10: 'exists' { match("exists"); } break; case 2 : // Formula.g:564:21: '\\\\exists' { match("\\exists"); } break; case 3 : // Formula.g:564:34: '\\u2203' { match('\u2203'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "EXISTS" // $ANTLR start "IN" public final void mIN() throws RecognitionException { try { int _type = IN; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:566:4: ( 'in' | '\\\\in' | '\\u220A' ) int alt3=3; switch ( input.LA(1) ) { case 'i': { alt3=1; } break; case '\\': { alt3=2; } break; case '\u220A': { alt3=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 3, 0, input); throw nvae; } switch (alt3) { case 1 : // Formula.g:566:6: 'in' { match("in"); } break; case 2 : // Formula.g:566:13: '\\\\in' { match("\\in"); } break; case 3 : // Formula.g:566:22: '\\u220A' { match('\u220A'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "IN" // $ANTLR start "EQUIVALENCE" public final void mEQUIVALENCE() throws RecognitionException { try { int _type = EQUIVALENCE; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:568:13: ( '<=>' | '\\\\Leftrightarrow' | '\\u21D4' ) int alt4=3; switch ( input.LA(1) ) { case '<': { alt4=1; } break; case '\\': { alt4=2; } break; case '\u21D4': { alt4=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 4, 0, input); throw nvae; } switch (alt4) { case 1 : // Formula.g:568:15: '<=>' { match("<=>"); } break; case 2 : // Formula.g:568:23: '\\\\Leftrightarrow' { match("\\Leftrightarrow"); } break; case 3 : // Formula.g:568:44: '\\u21D4' { match('\u21D4'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "EQUIVALENCE" // $ANTLR start "IMPLICATION" public final void mIMPLICATION() throws RecognitionException { try { int _type = IMPLICATION; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:570:13: ( '=>' | '\\\\Rightarrow' | '\\u21D2' ) int alt5=3; switch ( input.LA(1) ) { case '=': { alt5=1; } break; case '\\': { alt5=2; } break; case '\u21D2': { alt5=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 5, 0, input); throw nvae; } switch (alt5) { case 1 : // Formula.g:570:15: '=>' { match("=>"); } break; case 2 : // Formula.g:570:22: '\\\\Rightarrow' { match("\\Rightarrow"); } break; case 3 : // Formula.g:570:39: '\\u21D2' { match('\u21D2'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "IMPLICATION" // $ANTLR start "AND" public final void mAND() throws RecognitionException { try { int _type = AND; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:572:5: ( 'and' | '\\\\wedge' | '\\u2227' ) int alt6=3; switch ( input.LA(1) ) { case 'a': { alt6=1; } break; case '\\': { alt6=2; } break; case '\u2227': { alt6=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 6, 0, input); throw nvae; } switch (alt6) { case 1 : // Formula.g:572:7: 'and' { match("and"); } break; case 2 : // Formula.g:572:15: '\\\\wedge' { match("\\wedge"); } break; case 3 : // Formula.g:572:27: '\\u2227' { match('\u2227'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "AND" // $ANTLR start "OR" public final void mOR() throws RecognitionException { try { int _type = OR; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:574:4: ( 'or' | '\\\\vee' | '\\u2228' ) int alt7=3; switch ( input.LA(1) ) { case 'o': { alt7=1; } break; case '\\': { alt7=2; } break; case '\u2228': { alt7=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 7, 0, input); throw nvae; } switch (alt7) { case 1 : // Formula.g:574:6: 'or' { match("or"); } break; case 2 : // Formula.g:574:13: '\\\\vee' { match("\\vee"); } break; case 3 : // Formula.g:574:23: '\\u2228' { match('\u2228'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "OR" // $ANTLR start "NOT" public final void mNOT() throws RecognitionException { try { int _type = NOT; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:576:5: ( 'not' | '!' | '\\\\neg' | '\\u00AC' ) int alt8=4; switch ( input.LA(1) ) { case 'n': { alt8=1; } break; case '!': { alt8=2; } break; case '\\': { alt8=3; } break; case '\u00AC': { alt8=4; } break; default: NoViableAltException nvae = new NoViableAltException("", 8, 0, input); throw nvae; } switch (alt8) { case 1 : // Formula.g:576:7: 'not' { match("not"); } break; case 2 : // Formula.g:576:15: '!' { match('!'); } break; case 3 : // Formula.g:576:21: '\\\\neg' { match("\\neg"); } break; case 4 : // Formula.g:576:31: '\\u00AC' { match('\u00AC'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "NOT" // $ANTLR start "EQ" public final void mEQ() throws RecognitionException { try { int _type = EQ; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:578:4: ( '=' ) // Formula.g:578:6: '=' { match('='); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "EQ" // $ANTLR start "NE" public final void mNE() throws RecognitionException { try { int _type = NE; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:580:4: ( '!=' | '<>' | '\\\\neq' | '\\u2260' ) int alt9=4; switch ( input.LA(1) ) { case '!': { alt9=1; } break; case '<': { alt9=2; } break; case '\\': { alt9=3; } break; case '\u2260': { alt9=4; } break; default: NoViableAltException nvae = new NoViableAltException("", 9, 0, input); throw nvae; } switch (alt9) { case 1 : // Formula.g:580:6: '!=' { match("!="); } break; case 2 : // Formula.g:580:13: '<>' { match("<>"); } break; case 3 : // Formula.g:580:20: '\\\\neq' { match("\\neq"); } break; case 4 : // Formula.g:580:30: '\\u2260' { match('\u2260'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "NE" // $ANTLR start "LT" public final void mLT() throws RecognitionException { try { int _type = LT; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:582:4: ( '<' ) // Formula.g:582:6: '<' { match('<'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "LT" // $ANTLR start "LE" public final void mLE() throws RecognitionException { try { int _type = LE; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:584:4: ( '<=' | '\\\\leq' | '\\u2264' ) int alt10=3; switch ( input.LA(1) ) { case '<': { alt10=1; } break; case '\\': { alt10=2; } break; case '\u2264': { alt10=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 10, 0, input); throw nvae; } switch (alt10) { case 1 : // Formula.g:584:6: '<=' { match("<="); } break; case 2 : // Formula.g:584:13: '\\\\leq' { match("\\leq"); } break; case 3 : // Formula.g:584:23: '\\u2264' { match('\u2264'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "LE" // $ANTLR start "GT" public final void mGT() throws RecognitionException { try { int _type = GT; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:586:4: ( '>' ) // Formula.g:586:6: '>' { match('>'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "GT" // $ANTLR start "GE" public final void mGE() throws RecognitionException { try { int _type = GE; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:588:4: ( '>=' | '\\\\geq' | '\\u2265' ) int alt11=3; switch ( input.LA(1) ) { case '>': { alt11=1; } break; case '\\': { alt11=2; } break; case '\u2265': { alt11=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 11, 0, input); throw nvae; } switch (alt11) { case 1 : // Formula.g:588:6: '>=' { match(">="); } break; case 2 : // Formula.g:588:13: '\\\\geq' { match("\\geq"); } break; case 3 : // Formula.g:588:23: '\\u2265' { match('\u2265'); } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "GE" // $ANTLR start "ID" public final void mID() throws RecognitionException { try { int _type = ID; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:590:4: ( ( 'a' .. 'z' | 'A' .. 'Z' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* ) // Formula.g:590:6: ( 'a' .. 'z' | 'A' .. 'Z' ) ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* { if ( (input.LA(1)>='A' && input.LA(1)<='Z')||(input.LA(1)>='a' && input.LA(1)<='z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} // Formula.g:590:26: ( 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' )* loop12: do { int alt12=2; int LA12_0 = input.LA(1); if ( ((LA12_0>='0' && LA12_0<='9')||(LA12_0>='A' && LA12_0<='Z')||LA12_0=='_'||(LA12_0>='a' && LA12_0<='z')) ) { alt12=1; } switch (alt12) { case 1 : // Formula.g: { if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop12; } } while (true); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "ID" // $ANTLR start "NUMBER" public final void mNUMBER() throws RecognitionException { try { int _type = NUMBER; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:592:8: ( ( '0' .. '9' )+ ( '.' ( '0' .. '9' )+ )? ( EXPONENT )? | '.' ( '0' .. '9' )+ ( EXPONENT )? ) int alt19=2; int LA19_0 = input.LA(1); if ( ((LA19_0>='0' && LA19_0<='9')) ) { alt19=1; } else if ( (LA19_0=='.') ) { alt19=2; } else { NoViableAltException nvae = new NoViableAltException("", 19, 0, input); throw nvae; } switch (alt19) { case 1 : // Formula.g:592:10: ( '0' .. '9' )+ ( '.' ( '0' .. '9' )+ )? ( EXPONENT )? { // Formula.g:592:10: ( '0' .. '9' )+ int cnt13=0; loop13: do { int alt13=2; int LA13_0 = input.LA(1); if ( ((LA13_0>='0' && LA13_0<='9')) ) { alt13=1; } switch (alt13) { case 1 : // Formula.g:592:10: '0' .. '9' { matchRange('0','9'); } break; default : if ( cnt13 >= 1 ) break loop13; EarlyExitException eee = new EarlyExitException(13, input); throw eee; } cnt13++; } while (true); // Formula.g:592:20: ( '.' ( '0' .. '9' )+ )? int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0=='.') ) { alt15=1; } switch (alt15) { case 1 : // Formula.g:592:21: '.' ( '0' .. '9' )+ { match('.'); // Formula.g:592:25: ( '0' .. '9' )+ int cnt14=0; loop14: do { int alt14=2; int LA14_0 = input.LA(1); if ( ((LA14_0>='0' && LA14_0<='9')) ) { alt14=1; } switch (alt14) { case 1 : // Formula.g:592:25: '0' .. '9' { matchRange('0','9'); } break; default : if ( cnt14 >= 1 ) break loop14; EarlyExitException eee = new EarlyExitException(14, input); throw eee; } cnt14++; } while (true); } break; } // Formula.g:592:37: ( EXPONENT )? int alt16=2; int LA16_0 = input.LA(1); if ( (LA16_0=='E'||LA16_0=='e') ) { alt16=1; } switch (alt16) { case 1 : // Formula.g:592:37: EXPONENT { mEXPONENT(); } break; } } break; case 2 : // Formula.g:592:49: '.' ( '0' .. '9' )+ ( EXPONENT )? { match('.'); // Formula.g:592:53: ( '0' .. '9' )+ int cnt17=0; loop17: do { int alt17=2; int LA17_0 = input.LA(1); if ( ((LA17_0>='0' && LA17_0<='9')) ) { alt17=1; } switch (alt17) { case 1 : // Formula.g:592:53: '0' .. '9' { matchRange('0','9'); } break; default : if ( cnt17 >= 1 ) break loop17; EarlyExitException eee = new EarlyExitException(17, input); throw eee; } cnt17++; } while (true); // Formula.g:592:63: ( EXPONENT )? int alt18=2; int LA18_0 = input.LA(1); if ( (LA18_0=='E'||LA18_0=='e') ) { alt18=1; } switch (alt18) { case 1 : // Formula.g:592:63: EXPONENT { mEXPONENT(); } break; } } break; } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "NUMBER" // $ANTLR start "EXPONENT" public final void mEXPONENT() throws RecognitionException { try { // Formula.g:595:10: ( ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ ) // Formula.g:595:12: ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ { if ( input.LA(1)=='E'||input.LA(1)=='e' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} // Formula.g:595:22: ( '+' | '-' )? int alt20=2; int LA20_0 = input.LA(1); if ( (LA20_0=='+'||LA20_0=='-') ) { alt20=1; } switch (alt20) { case 1 : // Formula.g: { if ( input.LA(1)=='+'||input.LA(1)=='-' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; } // Formula.g:595:33: ( '0' .. '9' )+ int cnt21=0; loop21: do { int alt21=2; int LA21_0 = input.LA(1); if ( ((LA21_0>='0' && LA21_0<='9')) ) { alt21=1; } switch (alt21) { case 1 : // Formula.g:595:34: '0' .. '9' { matchRange('0','9'); } break; default : if ( cnt21 >= 1 ) break loop21; EarlyExitException eee = new EarlyExitException(21, input); throw eee; } cnt21++; } while (true); } } finally { } } // $ANTLR end "EXPONENT" // $ANTLR start "STRING" public final void mSTRING() throws RecognitionException { try { int _type = STRING; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:597:8: ( '\"' ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )* '\"' ) // Formula.g:597:10: '\"' ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )* '\"' { match('\"'); // Formula.g:597:14: ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )* loop22: do { int alt22=3; int LA22_0 = input.LA(1); if ( (LA22_0=='\\') ) { alt22=1; } else if ( ((LA22_0>='\u0000' && LA22_0<='!')||(LA22_0>='#' && LA22_0<='[')||(LA22_0>=']' && LA22_0<='\uFFFF')) ) { alt22=2; } switch (alt22) { case 1 : // Formula.g:597:16: ESC_SEQ { mESC_SEQ(); } break; case 2 : // Formula.g:597:26: ~ ( '\\\\' | '\"' ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop22; } } while (true); match('\"'); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "STRING" // $ANTLR start "ESC_SEQ" public final void mESC_SEQ() throws RecognitionException { try { // Formula.g:600:9: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) | OCTAL_ESC | UNICODE_ESC ) int alt23=3; int LA23_0 = input.LA(1); if ( (LA23_0=='\\') ) { switch ( input.LA(2) ) { case '\"': case '\'': case '\\': case 'b': case 'f': case 'n': case 'r': case 't': { alt23=1; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { alt23=2; } break; case 'u': { alt23=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 23, 1, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 23, 0, input); throw nvae; } switch (alt23) { case 1 : // Formula.g:600:11: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) { match('\\'); if ( input.LA(1)=='\"'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||input.LA(1)=='t' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; case 2 : // Formula.g:600:55: OCTAL_ESC { mOCTAL_ESC(); } break; case 3 : // Formula.g:600:67: UNICODE_ESC { mUNICODE_ESC(); } break; } } finally { } } // $ANTLR end "ESC_SEQ" // $ANTLR start "OCTAL_ESC" public final void mOCTAL_ESC() throws RecognitionException { try { // Formula.g:603:11: ( '\\\\' '0' .. '3' '0' .. '7' '0' .. '7' | '\\\\' '0' .. '7' '0' .. '7' | '\\\\' '0' .. '7' ) int alt24=3; int LA24_0 = input.LA(1); if ( (LA24_0=='\\') ) { int LA24_1 = input.LA(2); if ( ((LA24_1>='0' && LA24_1<='3')) ) { int LA24_2 = input.LA(3); if ( ((LA24_2>='0' && LA24_2<='7')) ) { int LA24_4 = input.LA(4); if ( ((LA24_4>='0' && LA24_4<='7')) ) { alt24=1; } else { alt24=2;} } else { alt24=3;} } else if ( ((LA24_1>='4' && LA24_1<='7')) ) { int LA24_3 = input.LA(3); if ( ((LA24_3>='0' && LA24_3<='7')) ) { alt24=2; } else { alt24=3;} } else { NoViableAltException nvae = new NoViableAltException("", 24, 1, input); throw nvae; } } else { NoViableAltException nvae = new NoViableAltException("", 24, 0, input); throw nvae; } switch (alt24) { case 1 : // Formula.g:603:13: '\\\\' '0' .. '3' '0' .. '7' '0' .. '7' { match('\\'); matchRange('0','3'); matchRange('0','7'); matchRange('0','7'); } break; case 2 : // Formula.g:603:47: '\\\\' '0' .. '7' '0' .. '7' { match('\\'); matchRange('0','7'); matchRange('0','7'); } break; case 3 : // Formula.g:604:3: '\\\\' '0' .. '7' { match('\\'); matchRange('0','7'); } break; } } finally { } } // $ANTLR end "OCTAL_ESC" // $ANTLR start "UNICODE_ESC" public final void mUNICODE_ESC() throws RecognitionException { try { // Formula.g:607:13: ( '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ) // Formula.g:607:15: '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT { match('\\'); match('u'); mHEX_DIGIT(); mHEX_DIGIT(); mHEX_DIGIT(); mHEX_DIGIT(); } } finally { } } // $ANTLR end "UNICODE_ESC" // $ANTLR start "HEX_DIGIT" public final void mHEX_DIGIT() throws RecognitionException { try { // Formula.g:610:11: ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) // Formula.g: { if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='F')||(input.LA(1)>='a' && input.LA(1)<='f') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } } finally { } } // $ANTLR end "HEX_DIGIT" // $ANTLR start "COMMENT" public final void mCOMMENT() throws RecognitionException { try { int _type = COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:612:9: ( '#' ( . )* ( '\\r' | '\\n' ) ) // Formula.g:612:11: '#' ( . )* ( '\\r' | '\\n' ) { match('#'); // Formula.g:612:15: ( . )* loop25: do { int alt25=2; int LA25_0 = input.LA(1); if ( (LA25_0=='\n'||LA25_0=='\r') ) { alt25=2; } else if ( ((LA25_0>='\u0000' && LA25_0<='\t')||(LA25_0>='\u000B' && LA25_0<='\f')||(LA25_0>='\u000E' && LA25_0<='\uFFFF')) ) { alt25=1; } switch (alt25) { case 1 : // Formula.g:612:15: . { matchAny(); } break; default : break loop25; } } while (true); if ( input.LA(1)=='\n'||input.LA(1)=='\r' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} skip(); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "COMMENT" // $ANTLR start "WHITESPACE" public final void mWHITESPACE() throws RecognitionException { try { int _type = WHITESPACE; int _channel = DEFAULT_TOKEN_CHANNEL; // Formula.g:616:12: ( ( ' ' | '\\t' | '\\r' | '\\n' ) ) // Formula.g:616:14: ( ' ' | '\\t' | '\\r' | '\\n' ) { if ( (input.LA(1)>='\t' && input.LA(1)<='\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} skip(); } state.type = _type; state.channel = _channel; } finally { } } // $ANTLR end "WHITESPACE" public void mTokens() throws RecognitionException { // Formula.g:1:8: ( LPAREN | RPAREN | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | FORALL | EXISTS | IN | EQUIVALENCE | IMPLICATION | AND | OR | NOT | EQ | NE | LT | LE | GT | GE | ID | NUMBER | STRING | COMMENT | WHITESPACE ) int alt26=30; alt26 = dfa26.predict(input); switch (alt26) { case 1 : // Formula.g:1:10: LPAREN { mLPAREN(); } break; case 2 : // Formula.g:1:17: RPAREN { mRPAREN(); } break; case 3 : // Formula.g:1:24: T__30 { mT__30(); } break; case 4 : // Formula.g:1:30: T__31 { mT__31(); } break; case 5 : // Formula.g:1:36: T__32 { mT__32(); } break; case 6 : // Formula.g:1:42: T__33 { mT__33(); } break; case 7 : // Formula.g:1:48: T__34 { mT__34(); } break; case 8 : // Formula.g:1:54: T__35 { mT__35(); } break; case 9 : // Formula.g:1:60: T__36 { mT__36(); } break; case 10 : // Formula.g:1:66: T__37 { mT__37(); } break; case 11 : // Formula.g:1:72: T__38 { mT__38(); } break; case 12 : // Formula.g:1:78: FORALL { mFORALL(); } break; case 13 : // Formula.g:1:85: EXISTS { mEXISTS(); } break; case 14 : // Formula.g:1:92: IN { mIN(); } break; case 15 : // Formula.g:1:95: EQUIVALENCE { mEQUIVALENCE(); } break; case 16 : // Formula.g:1:107: IMPLICATION { mIMPLICATION(); } break; case 17 : // Formula.g:1:119: AND { mAND(); } break; case 18 : // Formula.g:1:123: OR { mOR(); } break; case 19 : // Formula.g:1:126: NOT { mNOT(); } break; case 20 : // Formula.g:1:130: EQ { mEQ(); } break; case 21 : // Formula.g:1:133: NE { mNE(); } break; case 22 : // Formula.g:1:136: LT { mLT(); } break; case 23 : // Formula.g:1:139: LE { mLE(); } break; case 24 : // Formula.g:1:142: GT { mGT(); } break; case 25 : // Formula.g:1:145: GE { mGE(); } break; case 26 : // Formula.g:1:148: ID { mID(); } break; case 27 : // Formula.g:1:151: NUMBER { mNUMBER(); } break; case 28 : // Formula.g:1:158: STRING { mSTRING(); } break; case 29 : // Formula.g:1:165: COMMENT { mCOMMENT(); } break; case 30 : // Formula.g:1:173: WHITESPACE { mWHITESPACE(); } break; } } protected DFA26 dfa26 = new DFA26(this); static final String DFA26_eotS = "\5\uffff\2\41\7\uffff\1\41\1\uffff\1\41\1\uffff\1\55\1\uffff\1\56"+ "\1\uffff\1\41\1\uffff\1\41\1\uffff\1\41\1\34\3\uffff\1\62\6\uffff"+ "\3\41\1\uffff\1\41\1\21\1\36\2\uffff\1\41\1\31\1\41\1\uffff\3\41"+ "\1\uffff\1\41\1\27\1\34\12\41\1\15\1\17\10\41\1\120\1\121\2\uffff"; static final String DFA26_eofS = "\122\uffff"; static final String DFA26_minS = "\1\11\4\uffff\1\165\1\141\5\uffff\1\114\1\uffff\1\170\1\uffff\1"+ "\156\1\uffff\1\75\1\uffff\1\76\1\uffff\1\156\1\uffff\1\162\1\uffff"+ "\1\157\1\75\3\uffff\1\75\6\uffff\1\143\1\151\1\162\1\145\1\151\1"+ "\60\1\76\2\uffff\1\144\1\60\1\164\1\uffff\1\143\1\154\1\141\1\147"+ "\1\163\2\60\1\145\1\165\1\154\1\164\1\163\1\162\1\154\2\163\1\145"+ "\2\60\2\137\2\155\2\163\2\147\2\60\2\uffff"; static final String DFA26_maxS = "\1\u2265\4\uffff\1\165\1\157\5\uffff\1\167\1\uffff\1\170\1\uffff"+ "\1\156\1\uffff\1\76\1\uffff\1\76\1\uffff\1\156\1\uffff\1\162\1\uffff"+ "\1\157\1\75\3\uffff\1\75\6\uffff\1\143\1\151\1\162\1\145\1\151\1"+ "\172\1\76\2\uffff\1\144\1\172\1\164\1\uffff\1\143\1\154\1\141\1"+ "\161\1\163\2\172\1\145\1\165\1\154\1\164\1\163\1\162\1\154\2\163"+ "\1\145\2\172\2\137\2\155\2\163\2\147\2\172\2\uffff"; static final String DFA26_acceptS = "\1\uffff\1\1\1\2\1\3\1\4\2\uffff\1\7\1\10\1\11\1\12\1\13\1\uffff"+ "\1\14\1\uffff\1\15\1\uffff\1\16\1\uffff\1\17\1\uffff\1\20\1\uffff"+ "\1\21\1\uffff\1\22\2\uffff\1\23\1\25\1\27\1\uffff\1\31\1\32\1\33"+ "\1\34\1\35\1\36\7\uffff\1\26\1\24\3\uffff\1\30\35\uffff\1\5\1\6"; static final String DFA26_specialS = "\122\uffff}>"; static final String[] DFA26_transitionS = { "\2\45\2\uffff\1\45\22\uffff\1\45\1\33\1\43\1\44\4\uffff\1\1"+ "\1\2\1\12\1\10\1\4\1\11\1\42\1\13\12\42\1\7\1\3\1\22\1\24\1"+ "\37\2\uffff\32\41\1\uffff\1\14\4\uffff\1\26\3\41\1\16\1\6\2"+ "\41\1\20\4\41\1\32\1\30\3\41\1\5\7\41\61\uffff\1\34\u2125\uffff"+ "\1\25\1\uffff\1\23\53\uffff\1\15\2\uffff\1\17\6\uffff\1\21\34"+ "\uffff\1\27\1\31\67\uffff\1\35\3\uffff\1\36\1\40", "", "", "", "", "\1\46", "\1\47\15\uffff\1\50", "", "", "", "", "", "\1\23\5\uffff\1\25\22\uffff\1\17\1\15\1\40\1\uffff\1\21\2\uffff"+ "\1\36\1\uffff\1\51\7\uffff\1\31\1\27", "", "\1\52", "", "\1\53", "", "\1\54\1\35", "", "\1\25", "", "\1\57", "", "\1\60", "", "\1\61", "\1\35", "", "", "", "\1\40", "", "", "", "", "", "", "\1\63", "\1\64", "\1\65", "\1\66", "\1\67", "\12\41\7\uffff\32\41\4\uffff\1\41\1\uffff\32\41", "\1\23", "", "", "\1\70", "\12\41\7\uffff\32\41\4\uffff\1\41\1\uffff\32\41", "\1\71", "", "\1\72", "\1\73", "\1\74", "\1\34\11\uffff\1\35", "\1\75", "\12\41\7\uffff\32\41\4\uffff\1\41\1\uffff\32\41", "\12\41\7\uffff\32\41\4\uffff\1\41\1\uffff\32\41", "\1\76", "\1\77", "\1\100", "\1\101", "\1\102", "\1\103", "\1\104", "\1\105", "\1\106", "\1\107", "\12\41\7\uffff\32\41\4\uffff\1\41\1\uffff\32\41", "\12\41\7\uffff\32\41\4\uffff\1\41\1\uffff\32\41", "\1\110", "\1\111", "\1\112", "\1\113", "\1\114", "\1\115", "\1\116", "\1\117", "\12\41\7\uffff\32\41\4\uffff\1\41\1\uffff\32\41", "\12\41\7\uffff\32\41\4\uffff\1\41\1\uffff\32\41", "", "" }; static final short[] DFA26_eot = DFA.unpackEncodedString(DFA26_eotS); static final short[] DFA26_eof = DFA.unpackEncodedString(DFA26_eofS); static final char[] DFA26_min = DFA.unpackEncodedStringToUnsignedChars(DFA26_minS); static final char[] DFA26_max = DFA.unpackEncodedStringToUnsignedChars(DFA26_maxS); static final short[] DFA26_accept = DFA.unpackEncodedString(DFA26_acceptS); static final short[] DFA26_special = DFA.unpackEncodedString(DFA26_specialS); static final short[][] DFA26_transition; static { int numStates = DFA26_transitionS.length; DFA26_transition = new short[numStates][]; for (int i=0; i<numStates; i++) { DFA26_transition[i] = DFA.unpackEncodedString(DFA26_transitionS[i]); } } class DFA26 extends DFA { public DFA26(BaseRecognizer recognizer) { this.recognizer = recognizer; this.decisionNumber = 26; this.eot = DFA26_eot; this.eof = DFA26_eof; this.min = DFA26_min; this.max = DFA26_max; this.accept = DFA26_accept; this.special = DFA26_special; this.transition = DFA26_transition; } public String getDescription() { return "1:1: Tokens : ( LPAREN | RPAREN | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | FORALL | EXISTS | IN | EQUIVALENCE | IMPLICATION | AND | OR | NOT | EQ | NE | LT | LE | GT | GE | ID | NUMBER | STRING | COMMENT | WHITESPACE );"; } } }
/** * 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.storm.kafka; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.storm.Config; import org.apache.storm.kafka.KafkaSpout.EmitState; import org.apache.storm.kafka.PartitionManager.KafkaMessageId; import org.apache.storm.kafka.trident.ZkBrokerReader; import org.apache.storm.spout.ISpoutOutputCollector; import org.apache.storm.spout.SpoutOutputCollector; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; public class PartitionManagerTest { private static final String TOPIC_NAME = "testTopic"; private KafkaTestBroker broker; private TestingSpoutOutputCollector outputCollector; private ZkState zkState; private ZkCoordinator coordinator; private KafkaProducer<String, String> producer; @Before public void setup() { outputCollector = new TestingSpoutOutputCollector(); Properties brokerProps = new Properties(); brokerProps.setProperty("log.retention.check.interval.ms", "1000"); broker = new KafkaTestBroker(brokerProps); // Configure Kafka to remove messages after 2 seconds Properties topicProperties = new Properties(); topicProperties.put("delete.retention.ms", "2000"); topicProperties.put("retention.ms", "2000"); broker.createTopic(TOPIC_NAME, 1, topicProperties); Map<String, Object> conf = new HashMap<>(); conf.put(Config.TRANSACTIONAL_ZOOKEEPER_PORT, broker.getZookeeperPort()); conf.put(Config.TRANSACTIONAL_ZOOKEEPER_SERVERS, Collections.singletonList("127.0.0.1")); conf.put(Config.STORM_ZOOKEEPER_SESSION_TIMEOUT, 20000); conf.put(Config.STORM_ZOOKEEPER_CONNECTION_TIMEOUT, 20000); conf.put(Config.STORM_ZOOKEEPER_RETRY_TIMES, 3); conf.put(Config.STORM_ZOOKEEPER_RETRY_INTERVAL, 30); conf.put(Config.TOPOLOGY_NAME, "test"); zkState = new ZkState(conf); ZkHosts zkHosts = new ZkHosts(broker.getZookeeperConnectionString()); SpoutConfig spoutConfig = new SpoutConfig(zkHosts, TOPIC_NAME, "/test", "id"); coordinator = new ZkCoordinator( new DynamicPartitionConnections(spoutConfig, new ZkBrokerReader(conf, TOPIC_NAME, zkHosts)), conf, spoutConfig, zkState, 0, 1, 1, "topo" ); Properties producerProps = new Properties(); producerProps.put("acks", "1"); producerProps.put("bootstrap.servers", broker.getBrokerConnectionString()); producerProps.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); producerProps.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); producerProps.put("metadata.fetch.timeout.ms", 1000); producer = new KafkaProducer<>(producerProps); } @After public void shutdown() { producer.close(); broker.shutdown(); } /** * Test for STORM-2608 * * - Send a few messages to topic * - Emit those messages from the partition manager * - Fail those tuples so that they are added to the failedMsgRetryManager * - Commit partition info to Zookeeper * - Wait for kafka to roll logs and remove those messages * - Send a new message to the topic * - On the next fetch request, a TopicOffsetOutOfRangeException is thrown and the new offset is after * the offset that is currently sitting in both the pending tree and the failedMsgRetryManager * - Ack latest message to partition manager * - Commit partition info to zookeeper * - The committed offset should be the next offset _after_ the last one that was committed * */ @Test public void test2608() throws Exception { SpoutOutputCollector spoutOutputCollector = new SpoutOutputCollector(outputCollector); List<PartitionManager> partitionManagers = coordinator.getMyManagedPartitions(); Assert.assertEquals(1, partitionManagers.size()); PartitionManager partitionManager = partitionManagers.get(0); for (int i=0; i < 5; i++) { sendMessage("message-" + i); } waitForEmitState(partitionManager, spoutOutputCollector, EmitState.EMITTED_MORE_LEFT); waitForEmitState(partitionManager, spoutOutputCollector, EmitState.EMITTED_MORE_LEFT); waitForEmitState(partitionManager, spoutOutputCollector, EmitState.EMITTED_MORE_LEFT); waitForEmitState(partitionManager, spoutOutputCollector, EmitState.EMITTED_MORE_LEFT); waitForEmitState(partitionManager, spoutOutputCollector, EmitState.EMITTED_END); partitionManager.commit(); Map<KafkaMessageId, List<Object>> emitted = outputCollector.getEmitted(); Assert.assertEquals(5, emitted.size()); for (KafkaMessageId messageId : emitted.keySet()) { partitionManager.fail(messageId.offset); } // Kafka log roller task has an initial delay of 30 seconds so we need to wait for it Thread.sleep(TimeUnit.SECONDS.toMillis(35)); outputCollector.clearEmittedMessages(); sendMessage("new message"); // First request will fail due to offset out of range Assert.assertEquals(EmitState.NO_EMITTED, partitionManager.next(spoutOutputCollector)); waitForEmitState(partitionManager, spoutOutputCollector, EmitState.EMITTED_END); emitted = outputCollector.getEmitted(); Assert.assertEquals(1, emitted.size()); KafkaMessageId messageId = emitted.keySet().iterator().next(); partitionManager.ack(messageId.offset); partitionManager.commit(); Map<Object, Object> json = zkState.readJSON(partitionManager.committedPath()); Assert.assertNotNull(json); long committedOffset = (long) json.get("offset"); Assert.assertEquals(messageId.offset + 1, committedOffset); } private void waitForEmitState(PartitionManager partitionManager, SpoutOutputCollector outputCollector, EmitState expectedState) { int maxRetries = 5; EmitState state = null; for (int retryCount = 0; retryCount < maxRetries; retryCount++) { state = partitionManager.next(outputCollector); if (state == EmitState.NO_EMITTED) { retryCount++; try { Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted while waiting for message"); } } else { break; } } Assert.assertEquals(expectedState, state); } private void sendMessage(String value) { try { producer.send(new ProducerRecord<>(TOPIC_NAME, (String) null, value)).get(); } catch (Exception e) { Assert.fail(e.getMessage()); } } private static class TestingSpoutOutputCollector implements ISpoutOutputCollector { private final Map<KafkaMessageId, List<Object>> emitted = new HashMap<>(); Map<KafkaMessageId, List<Object>> getEmitted() { return emitted; } void clearEmittedMessages() { emitted.clear(); } @Override public List<Integer> emit(String streamId, List<Object> tuple, Object messageId) { emitted.put((KafkaMessageId) messageId, tuple); return Collections.emptyList(); } @Override public void reportError(Throwable error) { throw new RuntimeException("Spout error", error); } @Override public void emitDirect(int taskId, String streamId, List<Object> tuple, Object messageId) { throw new UnsupportedOperationException(); } @Override public long getPendingCount() { throw new UnsupportedOperationException(); } } }
package com.ymsino.water.service.data.testMeterCodeData; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p> * Java class for testMeterCodeDataReturn complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="testMeterCodeDataReturn"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="batteryVoltage" type="{http://www.w3.org/2001/XMLSchema}float" minOccurs="0"/> * &lt;element name="chargingUnitId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="concHardwareId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="createTimestamp" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="dataType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="errorStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="magneticAttack" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="meterHardwareId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="meterReading" type="{http://www.w3.org/2001/XMLSchema}float" minOccurs="0"/> * &lt;element name="parentUnits" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="realTimestamp" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="replyStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="userId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="valveStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="waterCustomerId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "testMeterCodeDataReturn", propOrder = { "batteryVoltage", "chargingUnitId", "concHardwareId", "createTimestamp", "dataType", "errorStatus", "id", "magneticAttack", "meterHardwareId", "meterReading", "parentUnits", "realTimestamp", "replyStatus", "userId", "valveStatus", "waterCustomerId" }) public class TestMeterCodeDataReturn { protected Float batteryVoltage; protected String chargingUnitId; protected String concHardwareId; protected Long createTimestamp; protected String dataType; protected String errorStatus; protected Long id; protected String magneticAttack; protected String meterHardwareId; protected Float meterReading; protected String parentUnits; protected Long realTimestamp; protected String replyStatus; protected String userId; protected String valveStatus; protected String waterCustomerId; /** * Gets the value of the batteryVoltage property. * * @return possible object is {@link Float } * */ public Float getBatteryVoltage() { return batteryVoltage; } /** * Sets the value of the batteryVoltage property. * * @param value * allowed object is {@link Float } * */ public void setBatteryVoltage(Float value) { this.batteryVoltage = value; } /** * Gets the value of the chargingUnitId property. * * @return possible object is {@link String } * */ public String getChargingUnitId() { return chargingUnitId; } /** * Sets the value of the chargingUnitId property. * * @param value * allowed object is {@link String } * */ public void setChargingUnitId(String value) { this.chargingUnitId = value; } /** * Gets the value of the concHardwareId property. * * @return possible object is {@link String } * */ public String getConcHardwareId() { return concHardwareId; } /** * Sets the value of the concHardwareId property. * * @param value * allowed object is {@link String } * */ public void setConcHardwareId(String value) { this.concHardwareId = value; } /** * Gets the value of the createTimestamp property. * * @return possible object is {@link Long } * */ public Long getCreateTimestamp() { return createTimestamp; } /** * Sets the value of the createTimestamp property. * * @param value * allowed object is {@link Long } * */ public void setCreateTimestamp(Long value) { this.createTimestamp = value; } /** * Gets the value of the dataType property. * * @return possible object is {@link String } * */ public String getDataType() { return dataType; } /** * Sets the value of the dataType property. * * @param value * allowed object is {@link String } * */ public void setDataType(String value) { this.dataType = value; } /** * Gets the value of the errorStatus property. * * @return possible object is {@link String } * */ public String getErrorStatus() { return errorStatus; } /** * Sets the value of the errorStatus property. * * @param value * allowed object is {@link String } * */ public void setErrorStatus(String value) { this.errorStatus = value; } /** * Gets the value of the id property. * * @return possible object is {@link Long } * */ public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link Long } * */ public void setId(Long value) { this.id = value; } /** * Gets the value of the magneticAttack property. * * @return possible object is {@link String } * */ public String getMagneticAttack() { return magneticAttack; } /** * Sets the value of the magneticAttack property. * * @param value * allowed object is {@link String } * */ public void setMagneticAttack(String value) { this.magneticAttack = value; } /** * Gets the value of the meterHardwareId property. * * @return possible object is {@link String } * */ public String getMeterHardwareId() { return meterHardwareId; } /** * Sets the value of the meterHardwareId property. * * @param value * allowed object is {@link String } * */ public void setMeterHardwareId(String value) { this.meterHardwareId = value; } /** * Gets the value of the meterReading property. * * @return possible object is {@link Float } * */ public Float getMeterReading() { return meterReading; } /** * Sets the value of the meterReading property. * * @param value * allowed object is {@link Float } * */ public void setMeterReading(Float value) { this.meterReading = value; } /** * Gets the value of the parentUnits property. * * @return possible object is {@link String } * */ public String getParentUnits() { return parentUnits; } /** * Sets the value of the parentUnits property. * * @param value * allowed object is {@link String } * */ public void setParentUnits(String value) { this.parentUnits = value; } /** * Gets the value of the realTimestamp property. * * @return possible object is {@link Long } * */ public Long getRealTimestamp() { return realTimestamp; } /** * Sets the value of the realTimestamp property. * * @param value * allowed object is {@link Long } * */ public void setRealTimestamp(Long value) { this.realTimestamp = value; } /** * Gets the value of the replyStatus property. * * @return possible object is {@link String } * */ public String getReplyStatus() { return replyStatus; } /** * Sets the value of the replyStatus property. * * @param value * allowed object is {@link String } * */ public void setReplyStatus(String value) { this.replyStatus = value; } /** * Gets the value of the userId property. * * @return possible object is {@link String } * */ public String getUserId() { return userId; } /** * Sets the value of the userId property. * * @param value * allowed object is {@link String } * */ public void setUserId(String value) { this.userId = value; } /** * Gets the value of the valveStatus property. * * @return possible object is {@link String } * */ public String getValveStatus() { return valveStatus; } /** * Sets the value of the valveStatus property. * * @param value * allowed object is {@link String } * */ public void setValveStatus(String value) { this.valveStatus = value; } /** * Gets the value of the waterCustomerId property. * * @return possible object is {@link String } * */ public String getWaterCustomerId() { return waterCustomerId; } /** * Sets the value of the waterCustomerId property. * * @param value * allowed object is {@link String } * */ public void setWaterCustomerId(String value) { this.waterCustomerId = value; } }
/* * 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.beam.runners.apex.translation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import com.datatorrent.lib.util.KryoCloneUtils; import java.util.Arrays; import org.apache.beam.runners.apex.translation.utils.ApexStateInternals; import org.apache.beam.runners.apex.translation.utils.ApexStateInternals.ApexStateBackend; import org.apache.beam.runners.apex.translation.utils.ApexStateInternals.ApexStateInternalsFactory; import org.apache.beam.runners.core.StateMerging; import org.apache.beam.runners.core.StateNamespace; import org.apache.beam.runners.core.StateNamespaceForTest; import org.apache.beam.runners.core.StateTag; import org.apache.beam.runners.core.StateTags; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.coders.VarIntCoder; import org.apache.beam.sdk.transforms.Sum; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.IntervalWindow; import org.apache.beam.sdk.transforms.windowing.TimestampCombiner; import org.apache.beam.sdk.util.state.BagState; import org.apache.beam.sdk.util.state.CombiningState; import org.apache.beam.sdk.util.state.GroupingState; import org.apache.beam.sdk.util.state.ReadableState; import org.apache.beam.sdk.util.state.ValueState; import org.apache.beam.sdk.util.state.WatermarkHoldState; import org.hamcrest.Matchers; import org.joda.time.Instant; import org.junit.Before; import org.junit.Test; /** * Tests for {@link ApexStateInternals}. This is based on the tests for * {@code InMemoryStateInternals}. */ public class ApexStateInternalsTest { private static final BoundedWindow WINDOW_1 = new IntervalWindow(new Instant(0), new Instant(10)); private static final StateNamespace NAMESPACE_1 = new StateNamespaceForTest("ns1"); private static final StateNamespace NAMESPACE_2 = new StateNamespaceForTest("ns2"); private static final StateNamespace NAMESPACE_3 = new StateNamespaceForTest("ns3"); private static final StateTag<Object, ValueState<String>> STRING_VALUE_ADDR = StateTags.value("stringValue", StringUtf8Coder.of()); private static final StateTag<Object, CombiningState<Integer, int[], Integer>> SUM_INTEGER_ADDR = StateTags.combiningValueFromInputInternal( "sumInteger", VarIntCoder.of(), Sum.ofIntegers()); private static final StateTag<Object, BagState<String>> STRING_BAG_ADDR = StateTags.bag("stringBag", StringUtf8Coder.of()); private static final StateTag<Object, WatermarkHoldState> WATERMARK_EARLIEST_ADDR = StateTags.watermarkStateInternal("watermark", TimestampCombiner.EARLIEST); private static final StateTag<Object, WatermarkHoldState> WATERMARK_LATEST_ADDR = StateTags.watermarkStateInternal("watermark", TimestampCombiner.LATEST); private static final StateTag<Object, WatermarkHoldState> WATERMARK_EOW_ADDR = StateTags.watermarkStateInternal("watermark", TimestampCombiner.END_OF_WINDOW); private ApexStateInternals<String> underTest; @Before public void initStateInternals() { underTest = new ApexStateInternals.ApexStateBackend() .newStateInternalsFactory(StringUtf8Coder.of()) .stateInternalsForKey((String) null); } @Test public void testBag() throws Exception { BagState<String> value = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); assertEquals(value, underTest.state(NAMESPACE_1, STRING_BAG_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, STRING_BAG_ADDR))); assertThat(value.read(), Matchers.emptyIterable()); value.add("hello"); assertThat(value.read(), Matchers.containsInAnyOrder("hello")); value.add("world"); assertThat(value.read(), Matchers.containsInAnyOrder("hello", "world")); value.clear(); assertThat(value.read(), Matchers.emptyIterable()); assertEquals(underTest.state(NAMESPACE_1, STRING_BAG_ADDR), value); } @Test public void testBagIsEmpty() throws Exception { BagState<String> value = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); ReadableState<Boolean> readFuture = value.isEmpty(); value.add("hello"); assertThat(readFuture.read(), Matchers.is(false)); value.clear(); assertThat(readFuture.read(), Matchers.is(true)); } @Test public void testMergeBagIntoSource() throws Exception { BagState<String> bag1 = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); BagState<String> bag2 = underTest.state(NAMESPACE_2, STRING_BAG_ADDR); bag1.add("Hello"); bag2.add("World"); bag1.add("!"); StateMerging.mergeBags(Arrays.asList(bag1, bag2), bag1); // Reading the merged bag gets both the contents assertThat(bag1.read(), Matchers.containsInAnyOrder("Hello", "World", "!")); assertThat(bag2.read(), Matchers.emptyIterable()); } @Test public void testMergeBagIntoNewNamespace() throws Exception { BagState<String> bag1 = underTest.state(NAMESPACE_1, STRING_BAG_ADDR); BagState<String> bag2 = underTest.state(NAMESPACE_2, STRING_BAG_ADDR); BagState<String> bag3 = underTest.state(NAMESPACE_3, STRING_BAG_ADDR); bag1.add("Hello"); bag2.add("World"); bag1.add("!"); StateMerging.mergeBags(Arrays.asList(bag1, bag2, bag3), bag3); // Reading the merged bag gets both the contents assertThat(bag3.read(), Matchers.containsInAnyOrder("Hello", "World", "!")); assertThat(bag1.read(), Matchers.emptyIterable()); assertThat(bag2.read(), Matchers.emptyIterable()); } @Test public void testCombiningValue() throws Exception { GroupingState<Integer, Integer> value = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR))); assertThat(value.read(), Matchers.equalTo(0)); value.add(2); assertThat(value.read(), Matchers.equalTo(2)); value.add(3); assertThat(value.read(), Matchers.equalTo(5)); value.clear(); assertThat(value.read(), Matchers.equalTo(0)); assertEquals(underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR), value); } @Test public void testCombiningIsEmpty() throws Exception { GroupingState<Integer, Integer> value = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); ReadableState<Boolean> readFuture = value.isEmpty(); value.add(5); assertThat(readFuture.read(), Matchers.is(false)); value.clear(); assertThat(readFuture.read(), Matchers.is(true)); } @Test public void testMergeCombiningValueIntoSource() throws Exception { CombiningState<Integer, int[], Integer> value1 = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); CombiningState<Integer, int[], Integer> value2 = underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); value1.add(5); value2.add(10); value1.add(6); assertThat(value1.read(), Matchers.equalTo(11)); assertThat(value2.read(), Matchers.equalTo(10)); // Merging clears the old values and updates the result value. StateMerging.mergeCombiningValues(Arrays.asList(value1, value2), value1); assertThat(value1.read(), Matchers.equalTo(21)); assertThat(value2.read(), Matchers.equalTo(0)); } @Test public void testMergeCombiningValueIntoNewNamespace() throws Exception { CombiningState<Integer, int[], Integer> value1 = underTest.state(NAMESPACE_1, SUM_INTEGER_ADDR); CombiningState<Integer, int[], Integer> value2 = underTest.state(NAMESPACE_2, SUM_INTEGER_ADDR); CombiningState<Integer, int[], Integer> value3 = underTest.state(NAMESPACE_3, SUM_INTEGER_ADDR); value1.add(5); value2.add(10); value1.add(6); StateMerging.mergeCombiningValues(Arrays.asList(value1, value2), value3); // Merging clears the old values and updates the result value. assertThat(value1.read(), Matchers.equalTo(0)); assertThat(value2.read(), Matchers.equalTo(0)); assertThat(value3.read(), Matchers.equalTo(21)); } @Test public void testWatermarkEarliestState() throws Exception { WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_EARLIEST_ADDR))); assertThat(value.read(), Matchers.nullValue()); value.add(new Instant(2000)); assertThat(value.read(), Matchers.equalTo(new Instant(2000))); value.add(new Instant(3000)); assertThat(value.read(), Matchers.equalTo(new Instant(2000))); value.add(new Instant(1000)); assertThat(value.read(), Matchers.equalTo(new Instant(1000))); value.clear(); assertThat(value.read(), Matchers.equalTo(null)); assertEquals(underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR), value); } @Test public void testWatermarkLatestState() throws Exception { WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_LATEST_ADDR))); assertThat(value.read(), Matchers.nullValue()); value.add(new Instant(2000)); assertThat(value.read(), Matchers.equalTo(new Instant(2000))); value.add(new Instant(3000)); assertThat(value.read(), Matchers.equalTo(new Instant(3000))); value.add(new Instant(1000)); assertThat(value.read(), Matchers.equalTo(new Instant(3000))); value.clear(); assertThat(value.read(), Matchers.equalTo(null)); assertEquals(underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR), value); } @Test public void testWatermarkEndOfWindowState() throws Exception { WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR); // State instances are cached, but depend on the namespace. assertEquals(value, underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR)); assertFalse(value.equals(underTest.state(NAMESPACE_2, WATERMARK_EOW_ADDR))); assertThat(value.read(), Matchers.nullValue()); value.add(new Instant(2000)); assertThat(value.read(), Matchers.equalTo(new Instant(2000))); value.clear(); assertThat(value.read(), Matchers.equalTo(null)); assertEquals(underTest.state(NAMESPACE_1, WATERMARK_EOW_ADDR), value); } @Test public void testWatermarkStateIsEmpty() throws Exception { WatermarkHoldState value = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); assertThat(value.isEmpty().read(), Matchers.is(true)); ReadableState<Boolean> readFuture = value.isEmpty(); value.add(new Instant(1000)); assertThat(readFuture.read(), Matchers.is(false)); value.clear(); assertThat(readFuture.read(), Matchers.is(true)); } @Test public void testMergeEarliestWatermarkIntoSource() throws Exception { WatermarkHoldState value1 = underTest.state(NAMESPACE_1, WATERMARK_EARLIEST_ADDR); WatermarkHoldState value2 = underTest.state(NAMESPACE_2, WATERMARK_EARLIEST_ADDR); value1.add(new Instant(3000)); value2.add(new Instant(5000)); value1.add(new Instant(4000)); value2.add(new Instant(2000)); // Merging clears the old values and updates the merged value. StateMerging.mergeWatermarks(Arrays.asList(value1, value2), value1, WINDOW_1); assertThat(value1.read(), Matchers.equalTo(new Instant(2000))); assertThat(value2.read(), Matchers.equalTo(null)); } @Test public void testMergeLatestWatermarkIntoSource() throws Exception { WatermarkHoldState value1 = underTest.state(NAMESPACE_1, WATERMARK_LATEST_ADDR); WatermarkHoldState value2 = underTest.state(NAMESPACE_2, WATERMARK_LATEST_ADDR); WatermarkHoldState value3 = underTest.state(NAMESPACE_3, WATERMARK_LATEST_ADDR); value1.add(new Instant(3000)); value2.add(new Instant(5000)); value1.add(new Instant(4000)); value2.add(new Instant(2000)); // Merging clears the old values and updates the result value. StateMerging.mergeWatermarks(Arrays.asList(value1, value2), value3, WINDOW_1); // Merging clears the old values and updates the result value. assertThat(value3.read(), Matchers.equalTo(new Instant(5000))); assertThat(value1.read(), Matchers.equalTo(null)); assertThat(value2.read(), Matchers.equalTo(null)); } @Test public void testSerialization() throws Exception { ApexStateInternalsFactory<String> sif = new ApexStateBackend(). newStateInternalsFactory(StringUtf8Coder.of()); ApexStateInternals<String> keyAndState = sif.stateInternalsForKey("dummy"); ValueState<String> value = keyAndState.state(NAMESPACE_1, STRING_VALUE_ADDR); assertEquals(keyAndState.state(NAMESPACE_1, STRING_VALUE_ADDR), value); value.write("hello"); ApexStateInternalsFactory<String> cloned; assertNotNull("Serialization", cloned = KryoCloneUtils.cloneObject(sif)); ApexStateInternals<String> clonedKeyAndState = cloned.stateInternalsForKey("dummy"); ValueState<String> clonedValue = clonedKeyAndState.state(NAMESPACE_1, STRING_VALUE_ADDR); assertThat(clonedValue.read(), Matchers.equalTo("hello")); assertEquals(clonedKeyAndState.state(NAMESPACE_1, STRING_VALUE_ADDR), value); } }
/******************************************************************************* * 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.ofbiz.service.jms; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.jms.JMSException; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.jms.XAQueueConnection; import javax.jms.XAQueueConnectionFactory; import javax.jms.XAQueueSession; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.transaction.xa.XAResource; import javolution.util.FastMap; import org.ofbiz.base.config.GenericConfigException; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.JNDIContextFactory; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilXml; import org.ofbiz.entity.transaction.GenericTransactionException; import org.ofbiz.entity.transaction.TransactionUtil; import org.ofbiz.service.GenericRequester; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.ModelService; import org.ofbiz.service.ServiceDispatcher; import org.ofbiz.service.ServiceUtil; import org.ofbiz.service.config.ServiceConfigUtil; import org.ofbiz.service.config.model.JmsService; import org.ofbiz.service.config.model.Server; import org.ofbiz.service.engine.AbstractEngine; import org.w3c.dom.Element; /** * AbstractJMSEngine */ public class JmsServiceEngine extends AbstractEngine { public static final String module = JmsServiceEngine.class.getName(); public JmsServiceEngine(ServiceDispatcher dispatcher) { super(dispatcher); } protected JmsService getServiceElement(ModelService modelService) throws GenericServiceException { String location = this.getLocation(modelService); try { return ServiceConfigUtil.getServiceEngine().getJmsServiceByName(location); } catch (GenericConfigException e) { throw new GenericServiceException(e); } } protected Message makeMessage(Session session, ModelService modelService, Map<String, Object> context) throws GenericServiceException, JMSException { List<String> outParams = modelService.getParameterNames(ModelService.OUT_PARAM, false); if (UtilValidate.isNotEmpty(outParams)) throw new GenericServiceException("JMS service cannot have required OUT parameters; no parameters will be returned."); String xmlContext = null; try { if (Debug.verboseOn()) Debug.logVerbose("Serializing Context --> " + context, module); xmlContext = JmsSerializer.serialize(context); } catch (Exception e) { throw new GenericServiceException("Cannot serialize context.", e); } MapMessage message = session.createMapMessage(); message.setString("serviceName", modelService.invoke); message.setString("serviceContext", xmlContext); return message; } protected List<? extends Element> serverList(Element serviceElement) throws GenericServiceException { String sendMode = serviceElement.getAttribute("send-mode"); List<? extends Element> serverList = UtilXml.childElementList(serviceElement, "server"); if (sendMode.equals("none")) { return new ArrayList<Element>(); } else if (sendMode.equals("all")) { return serverList; } else { throw new GenericServiceException("Requested send mode not supported."); } } protected Map<String, Object> runTopic(ModelService modelService, Map<String, Object> context, Server server) throws GenericServiceException { String serverName = server.getJndiServerName(); String jndiName = server.getJndiName(); String topicName = server.getTopicQueue(); String userName = server.getUsername(); String password = server.getPassword(); String clientId = server.getClientId(); InitialContext jndi = null; TopicConnectionFactory factory = null; TopicConnection con = null; try { jndi = JNDIContextFactory.getInitialContext(serverName); factory = (TopicConnectionFactory) jndi.lookup(jndiName); } catch (GeneralException ge) { throw new GenericServiceException("Problems getting JNDI InitialContext.", ge.getNested()); } catch (NamingException ne) { JNDIContextFactory.clearInitialContext(serverName); try { jndi = JNDIContextFactory.getInitialContext(serverName); factory = (TopicConnectionFactory) jndi.lookup(jndiName); } catch (GeneralException ge2) { throw new GenericServiceException("Problems getting JNDI InitialContext.", ge2.getNested()); } catch (NamingException ne2) { throw new GenericServiceException("JNDI lookup problems.", ne); } } try { con = factory.createTopicConnection(userName, password); if (clientId != null && clientId.length() > 1) con.setClientID(clientId); con.start(); TopicSession session = con.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = (Topic) jndi.lookup(topicName); TopicPublisher publisher = session.createPublisher(topic); // create/send the message Message message = makeMessage(session, modelService, context); publisher.publish(message); if (Debug.verboseOn()) Debug.logVerbose("Sent JMS Message to " + topicName, module); // close the connections publisher.close(); session.close(); con.close(); } catch (NamingException ne) { throw new GenericServiceException("Problems with JNDI lookup.", ne); } catch (JMSException je) { throw new GenericServiceException("JMS Internal Error.", je); } return ServiceUtil.returnSuccess(); } protected Map<String, Object> runQueue(ModelService modelService, Map<String, Object> context, Server server) throws GenericServiceException { String serverName = server.getJndiServerName(); String jndiName = server.getJndiName(); String queueName = server.getTopicQueue(); String userName = server.getUsername(); String password = server.getPassword(); String clientId = server.getClientId(); InitialContext jndi = null; QueueConnectionFactory factory = null; QueueConnection con = null; try { jndi = JNDIContextFactory.getInitialContext(serverName); factory = (QueueConnectionFactory) jndi.lookup(jndiName); } catch (GeneralException ge) { throw new GenericServiceException("Problems getting JNDI InitialContext.", ge.getNested()); } catch (NamingException ne) { JNDIContextFactory.clearInitialContext(serverName); try { jndi = JNDIContextFactory.getInitialContext(serverName); factory = (QueueConnectionFactory) jndi.lookup(jndiName); } catch (GeneralException ge2) { throw new GenericServiceException("Problems getting JNDI InitialContext.", ge2.getNested()); } catch (NamingException ne2) { throw new GenericServiceException("JNDI lookup problem.", ne2); } } try { con = factory.createQueueConnection(userName, password); if (clientId != null && clientId.length() > 1) con.setClientID(clientId); con.start(); QueueSession session = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = (Queue) jndi.lookup(queueName); QueueSender sender = session.createSender(queue); // create/send the message Message message = makeMessage(session, modelService, context); sender.send(message); if (Debug.verboseOn()) Debug.logVerbose("Sent JMS Message to " + queueName, module); // close the connections sender.close(); session.close(); con.close(); } catch (NamingException ne) { throw new GenericServiceException("Problems with JNDI lookup.", ne); } catch (JMSException je) { throw new GenericServiceException("JMS Internal Error.", je); } return ServiceUtil.returnSuccess(); } protected Map<String, Object> runXaQueue(ModelService modelService, Map<String, Object> context, Element server) throws GenericServiceException { String serverName = server.getAttribute("jndi-server-name"); String jndiName = server.getAttribute("jndi-name"); String queueName = server.getAttribute("topic-queue"); String userName = server.getAttribute("username"); String password = server.getAttribute("password"); String clientId = server.getAttribute("client-id"); InitialContext jndi = null; XAQueueConnectionFactory factory = null; XAQueueConnection con = null; try { jndi = JNDIContextFactory.getInitialContext(serverName); factory = (XAQueueConnectionFactory) jndi.lookup(jndiName); } catch (GeneralException ge) { throw new GenericServiceException("Problems getting JNDI InitialContext.", ge.getNested()); } catch (NamingException ne) { JNDIContextFactory.clearInitialContext(serverName); try { jndi = JNDIContextFactory.getInitialContext(serverName); factory = (XAQueueConnectionFactory) jndi.lookup(jndiName); } catch (GeneralException ge2) { throw new GenericServiceException("Problems getting JNDI InitialContext.", ge2.getNested()); } catch (NamingException ne2) { throw new GenericServiceException("JNDI lookup problems.", ne2); } } try { con = factory.createXAQueueConnection(userName, password); if (clientId != null && clientId.length() > 1) con.setClientID(userName); con.start(); // enlist the XAResource XAQueueSession session = con.createXAQueueSession(); XAResource resource = session.getXAResource(); if (TransactionUtil.getStatus() == TransactionUtil.STATUS_ACTIVE) TransactionUtil.enlistResource(resource); Queue queue = (Queue) jndi.lookup(queueName); QueueSession qSession = session.getQueueSession(); QueueSender sender = qSession.createSender(queue); // create/send the message Message message = makeMessage(session, modelService, context); sender.send(message); if (TransactionUtil.getStatus() != TransactionUtil.STATUS_ACTIVE) session.commit(); Debug.logInfo("Message sent.", module); // close the connections sender.close(); session.close(); con.close(); } catch (GenericTransactionException gte) { throw new GenericServiceException("Problems enlisting resource w/ transaction manager.", gte.getNested()); } catch (NamingException ne) { throw new GenericServiceException("Problems with JNDI lookup.", ne); } catch (JMSException je) { throw new GenericServiceException("JMS Internal Error.", je); } return ServiceUtil.returnSuccess(); } protected Map<String, Object> run(ModelService modelService, Map<String, Object> context) throws GenericServiceException { JmsService serviceElement = getServiceElement(modelService); List<Server> serverList = serviceElement.getServers(); Map<String, Object> result = FastMap.newInstance(); for (Server server: serverList) { String serverType = server.getType(); if (serverType.equals("topic")) result.putAll(runTopic(modelService, context, server)); else if (serverType.equals("queue")) result.putAll(runQueue(modelService, context, server)); else throw new GenericServiceException("Illegal server messaging type."); } return result; } /** * @see org.ofbiz.service.engine.GenericEngine#runSync(java.lang.String, org.ofbiz.service.ModelService, java.util.Map) */ public Map<String, Object> runSync(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException { return run(modelService, context); } /** * @see org.ofbiz.service.engine.GenericEngine#runSyncIgnore(java.lang.String, org.ofbiz.service.ModelService, java.util.Map) */ public void runSyncIgnore(String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException { run(modelService, context); } /** * @see org.ofbiz.service.engine.GenericEngine#runAsync(java.lang.String, org.ofbiz.service.ModelService, java.util.Map, org.ofbiz.service.GenericRequester, boolean) */ public void runAsync(String localName, ModelService modelService, Map<String, Object> context, GenericRequester requester, boolean persist) throws GenericServiceException { Map<String, Object> result = run(modelService, context); requester.receiveResult(result); } /** * @see org.ofbiz.service.engine.GenericEngine#runAsync(java.lang.String, org.ofbiz.service.ModelService, java.util.Map, boolean) */ public void runAsync(String localName, ModelService modelService, Map<String, Object> context, boolean persist) throws GenericServiceException { run(modelService, context); } }
/* * 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.component.spring.ws; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.security.GeneralSecurityException; import java.util.Iterator; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.xml.namespace.QName; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.RuntimeCamelException; import org.apache.camel.attachment.AttachmentMessage; import org.apache.camel.support.DefaultProducer; import org.apache.camel.support.ExchangeHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ws.WebServiceMessage; import org.springframework.ws.client.core.WebServiceMessageCallback; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.mime.Attachment; import org.springframework.ws.soap.SoapHeader; import org.springframework.ws.soap.SoapHeaderElement; import org.springframework.ws.soap.SoapMessage; import org.springframework.ws.soap.addressing.client.ActionCallback; import org.springframework.ws.soap.addressing.core.EndpointReference; import org.springframework.ws.soap.client.core.SoapActionCallback; import org.springframework.ws.transport.WebServiceConnection; import org.springframework.ws.transport.WebServiceMessageSender; import org.springframework.ws.transport.http.AbstractHttpWebServiceMessageSender; import org.springframework.ws.transport.http.HttpComponentsMessageSender; import org.springframework.ws.transport.http.HttpUrlConnection; import org.springframework.ws.transport.http.HttpUrlConnectionMessageSender; import static org.apache.camel.component.spring.ws.SpringWebserviceHelper.toResult; public class SpringWebserviceProducer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(SpringWebserviceProducer.class); public SpringWebserviceProducer(Endpoint endpoint) { super(endpoint); prepareMessageSenders(getEndpoint().getConfiguration()); } @Override public SpringWebserviceEndpoint getEndpoint() { return (SpringWebserviceEndpoint) super.getEndpoint(); } @Override public void process(Exchange exchange) throws Exception { // Let Camel TypeConverter hierarchy handle the conversion of XML messages to Source objects Source sourcePayload = exchange.getIn().getMandatoryBody(Source.class); // Extract optional headers String endpointUriHeader = exchange.getIn().getHeader(SpringWebserviceConstants.SPRING_WS_ENDPOINT_URI, String.class); String soapActionHeader = exchange.getIn().getHeader(SpringWebserviceConstants.SPRING_WS_SOAP_ACTION, String.class); URI wsAddressingActionHeader = exchange.getIn().getHeader(SpringWebserviceConstants.SPRING_WS_ADDRESSING_ACTION, URI.class); URI wsReplyToHeader = exchange.getIn().getHeader(SpringWebserviceConstants.SPRING_WS_ADDRESSING_PRODUCER_REPLY_TO, URI.class); URI wsFaultToHeader = exchange.getIn().getHeader(SpringWebserviceConstants.SPRING_WS_ADDRESSING_PRODUCER_FAULT_TO, URI.class); Source soapHeaderSource = exchange.getIn().getHeader(SpringWebserviceConstants.SPRING_WS_SOAP_HEADER, Source.class); WebServiceMessageCallback callback = new DefaultWebserviceMessageCallback( soapActionHeader, wsAddressingActionHeader, wsReplyToHeader, wsFaultToHeader, soapHeaderSource, getEndpoint().getConfiguration(), exchange); if (endpointUriHeader == null) { endpointUriHeader = getEndpoint().getConfiguration().getWebServiceTemplate().getDefaultUri(); } getEndpoint().getConfiguration().getWebServiceTemplate().sendAndReceive(endpointUriHeader, new WebServiceMessageCallback() { @Override public void doWithMessage(WebServiceMessage requestMessage) throws IOException, TransformerException { toResult(sourcePayload, requestMessage.getPayloadResult()); callback.doWithMessage(requestMessage); } }, new WebServiceMessageCallback() { @Override public void doWithMessage(WebServiceMessage responseMessage) throws IOException, TransformerException { SoapMessage soapMessage = (SoapMessage) responseMessage; if (ExchangeHelper.isOutCapable(exchange)) { exchange.getOut().copyFromWithNewBody(exchange.getIn(), soapMessage.getPayloadSource()); populateHeaderAndAttachmentsFromResponse(exchange.getOut(AttachmentMessage.class), soapMessage); } else { exchange.getIn().setBody(soapMessage.getPayloadSource()); populateHeaderAndAttachmentsFromResponse(exchange.getIn(AttachmentMessage.class), soapMessage); } } }); } /** * Populates soap message headers and attachments from soap response */ private void populateHeaderAndAttachmentsFromResponse(AttachmentMessage inOrOut, SoapMessage soapMessage) { if (soapMessage.getSoapHeader() != null && getEndpoint().getConfiguration().isAllowResponseHeaderOverride()) { populateMessageHeaderFromResponse(inOrOut, soapMessage.getSoapHeader()); } if (soapMessage.getAttachments() != null && getEndpoint().getConfiguration().isAllowResponseAttachmentOverride()) { populateMessageAttachmentsFromResponse(inOrOut, soapMessage.getAttachments()); } } /** * Populates message headers from soapHeader response */ private void populateMessageHeaderFromResponse(Message message, SoapHeader soapHeader) { message.setHeader(SpringWebserviceConstants.SPRING_WS_SOAP_HEADER, soapHeader.getSource()); // Set header values for the soap header attributes Iterator<QName> attIter = soapHeader.getAllAttributes(); while (attIter.hasNext()) { QName name = attIter.next(); message.getHeaders().put(name.getLocalPart(), soapHeader.getAttributeValue(name)); } // Set header values for the soap header elements Iterator<SoapHeaderElement> elementIter = soapHeader.examineAllHeaderElements(); while (elementIter.hasNext()) { SoapHeaderElement element = elementIter.next(); QName name = element.getName(); message.getHeaders().put(name.getLocalPart(), element); } } /** * Populates message attachments from soap response attachments */ private void populateMessageAttachmentsFromResponse(AttachmentMessage inOrOut, Iterator<Attachment> attachments) { while (attachments.hasNext()) { Attachment attachment = attachments.next(); inOrOut.addAttachment(attachment.getContentId(), attachment.getDataHandler()); } } private void prepareMessageSenders(SpringWebserviceConfiguration configuration) { // Skip this whole thing if none of the relevant config options are set. if (!(configuration.getTimeout() > -1) && configuration.getSslContextParameters() == null) { return; } WebServiceTemplate webServiceTemplate = configuration.getWebServiceTemplate(); WebServiceMessageSender[] messageSenders = webServiceTemplate.getMessageSenders(); for (int i = 0; i < messageSenders.length; i++) { WebServiceMessageSender messageSender = messageSenders[i]; if (messageSender instanceof HttpComponentsMessageSender) { if (configuration.getSslContextParameters() != null) { LOG.warn("Not applying SSLContextParameters based configuration to HttpComponentsMessageSender. " + "If you are using this MessageSender, which you are not by default, you will need " + "to configure SSL using the Commons HTTP 3.x Protocol registry."); } if (configuration.getTimeout() > -1) { if (messageSender.getClass().equals(HttpComponentsMessageSender.class)) { ((HttpComponentsMessageSender) messageSender).setReadTimeout(configuration.getTimeout()); } else { LOG.warn("Not applying timeout configuration to HttpComponentsMessageSender based implementation. " + "You are using what appears to be a custom MessageSender, which you are not doing by default. " + "You will need configure timeout on your own."); } } } else if (messageSender.getClass().equals(HttpUrlConnectionMessageSender.class)) { // Only if exact match denoting likely use of default configuration. We don't want to get // sub-classes that might have been otherwise injected. messageSenders[i] = new AbstractHttpWebServiceMessageSenderDecorator( (HttpUrlConnectionMessageSender) messageSender, configuration, getEndpoint().getCamelContext()); } else { // For example this will be the case during unit-testing with the net.javacrumbs.spring-ws-test API LOG.warn("Ignoring the timeout and SSLContextParameters options for {}. You will need to configure " + "these options directly on your custom configured WebServiceMessageSender", messageSender); } } } /** * A decorator of {@link HttpUrlConnectionMessageSender} instances that can apply configuration options from the * Camel component/endpoint configuration without replacing the actual implementation which may actually be an * end-user implementation and not one of the built-in implementations. */ protected static final class AbstractHttpWebServiceMessageSenderDecorator extends AbstractHttpWebServiceMessageSender { private final AbstractHttpWebServiceMessageSender delegate; private final SpringWebserviceConfiguration configuration; private final CamelContext camelContext; private SSLContext sslContext; public AbstractHttpWebServiceMessageSenderDecorator(AbstractHttpWebServiceMessageSender delegate, SpringWebserviceConfiguration configuration, CamelContext camelContext) { this.delegate = delegate; this.configuration = configuration; this.camelContext = camelContext; } @Override public WebServiceConnection createConnection(URI uri) throws IOException { WebServiceConnection wsc = delegate.createConnection(uri); if (wsc instanceof HttpUrlConnection) { HttpURLConnection connection = ((HttpUrlConnection) wsc).getConnection(); if (configuration.getTimeout() > -1) { connection.setReadTimeout(configuration.getTimeout()); } if (configuration.getSslContextParameters() != null && connection instanceof HttpsURLConnection) { try { synchronized (this) { if (sslContext == null) { sslContext = configuration.getSslContextParameters().createSSLContext(camelContext); } } } catch (GeneralSecurityException e) { throw new RuntimeCamelException("Error creating SSLContext based on SSLContextParameters.", e); } ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } } else { throw new RuntimeCamelException( "Unsupported delegate. Delegate must return a org.springframework.ws.transport.http.HttpUrlConnection. Found " + wsc.getClass()); } return wsc; } @Override public boolean isAcceptGzipEncoding() { return delegate.isAcceptGzipEncoding(); } @Override public void setAcceptGzipEncoding(boolean acceptGzipEncoding) { delegate.setAcceptGzipEncoding(acceptGzipEncoding); } @Override public boolean supports(URI uri) { return delegate.supports(uri); } } protected static class DefaultWebserviceMessageCallback implements WebServiceMessageCallback { private final String soapActionHeader; private final URI wsAddressingActionHeader; private final URI wsReplyToHeader; private final URI wsFaultToHeader; private final Source soapHeaderSource; private final SpringWebserviceConfiguration configuration; private final Exchange exchange; public DefaultWebserviceMessageCallback(String soapAction, URI wsAddressingAction, URI wsReplyTo, URI wsFaultTo, Source soapHeaderSource, SpringWebserviceConfiguration configuration, Exchange exchange) { this.soapActionHeader = soapAction; this.wsAddressingActionHeader = wsAddressingAction; this.wsReplyToHeader = wsReplyTo; this.wsFaultToHeader = wsFaultTo; this.soapHeaderSource = soapHeaderSource; this.configuration = configuration; this.exchange = exchange; } @Override public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { // Add SoapAction to webservice request. Note that exchange header // takes precedence over endpoint option String soapAction = soapActionHeader != null ? soapActionHeader : configuration.getSoapAction(); if (soapAction != null) { new SoapActionCallback(soapAction).doWithMessage(message); } // Add WS-Addressing Action to webservice request (the WS-Addressing // 'to' header will default to the URL of the connection). // Note that exchange header takes precedence over endpoint option URI wsAddressingAction = wsAddressingActionHeader != null ? wsAddressingActionHeader : configuration.getWsAddressingAction(); URI wsReplyTo = wsReplyToHeader != null ? wsReplyToHeader : configuration.getReplyTo(); URI wsFaultTo = wsFaultToHeader != null ? wsFaultToHeader : configuration.getFaultTo(); // Create the SOAP header if (soapHeaderSource != null) { SoapHeader header = ((SoapMessage) message).getSoapHeader(); toResult(soapHeaderSource, header.getResult()); } if (wsAddressingAction != null) { ActionCallback actionCallback = new ActionCallback(wsAddressingAction); if (configuration.getMessageIdStrategy() != null) { actionCallback.setMessageIdStrategy(configuration.getMessageIdStrategy()); } if (wsReplyTo != null) { actionCallback.setReplyTo(new EndpointReference(wsReplyTo)); } if (wsFaultTo != null) { actionCallback.setFaultTo(new EndpointReference(wsFaultTo)); } actionCallback.doWithMessage(message); } configuration.getMessageFilter().filterProducer(exchange, message); } } }
package org.edx.mobile.view; import android.app.ActionBar; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import org.edx.mobile.R; import org.edx.mobile.base.MyVideosBaseFragment; import org.edx.mobile.interfaces.SectionItemInterface; import org.edx.mobile.logger.Logger; import org.edx.mobile.model.api.ProfileModel; import org.edx.mobile.model.api.VideoResponseModel; import org.edx.mobile.model.db.DownloadEntry; import org.edx.mobile.module.analytics.ISegment; import org.edx.mobile.module.db.DataCallback; import org.edx.mobile.module.prefs.PrefManager; import org.edx.mobile.player.PlayerFragment; import org.edx.mobile.player.VideoListFragment.VideoListCallback; import org.edx.mobile.util.AppConstants; import org.edx.mobile.util.NetworkUtil; import org.edx.mobile.util.ResourceUtil; import org.edx.mobile.util.UiUtil; import org.edx.mobile.view.adapters.MyRecentVideoAdapter; import org.edx.mobile.view.dialog.DeleteVideoDialogFragment; import org.edx.mobile.view.dialog.IDialogCallback; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class MyRecentVideosFragment extends MyVideosBaseFragment { private MyRecentVideoAdapter adapter; private ListView videoListView; private DeleteVideoDialogFragment deleteDialogFragment; private int playingVideoIndex = -1; private VideoListCallback callback; private MyVideosTabActivity containerActivity; private DownloadEntry videoModel; private Button deleteButton = null; private final Handler handler = new Handler(); protected final Logger logger = new Logger(getClass().getName()); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_video_list_with_player_container, null); environment.getSegment().trackScreenView(ISegment.Screens.MY_VIDEOS_RECENT); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); restore(savedInstanceState); try{ videoListView = (ListView) getView().findViewById(R.id.list_video); if (videoListView != null) { String selectedId = null; if(adapter!=null){ selectedId = adapter.getVideoId(); } adapter = new MyRecentVideoAdapter(getActivity(), environment) { @Override protected boolean onTouchEvent(SectionItemInterface model, int position, MotionEvent event) { logger.debug("event action: " + event.getAction()); final MyVideosTabActivity activity = ((MyVideosTabActivity) getActivity()); if (event.getAction() == MotionEvent.ACTION_DOWN) { activity.setTabChangeEnabled(false); } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) { if (model.isDownload() && event.getAction() == MotionEvent.ACTION_UP) { // ACTION_UP verifies a CLICK event if ( !isPlayerVisible()) { // don't try to showPlayer() if already shown here // this will cause player to freeze showPlayer(); } // initialize index for this model playingVideoIndex = position; //Set videoId to adaptor to determine the currently playing video DownloadEntry downloadEntry = (DownloadEntry) model; adapter.setVideoId(downloadEntry.videoId); play(model); notifyAdapter(); } handler.postDelayed(new Runnable() { @Override public void run() { if (activity != null) activity.setTabChangeEnabled(true); } }, 500); } return true; } @Override public void onSelectItem() { handleCheckboxSelection(); } }; // videoAdaptor.setItems(sectionList); if(selectedId!=null){ adapter.setVideoId(selectedId); } adapter.setSelectedPosition(playingVideoIndex); videoListView.setEmptyView(getView().findViewById(R.id.empty_list_view)); videoListView.setAdapter(adapter); showDeletePanel(getView()); if (!(NetworkUtil.isConnected(getActivity().getBaseContext()))) { AppConstants.offline_flag = true; } else { AppConstants.offline_flag = false; } videoListView.setOnItemClickListener(adapter); } else { // probably the landscape player view, so hide action bar ActionBar bar = getActivity().getActionBar(); if(bar!=null){ bar.hide(); } } }catch(Exception e){ logger.error(e); } } @Override public void onResume() { super.onResume(); try { addToRecentAdapter(getView()); } catch (Exception ex) { logger.error(ex); } if (containerActivity.playerFragment != null) { showPlayer(); } notifyAdapter(); } @Override public void onStop() { super.onStop(); hideConfirmDeleteDialog(); if (getActivity() instanceof MyVideosTabActivity) { ((MyVideosTabActivity) getActivity()).invalidateOptionsMenu(); } } @Override public void onDestroy() { super.onDestroy(); } private void addToRecentAdapter(View view) { try { logger.debug("reloading adapter..."); String selectedId = null; if(adapter!=null){ selectedId = adapter.getVideoId(); } ArrayList<SectionItemInterface> list = environment.getStorage().getRecentDownloadedVideosList(); if (list != null) { adapter.clear(); for (SectionItemInterface m : list) { adapter.add(m); } logger.debug("reload done"); } if(adapter.getCount()<=0){ hideDeletePanel(view); } videoListView.setOnItemClickListener(adapter); if(selectedId!=null){ adapter.setVideoId(selectedId); } } catch (Exception e) { logger.error(e); } } private void play(SectionItemInterface model) { if (model instanceof DownloadEntry) { DownloadEntry v = (DownloadEntry) model; try { String prefName = PrefManager.getPrefNameForLastAccessedBy(getProfile() .username, v.eid); PrefManager prefManager = new PrefManager(getActivity(), prefName); VideoResponseModel vrm = environment.getServiceManager().getVideoById(v.eid, v.videoId); prefManager.putLastAccessedSubsection(vrm.getSection().getId(), false); if (callback != null) { videoModel = v; if (getActivity() instanceof MyVideosTabActivity) { ((MyVideosTabActivity)getActivity()) .setRecentNextPrevListeners(getNextListener(), getPreviousListener()); } callback.playVideoModel(v); adapter.setVideoId(videoModel.videoId); } } catch (Exception e) { logger.error(e); } } } private void showPlayer() { if (!isResumed() || isRemoving()) { logger.warn("not showing player because fragment is being stopped"); return; } final MyVideosTabActivity activity = ((MyVideosTabActivity) getActivity()); activity.setTabChangeEnabled(false); hideDeletePanel(getView()); try { View container = getView().findViewById(R.id.container_player); if (container.getVisibility() != View.VISIBLE) { container.setVisibility(View.VISIBLE); } // add and display player fragment if (containerActivity.playerFragment == null) { containerActivity.playerFragment = new PlayerFragment(); } // this is for INLINE player only if (isResumed() && !isLandscape() && !isRemoving()) { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); if (containerActivity.playerFragment.isAdded()) { ft.detach(containerActivity.playerFragment); logger.debug("removing player from view ..."); ft.attach(containerActivity.playerFragment); logger.debug("adding player to view ..."); } else { ft.replace(R.id.container_player, containerActivity.playerFragment, "player"); } ft.commit(); logger.debug("showing player ..."); } } catch (Exception ex) { logger.error(ex); logger.warn("Error in showing player"); } finally { /* After a while, enable tabs. 300 milliseconds is enough time for player view to be shown. Enabling the tabs immediately will allow simultaneous taps and will let the player play in background. */ handler.postDelayed(new Runnable() { @Override public void run() { if (activity != null) activity.setTabChangeEnabled(true); } }, 300); } } public void onOffline() { try{ AppConstants.offline_flag = true; notifyAdapter(); videoListView.setOnItemClickListener(adapter); }catch(Exception e){ logger.error(e); } } protected void onOnline() { try{ AppConstants.offline_flag = false; notifyAdapter(); videoListView.setOnItemClickListener(adapter); }catch(Exception e){ logger.error(e); } } private void hideDeletePanel(View view) { try { // hide delete button panel at bottom view.findViewById(R.id.delete_button_panel).setVisibility(View.GONE); handler.postDelayed(new Runnable() { public void run() { try { // hide checkbox in action bar MyVideosTabActivity activity = ((MyVideosTabActivity) getActivity()); if (activity != null) activity.hideCheckBox(); // hide checkboxes in list notifyAdapter(); } catch (Exception ex) { logger.error(ex); } } }, 300); } catch (Exception ex) { logger.error(ex); logger.warn("error in hiding delete button Panel"); } } public void showDeletePanel(View view) { try { if (!isPlayerVisible()) { LinearLayout deletePanel = (LinearLayout) view .findViewById(R.id.delete_button_panel); deletePanel.setVisibility(View.VISIBLE); deleteButton = (Button) view .findViewById(R.id.delete_btn); final Button editButton = (Button) view .findViewById(R.id.edit_btn); editButton.setVisibility(View.VISIBLE); final Button cancelButton = (Button) view .findViewById(R.id.cancel_btn); if(AppConstants.myVideosDeleteMode){ deleteButton.setVisibility(View.VISIBLE); cancelButton.setVisibility(View.VISIBLE); editButton.setVisibility(View.GONE); }else{ deleteButton.setVisibility(View.GONE); cancelButton.setVisibility(View.GONE); editButton.setVisibility(View.VISIBLE); } deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ArrayList<SectionItemInterface> list = adapter .getSelectedItems(); if (list != null && list.size() > 0) showConfirmDeleteDialog(list.size()); } }); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { editButton.setVisibility(View.VISIBLE); videoListView.setOnItemClickListener(adapter); AppConstants.myVideosDeleteMode = false; if (getActivity() instanceof MyVideosTabActivity) { ((MyVideosTabActivity) getActivity()).hideCheckBox(); } adapter.unselectAll(); AppConstants.myVideosDeleteMode = false; notifyAdapter(); deleteButton.setVisibility(View.GONE); cancelButton.setVisibility(View.GONE); } }); editButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { editButton.setVisibility(View.GONE); AppConstants.myVideosDeleteMode = true; notifyAdapter(); videoListView.setOnItemClickListener(null); disableDeleteButton(); deleteButton.setVisibility(View.VISIBLE); cancelButton.setVisibility(View.VISIBLE); if (getActivity() instanceof MyVideosTabActivity) { ((MyVideosTabActivity) getActivity()).showCheckBox(); } } }); }else{ hideDeletePanel(view); } } catch (Exception ex) { logger.error(ex); logger.debug("error in showing delete panel"); } } protected void showConfirmDeleteDialog(int itemCount) { Map<String, String> dialogMap = new HashMap<String, String>(); dialogMap.put("title", getString(R.string.delete_dialog_title_help)); dialogMap.put("message_1", getResources().getQuantityString(R.plurals.delete_video_dialog_msg, itemCount)); dialogMap.put("yes_button", getString(R.string.label_delete)); dialogMap.put("no_button", getString(R.string.label_cancel)); deleteDialogFragment = DeleteVideoDialogFragment.newInstance(dialogMap, new IDialogCallback() { @Override public void onPositiveClicked() { onConfirmDelete(); deleteDialogFragment.dismiss(); } @Override public void onNegativeClicked() { deleteDialogFragment.dismiss(); } }); deleteDialogFragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0); deleteDialogFragment.show(getFragmentManager(), "dialog"); deleteDialogFragment.setCancelable(false); } protected void hideConfirmDeleteDialog() { try{ if(deleteDialogFragment!=null){ deleteDialogFragment.dismiss(); } }catch(Exception e){ logger.error(e); } } //Deleting Downloaded videos on getting confirmation private void onConfirmDelete() { try{ int deletedVideoCount = 0; ArrayList<SectionItemInterface> list = adapter.getSelectedItems(); if (list != null) { for (SectionItemInterface section : list) { if (section.isDownload()) { DownloadEntry de = (DownloadEntry) section; environment.getStorage().removeDownload(de); deletedVideoCount++; } } } addToRecentAdapter(getView()); notifyAdapter(); videoListView.setOnItemClickListener(adapter); AppConstants.myVideosDeleteMode = false; ((MyVideosTabActivity) getActivity()).hideCheckBox(); if(deletedVideoCount>0){ UiUtil.showMessage(MyRecentVideosFragment.this.getView(), ResourceUtil.getFormattedStringForQuantity(getResources(), R.plurals.deleted_video, "video_count", deletedVideoCount).toString()); } }catch(Exception ex){ logger.error(ex); } finally { getView().findViewById(R.id.delete_btn).setVisibility(View.GONE); getView().findViewById(R.id.edit_btn).setVisibility(View.VISIBLE); getView().findViewById(R.id.cancel_btn).setVisibility(View.GONE); } } //Handle check box selection in Delete mode private void handleCheckboxSelection(){ try{ int selectedItemsNo = adapter.getSelectedVideoItemsCount(); int totalVideos = adapter.getTotalVideoItemsCount(); if(selectedItemsNo==0){ disableDeleteButton(); }else{ enableDeleteButton(); } if(selectedItemsNo==totalVideos){ ((MyVideosTabActivity) getActivity()).setMyVideosCheckBoxSelected(); }else if(selectedItemsNo<totalVideos){ ((MyVideosTabActivity) getActivity()).unsetMyVideosCheckBoxSelected(); } }catch(Exception ex){ logger.error(ex); } } //Selecting all downloaded videos in the list for Delete public void setAllVideosSectionChecked() { try{ adapter.selectAll(); notifyAdapter(); enableDeleteButton(); }catch(Exception e){ logger.error(e); } } //DeSelecting all downloaded videos in the list for Delete public void unsetAllVideosSectionChecked() { try{ adapter.unselectAll(); notifyAdapter(); disableDeleteButton(); }catch(Exception e){ logger.error(e); } } //Disabling Delete button until no video is checked private void disableDeleteButton(){ try{ deleteButton.setEnabled(false); }catch(Exception ex){ logger.error(ex); } } //Enabling Delete button until no video is checked private void enableDeleteButton(){ try{ deleteButton.setEnabled(true); }catch(Exception ex){ logger.error(ex); } } public void markPlaying() { environment.getStorage().markVideoPlaying(videoModel, watchedStateCallback); } public void saveCurrentPlaybackPosition(int offset) { try { DownloadEntry v = videoModel; if (v != null) { // mark this as partially watches, as playing has started environment.getDatabase().updateVideoLastPlayedOffset(v.videoId, offset, setCurrentPositionCallback); } } catch (Exception ex) { logger.error(ex); } } public void onPlaybackComplete() { try { DownloadEntry v = videoModel; if (v != null) { if (v.watched == DownloadEntry.WatchedState.PARTIALLY_WATCHED) { videoModel.watched = DownloadEntry.WatchedState.WATCHED; // mark this as partially watches, as playing has started environment.getDatabase().updateVideoWatchedState(v.videoId, DownloadEntry.WatchedState.WATCHED, watchedStateCallback); } } } catch (Exception ex) { logger.error(ex); } } private boolean isPlayerVisible() { try{ if (getActivity() == null) { return false; } View container = getActivity().findViewById(R.id.container_player); return (container != null && container.getVisibility() == View.VISIBLE); }catch(Exception ex){ logger.error(ex); } return false; } public void setCallback(VideoListCallback callback) { this.callback = callback; } public void setContainerActivity(MyVideosTabActivity activity) { this.containerActivity = activity; } public void notifyAdapter() { adapter.setSelectedPosition(playingVideoIndex); adapter.notifyDataSetChanged(); } /** * Returns true if current orientation is LANDSCAPE, false otherwise. * @return */ protected boolean isLandscape() { return (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE); } @Override public void onSaveInstanceState(Bundle outState) { logger.debug("In onSaveInstance State"); try{ outState.putInt("playingVideoIndex", playingVideoIndex); outState.putSerializable("model", videoModel); super.onSaveInstanceState(outState); }catch(Exception ex){ logger.error(ex); } } /** * Container tab will call this method to restore the saved data * @param savedInstanceState */ public void restore(Bundle savedInstanceState) { try{ if (savedInstanceState != null) { playingVideoIndex = savedInstanceState.getInt("playingVideoIndex", -1); videoModel = (DownloadEntry) savedInstanceState.getSerializable("model"); } }catch(Exception ex){ logger.error(ex); } } public void setSelectionEmpty() { try{ playingVideoIndex = -1; if (adapter != null) { adapter.setSelectedPosition(playingVideoIndex); notifyAdapter(); } }catch(Exception ex){ logger.error(ex); } } //Play the nextVideo if user selects next from Dialog public void playNext() { try{ playingVideoIndex++; // check next playable video entry while (playingVideoIndex < adapter.getCount()) { SectionItemInterface i = adapter.getItem(playingVideoIndex); if (i!=null && i instanceof DownloadEntry) { videoModel = (DownloadEntry) i; if (callback != null) { adapter.setSelectedPosition(playingVideoIndex); adapter.setVideoId(videoModel.videoId); play(videoModel); break; } } // try next playingVideoIndex++; } }catch(Exception ex){ logger.error(ex); } } //Check if next video is available in the Video List public boolean hasNextVideo(int index) { try{ if(index==-1){ index = playingVideoIndex; } for (int i=(index+1) ; i<adapter.getCount(); i++) { SectionItemInterface d = adapter.getItem(i); if (d!=null && d instanceof DownloadEntry) { return true; } } }catch(Exception ex){ logger.error(ex); } return false; } public void playPrevious() { try{ playingVideoIndex--; // check next playable video entry while (playingVideoIndex >= 0) { SectionItemInterface i = adapter.getItem(playingVideoIndex); if (i!=null && i instanceof DownloadEntry) { videoModel = (DownloadEntry) i; if (callback != null) { adapter.setSelectedPosition(playingVideoIndex); adapter.setVideoId(videoModel.videoId); play(videoModel); //callback.playVideoModel(videoModel); break; } } // try next playingVideoIndex--; } }catch(Exception e){ logger.error(e); } } public boolean hasPreviousVideo(int playingIndex) { try{ for (int i=(playingIndex-1) ; i>=0; i--) { SectionItemInterface d = adapter.getItem(i); if (d!=null && d instanceof DownloadEntry) { return true; } } }catch(Exception e){ logger.error(e); } return false; } public View.OnClickListener getNextListener(){ if(hasNextVideo(playingVideoIndex)){ return new NextClickListener(); } return null; } public View.OnClickListener getPreviousListener(){ if(hasPreviousVideo(playingVideoIndex)){ return new PreviousClickListener(); } return null; } @Override public void reloadList() { if(getView()!=null){ addToRecentAdapter(getView()); notifyAdapter(); } } private class NextClickListener implements OnClickListener{ @Override public void onClick(View v) { playNext(); } } private class PreviousClickListener implements OnClickListener{ @Override public void onClick(View v) { playPrevious(); } } private DataCallback<Integer> watchedStateCallback = new DataCallback<Integer>() { @Override public void onResult(Integer result) { logger.debug("Watched State Updated"); } @Override public void onFail(Exception ex) { logger.error(ex); } }; private DataCallback<Integer> setCurrentPositionCallback = new DataCallback<Integer>() { @Override public void onResult(Integer result) { logger.debug("Current Playback Position Updated"); } @Override public void onFail(Exception ex) { logger.error(ex); } }; /** * Returns user's profile. * @return */ protected ProfileModel getProfile() { PrefManager prefManager = new PrefManager(getActivity(), PrefManager.Pref.LOGIN); return prefManager.getCurrentUserProfile(); } /** * Set the current playing videoId as null in adapter */ public void setCurrentPlayingVideoIdAsNull(){ if(adapter!=null){ adapter.setVideoId(null); } } }
//============================================================================ // // Copyright (C) 2006-2022 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // //============================================================================ package org.talend.components.salesforce.test; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import org.junit.Before; import org.junit.Test; import org.talend.components.api.container.RuntimeContainer; import org.talend.components.common.oauth.OAuth2FlowType; import org.talend.components.salesforce.SalesforceConnectionProperties; import org.talend.components.salesforce.SalesforceTestBase; import org.talend.daikon.properties.ValidationResult; import org.talend.daikon.properties.ValidationResultMutable; import org.talend.daikon.properties.presentation.Form; /** * */ public class SalesforceConnectionPropertiesTest extends SalesforceTestBase { private SalesforceConnectionProperties properties; @Before public void setUp() { properties = spy(new SalesforceConnectionProperties("connection")); } @Test public void testSetupProperties() { properties.setupProperties(); assertEquals(SalesforceConnectionProperties.URL, properties.endpoint.getValue()); assertEquals(SalesforceConnectionProperties.DEFAULT_API_VERSION, properties.apiVersion.getValue()); assertEquals(SalesforceConnectionProperties.LoginType.Basic, properties.loginType.getValue()); assertEquals(Boolean.FALSE, properties.reuseSession.getValue()); assertEquals(Integer.valueOf(60000), properties.timeout.getValue()); assertEquals(Boolean.TRUE, properties.httpChunked.getValue()); assertNull(properties.getReferencedComponentId()); assertNull(properties.getReferencedConnectionProperties()); } @Test public void testLayout() { properties.init(); Form mainForm = properties.getForm(Form.MAIN); assertNotNull(mainForm); assertTrue(mainForm.getWidget(properties.userPassword.getName()).isVisible()); Form advForm = properties.getForm(Form.ADVANCED); assertNotNull(advForm); Form refForm = properties.getForm(Form.REFERENCE); assertNotNull(refForm); Form wizardForm = properties.getForm(SalesforceConnectionProperties.FORM_WIZARD); assertNotNull(wizardForm); } @Test public void testChangeReuseSession() { properties.init(); reset(properties); properties.reuseSession.setValue(true); properties.afterReuseSession(); Form advForm = properties.getForm(Form.ADVANCED); verify(properties, times(1)).refreshLayout(advForm); assertTrue(advForm.getWidget(properties.reuseSession.getName()).isVisible()); } @Test public void testChangeLoginType() { properties.init(); reset(properties); properties.loginType.setValue(SalesforceConnectionProperties.LoginType.OAuth); properties.oauth2FlowType.setValue(OAuth2FlowType.JWT_Flow); properties.afterLoginType(); verify(properties, times(3)).refreshLayout(any(Form.class)); Form mainForm = properties.getForm(Form.MAIN); assertEquals(SalesforceConnectionProperties.OAUTH_URL, properties.endpoint.getValue()); testLoginTypeWidgets(mainForm); Form wizardForm = properties.getForm(SalesforceConnectionProperties.FORM_WIZARD); testLoginTypeWidgets(wizardForm); // Switch back to Basic auth mode properties.loginType.setValue(SalesforceConnectionProperties.LoginType.Basic); properties.afterLoginType(); assertEquals(SalesforceConnectionProperties.URL, properties.endpoint.getValue()); } @Test public void testChangeReferencedComponent() { properties.init(); reset(properties); SalesforceConnectionProperties referencedProperties = new SalesforceConnectionProperties("reference"); properties.referencedComponent.componentInstanceId.setValue("tSalesforceConnection_1"); properties.referencedComponent.setReference(referencedProperties); properties.afterReferencedComponent(); verify(properties, times(3)).refreshLayout(any(Form.class)); assertEquals("tSalesforceConnection_1", properties.getReferencedComponentId()); assertEquals(referencedProperties, properties.getReferencedConnectionProperties()); Form mainForm = properties.getForm(Form.MAIN); assertFalse(mainForm.getWidget(properties.loginType.getName()).isVisible()); assertFalse(mainForm.getWidget(properties.userPassword.getName()).isVisible()); Form advForm = properties.getForm(Form.ADVANCED); assertFalse(advForm.getWidget(properties.proxy.getName()).isVisible()); assertFalse(advForm.getWidget(properties.timeout.getName()).isVisible()); assertFalse(advForm.getWidget(properties.httpChunked.getName()).isVisible()); } @Test public void testValidateTestConnection() throws Exception { properties.init(); Form wizardForm = properties.getForm(SalesforceConnectionProperties.FORM_WIZARD); try (MockRuntimeSourceOrSinkTestFixture testFixture = new MockRuntimeSourceOrSinkTestFixture(equalTo(properties), createDefaultTestDataset())) { testFixture.setUp(); // Valid ValidationResult vr1 = properties.validateTestConnection(); assertEquals(ValidationResult.Result.OK, vr1.getStatus()); assertTrue(wizardForm.isAllowForward()); // Not valid when(testFixture.runtimeSourceOrSink.validate(any())) .thenReturn(new ValidationResultMutable().setStatus(ValidationResult.Result.ERROR).setMessage("Error")); ValidationResult vr2 = properties.validateTestConnection(); assertEquals(ValidationResult.Result.ERROR, vr2.getStatus()); assertFalse(wizardForm.isAllowForward()); } } @Test public void testMutualAuth() { properties.init(); reset(properties); properties.loginType.setValue(SalesforceConnectionProperties.LoginType.OAuth); properties.oauth2FlowType.setValue(OAuth2FlowType.JWT_Flow); properties.afterLoginType(); verify(properties, times(3)).refreshLayout(any(Form.class)); Form mainForm = properties.getForm(Form.MAIN); Form sslForm = mainForm.getChildForm(properties.sslProperties.getName()); assertFalse(sslForm.getWidget(properties.sslProperties.mutualAuth.getName()).isVisible()); assertFalse(sslForm.getWidget(properties.sslProperties.keyStorePath.getName()).isVisible()); assertFalse(sslForm.getWidget(properties.sslProperties.keyStorePwd.getName()).isVisible()); properties.loginType.setValue(SalesforceConnectionProperties.LoginType.Basic); properties.afterLoginType(); mainForm = properties.getForm(Form.MAIN); sslForm = mainForm.getChildForm(properties.sslProperties.getName()); assertTrue(sslForm.getWidget(properties.sslProperties.mutualAuth.getName()).isVisible()); assertFalse(sslForm.getWidget(properties.sslProperties.keyStorePath.getName()).isVisible()); assertFalse(sslForm.getWidget(properties.sslProperties.keyStorePwd.getName()).isVisible()); properties.sslProperties.mutualAuth.setValue(true); properties.sslProperties.afterMutualAuth(); mainForm = properties.getForm(Form.MAIN); sslForm = mainForm.getChildForm(properties.sslProperties.getName()); assertTrue(sslForm.getWidget(properties.sslProperties.keyStorePath.getName()).isVisible()); assertTrue(sslForm.getWidget(properties.sslProperties.keyStorePwd.getName()).isVisible()); } private void testLoginTypeWidgets(Form form) { assertFalse(form.getWidget(properties.userPassword.getName()).isVisible()); } }
/** * Copyright 2013-2014 Guidewire Software * * 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.guidewire.build.ijdevkitmvn.ijplugin; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.LibraryOrderEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.OrderEnumerator; import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Processor; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.devkit.build.PluginBuildConfiguration; import org.jetbrains.idea.devkit.module.PluginModuleType; import org.jetbrains.idea.maven.importing.MavenImporter; import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider; import org.jetbrains.idea.maven.importing.MavenRootModelAdapter; import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.model.MavenPlugin; import org.jetbrains.idea.maven.project.MavenConsole; import org.jetbrains.idea.maven.project.MavenEmbeddersManager; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectChanges; import org.jetbrains.idea.maven.project.MavenProjectsProcessorTask; import org.jetbrains.idea.maven.project.MavenProjectsTree; import org.jetbrains.idea.maven.project.SupportedRequestType; import org.jetbrains.idea.maven.utils.MavenProcessCanceledException; import org.jetbrains.idea.maven.utils.MavenProgressIndicator; import org.jetbrains.idea.maven.utils.MavenUtil; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** */ public class PluginModuleImporter extends MavenImporter { public static final String IJ_PLUGIN_PACKAGING = "ij-plugin"; public static final String IDEA_SDK_PREFIX = "com.jetbrains.intellij."; public static final String IJPLUGIN_GROUP_ID = "com.guidewire.build"; public static final String IJPLUGIN_ARTIFACT_ID = "ijplugin-maven-plugin"; public static final String IJPLUGIN_PROPERTY = "ij.plugin"; public static final String IJPLUGIN_DESCRIPTOR_PROPERTY = "ij.pluginDescriptor"; public static final String MANIFEST_LOCATION_PARAMETER = "manifestLocation"; public PluginModuleImporter() { super(IJPLUGIN_GROUP_ID, IJPLUGIN_ARTIFACT_ID); } @Override public void preProcess(Module module, MavenProject mavenProject, MavenProjectChanges mavenProjectChanges, IdeModifiableModelsProvider mavenModifiableModelsProvider) { } @Override public void process(IdeModifiableModelsProvider modelsProvider, Module module, MavenRootModelAdapter mavenRootModelAdapter, MavenProjectsTree mavenProjectsTree, MavenProject mavenProject, MavenProjectChanges mavenProjectChanges, Map<MavenProject, String> mavenProjectStringMap, List<MavenProjectsProcessorTask> mavenProjectsProcessorTasks) { // Remove all entries with groupIds starting from com.jetbrains.intellij. // They should be provided through IntelliJ SDK ModifiableRootModel rootModel = mavenRootModelAdapter.getRootModel(); List<Library> libraries = new ArrayList<Library>(); for (OrderEntry entry : rootModel.getOrderEntries()) { if (entry instanceof LibraryOrderEntry) { LibraryOrderEntry loe = (LibraryOrderEntry) entry; String libraryName = loe.getLibraryName(); if (libraryName != null && libraryName.startsWith("Maven: " + IDEA_SDK_PREFIX)) { rootModel.removeOrderEntry(entry); libraries.add(loe.getLibrary()); } } } updateManifestLocation(module, mavenProject); // Workaround for Maven plugin bug which does not allow newly created unused libraries to be properly removed // We schedule our own post-processing task that will clean out unused libraries scheduleAnalyzeLibraryTask(mavenProjectsProcessorTasks, libraries); } private void updateManifestLocation(Module module, MavenProject mavenProject) { String manifestLocation = findManifestLocation(mavenProject); PluginBuildConfiguration config = PluginBuildConfiguration.getInstance(module); if (config != null) { VirtualFile basedir = mavenProject.getDirectoryFile(); VirtualFile pluginXml = basedir.findFileByRelativePath(manifestLocation); if (pluginXml != null && pluginXml.exists()) { setPluginXmlPath(config, pluginXml.getPath()); } } } private void setPluginXmlPath(PluginBuildConfiguration config, String path) { try { Method m; try { // IntelliJ 12 m = config.getClass().getMethod("setPluginXmlPathAndCreateDescriptorIfDoesntExist", String.class); } catch (NoSuchMethodException e) { // IntelliJ 11 m = config.getClass().getMethod("setPluginXmlPath", String.class); } m.invoke(config, path); } catch (Exception e) { // No big deal, let's not set it. } } private String findManifestLocation(MavenProject mavenProject) { String manifestLocation = null; // Try ijplugin-maven-plugin configuration MavenPlugin plugin = mavenProject.findPlugin(myPluginGroupID, myPluginArtifactID); if (plugin != null) { Element config = plugin.getConfigurationElement(); if (config != null) { Element child = config.getChild(MANIFEST_LOCATION_PARAMETER); manifestLocation = child.getText(); } } // Try ij.pluginDescriptor if (manifestLocation == null) { manifestLocation = mavenProject.getProperties().getProperty(IJPLUGIN_DESCRIPTOR_PROPERTY); } if (manifestLocation == null) { // Default location manifestLocation = "META-INF/plugin.xml"; } return manifestLocation; } private void scheduleAnalyzeLibraryTask(List<MavenProjectsProcessorTask> mavenProjectsProcessorTasks, List<Library> libraries) { // First, look if task is in the list already RemoveUnusedLibrariesTask task = null; for (MavenProjectsProcessorTask t : mavenProjectsProcessorTasks) { if (t instanceof RemoveUnusedLibrariesTask) { task = (RemoveUnusedLibrariesTask) t; break; } } // Create new task if (task == null) { task = new RemoveUnusedLibrariesTask(); mavenProjectsProcessorTasks.add(task); } // Schedule task task.addLibaries(libraries); } private static class RemoveUnusedLibrariesTask implements MavenProjectsProcessorTask { private final Set<Library> _libraries = new THashSet<Library>(); public void addLibaries(Collection<Library> libraries) { _libraries.addAll(libraries); } @Override public void perform(Project project, MavenEmbeddersManager embeddersManager, MavenConsole console, MavenProgressIndicator indicator) throws MavenProcessCanceledException { if (!_libraries.isEmpty()) { removeUnusedProjectLibraries(project); } } private void removeUnusedProjectLibraries(Project project) { final Set<Library> unusedLibraries = new THashSet<Library>(_libraries); ModuleManager moduleManager = ModuleManager.getInstance(project); for (Module m : moduleManager.getModules()) { OrderEnumerator.orderEntries(m).forEach(new Processor<OrderEntry>() { @Override public boolean process(OrderEntry orderEntry) { if (orderEntry instanceof LibraryOrderEntry) { Library lib = ((LibraryOrderEntry) orderEntry).getLibrary(); unusedLibraries.remove(lib); } return true; } }); } // Remove all unused libraries if (!unusedLibraries.isEmpty()) { final LibraryTable.ModifiableModel rootModel = ProjectLibraryTable.getInstance(project).getModifiableModel(); for (Library lib : unusedLibraries) { rootModel.removeLibrary(lib); } MavenUtil.invokeAndWaitWriteAction(project, new Runnable() { @Override public void run() { rootModel.commit(); } }); } } } /** * Enable importer for JAR projects with plugin attached to the lifecycle or for the projects * explicitly marked with "ij-plugin" packaging. */ @Override public boolean isApplicable(MavenProject mavenProject) { String type = mavenProject.getPackaging(); if (IJ_PLUGIN_PACKAGING.equals(type)) { return true; } else if (MavenConstants.TYPE_JAR.equals(type)) { return super.isApplicable(mavenProject) || Boolean.valueOf(mavenProject.getProperties().getProperty(IJPLUGIN_PROPERTY)); } return false; } @Override public void getSupportedPackagings(Collection<String> result) { result.add(IJ_PLUGIN_PACKAGING); result.add(MavenConstants.TYPE_JAR); } @Override public void getSupportedDependencyTypes(Collection<String> result, SupportedRequestType type) { result.add(IJ_PLUGIN_PACKAGING); result.add(MavenConstants.TYPE_JAR); } @NotNull @Override public ModuleType getModuleType() { return PluginModuleType.getInstance(); } }
/* * 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.db; import static com.google.common.collect.Sets.newHashSet; import java.io.File; import java.io.FileFilter; import java.io.IOError; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicLong; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; import com.google.common.collect.Iterables; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.config.*; import org.apache.cassandra.io.FSError; import org.apache.cassandra.io.FSWriteError; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.io.sstable.*; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.Pair; /** * Encapsulate handling of paths to the data files. * * <pre> {@code * /<path_to_data_dir>/ks/<cf dir>/ks-cf1-jb-1-Data.db * /<cf dir>/la-2-Data.db * /<cf dir>/.<index name>/ks-cf1.idx-jb-1-Data.db * /<cf dir>/.<index name>/la-1-Data.db * ... * } </pre> * * Until v2.0, {@code <cf dir>} is just column family name. * Since v2.1, {@code <cf dir>} has column family ID(cfId) added to its end. * * SSTables from secondary indexes were put in the same directory as their parent. * Since v2.2, they have their own directory under the parent directory whose name is index name. * Upon startup, those secondary index files are moved to new directory when upgrading. * * For backward compatibility, Directories can use directory without cfId if exists. * * In addition, more that one 'root' data directory can be specified so that * {@code <path_to_data_dir>} potentially represents multiple locations. * Note that in the case of multiple locations, the manifest for the leveled * compaction is only in one of the location. * * Snapshots (resp. backups) are always created along the sstables there are * snapshotted (resp. backuped) but inside a subdirectory named 'snapshots' * (resp. backups) (and snapshots are further inside a subdirectory of the name * of the snapshot). For secondary indexes, snapshots (backups) are not created in * their own directory, but are in their parent's snapshot (backup) directory. * * This class abstracts all those details from the rest of the code. */ public class Directories { private static final Logger logger = LoggerFactory.getLogger(Directories.class); public static final String BACKUPS_SUBDIR = "backups"; public static final String SNAPSHOT_SUBDIR = "snapshots"; public static final String SECONDARY_INDEX_NAME_SEPARATOR = "."; public static final DataDirectory[] dataDirectories; static { String[] locations = DatabaseDescriptor.getAllDataFileLocations(); dataDirectories = new DataDirectory[locations.length]; for (int i = 0; i < locations.length; ++i) dataDirectories[i] = new DataDirectory(new File(locations[i])); } /** * Checks whether Cassandra has RWX permissions to the specified directory. Logs an error with * the details if it does not. * * @param dir File object of the directory. * @param dataDir String representation of the directory's location * @return status representing Cassandra's RWX permissions to the supplied folder location. */ public static boolean verifyFullPermissions(File dir, String dataDir) { if (!dir.isDirectory()) { logger.error("Not a directory {}", dataDir); return false; } else if (!FileAction.hasPrivilege(dir, FileAction.X)) { logger.error("Doesn't have execute permissions for {} directory", dataDir); return false; } else if (!FileAction.hasPrivilege(dir, FileAction.R)) { logger.error("Doesn't have read permissions for {} directory", dataDir); return false; } else if (dir.exists() && !FileAction.hasPrivilege(dir, FileAction.W)) { logger.error("Doesn't have write permissions for {} directory", dataDir); return false; } return true; } public enum FileAction { X, W, XW, R, XR, RW, XRW; private FileAction() { } public static boolean hasPrivilege(File file, FileAction action) { boolean privilege = false; switch (action) { case X: privilege = file.canExecute(); break; case W: privilege = file.canWrite(); break; case XW: privilege = file.canExecute() && file.canWrite(); break; case R: privilege = file.canRead(); break; case XR: privilege = file.canExecute() && file.canRead(); break; case RW: privilege = file.canRead() && file.canWrite(); break; case XRW: privilege = file.canExecute() && file.canRead() && file.canWrite(); break; } return privilege; } } private final CFMetaData metadata; private final File[] dataPaths; /** * Create Directories of given ColumnFamily. * SSTable directories are created under data_directories defined in cassandra.yaml if not exist at this time. * * @param metadata metadata of ColumnFamily */ public Directories(final CFMetaData metadata) { this.metadata = metadata; String cfId = ByteBufferUtil.bytesToHex(ByteBufferUtil.bytes(metadata.cfId)); int idx = metadata.cfName.indexOf(SECONDARY_INDEX_NAME_SEPARATOR); String cfName = idx >= 0 ? metadata.cfName.substring(0, idx) : metadata.cfName; String indexNameWithDot = idx >= 0 ? metadata.cfName.substring(idx) : null; this.dataPaths = new File[dataDirectories.length]; // If upgraded from version less than 2.1, use existing directories String oldSSTableRelativePath = join(metadata.ksName, cfName); for (int i = 0; i < dataDirectories.length; ++i) { // check if old SSTable directory exists dataPaths[i] = new File(dataDirectories[i].location, oldSSTableRelativePath); } boolean olderDirectoryExists = Iterables.any(Arrays.asList(dataPaths), new Predicate<File>() { public boolean apply(File file) { return file.exists(); } }); if (!olderDirectoryExists) { // use 2.1+ style String newSSTableRelativePath = join(metadata.ksName, cfName + '-' + cfId); for (int i = 0; i < dataDirectories.length; ++i) dataPaths[i] = new File(dataDirectories[i].location, newSSTableRelativePath); } // if index, then move to its own directory if (indexNameWithDot != null) { for (int i = 0; i < dataDirectories.length; ++i) dataPaths[i] = new File(dataPaths[i], indexNameWithDot); } for (File dir : dataPaths) { try { FileUtils.createDirectory(dir); } catch (FSError e) { // don't just let the default exception handler do this, we need the create loop to continue logger.error("Failed to create {} directory", dir); FileUtils.handleFSError(e); } } // if index, move existing older versioned SSTable files to new directory if (indexNameWithDot != null) { for (File dataPath : dataPaths) { File[] indexFiles = dataPath.getParentFile().listFiles(new FileFilter() { @Override public boolean accept(File file) { if (file.isDirectory()) return false; Pair<Descriptor, Component> pair = SSTable.tryComponentFromFilename(file.getParentFile(), file.getName()); return pair != null && pair.left.ksname.equals(metadata.ksName) && pair.left.cfname.equals(metadata.cfName); } }); for (File indexFile : indexFiles) { File destFile = new File(dataPath, indexFile.getName()); logger.trace("Moving index file {} to {}", indexFile, destFile); FileUtils.renameWithConfirm(indexFile, destFile); } } } } /** * Returns SSTable location which is inside given data directory. * * @param dataDirectory * @return SSTable location */ public File getLocationForDisk(DataDirectory dataDirectory) { if (dataDirectory != null) for (File dir : dataPaths) if (dir.getAbsolutePath().startsWith(dataDirectory.location.getAbsolutePath())) return dir; return null; } public Descriptor find(String filename) { for (File dir : dataPaths) { if (new File(dir, filename).exists()) return Descriptor.fromFilename(dir, filename).left; } return null; } /** * Basically the same as calling {@link #getWriteableLocationAsFile(long)} with an unknown size ({@code -1L}), * which may return any non-blacklisted directory - even a data directory that has no usable space. * Do not use this method in production code. * * @throws IOError if all directories are blacklisted. */ public File getDirectoryForNewSSTables() { return getWriteableLocationAsFile(-1L); } /** * Returns a non-blacklisted data directory that _currently_ has {@code writeSize} bytes as usable space. * * @throws IOError if all directories are blacklisted. */ public File getWriteableLocationAsFile(long writeSize) { return getLocationForDisk(getWriteableLocation(writeSize)); } /** * Returns a non-blacklisted data directory that _currently_ has {@code writeSize} bytes as usable space. * * @throws IOError if all directories are blacklisted. */ public DataDirectory getWriteableLocation(long writeSize) { List<DataDirectoryCandidate> candidates = new ArrayList<>(); long totalAvailable = 0L; // pick directories with enough space and so that resulting sstable dirs aren't blacklisted for writes. boolean tooBig = false; for (DataDirectory dataDir : dataDirectories) { if (BlacklistedDirectories.isUnwritable(getLocationForDisk(dataDir))) { logger.trace("removing blacklisted candidate {}", dataDir.location); continue; } DataDirectoryCandidate candidate = new DataDirectoryCandidate(dataDir); // exclude directory if its total writeSize does not fit to data directory if (candidate.availableSpace < writeSize) { logger.trace("removing candidate {}, usable={}, requested={}", candidate.dataDirectory.location, candidate.availableSpace, writeSize); tooBig = true; continue; } candidates.add(candidate); totalAvailable += candidate.availableSpace; } if (candidates.isEmpty()) if (tooBig) throw new RuntimeException("Insufficient disk space to write " + writeSize + " bytes"); else throw new FSWriteError(new IOException("All configured data directories have been blacklisted as unwritable for erroring out"), ""); // shortcut for single data directory systems if (candidates.size() == 1) return candidates.get(0).dataDirectory; sortWriteableCandidates(candidates, totalAvailable); return pickWriteableDirectory(candidates); } // separated for unit testing static DataDirectory pickWriteableDirectory(List<DataDirectoryCandidate> candidates) { // weighted random double rnd = ThreadLocalRandom.current().nextDouble(); for (DataDirectoryCandidate candidate : candidates) { rnd -= candidate.perc; if (rnd <= 0) return candidate.dataDirectory; } // last resort return candidates.get(0).dataDirectory; } // separated for unit testing static void sortWriteableCandidates(List<DataDirectoryCandidate> candidates, long totalAvailable) { // calculate free-space-percentage for (DataDirectoryCandidate candidate : candidates) candidate.calcFreePerc(totalAvailable); // sort directories by perc Collections.sort(candidates); } public boolean hasAvailableDiskSpace(long estimatedSSTables, long expectedTotalWriteSize) { long writeSize = expectedTotalWriteSize / estimatedSSTables; long totalAvailable = 0L; for (DataDirectory dataDir : dataDirectories) { if (BlacklistedDirectories.isUnwritable(getLocationForDisk(dataDir))) continue; DataDirectoryCandidate candidate = new DataDirectoryCandidate(dataDir); // exclude directory if its total writeSize does not fit to data directory if (candidate.availableSpace < writeSize) continue; totalAvailable += candidate.availableSpace; } return totalAvailable > expectedTotalWriteSize; } public static File getSnapshotDirectory(Descriptor desc, String snapshotName) { return getSnapshotDirectory(desc.directory, snapshotName); } /** * Returns directory to write snapshot. If directory does not exist, then one is created. * * If given {@code location} indicates secondary index, this will return * {@code <cf dir>/snapshots/<snapshot name>/.<index name>}. * Otherwise, this will return {@code <cf dir>/snapshots/<snapshot name>}. * * @param location base directory * @param snapshotName snapshot name * @return directory to write snapshot */ public static File getSnapshotDirectory(File location, String snapshotName) { if (location.getName().startsWith(SECONDARY_INDEX_NAME_SEPARATOR)) { return getOrCreate(location.getParentFile(), SNAPSHOT_SUBDIR, snapshotName, location.getName()); } else { return getOrCreate(location, SNAPSHOT_SUBDIR, snapshotName); } } public File getSnapshotManifestFile(String snapshotName) { File snapshotDir = getSnapshotDirectory(getDirectoryForNewSSTables(), snapshotName); return new File(snapshotDir, "manifest.json"); } public File getNewEphemeralSnapshotMarkerFile(String snapshotName) { File snapshotDir = new File(getWriteableLocationAsFile(1L), join(SNAPSHOT_SUBDIR, snapshotName)); return getEphemeralSnapshotMarkerFile(snapshotDir); } private static File getEphemeralSnapshotMarkerFile(File snapshotDirectory) { return new File(snapshotDirectory, "ephemeral.snapshot"); } public static File getBackupsDirectory(Descriptor desc) { return getBackupsDirectory(desc.directory); } public static File getBackupsDirectory(File location) { if (location.getName().startsWith(SECONDARY_INDEX_NAME_SEPARATOR)) { return getOrCreate(location.getParentFile(), BACKUPS_SUBDIR, location.getName()); } else { return getOrCreate(location, BACKUPS_SUBDIR); } } public SSTableLister sstableLister() { return new SSTableLister(); } public static class DataDirectory { public final File location; public DataDirectory(File location) { this.location = location; } public long getAvailableSpace() { return location.getUsableSpace(); } } static final class DataDirectoryCandidate implements Comparable<DataDirectoryCandidate> { final DataDirectory dataDirectory; final long availableSpace; double perc; public DataDirectoryCandidate(DataDirectory dataDirectory) { this.dataDirectory = dataDirectory; this.availableSpace = dataDirectory.getAvailableSpace(); } void calcFreePerc(long totalAvailableSpace) { double w = availableSpace; w /= totalAvailableSpace; perc = w; } public int compareTo(DataDirectoryCandidate o) { if (this == o) return 0; int r = Double.compare(perc, o.perc); if (r != 0) return -r; // last resort return System.identityHashCode(this) - System.identityHashCode(o); } } public class SSTableLister { private boolean skipTemporary; private boolean includeBackups; private boolean onlyBackups; private int nbFiles; private final Map<Descriptor, Set<Component>> components = new HashMap<>(); private boolean filtered; private String snapshotName; public SSTableLister skipTemporary(boolean b) { if (filtered) throw new IllegalStateException("list() has already been called"); skipTemporary = b; return this; } public SSTableLister includeBackups(boolean b) { if (filtered) throw new IllegalStateException("list() has already been called"); includeBackups = b; return this; } public SSTableLister onlyBackups(boolean b) { if (filtered) throw new IllegalStateException("list() has already been called"); onlyBackups = b; includeBackups = b; return this; } public SSTableLister snapshots(String sn) { if (filtered) throw new IllegalStateException("list() has already been called"); snapshotName = sn; return this; } public Map<Descriptor, Set<Component>> list() { filter(); return ImmutableMap.copyOf(components); } public List<File> listFiles() { filter(); List<File> l = new ArrayList<>(nbFiles); for (Map.Entry<Descriptor, Set<Component>> entry : components.entrySet()) { for (Component c : entry.getValue()) { l.add(new File(entry.getKey().filenameFor(c))); } } return l; } private void filter() { if (filtered) return; for (File location : dataPaths) { if (BlacklistedDirectories.isUnreadable(location)) continue; if (snapshotName != null) { getSnapshotDirectory(location, snapshotName).listFiles(getFilter()); continue; } if (!onlyBackups) location.listFiles(getFilter()); if (includeBackups) getBackupsDirectory(location).listFiles(getFilter()); } filtered = true; } private FileFilter getFilter() { return new FileFilter() { // This function always return false since accepts adds to the components map public boolean accept(File file) { if (file.isDirectory()) return false; Pair<Descriptor, Component> pair = SSTable.tryComponentFromFilename(file.getParentFile(), file.getName()); if (pair == null) return false; // we are only interested in the SSTable files that belong to the specific ColumnFamily if (!pair.left.ksname.equals(metadata.ksName) || !pair.left.cfname.equals(metadata.cfName)) return false; if (skipTemporary && pair.left.type.isTemporary) return false; Set<Component> previous = components.get(pair.left); if (previous == null) { previous = new HashSet<>(); components.put(pair.left, previous); } previous.add(pair.right); nbFiles++; return false; } }; } } /** * * @return Return a map of all snapshots to space being used * The pair for a snapshot has size on disk and true size. */ public Map<String, Pair<Long, Long>> getSnapshotDetails() { final Map<String, Pair<Long, Long>> snapshotSpaceMap = new HashMap<>(); for (File snapshot : listSnapshots()) { final long sizeOnDisk = FileUtils.folderSize(snapshot); final long trueSize = getTrueAllocatedSizeIn(snapshot); Pair<Long, Long> spaceUsed = snapshotSpaceMap.get(snapshot.getName()); if (spaceUsed == null) spaceUsed = Pair.create(sizeOnDisk,trueSize); else spaceUsed = Pair.create(spaceUsed.left + sizeOnDisk, spaceUsed.right + trueSize); snapshotSpaceMap.put(snapshot.getName(), spaceUsed); } return snapshotSpaceMap; } public List<String> listEphemeralSnapshots() { final List<String> ephemeralSnapshots = new LinkedList<>(); for (File snapshot : listSnapshots()) { if (getEphemeralSnapshotMarkerFile(snapshot).exists()) ephemeralSnapshots.add(snapshot.getName()); } return ephemeralSnapshots; } private List<File> listSnapshots() { final List<File> snapshots = new LinkedList<>(); for (final File dir : dataPaths) { File snapshotDir = dir.getName().startsWith(SECONDARY_INDEX_NAME_SEPARATOR) ? new File(dir.getParent(), SNAPSHOT_SUBDIR) : new File(dir, SNAPSHOT_SUBDIR); if (snapshotDir.exists() && snapshotDir.isDirectory()) { final File[] snapshotDirs = snapshotDir.listFiles(); if (snapshotDirs != null) { for (final File snapshot : snapshotDirs) { if (snapshot.isDirectory()) snapshots.add(snapshot); } } } } return snapshots; } public boolean snapshotExists(String snapshotName) { for (File dir : dataPaths) { File snapshotDir; if (dir.getName().startsWith(SECONDARY_INDEX_NAME_SEPARATOR)) { snapshotDir = new File(dir.getParentFile(), join(SNAPSHOT_SUBDIR, snapshotName, dir.getName())); } else { snapshotDir = new File(dir, join(SNAPSHOT_SUBDIR, snapshotName)); } if (snapshotDir.exists()) return true; } return false; } public static void clearSnapshot(String snapshotName, List<File> snapshotDirectories) { // If snapshotName is empty or null, we will delete the entire snapshot directory String tag = snapshotName == null ? "" : snapshotName; for (File dir : snapshotDirectories) { File snapshotDir = new File(dir, join(SNAPSHOT_SUBDIR, tag)); if (snapshotDir.exists()) { logger.trace("Removing snapshot directory {}", snapshotDir); try { FileUtils.deleteRecursive(snapshotDir); } catch (FSWriteError e) { if (FBUtilities.isWindows()) SnapshotDeletingTask.addFailedSnapshot(snapshotDir); else throw e; } } } } // The snapshot must exist public long snapshotCreationTime(String snapshotName) { for (File dir : dataPaths) { File snapshotDir = getSnapshotDirectory(dir, snapshotName); if (snapshotDir.exists()) return snapshotDir.lastModified(); } throw new RuntimeException("Snapshot " + snapshotName + " doesn't exist"); } /** * @return total snapshot size in byte for all snapshots. */ public long trueSnapshotsSize() { long result = 0L; for (File dir : dataPaths) { File snapshotDir = dir.getName().startsWith(SECONDARY_INDEX_NAME_SEPARATOR) ? new File(dir.getParent(), SNAPSHOT_SUBDIR) : new File(dir, SNAPSHOT_SUBDIR); result += getTrueAllocatedSizeIn(snapshotDir); } return result; } public long getTrueAllocatedSizeIn(File input) { if (!input.isDirectory()) return 0; TrueFilesSizeVisitor visitor = new TrueFilesSizeVisitor(); try { Files.walkFileTree(input.toPath(), visitor); } catch (IOException e) { logger.error("Could not calculate the size of {}. {}", input, e); } return visitor.getAllocatedSize(); } // Recursively finds all the sub directories in the KS directory. public static List<File> getKSChildDirectories(String ksName) { List<File> result = new ArrayList<>(); for (DataDirectory dataDirectory : dataDirectories) { File ksDir = new File(dataDirectory.location, ksName); File[] cfDirs = ksDir.listFiles(); if (cfDirs == null) continue; for (File cfDir : cfDirs) { if (cfDir.isDirectory()) result.add(cfDir); } } return result; } public List<File> getCFDirectories() { List<File> result = new ArrayList<>(); for (File dataDirectory : dataPaths) { if (dataDirectory.isDirectory()) result.add(dataDirectory); } return result; } private static File getOrCreate(File base, String... subdirs) { File dir = subdirs == null || subdirs.length == 0 ? base : new File(base, join(subdirs)); if (dir.exists()) { if (!dir.isDirectory()) throw new AssertionError(String.format("Invalid directory path %s: path exists but is not a directory", dir)); } else if (!dir.mkdirs() && !(dir.exists() && dir.isDirectory())) { throw new FSWriteError(new IOException("Unable to create directory " + dir), dir); } return dir; } private static String join(String... s) { return StringUtils.join(s, File.separator); } @VisibleForTesting static void overrideDataDirectoriesForTest(String loc) { for (int i = 0; i < dataDirectories.length; ++i) dataDirectories[i] = new DataDirectory(new File(loc)); } @VisibleForTesting static void resetDataDirectoriesAfterTest() { String[] locations = DatabaseDescriptor.getAllDataFileLocations(); for (int i = 0; i < locations.length; ++i) dataDirectories[i] = new DataDirectory(new File(locations[i])); } private class TrueFilesSizeVisitor extends SimpleFileVisitor<Path> { private final AtomicLong size = new AtomicLong(0); private final Set<String> visited = newHashSet(); //count each file only once private final Set<String> alive; TrueFilesSizeVisitor() { super(); Builder<String> builder = ImmutableSet.builder(); for (File file : sstableLister().listFiles()) builder.add(file.getName()); alive = builder.build(); } private boolean isAcceptable(Path file) { String fileName = file.toFile().getName(); Pair<Descriptor, Component> pair = SSTable.tryComponentFromFilename(file.getParent().toFile(), fileName); return pair != null && pair.left.ksname.equals(metadata.ksName) && pair.left.cfname.equals(metadata.cfName) && !visited.contains(fileName) && !alive.contains(fileName); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (isAcceptable(file)) { size.addAndGet(attrs.size()); visited.add(file.toFile().getName()); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } public long getAllocatedSize() { return size.get(); } } }
/* * Copyright 2010 JBoss 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.drools.core.reteoo.builder; import org.drools.core.ActivationListenerFactory; import org.drools.core.base.ClassObjectType; import org.drools.core.base.mvel.MVELSalienceExpression; import org.drools.core.common.BaseNode; import org.drools.core.common.InternalRuleBase; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.common.UpdateContext; import org.drools.core.phreak.AddRemoveRule; import org.drools.core.reteoo.LeftTupleSource; import org.drools.core.reteoo.ReteooBuilder; import org.drools.core.reteoo.RuleBuilder; import org.drools.core.reteoo.TerminalNode; import org.drools.core.reteoo.WindowNode; import org.drools.core.rule.Accumulate; import org.drools.core.rule.Collect; import org.drools.core.rule.ConditionalBranch; import org.drools.core.rule.EntryPointId; import org.drools.core.rule.EvalCondition; import org.drools.core.rule.Forall; import org.drools.core.rule.From; import org.drools.core.rule.GroupElement; import org.drools.core.rule.InvalidPatternException; import org.drools.core.rule.NamedConsequence; import org.drools.core.rule.Pattern; import org.drools.core.rule.QueryElement; import org.drools.core.rule.Rule; import org.drools.core.rule.WindowDeclaration; import org.drools.core.rule.WindowReference; import org.drools.core.time.TemporalDependencyMatrix; import org.drools.core.time.impl.Timer; import org.kie.api.conf.EventProcessingOption; import java.util.ArrayList; import java.util.List; public class ReteooRuleBuilder implements RuleBuilder { protected BuildUtils utils; public ReteooRuleBuilder() { this.utils = new BuildUtils(); this.utils.addBuilder( GroupElement.class, new GroupElementBuilder() ); this.utils.addBuilder( Pattern.class, new PatternBuilder() ); this.utils.addBuilder( EvalCondition.class, new EvalBuilder() ); this.utils.addBuilder( QueryElement.class, new QueryElementBuilder() ); this.utils.addBuilder( From.class, new FromBuilder() ); this.utils.addBuilder( Collect.class, new CollectBuilder() ); this.utils.addBuilder( Accumulate.class, new AccumulateBuilder() ); this.utils.addBuilder( Timer.class, new TimerBuilder() ); this.utils.addBuilder( Forall.class, new ForallBuilder() ); this.utils.addBuilder( EntryPointId.class, new EntryPointBuilder() ); this.utils.addBuilder( WindowReference.class, new WindowReferenceBuilder() ); this.utils.addBuilder( NamedConsequence.class, new NamedConsequenceBuilder() ); this.utils.addBuilder( ConditionalBranch.class, new ConditionalBranchBuilder() ); } /** * Creates the corresponting Rete network for the given <code>Rule</code> and adds it to * the given rule base. * * @param rule * The rule to add. * @param rulebase * The rulebase to add the rule to. * * @return a List<BaseNode> of terminal nodes for the rule * * @throws org.drools.core.RuleIntegrationException * if an error prevents complete construction of the network for * the <code>Rule</code>. * @throws InvalidPatternException */ public List<TerminalNode> addRule( final Rule rule, final InternalRuleBase rulebase, final ReteooBuilder.IdGenerator idGenerator ) throws InvalidPatternException { // the list of terminal nodes final List<TerminalNode> nodes = new ArrayList<TerminalNode>(); // transform rule and gets the array of subrules final GroupElement[] subrules = rule.getTransformedLhs( rulebase.getConfiguration().getComponentFactory().getLogicTransformerFactory().getLogicTransformer() ); for (int i = 0; i < subrules.length; i++) { // creates a clean build context for each subrule final BuildContext context = new BuildContext( rulebase, idGenerator ); context.setRule( rule ); // if running in STREAM mode, calculate temporal distance for events if (EventProcessingOption.STREAM.equals( rulebase.getConfiguration().getEventProcessingMode() )) { TemporalDependencyMatrix temporal = this.utils.calculateTemporalDistance( subrules[i] ); context.setTemporalDistance( temporal ); } if (rulebase.getConfiguration().isSequential() ) { context.setTupleMemoryEnabled( false ); context.setObjectTypeNodeMemoryEnabled( false ); } else { context.setTupleMemoryEnabled( true ); context.setObjectTypeNodeMemoryEnabled( true ); } // adds subrule final TerminalNode node = this.addSubRule( context, subrules[i], i, rule ); // adds the terminal node to the list of terminal nodes nodes.add( node ); } return nodes; } private TerminalNode addSubRule( final BuildContext context, final GroupElement subrule, final int subruleIndex, final Rule rule ) throws InvalidPatternException { context.setSubRule(subrule); // gets the appropriate builder ReteooComponentBuilder builder = this.utils.getBuilderFor( subrule ); // checks if an initial-fact is needed if (builder.requiresLeftActivation( this.utils, subrule )) { this.addInitialFactPattern( subrule ); } // builds and attach builder.build( context, this.utils, subrule ); if ( context.getRuleBase().getConfiguration().isPhreakEnabled() && rule.getTimer() != null ) { builder = this.utils.getBuilderFor( Timer.class ); builder.build( context, this.utils, rule.getTimer() ); } ActivationListenerFactory factory = context.getRuleBase().getConfiguration().getActivationListenerFactory( rule.getActivationListener() ); TerminalNode terminal = factory.createActivationListener( context.getNextId(), context.getTupleSource(), rule, subrule, subruleIndex, context ); BaseNode baseTerminalNode = (BaseNode) terminal; baseTerminalNode.networkUpdated(new UpdateContext()); baseTerminalNode.attach(context); if ( context.getRuleBase().getConfiguration().isPhreakEnabled() ) { AddRemoveRule.addRule( terminal, context.getWorkingMemories(), context.getRuleBase() ); } // adds the terminal node to the list of nodes created/added by this sub-rule context.getNodes().add( baseTerminalNode ); // assigns partition IDs to the new nodes //assignPartitionId(context); return terminal; } /** * Adds a query pattern to the given subrule * * @param subrule */ private void addInitialFactPattern( final GroupElement subrule ) { // creates a pattern for initial fact final Pattern pattern = new Pattern( 0, ClassObjectType.InitialFact_ObjectType ); // adds the pattern as the first child of the given AND group element subrule.addChild( 0, pattern ); } public void addEntryPoint( final String id, final InternalRuleBase rulebase, final ReteooBuilder.IdGenerator idGenerator ) { // creates a clean build context for each subrule final BuildContext context = new BuildContext( rulebase, idGenerator ); EntryPointId ep = new EntryPointId( id ); ReteooComponentBuilder builder = utils.getBuilderFor( ep ); builder.build(context, utils, ep); } public WindowNode addWindowNode( WindowDeclaration window, InternalRuleBase ruleBase, ReteooBuilder.IdGenerator idGenerator ) { // creates a clean build context for each subrule final BuildContext context = new BuildContext( ruleBase, idGenerator ); if ( ruleBase.getConfiguration().isSequential() ) { context.setTupleMemoryEnabled( false ); context.setObjectTypeNodeMemoryEnabled( false ); } else { context.setTupleMemoryEnabled( true ); context.setObjectTypeNodeMemoryEnabled( true ); } // gets the appropriate builder final WindowBuilder builder = WindowBuilder.INSTANCE; // builds and attach builder.build( context, this.utils, window ); return (WindowNode) context.getObjectSource(); } }
// Copyright 2018 The Bazel 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 com.google.devtools.build.lib.rules.java; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.concat; import static com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider.ClasspathType.BOTH; import static com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider.ClasspathType.COMPILE_ONLY; import static com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider.ClasspathType.RUNTIME_ONLY; import static com.google.devtools.build.lib.rules.java.JavaInfo.streamProviders; import static java.util.stream.Stream.concat; import com.google.common.base.Ascii; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.actions.ActionRegistry; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.FilesToRunProvider; import com.google.devtools.build.lib.analysis.Runfiles; import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext; import com.google.devtools.build.lib.analysis.actions.CustomCommandLine; import com.google.devtools.build.lib.analysis.actions.SpawnAction; import com.google.devtools.build.lib.analysis.config.CoreOptionConverters.StrictDepsMode; import com.google.devtools.build.lib.analysis.starlark.StarlarkActionFactory; import com.google.devtools.build.lib.analysis.starlark.StarlarkRuleContext; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider.ClasspathType; import com.google.devtools.build.lib.shell.ShellUtils; import com.google.devtools.build.lib.vfs.FileSystemUtils; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import javax.annotation.Nullable; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.Sequence; import net.starlark.java.eval.Starlark; import net.starlark.java.eval.StarlarkThread; import net.starlark.java.syntax.Location; /** Implements logic for creating JavaInfo from different set of input parameters. */ final class JavaInfoBuildHelper { private static final JavaInfoBuildHelper INSTANCE = new JavaInfoBuildHelper(); private JavaInfoBuildHelper() {} public static JavaInfoBuildHelper getInstance() { return INSTANCE; } /** * Creates JavaInfo instance from outputJar. * * @param outputJar the jar that was created as a result of a compilation (e.g. javac, scalac, * etc) * @param compileJar Jar added as a compile-time dependency to other rules. Typically produced by * ijar. * @param sourceJar the source jar that was used to create the output jar * @param neverlink if true only use this library for compilation and not at runtime * @param compileTimeDeps compile time dependencies that were used to create the output jar * @param runtimeDeps runtime dependencies that are needed for this library * @param exports libraries to make available for users of this library. <a * href="https://docs.bazel.build/versions/master/be/java.html#java_library" * target="_top">java_library.exports</a> * @param jdeps optional jdeps information for outputJar * @return new created JavaInfo instance */ JavaInfo createJavaInfo( Artifact outputJar, Artifact compileJar, @Nullable Artifact sourceJar, Boolean neverlink, Sequence<JavaInfo> compileTimeDeps, Sequence<JavaInfo> runtimeDeps, Sequence<JavaInfo> exports, @Nullable Artifact jdeps, Location location) { compileJar = compileJar != null ? compileJar : outputJar; ImmutableList<Artifact> sourceJars = sourceJar != null ? ImmutableList.of(sourceJar) : ImmutableList.of(); JavaInfo.Builder javaInfoBuilder = JavaInfo.Builder.create(); javaInfoBuilder.setLocation(location); JavaCompilationArgsProvider.Builder javaCompilationArgsBuilder = JavaCompilationArgsProvider.builder(); if (!neverlink) { javaCompilationArgsBuilder.addRuntimeJar(outputJar); } javaCompilationArgsBuilder.addDirectCompileTimeJar( /* interfaceJar= */ compileJar, /* fullJar= */ outputJar); JavaRuleOutputJarsProvider javaRuleOutputJarsProvider = JavaRuleOutputJarsProvider.builder() .addOutputJar(outputJar, compileJar, null /* manifestProto */, sourceJars) .setJdeps(jdeps) .build(); javaInfoBuilder.addProvider(JavaRuleOutputJarsProvider.class, javaRuleOutputJarsProvider); ClasspathType type = neverlink ? COMPILE_ONLY : BOTH; streamProviders(exports, JavaCompilationArgsProvider.class) .forEach(args -> javaCompilationArgsBuilder.addExports(args, type)); streamProviders(compileTimeDeps, JavaCompilationArgsProvider.class) .forEach(args -> javaCompilationArgsBuilder.addDeps(args, type)); streamProviders(runtimeDeps, JavaCompilationArgsProvider.class) .forEach(args -> javaCompilationArgsBuilder.addDeps(args, RUNTIME_ONLY)); javaInfoBuilder.addProvider( JavaCompilationArgsProvider.class, javaCompilationArgsBuilder.build()); javaInfoBuilder.addProvider(JavaExportsProvider.class, createJavaExportsProvider(exports)); javaInfoBuilder.addProvider(JavaPluginInfoProvider.class, createJavaPluginsProvider(exports)); javaInfoBuilder.addProvider( JavaSourceJarsProvider.class, createJavaSourceJarsProvider(sourceJars, concat(compileTimeDeps, runtimeDeps, exports))); javaInfoBuilder.addProvider( JavaGenJarsProvider.class, JavaGenJarsProvider.create( false, null, null, JavaPluginInfoProvider.empty(), JavaInfo.fetchProvidersFromList( concat(compileTimeDeps, exports), JavaGenJarsProvider.class))); javaInfoBuilder.setRuntimeJars(ImmutableList.of(outputJar)); return javaInfoBuilder.build(); } /** * Creates action which creates archive with all source files inside. Takes all filer from * sourceFiles collection and all files from every sourceJars. Name of Artifact generated based on * outputJar. * * @param outputJar name of output Jar artifact. * @param outputSourceJar name of output source Jar artifact, or {@code null}. If unset, defaults * to base name of the output jar with the suffix {@code -src.jar}. * @return generated artifact (can also be empty) */ Artifact packSourceFiles( StarlarkActionFactory actions, Artifact outputJar, Artifact outputSourceJar, List<Artifact> sourceFiles, List<Artifact> sourceJars, JavaToolchainProvider javaToolchain, JavaRuntimeInfo hostJavabase) throws EvalException { if (outputJar == null && outputSourceJar == null) { throw Starlark.errorf( "pack_sources requires at least one of the parameters output_jar or output_source_jar"); } // If we only have one source jar, return it directly to avoid action creation if (sourceFiles.isEmpty() && sourceJars.size() == 1 && outputSourceJar == null) { return sourceJars.get(0); } ActionRegistry actionRegistry = actions.asActionRegistry(actions); if (outputSourceJar == null) { outputSourceJar = getDerivedSourceJar(actions.getActionConstructionContext(), outputJar); } SingleJarActionBuilder.createSourceJarAction( actionRegistry, actions.getActionConstructionContext(), javaToolchain.getJavaSemantics(), NestedSetBuilder.<Artifact>wrap(Order.STABLE_ORDER, sourceFiles), NestedSetBuilder.<Artifact>wrap(Order.STABLE_ORDER, sourceJars), outputSourceJar, javaToolchain, hostJavabase); return outputSourceJar; } private JavaSourceJarsProvider createJavaSourceJarsProvider( Iterable<Artifact> sourceJars, Iterable<JavaInfo> transitiveDeps) { NestedSetBuilder<Artifact> transitiveSourceJars = NestedSetBuilder.stableOrder(); transitiveSourceJars.addAll(sourceJars); fetchSourceJars(transitiveDeps).forEach(transitiveSourceJars::addTransitive); return JavaSourceJarsProvider.create(transitiveSourceJars.build(), sourceJars); } private Stream<NestedSet<Artifact>> fetchSourceJars(Iterable<JavaInfo> javaInfos) { // TODO(b/123265803): This step should be only necessary if transitive source jar doesn't // include sourcejar at this level but they should. Stream<NestedSet<Artifact>> sourceJars = streamProviders(javaInfos, JavaSourceJarsProvider.class) .map(JavaSourceJarsProvider::getSourceJars) .map(sourceJarsList -> NestedSetBuilder.wrap(Order.STABLE_ORDER, sourceJarsList)); Stream<NestedSet<Artifact>> transitiveSourceJars = streamProviders(javaInfos, JavaSourceJarsProvider.class) .map(JavaSourceJarsProvider::getTransitiveSourceJars); return concat(sourceJars, transitiveSourceJars); } private JavaExportsProvider createJavaExportsProvider(Iterable<JavaInfo> javaInfos) { return JavaExportsProvider.merge( JavaInfo.fetchProvidersFromList(javaInfos, JavaExportsProvider.class)); } private JavaPluginInfoProvider createJavaPluginsProvider(Iterable<JavaInfo> javaInfos) { return JavaPluginInfoProvider.merge( JavaInfo.fetchProvidersFromList(javaInfos, JavaPluginInfoProvider.class)); } public JavaInfo createJavaCompileAction( StarlarkRuleContext starlarkRuleContext, List<Artifact> sourceJars, List<Artifact> sourceFiles, Artifact outputJar, Artifact outputSourceJar, List<String> javacOpts, List<JavaInfo> deps, List<JavaInfo> experimentalLocalCompileTimeDeps, List<JavaInfo> exports, List<JavaInfo> plugins, List<JavaInfo> exportedPlugins, List<Artifact> annotationProcessorAdditionalInputs, List<Artifact> annotationProcessorAdditionalOutputs, String strictDepsMode, JavaToolchainProvider javaToolchain, JavaRuntimeInfo hostJavabase, ImmutableList<Artifact> sourcepathEntries, List<Artifact> resources, Boolean neverlink, JavaSemantics javaSemantics, StarlarkThread thread) throws EvalException, InterruptedException { JavaToolchainProvider toolchainProvider = javaToolchain; JavaLibraryHelper helper = new JavaLibraryHelper(starlarkRuleContext.getRuleContext()) .setOutput(outputJar) .addSourceJars(sourceJars) .addSourceFiles(sourceFiles) .addResources(resources) .setSourcePathEntries(sourcepathEntries) .addAdditionalOutputs(annotationProcessorAdditionalOutputs) .setJavacOpts( ImmutableList.<String>builder() .addAll(toolchainProvider.getJavacOptions(starlarkRuleContext.getRuleContext())) .addAll( javaSemantics.getCompatibleJavacOptions( starlarkRuleContext.getRuleContext(), toolchainProvider)) .addAll( JavaCommon.computePerPackageJavacOpts( starlarkRuleContext.getRuleContext(), toolchainProvider)) .addAll(tokenize(javacOpts)) .build()); streamProviders(deps, JavaCompilationArgsProvider.class).forEach(helper::addDep); streamProviders(exports, JavaCompilationArgsProvider.class).forEach(helper::addExport); helper.setCompilationStrictDepsMode(getStrictDepsMode(Ascii.toUpperCase(strictDepsMode))); helper.setPlugins(createJavaPluginsProvider(concat(plugins, deps))); helper.setNeverlink(neverlink); NestedSet<Artifact> localCompileTimeDeps = JavaCompilationArgsProvider.merge( streamProviders(experimentalLocalCompileTimeDeps, JavaCompilationArgsProvider.class) .collect(toImmutableList())) .getTransitiveCompileTimeJars(); JavaRuleOutputJarsProvider.Builder outputJarsBuilder = JavaRuleOutputJarsProvider.builder(); if (outputSourceJar == null) { outputSourceJar = getDerivedSourceJar(starlarkRuleContext.getRuleContext(), outputJar); } JavaInfo.Builder javaInfoBuilder = JavaInfo.Builder.create(); JavaCompilationArtifacts artifacts = helper.build( javaSemantics, toolchainProvider, hostJavabase, outputJarsBuilder, /*createOutputSourceJar=*/ true, outputSourceJar, javaInfoBuilder, // Include JavaGenJarsProviders from both deps and exports in the JavaGenJarsProvider // added to javaInfoBuilder for this target. JavaInfo.fetchProvidersFromList(concat(deps, exports), JavaGenJarsProvider.class), ImmutableList.copyOf(annotationProcessorAdditionalInputs), localCompileTimeDeps); JavaCompilationArgsProvider javaCompilationArgsProvider = helper.buildCompilationArgsProvider(artifacts, true, neverlink); Runfiles runfiles = new Runfiles.Builder(starlarkRuleContext.getWorkspaceName()) .addTransitiveArtifactsWrappedInStableOrder( javaCompilationArgsProvider.getRuntimeJars()) .build(); ImmutableList<Artifact> outputSourceJars = ImmutableList.of(outputSourceJar); // When sources are not provided, the subsequent output Jar will be empty. As such, the output // Jar is omitted from the set of Runtime Jars. if (!sourceJars.isEmpty() || !sourceFiles.isEmpty()) { javaInfoBuilder.setRuntimeJars(ImmutableList.of(outputJar)); } return javaInfoBuilder .addProvider(JavaCompilationArgsProvider.class, javaCompilationArgsProvider) .addProvider( JavaSourceJarsProvider.class, createJavaSourceJarsProvider(outputSourceJars, concat(deps, exports))) .addProvider(JavaRuleOutputJarsProvider.class, outputJarsBuilder.build()) .addProvider(JavaRunfilesProvider.class, new JavaRunfilesProvider(runfiles)) .addProvider( JavaPluginInfoProvider.class, createJavaPluginsProvider(concat(exportedPlugins, exports))) .setNeverlink(neverlink) .build(); } private static List<String> tokenize(List<String> input) throws EvalException { List<String> output = new ArrayList<>(); for (String token : input) { try { ShellUtils.tokenize(output, token); } catch (ShellUtils.TokenizationException e) { throw Starlark.errorf("%s", e.getMessage()); } } return output; } public Artifact buildIjar( StarlarkActionFactory actions, Artifact inputJar, @Nullable Label targetLabel, JavaToolchainProvider javaToolchain) throws EvalException { String ijarBasename = FileSystemUtils.removeExtension(inputJar.getFilename()) + "-ijar.jar"; Artifact interfaceJar = actions.declareFile(ijarBasename, inputJar); FilesToRunProvider ijarTarget = javaToolchain.getIjar(); CustomCommandLine.Builder commandLine = CustomCommandLine.builder().addExecPath(inputJar).addExecPath(interfaceJar); if (targetLabel != null) { commandLine.addLabel("--target_label", targetLabel); } SpawnAction.Builder actionBuilder = new SpawnAction.Builder() .addInput(inputJar) .addOutput(interfaceJar) .setExecutable(ijarTarget) .setProgressMessage("Extracting interface for jar %s", inputJar.getFilename()) .addCommandLine(commandLine.build()) .useDefaultShellEnvironment() .setMnemonic("JavaIjar"); actions.registerAction(actionBuilder.build(actions.getActionConstructionContext())); return interfaceJar; } public Artifact stampJar( StarlarkActionFactory actions, Artifact inputJar, Label targetLabel, JavaToolchainProvider javaToolchain) throws EvalException { String basename = FileSystemUtils.removeExtension(inputJar.getFilename()) + "-stamped.jar"; Artifact outputJar = actions.declareFile(basename, inputJar); // ijar doubles as a stamping tool FilesToRunProvider ijarTarget = (javaToolchain).getIjar(); CustomCommandLine.Builder commandLine = CustomCommandLine.builder() .addExecPath(inputJar) .addExecPath(outputJar) .add("--nostrip_jar") .addLabel("--target_label", targetLabel); SpawnAction.Builder actionBuilder = new SpawnAction.Builder() .addInput(inputJar) .addOutput(outputJar) .setExecutable(ijarTarget) .setProgressMessage("Stamping target label into jar %s", inputJar.getFilename()) .addCommandLine(commandLine.build()) .useDefaultShellEnvironment() .setMnemonic("JavaIjar"); actions.registerAction(actionBuilder.build(actions.getActionConstructionContext())); return outputJar; } private static StrictDepsMode getStrictDepsMode(String strictDepsMode) { switch (strictDepsMode) { case "OFF": return StrictDepsMode.OFF; case "ERROR": case "DEFAULT": return StrictDepsMode.ERROR; case "WARN": return StrictDepsMode.WARN; default: throw new IllegalArgumentException( "StrictDepsMode " + strictDepsMode + " not allowed." + " Only OFF and ERROR values are accepted."); } } private static Artifact getDerivedSourceJar( ActionConstructionContext context, Artifact outputJar) { return JavaCompilationHelper.derivedArtifact(context, outputJar, "", "-src.jar"); } }
/* * 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.master; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Random; import java.util.TreeMap; import java.util.concurrent.ConcurrentSkipListMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.hbase.Abortable; import org.apache.hadoop.hbase.CellScannable; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.ChoreService; import org.apache.hadoop.hbase.CoordinatedStateManager; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableDescriptors; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.ZooKeeperConnectionException; import org.apache.hadoop.hbase.client.AsyncClusterConnection; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RegionInfoBuilder; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.locking.EntityLock; import org.apache.hadoop.hbase.executor.ExecutorService; import org.apache.hadoop.hbase.io.hfile.BlockCache; import org.apache.hadoop.hbase.ipc.HBaseRpcController; import org.apache.hadoop.hbase.ipc.RpcServerInterface; import org.apache.hadoop.hbase.mob.MobFileCache; import org.apache.hadoop.hbase.quotas.RegionServerRpcQuotaManager; import org.apache.hadoop.hbase.quotas.RegionServerSpaceQuotaManager; import org.apache.hadoop.hbase.quotas.RegionSizeStore; import org.apache.hadoop.hbase.regionserver.FlushRequester; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.HeapMemoryManager; import org.apache.hadoop.hbase.regionserver.LeaseManager; import org.apache.hadoop.hbase.regionserver.MetricsRegionServer; import org.apache.hadoop.hbase.regionserver.RegionServerAccounting; import org.apache.hadoop.hbase.regionserver.RegionServerServices; import org.apache.hadoop.hbase.regionserver.ReplicationSourceService; import org.apache.hadoop.hbase.regionserver.SecureBulkLoadManager; import org.apache.hadoop.hbase.regionserver.ServerNonceManager; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequester; import org.apache.hadoop.hbase.regionserver.regionreplication.RegionReplicationBufferManager; import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController; import org.apache.hadoop.hbase.security.access.AccessChecker; import org.apache.hadoop.hbase.security.access.ZKPermissionWatcher; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.wal.WAL; import org.apache.hadoop.hbase.zookeeper.ZKWatcher; import org.apache.hbase.thirdparty.com.google.protobuf.RpcController; import org.apache.hbase.thirdparty.com.google.protobuf.Service; import org.apache.hbase.thirdparty.com.google.protobuf.ServiceException; import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearCompactionQueuesRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearCompactionQueuesResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearRegionBlockCacheRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearRegionBlockCacheResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearSlowLogResponseRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearSlowLogResponses; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CloseRegionRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CloseRegionResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactRegionRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactRegionResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactionSwitchRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactionSwitchResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ExecuteProceduresRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ExecuteProceduresResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.FlushRegionRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.FlushRegionResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetOnlineRegionRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetOnlineRegionResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionLoadRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionLoadResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetServerInfoRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetServerInfoResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetStoreFileRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetStoreFileResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.OpenRegionRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.OpenRegionResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ReplicateWALEntryRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ReplicateWALEntryResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RollWALWriterRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RollWALWriterResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.StopServerRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.StopServerResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateConfigurationRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateConfigurationResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateFavoredNodesRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateFavoredNodesResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.WarmupRegionRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.WarmupRegionResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.BulkLoadHFileRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.BulkLoadHFileResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.CleanupBulkLoadRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.CleanupBulkLoadResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.CoprocessorServiceRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.CoprocessorServiceResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.GetRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.GetResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MultiRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutateRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutateResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.PrepareBulkLoadRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.PrepareBulkLoadResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ScanRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ScanResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos; import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetSpaceQuotaSnapshotsRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.GetSpaceQuotaSnapshotsResponse; /** * A mock RegionServer implementation. * Use this when you can't bend Mockito to your liking (e.g. return null result * when 'scanning' until master timesout and then return a coherent meta row * result thereafter. Have some facility for faking gets and scans. See * setGetResult(byte[], byte[], Result) for how to fill the backing data * store that the get pulls from. */ class MockRegionServer implements AdminProtos.AdminService.BlockingInterface, ClientProtos.ClientService.BlockingInterface, RegionServerServices { private final ServerName sn; private final ZKWatcher zkw; private final Configuration conf; private final Random random = new Random(); /** * Map of regions to map of rows and {@link Result}. Used as data source when * {@link #get(RpcController, ClientProtos.GetRequest)} is called. Because we have a byte * key, need to use TreeMap and provide a Comparator. Use * {@link #setGetResult(byte[], byte[], Result)} filling this map. */ private final Map<byte [], Map<byte [], Result>> gets = new TreeMap<>(Bytes.BYTES_COMPARATOR); /** * Map of regions to results to return when scanning. */ private final Map<byte [], Result []> nexts = new TreeMap<>(Bytes.BYTES_COMPARATOR); /** * Data structure that holds regionname and index used scanning. */ class RegionNameAndIndex { private final byte[] regionName; private int index = 0; RegionNameAndIndex(final byte[] regionName) { this.regionName = regionName; } byte[] getRegionName() { return this.regionName; } int getThenIncrement() { int currentIndex = this.index; this.index++; return currentIndex; } } /** * Outstanding scanners and their offset into <code>nexts</code> */ private final Map<Long, RegionNameAndIndex> scannersAndOffsets = new HashMap<>(); /** * @param sn Name of this mock regionserver * @throws IOException * @throws org.apache.hadoop.hbase.ZooKeeperConnectionException */ MockRegionServer(final Configuration conf, final ServerName sn) throws ZooKeeperConnectionException, IOException { this.sn = sn; this.conf = conf; this.zkw = new ZKWatcher(conf, sn.toString(), this, true); } /** * Use this method filling the backing data source used by * {@link #get(RpcController, ClientProtos.GetRequest)} * @param regionName the region name to assign * @param row the row key * @param r the single row result */ void setGetResult(final byte [] regionName, final byte [] row, final Result r) { Map<byte [], Result> value = this.gets.get(regionName); if (value == null) { // If no value already, create one. Needs to be treemap because we are // using byte array as key. Not thread safe. value = new TreeMap<>(Bytes.BYTES_COMPARATOR); this.gets.put(regionName, value); } value.put(row, r); } /** * Use this method to set what a scanner will reply as we next through * @param regionName * @param rs */ void setNextResults(final byte [] regionName, final Result [] rs) { this.nexts.put(regionName, rs); } @Override public boolean isStopped() { return false; } @Override public void abort(String why, Throwable e) { throw new RuntimeException(this.sn + ": " + why, e); } @Override public boolean isAborted() { return false; } public long openScanner(byte[] regionName, Scan scan) throws IOException { long scannerId = this.random.nextLong(); this.scannersAndOffsets.put(scannerId, new RegionNameAndIndex(regionName)); return scannerId; } public Result next(long scannerId) throws IOException { RegionNameAndIndex rnai = this.scannersAndOffsets.get(scannerId); int index = rnai.getThenIncrement(); Result [] results = this.nexts.get(rnai.getRegionName()); if (results == null) return null; return index < results.length? results[index]: null; } public Result [] next(long scannerId, int numberOfRows) throws IOException { // Just return one result whatever they ask for. Result r = next(scannerId); return r == null? null: new Result [] {r}; } public void close(final long scannerId) throws IOException { this.scannersAndOffsets.remove(scannerId); } @Override public void stop(String why) { this.zkw.close(); } @Override public void addRegion(HRegion r) { } @Override public boolean removeRegion(HRegion r, ServerName destination) { return false; } @Override public HRegion getRegion(String encodedRegionName) { return null; } @Override public Configuration getConfiguration() { return this.conf; } @Override public ZKWatcher getZooKeeper() { return this.zkw; } @Override public CoordinatedStateManager getCoordinatedStateManager() { return null; } @Override public Connection getConnection() { return null; } @Override public ServerName getServerName() { return this.sn; } @Override public boolean isStopping() { return false; } @Override public FlushRequester getFlushRequester() { return null; } @Override public CompactionRequester getCompactionRequestor() { return null; } @Override public RegionServerAccounting getRegionServerAccounting() { return null; } @Override public RegionServerRpcQuotaManager getRegionServerRpcQuotaManager() { return null; } @Override public void postOpenDeployTasks(PostOpenDeployContext context) throws IOException { } @Override public RpcServerInterface getRpcServer() { return null; } @Override public ConcurrentSkipListMap<byte[], Boolean> getRegionsInTransitionInRS() { return null; } @Override public FileSystem getFileSystem() { return null; } @Override public GetResponse get(RpcController controller, GetRequest request) throws ServiceException { byte[] regionName = request.getRegion().getValue().toByteArray(); Map<byte [], Result> m = this.gets.get(regionName); GetResponse.Builder builder = GetResponse.newBuilder(); if (m != null) { byte[] row = request.getGet().getRow().toByteArray(); builder.setResult(ProtobufUtil.toResult(m.get(row))); } return builder.build(); } @Override public MutateResponse mutate(RpcController controller, MutateRequest request) throws ServiceException { return null; } @Override public ScanResponse scan(RpcController controller, ScanRequest request) throws ServiceException { ScanResponse.Builder builder = ScanResponse.newBuilder(); try { if (request.hasScan()) { byte[] regionName = request.getRegion().getValue().toByteArray(); builder.setScannerId(openScanner(regionName, null)); builder.setMoreResults(true); } else { long scannerId = request.getScannerId(); Result result = next(scannerId); if (result != null) { builder.addCellsPerResult(result.size()); List<CellScannable> results = new ArrayList<>(1); results.add(result); ((HBaseRpcController) controller).setCellScanner(CellUtil .createCellScanner(results)); builder.setMoreResults(true); } else { builder.setMoreResults(false); close(scannerId); } } } catch (IOException ie) { throw new ServiceException(ie); } return builder.build(); } @Override public BulkLoadHFileResponse bulkLoadHFile(RpcController controller, BulkLoadHFileRequest request) throws ServiceException { return null; } @Override public ClientProtos.CoprocessorServiceResponse execService(RpcController controller, ClientProtos.CoprocessorServiceRequest request) throws ServiceException { return null; } @Override public ClientProtos.MultiResponse multi( RpcController controller, MultiRequest request) throws ServiceException { return null; } @Override public GetRegionInfoResponse getRegionInfo(RpcController controller, GetRegionInfoRequest request) throws ServiceException { GetRegionInfoResponse.Builder builder = GetRegionInfoResponse.newBuilder(); builder.setRegionInfo(ProtobufUtil.toRegionInfo(RegionInfoBuilder.FIRST_META_REGIONINFO)); return builder.build(); } @Override public GetRegionLoadResponse getRegionLoad(RpcController controller, GetRegionLoadRequest request) throws ServiceException { GetRegionLoadResponse.Builder builder = GetRegionLoadResponse.newBuilder(); return builder.build(); } @Override public ClearCompactionQueuesResponse clearCompactionQueues(RpcController controller, ClearCompactionQueuesRequest request) throws ServiceException { return null; } @Override public GetStoreFileResponse getStoreFile(RpcController controller, GetStoreFileRequest request) throws ServiceException { return null; } @Override public GetOnlineRegionResponse getOnlineRegion(RpcController controller, GetOnlineRegionRequest request) throws ServiceException { return null; } @Override public List<HRegion> getRegions() { return null; } @Override public OpenRegionResponse openRegion(RpcController controller, OpenRegionRequest request) throws ServiceException { return null; } @Override public WarmupRegionResponse warmupRegion(RpcController controller, WarmupRegionRequest request) throws ServiceException { return null; } @Override public CloseRegionResponse closeRegion(RpcController controller, CloseRegionRequest request) throws ServiceException { return null; } @Override public FlushRegionResponse flushRegion(RpcController controller, FlushRegionRequest request) throws ServiceException { return null; } @Override public CompactionSwitchResponse compactionSwitch(RpcController controller, CompactionSwitchRequest request) throws ServiceException { return null; } @Override public CompactRegionResponse compactRegion(RpcController controller, CompactRegionRequest request) throws ServiceException { return null; } @Override public ReplicateWALEntryResponse replicateWALEntry(RpcController controller, ReplicateWALEntryRequest request) throws ServiceException { return null; } @Override public RollWALWriterResponse rollWALWriter(RpcController controller, RollWALWriterRequest request) throws ServiceException { return null; } @Override public GetServerInfoResponse getServerInfo(RpcController controller, GetServerInfoRequest request) throws ServiceException { return null; } @Override public StopServerResponse stopServer(RpcController controller, StopServerRequest request) throws ServiceException { return null; } @Override public List<HRegion> getRegions(TableName tableName) throws IOException { return null; } @Override public LeaseManager getLeaseManager() { return null; } @Override public List<WAL> getWALs() throws IOException { return Collections.emptyList(); } @Override public WAL getWAL(RegionInfo regionInfo) throws IOException { return null; } @Override public ExecutorService getExecutorService() { return null; } @Override public ChoreService getChoreService() { return null; } @Override public void updateRegionFavoredNodesMapping(String encodedRegionName, List<org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ServerName> favoredNodes) { } @Override public InetSocketAddress[] getFavoredNodesForRegion(String encodedRegionName) { return null; } @Override public ReplicateWALEntryResponse replay(RpcController controller, ReplicateWALEntryRequest request) throws ServiceException { return null; } @Override public UpdateFavoredNodesResponse updateFavoredNodes(RpcController controller, UpdateFavoredNodesRequest request) throws ServiceException { return null; } @Override public ServerNonceManager getNonceManager() { return null; } @Override public boolean reportRegionStateTransition(RegionStateTransitionContext context) { return false; } @Override public boolean registerService(Service service) { return false; } @Override public CoprocessorServiceResponse execRegionServerService(RpcController controller, CoprocessorServiceRequest request) throws ServiceException { return null; } @Override public UpdateConfigurationResponse updateConfiguration( RpcController controller, UpdateConfigurationRequest request) throws ServiceException { return null; } @Override public ClearRegionBlockCacheResponse clearRegionBlockCache(RpcController controller, ClearRegionBlockCacheRequest request) throws ServiceException { return null; } @Override public HeapMemoryManager getHeapMemoryManager() { return null; } @Override public double getCompactionPressure() { return 0; } @Override public ThroughputController getFlushThroughputController() { return null; } @Override public double getFlushPressure() { return 0; } @Override public MetricsRegionServer getMetrics() { return null; } @Override public EntityLock regionLock(List<RegionInfo> regionInfos, String description, Abortable abort) throws IOException { return null; } @Override public PrepareBulkLoadResponse prepareBulkLoad(RpcController controller, PrepareBulkLoadRequest request) throws ServiceException { return null; } @Override public CleanupBulkLoadResponse cleanupBulkLoad(RpcController controller, CleanupBulkLoadRequest request) throws ServiceException { return null; } @Override public SecureBulkLoadManager getSecureBulkLoadManager() { return null; } @Override public void unassign(byte[] regionName) throws IOException { } @Override public RegionServerSpaceQuotaManager getRegionServerSpaceQuotaManager() { return null; } @Override public ExecuteProceduresResponse executeProcedures(RpcController controller, ExecuteProceduresRequest request) throws ServiceException { return null; } @Override public ClearSlowLogResponses clearSlowLogsResponses(RpcController controller, ClearSlowLogResponseRequest request) throws ServiceException { return null; } @Override public HBaseProtos.LogEntry getLogEntries(RpcController controller, HBaseProtos.LogRequest request) throws ServiceException { return null; } @Override public GetSpaceQuotaSnapshotsResponse getSpaceQuotaSnapshots( RpcController controller, GetSpaceQuotaSnapshotsRequest request) throws ServiceException { return null; } @Override public Connection createConnection(Configuration conf) throws IOException { return null; } @Override public boolean reportRegionSizesForQuotas(RegionSizeStore sizeStore) { return true; } @Override public boolean reportFileArchivalForQuotas( TableName tableName, Collection<Entry<String, Long>> archivedFiles) { return false; } public boolean isClusterUp() { return true; } @Override public ReplicationSourceService getReplicationSourceService() { return null; } @Override public TableDescriptors getTableDescriptors() { return null; } @Override public Optional<BlockCache> getBlockCache() { return Optional.empty(); } @Override public Optional<MobFileCache> getMobFileCache() { return Optional.empty(); } @Override public AccessChecker getAccessChecker() { return null; } @Override public ZKPermissionWatcher getZKPermissionWatcher() { return null; } @Override public AsyncClusterConnection getAsyncClusterConnection() { return null; } @Override public RegionReplicationBufferManager getRegionReplicationBufferManager() { return null; } @Override public ReplicateWALEntryResponse replicateToReplica(RpcController controller, ReplicateWALEntryRequest request) throws ServiceException { return null; } }
/* ======================================================================== * * This file is part of CODEC, which is a Java package for encoding * and decoding ASN.1 data structures. * * Author: Fraunhofer Institute for Computer Graphics Research IGD * Department A8: Security Technology * Fraunhoferstr. 5, 64283 Darmstadt, Germany * * Rights: Copyright (c) 2004 by Fraunhofer-Gesellschaft * zur Foerderung der angewandten Forschung e.V. * Hansastr. 27c, 80686 Munich, Germany. * * ------------------------------------------------------------------------ * * The software package is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software package; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA or obtain a copy of the license at * http://www.fsf.org/licensing/licenses/lgpl.txt. * * ------------------------------------------------------------------------ * * The CODEC library can solely be used and distributed according to * the terms and conditions of the GNU Lesser General Public License for * non-commercial research purposes and shall not be embedded in any * products or services of any user or of any third party and shall not * be linked with any products or services of any user or of any third * party that will be commercially exploited. * * The CODEC library has not been tested for the use or application * for a determined purpose. It is a developing version that can * possibly contain errors. Therefore, Fraunhofer-Gesellschaft zur * Foerderung der angewandten Forschung e.V. does not warrant that the * operation of the CODEC library will be uninterrupted or error-free. * Neither does Fraunhofer-Gesellschaft zur Foerderung der angewandten * Forschung e.V. warrant that the CODEC library will operate and * interact in an uninterrupted or error-free way together with the * computer program libraries of third parties which the CODEC library * accesses and which are distributed together with the CODEC library. * * Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. * does not warrant that the operation of the third parties's computer * program libraries themselves which the CODEC library accesses will * be uninterrupted or error-free. * * Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. * shall not be liable for any errors or direct, indirect, special, * incidental or consequential damages, including lost profits resulting * from the combination of the CODEC library with software of any user * or of any third party or resulting from the implementation of the * CODEC library in any products, systems or services of any user or * of any third party. * * Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. * does not provide any warranty nor any liability that utilization of * the CODEC library will not interfere with third party intellectual * property rights or with any other protected third party rights or will * cause damage to third parties. Fraunhofer Gesellschaft zur Foerderung * der angewandten Forschung e.V. is currently not aware of any such * rights. * * The CODEC library is supplied without any accompanying services. * * ======================================================================== */ package codec.x509; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Externalizable; import java.io.IOException; import java.security.cert.CertificateEncodingException; import java.util.HashSet; import java.util.Set; import codec.asn1.ASN1Boolean; import codec.asn1.ASN1Exception; import codec.asn1.ASN1ObjectIdentifier; import codec.asn1.ASN1OctetString; import codec.asn1.ASN1Sequence; import codec.asn1.ASN1Type; import codec.asn1.ConstraintException; import codec.asn1.DERDecoder; import codec.asn1.DEREncoder; /** * This class represents an X.509 extension of this form * <p> * * <pre> * Extension ::= SEQUENCE { * extnID OBJECT IDENTIFIER, * critical BOOLEAN DEFAULT FALSE, * extnValue OCTET STRING * } * </pre> * * Creation date: (18.08.99 15:23:09) * * @author Markus Tak */ public class X509Extension extends ASN1Sequence implements java.security.cert.X509Extension, Externalizable { protected ASN1ObjectIdentifier extnID = null; protected ASN1Boolean critical = null; protected ASN1OctetString extnValue = null; /** * Creates an instance ready for use in decoding extensions. */ public X509Extension() { /* * If used for decoding, ASN.1 objects do not need special * initialization values. On the contrary, ASN.1 objects generally * initialize for decoding when the default constructor is invoked. * --volker roth */ extnID = new ASN1ObjectIdentifier(); add(extnID); critical = new ASN1Boolean(false); critical.setOptional(true); add(critical); extnValue = new ASN1OctetString(); add(extnValue); } /** * Initializes this extension from the given DER code. * * @param b * The DER code. * @throws ASN1Exception * iff the data cannot be decoded correctly. */ public X509Extension(byte[] b) throws ASN1Exception, IOException { this(); /* * This method need not declare or throw an IOException. It would be * better to just catch it and throw a runtime exception (an error). * * --volker roth */ ByteArrayInputStream in; DERDecoder dec; if (b == null) { throw new NullPointerException("input array"); } in = new ByteArrayInputStream(b); dec = new DERDecoder(in); decode(dec); /* * Let stream free resources. */ in.close(); } /** * This constructor fills-up the data structure. * * @param theoid * This extension's OID * @param crit * TRUE if this extension shall be critical * @param val * The value of this extension as a ASN1Type. This one will * be DER-encoded and be put into an ASN1OctetString */ public X509Extension(ASN1ObjectIdentifier theoid, boolean crit, ASN1Type val) throws Exception { this(); this.setOID(theoid); this.setCritical(crit); this.setValue(val); } /** * From interface java.security.cert.X509Extension. * * @return either an empty Set if this extension is not critical or a Set * containing one element (this extension's OID) if this extension * is marked as critical. */ public Set getCriticalExtensionOIDs() { HashSet res = new HashSet(); if (isCritical()) res.add(getOID()); return res; } /** * Returns the DER encoding of this extension. From * java.security.cert.X509Extension * * @return a byte array containing the DER-encoding of this extension */ public byte[] getEncoded() throws CertificateEncodingException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DEREncoder enc = new DEREncoder(bos); try { this.encode(enc); bos.close(); } catch (IOException e) { System.err.println("getenc Internal error: shouldn't happen!"); e.printStackTrace(); } catch (ASN1Exception e) { throw new CertificateEncodingException(e.getMessage()); } return bos.toByteArray(); } /** * From java.security.cert.X509Extension. Returns the DER encoding of this * extension if the given OID matches * * @param oid * the OID to search for * @return a byte array containing the DER-encoding of this extension */ public byte[] getExtensionValue(String oid) { byte[] res = null; if (extnValue == null) return null; if (extnID.toString().equals(oid) || extnID.toString().equals(new String("OID." + oid))) { // res = extnValue.getByteArray(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEREncoder enc = new DEREncoder(baos); extnValue.encode(enc); res = baos.toByteArray(); baos.close(); } catch (ASN1Exception asn1e) { throw new IllegalStateException( "Caught ASN1Exception. Internal Error. Shouldn't happen"); } catch (IOException ioe) { throw new IllegalStateException( "Internal Error. Shouldn't happen"); } } return res; } public Set getNonCriticalExtensionOIDs() { HashSet res = new HashSet(); if (!isCritical()) res.add(getOID()); return res; } /** * Returns the OID of this extension * * @return This extension's OID */ public ASN1ObjectIdentifier getOID() { return extnID; } /** * Returns this extension's value. The value is tried to be decoded and * returned as a ASN1Type object. If decoding fails for some reason (e.g. * extension did not contain a DER encoded ASN.1 type, the ASN1OctetString * containing the original value is returned. */ public Object getValue() { ByteArrayInputStream bis; DERDecoder dec; ASN1Type res = null; try { bis = new ByteArrayInputStream(extnValue.getByteArray()); dec = new DERDecoder(bis); res = dec.readType(); dec.close(); } catch (IOException e) { System.err.println("Internal error: shouldn't happen!"); e.printStackTrace(); } catch (ASN1Exception e) { res = extnValue; } return res; } /** * This method allows to decode the extension value based on an ASN.1 * template. This implicitly checks the syntax of the decoded type. */ protected void decodeExtensionValue(ASN1Type t) throws ASN1Exception, IOException { ByteArrayInputStream bis; DERDecoder dec; if (t == null) { throw new NullPointerException("input parameter"); } bis = new ByteArrayInputStream(extnValue.getByteArray()); dec = new DERDecoder(bis); t.decode(dec); dec.close(); } /** * From java.security.cert.X509Extension * * @return always false */ public boolean hasUnsupportedCriticalExtension() { if (!isCritical()) return false; return false; } /** * Returns the critical flag of this extension * * @return true if this extension is marked as critical */ public boolean isCritical() { if (isOptional()) return false; return critical.isTrue(); } /** * Set the critical of this extension * * @param ncrit * true if this extension shall be marked critical */ public void setCritical(boolean ncrit) { if (!ncrit) critical.setOptional(true); else { critical.setTrue(ncrit); critical.setOptional(false); } } /** * Set this extension's OID * * @param noid * this extension's new OID */ public void setOID(ASN1ObjectIdentifier noid) throws ConstraintException { extnID.setOID(noid.getOID()); } /** * Set this extension's value * * @param nval * the new value of this extension. Note that this value will * be DER-encoded and stored inside an ASN1OctetString * @throws CertificateEncodingException * if encoding fails */ public void setValue(ASN1Type nval) throws CertificateEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { nval.encode(new DEREncoder(baos)); extnValue.setByteArray(baos.toByteArray()); } catch (Exception e) { throw new CertificateEncodingException(e.getMessage()); } } /** * Returns a human-readable String representation of this extension */ public String toString() { return toString(""); } /** * Returns a human-readable String representation of this extension with an * offset String. * * @param offset * String that will be put before each line of output */ public String toString(String offset) { String res = offset; res = "Extension " + extnID.toString(); if (critical.isTrue()) res = res + " (CRITICAL)"; else res = res + " (not critical)"; res = res + " Value=" + getValue().toString(); return res; } }
package com.adms.entity.cs; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Formula; import com.adms.common.domain.BaseAuditDomain; @Entity @Table(name="CUSTOMER") public class Customer extends BaseAuditDomain { private static final long serialVersionUID = 2155291361774705908L; @Id @Column(name="ID") @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column(name="TITLE") private String title; @Column(name="FIRST_NAME") private String firstName; @Column(name="LAST_NAME") private String lastName; @Formula(value = " CONCAT(" + " UPPER(LEFT(FIRST_NAME, 1)), LOWER(SUBSTRING(FIRST_NAME, 2, LEN(FIRST_NAME))) " + " , ' ' " + " , UPPER(LEFT(LAST_NAME, 1)), LOWER(SUBSTRING(LAST_NAME, 2, LEN(LAST_NAME)))) ") private String fullName; @Column(name="CITIZEN_ID") private String citizenId; @Column(name="PASSPORT_ID") private String passportId; @ManyToOne @JoinColumn(name="GENDER", referencedColumnName="PARAM_KEY") private ParamConfig gender; @Column(name="DOB") @Temporal(TemporalType.DATE) private Date dob; @Column(name="NATIONALITY") private String nationality; @Column(name="CITIZENSHIP") private String citizenship; @Column(name="MARITAL") private String marital; @Column(name="HOME_NO") private String homeNo; @Column(name="MOBILE_NO") private String mobileNo; @Column(name="OTHER_NO") private String otherNo; @Column(name="OFFICE_NO") private String officeNo; @Column(name="EMAIL") private String email; @Column(name="ADDRESS_1") private String address1; @Column(name="ADDRESS_2") private String address2; @Column(name="ADDRESS_3") private String address3; @Column(name="POST_CODE") private String postCode; @ManyToOne @JoinColumn(name="PROVINCE", referencedColumnName="PROVINCE_CODE") private Province province; @Column(name="VISIBLE") private String visible; public Long getId() { return id; } public Customer setId(Long id) { this.id = id; return this; } public String getTitle() { return title; } public Customer setTitle(String title) { this.title = title; return this; } public String getFirstName() { return firstName; } public Customer setFirstName(String firstName) { this.firstName = firstName; return this; } public String getLastName() { return lastName; } public Customer setLastName(String lastName) { this.lastName = lastName; return this; } public String getCitizenId() { return citizenId; } public Customer setCitizenId(String citizenId) { this.citizenId = citizenId; return this; } public String getPassportId() { return passportId; } public Customer setPassportId(String passportId) { this.passportId = passportId; return this; } public ParamConfig getGender() { return gender; } public Customer setGender(ParamConfig gender) { this.gender = gender; return this; } public Date getDob() { return dob; } public Customer setDob(Date dob) { this.dob = dob; return this; } public String getMarital() { return marital; } public Customer setMarital(String marital) { this.marital = marital; return this; } public String getFullName() { return fullName; } public Customer setFullName(String fullName) { this.fullName = fullName; return this; } public String getHomeNo() { return homeNo; } public Customer setHomeNo(String homeNo) { this.homeNo = homeNo; return this; } public String getMobileNo() { return mobileNo; } public Customer setMobileNo(String mobileNo) { this.mobileNo = mobileNo; return this; } public String getOtherNo() { return otherNo; } public Customer setOtherNo(String otherNo) { this.otherNo = otherNo; return this; } public String getOfficeNo() { return officeNo; } public Customer setOfficeNo(String officeNo) { this.officeNo = officeNo; return this; } public String getNationality() { return nationality; } public Customer setNationality(String nationality) { this.nationality = nationality; return this; } public String getCitizenship() { return citizenship; } public Customer setCitizenship(String citizenship) { this.citizenship = citizenship; return this; } public String getEmail() { return email; } public Customer setEmail(String email) { this.email = email; return this; } public String getAddress1() { return address1; } public Customer setAddress1(String address1) { this.address1 = address1; return this; } public String getAddress2() { return address2; } public Customer setAddress2(String address2) { this.address2 = address2; return this; } public String getAddress3() { return address3; } public Customer setAddress3(String address3) { this.address3 = address3; return this; } public String getPostCode() { return postCode; } public Customer setPostCode(String postCode) { this.postCode = postCode; return this; } public Province getProvince() { return province; } public Customer setProvince(Province province) { this.province = province; return this; } public String getVisible() { return visible; } public Customer setVisible(String visible) { this.visible = visible; return this; } }
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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. ******************************************************************************/ /* * Copyright 2010 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.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.badlogic.gdx.tests.utils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.badlogic.gdx.tests.*; import com.badlogic.gdx.tests.bench.TiledMapBench; import com.badlogic.gdx.tests.conformance.DisplayModeTest; import com.badlogic.gdx.tests.examples.MoveSpriteExample; import com.badlogic.gdx.tests.extensions.ControllersTest; import com.badlogic.gdx.tests.extensions.FreeTypeAtlasTest; import com.badlogic.gdx.tests.extensions.FreeTypeDisposeTest; import com.badlogic.gdx.tests.extensions.FreeTypeFontLoaderTest; import com.badlogic.gdx.tests.extensions.FreeTypeIncrementalTest; import com.badlogic.gdx.tests.extensions.FreeTypeMetricsTest; import com.badlogic.gdx.tests.extensions.FreeTypePackTest; import com.badlogic.gdx.tests.extensions.FreeTypeTest; import com.badlogic.gdx.tests.extensions.InternationalFontsTest; import com.badlogic.gdx.tests.g3d.Animation3DTest; import com.badlogic.gdx.tests.g3d.AnisotropyTest; import com.badlogic.gdx.tests.g3d.Basic3DSceneTest; import com.badlogic.gdx.tests.g3d.Basic3DTest; import com.badlogic.gdx.tests.g3d.Benchmark3DTest; import com.badlogic.gdx.tests.g3d.FogTest; import com.badlogic.gdx.tests.g3d.FrameBufferCubemapTest; import com.badlogic.gdx.tests.g3d.HeightMapTest; import com.badlogic.gdx.tests.g3d.LightsTest; import com.badlogic.gdx.tests.g3d.MaterialTest; import com.badlogic.gdx.tests.g3d.MaterialEmissiveTest; import com.badlogic.gdx.tests.g3d.MeshBuilderTest; import com.badlogic.gdx.tests.g3d.ModelCacheTest; import com.badlogic.gdx.tests.g3d.ModelTest; import com.badlogic.gdx.tests.g3d.MultipleRenderTargetTest; import com.badlogic.gdx.tests.g3d.ParticleControllerInfluencerSingleTest; import com.badlogic.gdx.tests.g3d.ParticleControllerTest; import com.badlogic.gdx.tests.g3d.PolarAccelerationTest; import com.badlogic.gdx.tests.g3d.ShaderCollectionTest; import com.badlogic.gdx.tests.g3d.ShaderTest; import com.badlogic.gdx.tests.g3d.ShadowMappingTest; import com.badlogic.gdx.tests.g3d.SkeletonTest; import com.badlogic.gdx.tests.g3d.TangentialAccelerationTest; import com.badlogic.gdx.tests.g3d.TextureArrayTest; import com.badlogic.gdx.tests.g3d.TextureRegion3DTest; import com.badlogic.gdx.tests.gles2.HelloTriangle; import com.badlogic.gdx.tests.gles2.SimpleVertexShader; import com.badlogic.gdx.tests.net.NetAPITest; import com.badlogic.gdx.tests.superkoalio.SuperKoalio; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.StreamUtils; /** List of GdxTest classes. To be used by the test launchers. If you write your own test, add it in here! * * @author badlogicgames@gmail.com */ public class GdxTests { public static final List<Class<? extends GdxTest>> tests = new ArrayList<Class<? extends GdxTest>>(Arrays.asList( // @off IssueTest.class, AccelerometerTest.class, ActionSequenceTest.class, ActionTest.class, Affine2Test.class, AlphaTest.class, Animation3DTest.class, AnimationTest.class, AnisotropyTest.class, AnnotationTest.class, AssetManagerTest.class, AtlasIssueTest.class, AudioDeviceTest.class, AudioRecorderTest.class, Basic3DSceneTest.class, Basic3DTest.class, Benchmark3DTest.class, BitmapFontAlignmentTest.class, BitmapFontDistanceFieldTest.class, BitmapFontFlipTest.class, BitmapFontMetricsTest.class, BitmapFontTest.class, BitmapFontAtlasRegionTest.class, BlitTest.class, Box2DTest.class, Box2DTestCollection.class, Bresenham2Test.class, BufferUtilsTest.class, BulletTestCollection.class, ClipboardTest.class, CollectionsTest.class, ColorTest.class, ContainerTest.class, CpuSpriteBatchTest.class, CullTest.class, CursorTest.class, DecalTest.class, DelaunayTriangulatorTest.class, DeltaTimeTest.class, DirtyRenderingTest.class, DisplayModeTest.class, DragAndDropTest.class, ETC1Test.class, // EarClippingTriangulatorTest.class, EdgeDetectionTest.class, ExitTest.class, ExternalMusicTest.class, FilesTest.class, FilterPerformanceTest.class, FloatTextureTest.class, FogTest.class, FrameBufferCubemapTest.class, FrameBufferTest.class, FramebufferToTextureTest.class, FullscreenTest.class, ControllersTest.class, Gdx2DTest.class, GestureDetectorTest.class, GLES30Test.class, GLProfilerErrorTest.class, GroupCullingTest.class, GroupFadeTest.class, GroupTest.class, HeightMapTest.class, HelloTriangle.class, HexagonalTiledMapTest.class, I18NMessageTest.class, I18NSimpleMessageTest.class, ImageScaleTest.class, ImageTest.class, ImmediateModeRendererTest.class, IndexBufferObjectShaderTest.class, InputTest.class, IntegerBitmapFontTest.class, InterpolationTest.class, InverseKinematicsTest.class, IsometricTileTest.class, KinematicBodyTest.class, KTXTest.class, LabelScaleTest.class, LabelTest.class, LifeCycleTest.class, LightsTest.class, MaterialTest.class, MaterialEmissiveTest.class, MatrixJNITest.class, MeshBuilderTest.class, MeshShaderTest.class, MipMapTest.class, ModelTest.class, ModelCacheTest.class, MoveSpriteExample.class, MultipleRenderTargetTest.class, MultitouchTest.class, MusicTest.class, NetAPITest.class, NinePatchTest.class, NoncontinuousRenderingTest.class, OnscreenKeyboardTest.class, PathTest.class, ParallaxTest.class, ParticleControllerInfluencerSingleTest.class, ParticleControllerTest.class, ParticleEmitterTest.class, ParticleEmittersTest.class, ParticleEmitterChangeSpriteTest.class, PixelsPerInchTest.class, PixmapBlendingTest.class, PixmapPackerTest.class, PixmapPackerIOTest.class, PixmapTest.class, PolarAccelerationTest.class, PolygonRegionTest.class, PolygonSpriteTest.class, PreferencesTest.class, ProjectTest.class, ProjectiveTextureTest.class, ReflectionTest.class, ReflectionCorrectnessTest.class, RotationTest.class, RunnablePostTest.class, Scene2dTest.class, ScrollPane2Test.class, ScrollPaneScrollBarsTest.class, ScrollPaneTest.class, ScrollPaneTextAreaTest.class, ScrollPaneWithDynamicScrolling.class, SelectTest.class, SensorTest.class, ShaderCollectionTest.class, ShaderMultitextureTest.class, ShaderTest.class, ShadowMappingTest.class, ShapeRendererTest.class, SimpleAnimationTest.class, SimpleDecalTest.class, SimpleStageCullingTest.class, SimpleVertexShader.class, SkeletonTest.class, SoftKeyboardTest.class, SortedSpriteTest.class, SoundTest.class, SpriteBatchRotationTest.class, SpriteBatchShaderTest.class, SpriteBatchTest.class, SpriteCacheOffsetTest.class, SpriteCacheTest.class, StageDebugTest.class, StagePerformanceTest.class, StageTest.class, SuperKoalio.class, TableLayoutTest.class, TableTest.class, TangentialAccelerationTest.class, TextAreaTest.class, TextAreaTest2.class, TextButtonTest.class, TextInputDialogTest.class, TextureAtlasTest.class, TextureArrayTest.class, TextureDataTest.class, TextureDownloadTest.class, TextureFormatTest.class, TextureRegion3DTest.class, TideMapAssetManagerTest.class, TideMapDirectLoaderTest.class, TileTest.class, TiledMapAnimationLoadingTest.class, TiledMapAssetManagerTest.class, TiledMapGroupLayerTest.class, TiledMapAtlasAssetManagerTest.class, TiledMapDirectLoaderTest.class, TiledMapModifiedExternalTilesetTest.class, TiledMapObjectLoadingTest.class, TiledMapBench.class, TiledMapLayerOffsetTest.class, TimerTest.class, TimeUtilsTest.class, TouchpadTest.class, TreeTest.class, UISimpleTest.class, UITest.class, VBOWithVAOPerformanceTest.class, Vector2dTest.class, VertexBufferObjectShaderTest.class, VibratorTest.class, ViewportTest1.class, ViewportTest2.class, ViewportTest3.class, YDownTest.class, FreeTypeFontLoaderTest.class, FreeTypeDisposeTest.class, FreeTypeMetricsTest.class, FreeTypeIncrementalTest.class, FreeTypePackTest.class, FreeTypeAtlasTest.class, FreeTypeTest.class, InternationalFontsTest.class, PngTest.class, JsonTest.class // @on // SoundTouchTest.class, Mpg123Test.class, WavTest.class, FreeTypeTest.class, // VorbisTest.class )); static final ObjectMap<String, String> obfuscatedToOriginal = new ObjectMap(); static final ObjectMap<String, String> originalToObfuscated = new ObjectMap(); static { InputStream mappingInput = GdxTests.class.getResourceAsStream("/mapping.txt"); if (mappingInput != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(mappingInput), 512); while (true) { String line = reader.readLine(); if (line == null) break; if (line.startsWith(" ")) continue; String[] split = line.replace(":", "").split(" -> "); String original = split[0]; if (original.indexOf('.') != -1) original = original.substring(original.lastIndexOf('.') + 1); originalToObfuscated.put(original, split[1]); obfuscatedToOriginal.put(split[1], original); } reader.close(); } catch (Exception ex) { System.out.println("GdxTests: Error reading mapping file: mapping.txt"); ex.printStackTrace(); } finally { StreamUtils.closeQuietly(reader); } } } public static List<String> getNames () { List<String> names = new ArrayList<String>(tests.size()); for (Class clazz : tests) names.add(obfuscatedToOriginal.get(clazz.getSimpleName(), clazz.getSimpleName())); Collections.sort(names); return names; } private static Class<? extends GdxTest> forName (String name) { name = originalToObfuscated.get(name, name); for (Class clazz : tests) if (clazz.getSimpleName().equals(name)) return clazz; return null; } public static GdxTest newTest (String testName) { testName = originalToObfuscated.get(testName, testName); try { return forName(testName).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } }
package com.cloudTop.starshare.ui.wangyi.common.infra; import android.annotation.TargetApi; import android.os.Build; import java.util.Comparator; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class TaskExecutor implements Executor { private final static int QUEUE_INIT_CAPACITY = 11; private static final int CORE = 3; private static final int MAX = 5; private static final int TIMEOUT = 30 * 1000; public static final Executor IMMEDIATE_EXECUTOR = new Executor() { @Override public void execute(Runnable command) { command.run(); } }; public static class Config { public int core; public int max; public int timeout; public boolean allowCoreTimeOut; public Config(int core, int max, int timeout, boolean allowCoreTimeOut) { this.core = core; this.max = max; this.timeout = timeout; this.allowCoreTimeOut = allowCoreTimeOut; } } public static Config defaultConfig = new Config(CORE, MAX, TIMEOUT, true); private final String name; private final Config config; private ExecutorService service; public TaskExecutor(String name) { this(name, defaultConfig); } public TaskExecutor(String name, Config config) { this(name, config, true); } public TaskExecutor(String name, Config config, boolean startup) { this.name = name; this.config = config; if (startup) { startup(); } } public void startup() { synchronized (this) { // has startup if (service != null && !service.isShutdown()) { return; } // create service = createExecutor(config); } } public void shutdown() { ExecutorService executor = null; synchronized (this) { // swap if (service != null) { executor = service; service = null; } } if (executor != null) { // shutdown if (!executor.isShutdown()) { executor.shutdown(); } // recycle executor = null; } } @Override public void execute(Runnable runnable) { // executeRunnable runnable with default priority executeRunnable(new PRunnable(runnable, 0)); } public Future<?> submit(Runnable runnable) { synchronized (this) { if (service == null || service.isShutdown()) { return null; } return service.submit(new PRunnable(runnable, 0)); } } public void execute(Runnable runnable, int priority) { // executeRunnable runnable with priority executeRunnable(new PRunnable(runnable, priority)); } private void executeRunnable(Runnable runnable) { synchronized (this) { // has shutdown, reject if (service == null || service.isShutdown()) { return; } // execute service.execute(runnable); } } private ExecutorService createExecutor(Config config) { ThreadPoolExecutor service = new ThreadPoolExecutor(config.core, config.max, config.timeout, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(QUEUE_INIT_CAPACITY, mQueueComparator), new TaskThreadFactory(name), new ThreadPoolExecutor.DiscardPolicy()); allowCoreThreadTimeOut(service, config.allowCoreTimeOut); return service; } private static class PRunnable implements Runnable { private static int sSerial = 0; private Runnable runnable; private int priority; private int serial; public PRunnable(Runnable r, int p) { serial = sSerial++; runnable = r; priority = p; } @Override public void run() { if (runnable != null) { runnable.run(); } } public static final int compare(PRunnable r1, PRunnable r2) { if (r1.priority != r2.priority) { return r2.priority - r1.priority; } else { return r1.serial - r2.serial; } } } Comparator<Runnable> mQueueComparator = new Comparator<Runnable>() { @Override public int compare(Runnable lhs, Runnable rhs) { PRunnable r1 = (PRunnable) lhs; PRunnable r2 = (PRunnable) rhs; return PRunnable.compare(r1, r2); } }; static class TaskThreadFactory implements ThreadFactory { private final ThreadGroup mThreadGroup; private final AtomicInteger mThreadNumber = new AtomicInteger(1); private final String mNamePrefix; TaskThreadFactory(String name) { SecurityManager s = System.getSecurityManager(); mThreadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); mNamePrefix = name + "#"; } public Thread newThread(Runnable r) { Thread t = new Thread(mThreadGroup, r, mNamePrefix + mThreadNumber.getAndIncrement(), 0); // no daemon if (t.isDaemon()) t.setDaemon(false); // normal priority if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } } private static final void allowCoreThreadTimeOut(ThreadPoolExecutor service, boolean value) { if (Build.VERSION.SDK_INT >= 9) { allowCoreThreadTimeOut9(service, value); } } @TargetApi(9) private static final void allowCoreThreadTimeOut9(ThreadPoolExecutor service, boolean value) { service.allowCoreThreadTimeOut(value); } }
/* * Copyright 2017 StreamSets 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.streamsets.pipeline.lib.jdbc; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.ListBeanModel; import com.streamsets.pipeline.api.Stage; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.api.ValueChooserModel; import com.streamsets.pipeline.api.credential.CredentialValue; import com.streamsets.pipeline.lib.el.TimeEL; import com.streamsets.pipeline.stage.destination.jdbc.Groups; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class HikariPoolConfigBean { private static final int TEN_MINUTES = 600; private static final int THIRTY_MINUTES = 1800; private static final int THIRTY_SECONDS = 30; private static final String DEFAULT_CONNECTION_TIMEOUT_EL = "${30 * SECONDS}"; private static final String DEFAULT_IDLE_TIMEOUT_EL = "${10 * MINUTES}"; private static final String DEFAULT_MAX_LIFETIME_EL = "${30 * MINUTES}"; private static final int MAX_POOL_SIZE_MIN = 1; private static final int MIN_IDLE_MIN = 0; private static final int CONNECTION_TIMEOUT_MIN = 1; private static final int IDLE_TIMEOUT_MIN = 0; private static final int MAX_LIFETIME_MIN = 1800; public static final int MILLISECONDS = 1000; public static final int DEFAULT_CONNECTION_TIMEOUT = THIRTY_SECONDS; public static final int DEFAULT_IDLE_TIMEOUT = TEN_MINUTES; public static final int DEFAULT_MAX_LIFETIME = THIRTY_MINUTES; public static final int DEFAULT_MAX_POOL_SIZE = 1; public static final int DEFAULT_MIN_IDLE = 1; public static final boolean DEFAULT_READ_ONLY = true; public static final String HIKARI_BEAN_NAME = "hikariConfigBean."; public static final String MAX_POOL_SIZE_NAME = "maximumPoolSize"; public static final String MIN_IDLE_NAME = "minIdle"; public static final String CONNECTION_TIMEOUT_NAME = "connectionTimeout"; public static final String IDLE_TIMEOUT_NAME = "idleTimeout"; public static final String MAX_LIFETIME_NAME = "maxLifetime"; public static final String READ_ONLY_NAME = "readOnly"; @ConfigDef( required = true, type = ConfigDef.Type.STRING, label = "JDBC Connection String", displayPosition = 10, group = "JDBC" ) public String connectionString = ""; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, defaultValue = "true", label = "Use Credentials", displayPosition = 15, group = "JDBC" ) public boolean useCredentials; @ConfigDef( required = true, type = ConfigDef.Type.CREDENTIAL, dependsOn = "useCredentials", triggeredByValue = "true", label = "Username", displayPosition = 110, group = "CREDENTIALS" ) public CredentialValue username; @ConfigDef( required = true, type = ConfigDef.Type.CREDENTIAL, dependsOn = "useCredentials", triggeredByValue = "true", label = "Password", displayPosition = 120, group = "CREDENTIALS" ) public CredentialValue password; @ConfigDef( required = false, type = ConfigDef.Type.MODEL, defaultValue = "[]", label = "Additional JDBC Configuration Properties", description = "Additional properties to pass to the underlying JDBC driver.", displayPosition = 999, group = "JDBC" ) @ListBeanModel public List<ConnectionPropertyBean> driverProperties = new ArrayList<>(); @ConfigDef( required = false, type = ConfigDef.Type.STRING, label = "JDBC Driver Class Name", description = "Class name for pre-JDBC 4 compliant drivers.", displayPosition = 10, group = "LEGACY" ) public String driverClassName = ""; @ConfigDef( required = false, type = ConfigDef.Type.TEXT, mode = ConfigDef.Mode.SQL, label = "Connection Health Test Query", description = "Not recommended for JDBC 4 compliant drivers. Runs when a new database connection is established.", displayPosition = 20, group = "LEGACY" ) public String connectionTestQuery = ""; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Maximum Pool Size", description = "Maximum number of connections to create to the data source", min = 1, defaultValue = "1", displayPosition = 10, group = "ADVANCED" ) public int maximumPoolSize = DEFAULT_MAX_POOL_SIZE; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Minimum Idle Connections", description = "Minimum number of connections to maintain. It is recommended to set this to the same value" + "as Maximum Pool Size which effectively creates a fixed connection pool.", min = 0, defaultValue = "1", displayPosition = 20, group = "ADVANCED" ) public int minIdle = DEFAULT_MIN_IDLE; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Connection Timeout (Seconds)", description = "Maximum time to wait for a connection to become available. Exceeding will cause a pipeline error.", min = 1, defaultValue = DEFAULT_CONNECTION_TIMEOUT_EL, elDefs = {TimeEL.class}, displayPosition = 30, group = "ADVANCED" ) public int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Idle Timeout (Seconds)", description = "Maximum amount of time that a connection is allowed to sit idle in the pool. " + "Use 0 to opt out of an idle timeout. " + "If set too close to or more than Max Connection Lifetime, the property is ignored.", min = 0, defaultValue = DEFAULT_IDLE_TIMEOUT_EL, elDefs = {TimeEL.class}, displayPosition = 40, group = "ADVANCED" ) public int idleTimeout = DEFAULT_IDLE_TIMEOUT; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, label = "Max Connection Lifetime (Seconds)", description = "Maximum lifetime of a connection in the pool. When reached, the connection is retired from the pool. " + "Use 0 to set no maximum lifetime. When set, the minimum lifetime is 30 minutes.", min = 0, defaultValue = DEFAULT_MAX_LIFETIME_EL, elDefs = {TimeEL.class}, displayPosition = 50, group = "ADVANCED" ) public int maxLifetime = DEFAULT_MAX_LIFETIME; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, label = "Auto Commit", description = "Whether the connection should have property auto-commit set to true or not.", defaultValue = "false", displayPosition = 55, group = "ADVANCED" ) public boolean autoCommit = false; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, label = "Enforce Read-only Connection", description = "Should be set to true whenever possible to avoid unintended writes. Set to false with extreme " + "caution.", defaultValue = "true", displayPosition = 60, group = "ADVANCED" ) public boolean readOnly = true; @ConfigDef( required = false, type = ConfigDef.Type.TEXT, mode = ConfigDef.Mode.SQL, label = "Init Query", description = "SQL query that will be executed on all new connections when they are created, before they are" + " added to connection pool.", displayPosition = 80, group = "ADVANCED" ) public String initialQuery = ""; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, label = "Transaction Isolation", description = "Transaction isolation that should be used for all database connections.", defaultValue = "DEFAULT", displayPosition = 70, group = "ADVANCED" ) @ValueChooserModel(TransactionIsolationLevelChooserValues.class) public TransactionIsolationLevel transactionIsolation = TransactionIsolationLevel.DEFAULT; private static final String HIKARI_CONFIG_PREFIX = "hikariConfigBean."; private static final String DRIVER_CLASSNAME = HIKARI_CONFIG_PREFIX + "driverClassName"; public List<Stage.ConfigIssue> validateConfigs(Stage.Context context, List<Stage.ConfigIssue> issues) { // Validation for NUMBER fields is currently disabled due to allowing ELs so we do our own here. if (maximumPoolSize < MAX_POOL_SIZE_MIN) { issues.add( context.createConfigIssue( Groups.ADVANCED.name(), MAX_POOL_SIZE_NAME, JdbcErrors.JDBC_10, maximumPoolSize, MAX_POOL_SIZE_NAME ) ); } if (minIdle < MIN_IDLE_MIN) { issues.add( context.createConfigIssue( Groups.ADVANCED.name(), MIN_IDLE_NAME, JdbcErrors.JDBC_10, minIdle, MIN_IDLE_MIN ) ); } if (minIdle > maximumPoolSize) { issues.add( context.createConfigIssue( Groups.ADVANCED.name(), MIN_IDLE_NAME, JdbcErrors.JDBC_11, minIdle, maximumPoolSize ) ); } if (connectionTimeout < CONNECTION_TIMEOUT_MIN) { issues.add( context.createConfigIssue( Groups.ADVANCED.name(), CONNECTION_TIMEOUT_NAME, JdbcErrors.JDBC_10, connectionTimeout, CONNECTION_TIMEOUT_MIN ) ); } if (idleTimeout < IDLE_TIMEOUT_MIN) { issues.add( context.createConfigIssue( Groups.ADVANCED.name(), IDLE_TIMEOUT_NAME, JdbcErrors.JDBC_10, idleTimeout, IDLE_TIMEOUT_MIN ) ); } if (maxLifetime < MAX_LIFETIME_MIN) { issues.add( context.createConfigIssue( Groups.ADVANCED.name(), MAX_LIFETIME_NAME, JdbcErrors.JDBC_10, maxLifetime, MAX_LIFETIME_MIN ) ); } if (!driverClassName.isEmpty()) { try { Class.forName(driverClassName); } catch (ClassNotFoundException e) { issues.add(context.createConfigIssue(com.streamsets.pipeline.stage.origin.jdbc.Groups.LEGACY.name(), DRIVER_CLASSNAME, JdbcErrors.JDBC_28, e.toString())); } } return issues; } public Properties getDriverProperties() throws StageException { Properties properties = new Properties(); for (ConnectionPropertyBean bean : driverProperties) { properties.setProperty(bean.key, bean.value.get()); } return properties; } public String getConnectionString() { return connectionString; } }
/* * Copyright 2000-2016 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.openapi.options.newEditor; import com.intellij.icons.AllIcons; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.ide.projectView.PresentationData; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.Disposable; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.options.*; import com.intellij.openapi.options.ex.ConfigurableWrapper; import com.intellij.openapi.options.ex.SortedConfigurableGroup; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.*; import com.intellij.ui.components.GradientViewport; import com.intellij.ui.treeStructure.*; import com.intellij.ui.treeStructure.filtered.FilteringTreeBuilder; import com.intellij.ui.treeStructure.filtered.FilteringTreeStructure; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.ui.tree.WideSelectionTreeUI; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.TreeUI; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.datatransfer.Transferable; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.List; /** * @author Sergey.Malenkov */ public class SettingsTreeView extends JComponent implements Accessible, Disposable, OptionsEditorColleague { private static final int ICON_GAP = 5; private static final String NODE_ICON = "settings.tree.view.icon"; private static final Color WRONG_CONTENT = JBColor.RED; private static final Color MODIFIED_CONTENT = JBColor.BLUE; public static final Color FOREGROUND = new JBColor(Gray.x1A, Gray.xBB); final SimpleTree myTree; final FilteringTreeBuilder myBuilder; private final SettingsFilter myFilter; private final MyRoot myRoot; private final JScrollPane myScroller; private final IdentityHashMap<Configurable, MyNode> myConfigurableToNodeMap = new IdentityHashMap<>(); private final IdentityHashMap<UnnamedConfigurable, ConfigurableWrapper> myConfigurableToWrapperMap = new IdentityHashMap<>(); private final MergingUpdateQueue myQueue = new MergingUpdateQueue("SettingsTreeView", 150, false, this, this, this) .setRestartTimerOnAdd(true); private Configurable myQueuedConfigurable; private boolean myPaintInternalInfo; public SettingsTreeView(SettingsFilter filter, ConfigurableGroup[] groups) { myFilter = filter; myRoot = new MyRoot(groups); myTree = new MyTree(); myTree.putClientProperty(WideSelectionTreeUI.TREE_TABLE_TREE_KEY, Boolean.TRUE); myTree.setBackground(UIUtil.SIDE_PANEL_BACKGROUND); myTree.getInputMap().clear(); TreeUtil.installActions(myTree); myTree.setOpaque(true); myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); myTree.setCellRenderer(new MyRenderer()); myTree.setRootVisible(false); myTree.setShowsRootHandles(false); myTree.setExpandableItemsEnabled(false); RelativeFont.BOLD.install(myTree); setComponentPopupMenuTo(myTree); myTree.setTransferHandler(new TransferHandler() { @Nullable @Override protected Transferable createTransferable(JComponent c) { return SettingsTreeView.createTransferable(myTree.getSelectionPath()); } @Override public int getSourceActions(JComponent c) { return COPY; } }); myScroller = ScrollPaneFactory.createScrollPane(null, true); myScroller.setViewport(new GradientViewport(myTree, JBUI.insetsTop(5), true) { private JLabel myHeader; @Override protected Component getHeader() { if (0 == myTree.getY()) { return null; // separator is not needed without scrolling } if (myHeader == null) { myHeader = new JLabel(); myHeader.setForeground(FOREGROUND); myHeader.setIconTextGap(ICON_GAP); myHeader.setBorder(BorderFactory.createEmptyBorder(1, 10 + getLeftMargin(0), 0, 0)); } myHeader.setFont(myTree.getFont()); myHeader.setIcon(myTree.getEmptyHandle()); int height = myHeader.getPreferredSize().height; String group = findGroupNameAt(0, height + 3); if (group == null || !group.equals(findGroupNameAt(0, 0))) { return null; // do not show separator over another group } myHeader.setText(group); return myHeader; } }); if (!Registry.is("ide.scroll.background.auto")) { myScroller.setBackground(UIUtil.SIDE_PANEL_BACKGROUND); myScroller.getViewport().setBackground(UIUtil.SIDE_PANEL_BACKGROUND); myScroller.getVerticalScrollBar().setBackground(UIUtil.SIDE_PANEL_BACKGROUND); } add(myScroller); myTree.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { myBuilder.revalidateTree(); } @Override public void componentMoved(ComponentEvent e) { myBuilder.revalidateTree(); } @Override public void componentShown(ComponentEvent e) { myBuilder.revalidateTree(); } }); myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent event) { MyNode node = extractNode(event.getNewLeadSelectionPath()); select(node == null ? null : node.myConfigurable); } }); if (Registry.is("show.configurables.ids.in.settings")) { new HeldDownKeyListener() { @Override protected void heldKeyTriggered(JComponent component, boolean pressed) { myPaintInternalInfo = pressed; SettingsTreeView.this.setMinimumSize(null); // an easy way to repaint the tree ((Tree)component).setCellRenderer(new MyRenderer()); } }.installOn(myTree); } myBuilder = new MyBuilder(new SimpleTreeStructure.Impl(myRoot)); myBuilder.setFilteringMerge(300, null); Disposer.register(this, myBuilder); } private static void setComponentPopupMenuTo(JTree tree) { tree.setComponentPopupMenu(new JPopupMenu() { private Transferable transferable; @Override public void show(Component invoker, int x, int y) { if (invoker != tree) return; TreePath path = tree.getClosestPathForLocation(x, y); transferable = createTransferable(path); if (transferable == null) return; Rectangle bounds = tree.getPathBounds(path); if (bounds == null || bounds.y > y) return; bounds.y += bounds.height; if (bounds.y < y) return; super.show(invoker, x, bounds.y); } { add(new CopyAction(() -> transferable)); } }); } private static Transferable createTransferable(TreePath path) { MyNode node = path == null ? null : extractNode(path); return node == null ? null : CopyAction.createTransferable(getPathNames(node)); } @NotNull Collection<String> getPathNames(Configurable configurable) { return getPathNames(findNode(configurable)); } private static Collection<String> getPathNames(MyNode node) { ArrayDeque<String> path = new ArrayDeque<>(); while (node != null) { path.push(node.myDisplayName); SimpleNode parent = node.getParent(); node = parent instanceof MyNode ? (MyNode)parent : null; } return path; } static Configurable getConfigurable(SimpleNode node) { return node instanceof MyNode ? ((MyNode)node).myConfigurable : null; } @Nullable MyNode findNode(Configurable configurable) { ConfigurableWrapper wrapper = myConfigurableToWrapperMap.get(configurable); return myConfigurableToNodeMap.get(wrapper != null ? wrapper : configurable); } @Nullable SearchableConfigurable findConfigurableById(@NotNull String id) { for (Configurable configurable : myConfigurableToNodeMap.keySet()) { if (configurable instanceof SearchableConfigurable) { SearchableConfigurable searchable = (SearchableConfigurable)configurable; if (id.equals(searchable.getId())) { return searchable; } } } return null; } @Nullable <T extends UnnamedConfigurable> T findConfigurable(@NotNull Class<T> type) { for (UnnamedConfigurable configurable : myConfigurableToNodeMap.keySet()) { if (configurable instanceof ConfigurableWrapper) { ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable; configurable = wrapper.getConfigurable(); myConfigurableToWrapperMap.put(configurable, wrapper); } if (type.isInstance(configurable)) { return type.cast(configurable); } } return null; } @Nullable Project findConfigurableProject(@Nullable Configurable configurable) { MyNode node = findNode(configurable); return node == null ? null : findConfigurableProject(node, true); } @Nullable private static Project findConfigurableProject(@NotNull MyNode node, boolean checkProjectLevel) { Configurable configurable = node.myConfigurable; Project project = node.getProject(); if (checkProjectLevel) { Configurable.VariableProjectAppLevel wrapped = ConfigurableWrapper.cast(Configurable.VariableProjectAppLevel.class, configurable); if (wrapped != null) return wrapped.isProjectLevel() ? project : null; } if (configurable instanceof ConfigurableWrapper) return project; if (configurable instanceof SortedConfigurableGroup) return project; SimpleNode parent = node.getParent(); return parent instanceof MyNode ? findConfigurableProject((MyNode)parent, checkProjectLevel) : null; } @Nullable private static Project prepareProject(CachingSimpleNode parent, Configurable configurable) { if (configurable instanceof ConfigurableWrapper) { ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable; return wrapper.getExtensionPoint().getProject(); } if (configurable instanceof SortedConfigurableGroup) { SortedConfigurableGroup group = (SortedConfigurableGroup)configurable; Configurable[] configurables = group.getConfigurables(); if (configurables != null && configurables.length != 0) { Project project = prepareProject(parent, configurables[0]); if (project != null) { for (int i = 1; i < configurables.length; i++) { if (project != prepareProject(parent, configurables[i])) { return null; } } } return project; } } return parent == null ? null : parent.getProject(); } private static int getLeftMargin(int level) { return 3 + level * (11 + ICON_GAP); } @Nullable private String findGroupNameAt(int x, int y) { TreePath path = myTree.getClosestPathForLocation(x - myTree.getX(), y - myTree.getY()); while (path != null) { MyNode node = extractNode(path); if (node == null) { return null; } if (myRoot == node.getParent()) { return node.myDisplayName; } path = path.getParentPath(); } return null; } @Nullable private static MyNode extractNode(@Nullable Object object) { if (object instanceof TreePath) { TreePath path = (TreePath)object; object = path.getLastPathComponent(); } if (object instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)object; object = node.getUserObject(); } if (object instanceof FilteringTreeStructure.FilteringNode) { FilteringTreeStructure.FilteringNode node = (FilteringTreeStructure.FilteringNode)object; object = node.getDelegate(); } return object instanceof MyNode ? (MyNode)object : null; } @Override public void doLayout() { myScroller.setBounds(0, 0, getWidth(), getHeight()); } void selectFirst() { for (ConfigurableGroup eachGroup : myRoot.myGroups) { Configurable[] kids = eachGroup.getConfigurables(); if (kids.length > 0) { select(kids[0]); return; } } } ActionCallback select(@Nullable final Configurable configurable) { if (myBuilder.isSelectionBeingAdjusted()) { return ActionCallback.REJECTED; } final ActionCallback callback = new ActionCallback(); myQueuedConfigurable = configurable; myQueue.queue(new Update(this) { public void run() { if (configurable == myQueuedConfigurable) { if (configurable == null) { fireSelected(null, callback); } else { myBuilder.getReady(this).doWhenDone(() -> { if (configurable != myQueuedConfigurable) return; MyNode editorNode = findNode(configurable); FilteringTreeStructure.FilteringNode editorUiNode = myBuilder.getVisibleNodeFor(editorNode); if (editorUiNode == null) return; if (!myBuilder.getSelectedElements().contains(editorUiNode)) { myBuilder.select(editorUiNode, () -> fireSelected(configurable, callback)); } else { myBuilder.scrollSelectionToVisible(() -> fireSelected(configurable, callback), false); } }); } } } @Override public void setRejected() { super.setRejected(); callback.setRejected(); } }); return callback; } private void fireSelected(Configurable configurable, ActionCallback callback) { ConfigurableWrapper wrapper = myConfigurableToWrapperMap.get(configurable); myFilter.myContext.fireSelected(wrapper != null ? wrapper : configurable, this).doWhenProcessed(callback.createSetDoneRunnable()); } @Override public void dispose() { myQueuedConfigurable = null; } @Override public ActionCallback onSelected(@Nullable Configurable configurable, Configurable oldConfigurable) { return select(configurable); } @Override public ActionCallback onModifiedAdded(Configurable configurable) { myTree.repaint(); return ActionCallback.DONE; } @Override public ActionCallback onModifiedRemoved(Configurable configurable) { myTree.repaint(); return ActionCallback.DONE; } @Override public ActionCallback onErrorsChanged() { return ActionCallback.DONE; } private final class MyRoot extends CachingSimpleNode { private final ConfigurableGroup[] myGroups; private MyRoot(ConfigurableGroup[] groups) { super(null); myGroups = groups; } @Override protected SimpleNode[] buildChildren() { if (myGroups == null || myGroups.length == 0) { return NO_CHILDREN; } ArrayList<MyNode> list = new ArrayList<>(); for (ConfigurableGroup group : myGroups) { for (Configurable configurable : group.getConfigurables()) { list.add(new MyNode(this, configurable, 0)); } } return list.toArray(new SimpleNode[list.size()]); } } private final class MyNode extends CachingSimpleNode { private final Configurable.Composite myComposite; private final Configurable myConfigurable; private final String myDisplayName; private final int myLevel; private MyNode(CachingSimpleNode parent, Configurable configurable, int level) { super(prepareProject(parent, configurable), parent); myComposite = configurable instanceof Configurable.Composite ? (Configurable.Composite)configurable : null; myConfigurable = configurable; String name = configurable.getDisplayName(); myDisplayName = name != null ? name.replace("\n", " ") : "{ " + configurable.getClass().getSimpleName() + " }"; myLevel = level; } @Override protected SimpleNode[] buildChildren() { if (myConfigurable != null) { myConfigurableToNodeMap.put(myConfigurable, this); } if (myComposite == null) { return NO_CHILDREN; } Configurable[] configurables = myComposite.getConfigurables(); if (configurables == null || configurables.length == 0) { return NO_CHILDREN; } SimpleNode[] result = new SimpleNode[configurables.length]; for (int i = 0; i < configurables.length; i++) { result[i] = new MyNode(this, configurables[i], myLevel + 1); if (myConfigurable != null) { myFilter.myContext.registerKid(myConfigurable, configurables[i]); } } return result; } protected void update(PresentationData presentation) { super.update(presentation); presentation.addText(myDisplayName, getPlainAttributes()); } @Override public boolean isAlwaysLeaf() { return myComposite == null; } } private final class MyRenderer extends CellRendererPanel implements TreeCellRenderer { final SimpleColoredComponent myTextLabel = new SimpleColoredComponent(); final JLabel myNodeIcon = new JLabel(); final JLabel myProjectIcon = new JLabel(); MyRenderer() { setLayout(new BorderLayout(ICON_GAP, 0)); myNodeIcon.setName(NODE_ICON); myTextLabel.setOpaque(false); add(BorderLayout.CENTER, myTextLabel); add(BorderLayout.WEST, myNodeIcon); add(BorderLayout.EAST, myProjectIcon); setBorder(BorderFactory.createEmptyBorder(1, 10, 3, 10)); } @Override public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new MyAccessibleContext(); } return accessibleContext; } // TODO: consider making MyRenderer a subclass of SimpleColoredComponent. // This should eliminate the need to add this accessibility stuff. private class MyAccessibleContext extends JPanel.AccessibleJPanel { @Override public String getAccessibleName() { return myTextLabel.getCharSequence(true).toString(); } } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean focused) { myTextLabel.clear(); setPreferredSize(null); MyNode node = extractNode(value); boolean isGroup = node != null && myRoot == node.getParent(); String name = node != null ? node.myDisplayName : String.valueOf(value); myTextLabel.append(name, isGroup ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES); myTextLabel.setFont(isGroup ? myTree.getFont() : UIUtil.getLabelFont()); // update font color for modified configurables myTextLabel.setForeground(selected ? UIUtil.getTreeSelectionForeground() : FOREGROUND); if (!selected && node != null) { Configurable configurable = node.myConfigurable; if (configurable != null) { if (myFilter.myContext.getErrors().containsKey(configurable)) { myTextLabel.setForeground(WRONG_CONTENT); } else if (myFilter.myContext.getModified().contains(configurable)) { myTextLabel.setForeground(MODIFIED_CONTENT); } } } // configure project icon Project project = null; if (node != null) { project = findConfigurableProject(node, false); } Configurable configurable = null; if(node != null) configurable = node.myConfigurable; setProjectIcon(myProjectIcon, configurable, project, selected); // configure node icon Icon nodeIcon = null; if (value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)value; if (0 == treeNode.getChildCount()) { nodeIcon = myTree.getEmptyHandle(); } else { nodeIcon = myTree.isExpanded(new TreePath(treeNode.getPath())) ? myTree.getExpandedHandle() : myTree.getCollapsedHandle(); } } myNodeIcon.setIcon(nodeIcon); if (node != null && myPaintInternalInfo) { String id = node.myConfigurable instanceof ConfigurableWrapper ? ((ConfigurableWrapper)node.myConfigurable).getId() : node.myConfigurable instanceof SearchableConfigurable ? ((SearchableConfigurable)node.myConfigurable).getId() : node.myConfigurable.getClass().getSimpleName(); PluginDescriptor plugin = node.myConfigurable instanceof ConfigurableWrapper ? ((ConfigurableWrapper)node.myConfigurable).getExtensionPoint().getPluginDescriptor() : null; String pluginId = plugin == null ? null : plugin.getPluginId().getIdString(); String pluginName = pluginId == null || PluginManagerCore.CORE_PLUGIN_ID.equals(pluginId) ? null : plugin instanceof IdeaPluginDescriptor ? ((IdeaPluginDescriptor)plugin).getName() : pluginId; myTextLabel.append(" ", SimpleTextAttributes.REGULAR_ATTRIBUTES, false); myTextLabel.append(pluginName == null ? id : id + " (" + pluginName + ")", SimpleTextAttributes.GRAYED_SMALL_ATTRIBUTES, false); } // calculate minimum size if (node != null && tree.isVisible()) { int width = getLeftMargin(node.myLevel) + getPreferredSize().width; Insets insets = tree.getInsets(); if (insets != null) { width += insets.left + insets.right; } JScrollBar bar = myScroller.getVerticalScrollBar(); if (bar != null && bar.isVisible()) { width += bar.getWidth(); } width = Math.min(width, 300); // maximal width for minimum size JComponent view = SettingsTreeView.this; Dimension size = view.getMinimumSize(); if (size.width < width) { size.width = width; view.setMinimumSize(size); view.revalidate(); view.repaint(); } } return this; } } protected void setProjectIcon(JLabel projectIcon, Configurable configurable, @Nullable Project project, boolean selected) { if (project != null) { projectIcon.setIcon(selected ? AllIcons.General.ProjectConfigurableSelected : AllIcons.General.ProjectConfigurable); projectIcon.setToolTipText(OptionsBundle.message(project.isDefault() ? "configurable.default.project.tooltip" : "configurable.current.project.tooltip")); projectIcon.setVisible(true); } else { projectIcon.setVisible(false); } } private final class MyTree extends SimpleTree { @Override public String getToolTipText(MouseEvent event) { if (event != null) { Component component = getDeepestRendererComponentAt(event.getX(), event.getY()); if (component instanceof JLabel) { JLabel label = (JLabel)component; if (label.getIcon() != null) { String text = label.getToolTipText(); if (text != null) { return text; } } } } return super.getToolTipText(event); } @Override protected boolean paintNodes() { return false; } @Override protected boolean highlightSingleNode() { return false; } @Override public void setUI(TreeUI ui) { super.setUI(ui instanceof MyTreeUi ? ui : new MyTreeUi()); } @Override protected boolean isCustomUI() { return true; } @Override protected void configureUiHelper(TreeUIHelper helper) { } @Override public boolean getScrollableTracksViewportWidth() { return true; } @Override public void processKeyEvent(KeyEvent e) { TreePath path = myTree.getSelectionPath(); if (path != null) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { if (isExpanded(path)) { collapsePath(path); return; } } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { if (isCollapsed(path)) { expandPath(path); return; } } } super.processKeyEvent(e); } @Override protected void processMouseEvent(MouseEvent event) { MyTreeUi ui = (MyTreeUi)myTree.getUI(); if (!ui.processMouseEvent(event)) { super.processMouseEvent(event); } } } private static final class MyTreeUi extends WideSelectionTreeUI { boolean processMouseEvent(MouseEvent event) { if (super.tree instanceof SimpleTree) { SimpleTree tree = (SimpleTree)super.tree; boolean toggleNow = MouseEvent.MOUSE_RELEASED == event.getID() && UIUtil.isActionClick(event, MouseEvent.MOUSE_RELEASED) && !isToggleEvent(event); if (toggleNow || MouseEvent.MOUSE_PRESSED == event.getID()) { Component component = tree.getDeepestRendererComponentAt(event.getX(), event.getY()); if (component != null && NODE_ICON.equals(component.getName())) { if (toggleNow) { toggleExpandState(tree.getPathForLocation(event.getX(), event.getY())); } event.consume(); return true; } } } return false; } @Override protected boolean shouldPaintExpandControl(TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { return false; } @Override protected void paintHorizontalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { } @Override protected void paintVerticalPartOfLeg(Graphics g, Rectangle clipBounds, Insets insets, TreePath path) { } @Override public void paint(Graphics g, JComponent c) { GraphicsUtil.setupAntialiasing(g); super.paint(g, c); } @Override protected void paintRow(Graphics g, Rectangle clipBounds, Insets insets, Rectangle bounds, TreePath path, int row, boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) { if (tree != null) { bounds.width = tree.getWidth(); Container parent = tree.getParent(); if (parent instanceof JViewport) { JViewport viewport = (JViewport)parent; bounds.width = viewport.getWidth() - viewport.getViewPosition().x - insets.right / 2; } bounds.width -= bounds.x; } super.paintRow(g, clipBounds, insets, bounds, path, row, isExpanded, hasBeenExpanded, isLeaf); } @Override protected int getRowX(int row, int depth) { return getLeftMargin(depth - 1); } } private final class MyBuilder extends FilteringTreeBuilder { List<Object> myToExpandOnResetFilter; boolean myRefilteringNow; boolean myWasHoldingFilter; public MyBuilder(SimpleTreeStructure structure) { super(myTree, myFilter, structure, null); myTree.addTreeExpansionListener(new TreeExpansionListener() { public void treeExpanded(TreeExpansionEvent event) { invalidateExpansions(); } public void treeCollapsed(TreeExpansionEvent event) { invalidateExpansions(); } }); } private void invalidateExpansions() { if (!myRefilteringNow) { myToExpandOnResetFilter = null; } } @Override protected boolean isSelectable(Object object) { return object instanceof MyNode; } @Override public boolean isAutoExpandNode(NodeDescriptor nodeDescriptor) { return myFilter.myContext.isHoldingFilter(); } @Override public boolean isToEnsureSelectionOnFocusGained() { return false; } @Override protected ActionCallback refilterNow(Object preferredSelection, boolean adjustSelection) { final List<Object> toRestore = new ArrayList<>(); if (myFilter.myContext.isHoldingFilter() && !myWasHoldingFilter && myToExpandOnResetFilter == null) { myToExpandOnResetFilter = myBuilder.getUi().getExpandedElements(); } else if (!myFilter.myContext.isHoldingFilter() && myWasHoldingFilter && myToExpandOnResetFilter != null) { toRestore.addAll(myToExpandOnResetFilter); myToExpandOnResetFilter = null; } myWasHoldingFilter = myFilter.myContext.isHoldingFilter(); ActionCallback result = super.refilterNow(preferredSelection, adjustSelection); myRefilteringNow = true; return result.doWhenDone(() -> { myRefilteringNow = false; if (!myFilter.myContext.isHoldingFilter() && getSelectedElements().isEmpty()) { restoreExpandedState(toRestore); } }); } private void restoreExpandedState(List<Object> toRestore) { TreePath[] selected = myTree.getSelectionPaths(); if (selected == null) { selected = new TreePath[0]; } List<TreePath> toCollapse = new ArrayList<>(); for (int eachRow = 0; eachRow < myTree.getRowCount(); eachRow++) { if (!myTree.isExpanded(eachRow)) continue; TreePath eachVisiblePath = myTree.getPathForRow(eachRow); if (eachVisiblePath == null) continue; Object eachElement = myBuilder.getElementFor(eachVisiblePath.getLastPathComponent()); if (toRestore.contains(eachElement)) continue; for (TreePath eachSelected : selected) { if (!eachVisiblePath.isDescendant(eachSelected)) { toCollapse.add(eachVisiblePath); } } } for (TreePath each : toCollapse) { myTree.collapsePath(each); } } } @Override public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleSettingsTreeView(); } return accessibleContext; } protected class AccessibleSettingsTreeView extends AccessibleJComponent { @Override public AccessibleRole getAccessibleRole() { return AccessibleRole.PANEL; } } }
package com.oracle.ptsdemo.healthcare.wsclient.osc.salesparty.generated; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for PersonPartySite complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PersonPartySite"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="PartySiteId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="PartyId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="LocationId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="LastUpdateDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/> * &lt;element name="PartySiteNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="LastUpdatedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CreationDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/> * &lt;element name="CreatedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="LastUpdateLogin" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="OrigSystemReference" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="StartDateActive" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="EndDateActive" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="Mailstop" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="IdentifyingAddressFlag" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="Language" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Status" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PartySiteName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Addressee" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ObjectVersionNumber" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="CreatedByModule" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="GlobalLocationNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="DUNSNumberC" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Comments" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PartySiteType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PartyNameDba" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PartyNameDivision" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PartyNameLegal" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="RelationshipId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="PartyUsageCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="OverallPrimaryFlag" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="PartySiteUse" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/}PartySiteUse" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="Phone" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/}Phone" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="OriginalSystemReference" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/}OriginalSystemReference" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="ContactPreference" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/}ContactPreference" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="PersonPartySiteInformation" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/flex/partySite/}PartySiteInformation" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PersonPartySite", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", propOrder = { "partySiteId", "partyId", "locationId", "lastUpdateDate", "partySiteNumber", "lastUpdatedBy", "creationDate", "createdBy", "lastUpdateLogin", "requestId", "origSystemReference", "startDateActive", "endDateActive", "mailstop", "identifyingAddressFlag", "language", "status", "partySiteName", "addressee", "objectVersionNumber", "createdByModule", "globalLocationNumber", "dunsNumberC", "comments", "partySiteType", "partyNameDba", "partyNameDivision", "partyNameLegal", "relationshipId", "partyUsageCode", "overallPrimaryFlag", "partySiteUse", "phone", "originalSystemReference", "contactPreference", "personPartySiteInformation" }) public class PersonPartySite { @XmlElement(name = "PartySiteId") protected Long partySiteId; @XmlElement(name = "PartyId") protected Long partyId; @XmlElement(name = "LocationId") protected Long locationId; @XmlElement(name = "LastUpdateDate") protected XMLGregorianCalendar lastUpdateDate; @XmlElement(name = "PartySiteNumber") protected String partySiteNumber; @XmlElement(name = "LastUpdatedBy") protected String lastUpdatedBy; @XmlElement(name = "CreationDate") protected XMLGregorianCalendar creationDate; @XmlElement(name = "CreatedBy") protected String createdBy; @XmlElementRef(name = "LastUpdateLogin", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> lastUpdateLogin; @XmlElementRef(name = "RequestId", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<Long> requestId; @XmlElement(name = "OrigSystemReference") protected String origSystemReference; @XmlElement(name = "StartDateActive") protected XMLGregorianCalendar startDateActive; @XmlElementRef(name = "EndDateActive", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<XMLGregorianCalendar> endDateActive; @XmlElementRef(name = "Mailstop", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> mailstop; @XmlElement(name = "IdentifyingAddressFlag") protected Boolean identifyingAddressFlag; @XmlElementRef(name = "Language", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> language; @XmlElement(name = "Status") protected String status; @XmlElementRef(name = "PartySiteName", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> partySiteName; @XmlElementRef(name = "Addressee", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> addressee; @XmlElement(name = "ObjectVersionNumber") protected Integer objectVersionNumber; @XmlElementRef(name = "CreatedByModule", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> createdByModule; @XmlElementRef(name = "GlobalLocationNumber", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> globalLocationNumber; @XmlElementRef(name = "DUNSNumberC", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> dunsNumberC; @XmlElementRef(name = "Comments", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> comments; @XmlElementRef(name = "PartySiteType", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> partySiteType; @XmlElementRef(name = "PartyNameDba", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> partyNameDba; @XmlElementRef(name = "PartyNameDivision", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> partyNameDivision; @XmlElementRef(name = "PartyNameLegal", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> partyNameLegal; @XmlElementRef(name = "RelationshipId", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<Long> relationshipId; @XmlElementRef(name = "PartyUsageCode", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/", type = JAXBElement.class) protected JAXBElement<String> partyUsageCode; @XmlElement(name = "OverallPrimaryFlag") protected Boolean overallPrimaryFlag; @XmlElement(name = "PartySiteUse") protected List<PartySiteUse> partySiteUse; @XmlElement(name = "Phone") protected List<Phone> phone; @XmlElement(name = "OriginalSystemReference") protected List<OriginalSystemReference> originalSystemReference; @XmlElement(name = "ContactPreference") protected List<ContactPreference> contactPreference; @XmlElement(name = "PersonPartySiteInformation") protected PartySiteInformation personPartySiteInformation; /** * Gets the value of the partySiteId property. * * @return * possible object is * {@link Long } * */ public Long getPartySiteId() { return partySiteId; } /** * Sets the value of the partySiteId property. * * @param value * allowed object is * {@link Long } * */ public void setPartySiteId(Long value) { this.partySiteId = value; } /** * Gets the value of the partyId property. * * @return * possible object is * {@link Long } * */ public Long getPartyId() { return partyId; } /** * Sets the value of the partyId property. * * @param value * allowed object is * {@link Long } * */ public void setPartyId(Long value) { this.partyId = value; } /** * Gets the value of the locationId property. * * @return * possible object is * {@link Long } * */ public Long getLocationId() { return locationId; } /** * Sets the value of the locationId property. * * @param value * allowed object is * {@link Long } * */ public void setLocationId(Long value) { this.locationId = value; } /** * Gets the value of the lastUpdateDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getLastUpdateDate() { return lastUpdateDate; } /** * Sets the value of the lastUpdateDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setLastUpdateDate(XMLGregorianCalendar value) { this.lastUpdateDate = value; } /** * Gets the value of the partySiteNumber property. * * @return * possible object is * {@link String } * */ public String getPartySiteNumber() { return partySiteNumber; } /** * Sets the value of the partySiteNumber property. * * @param value * allowed object is * {@link String } * */ public void setPartySiteNumber(String value) { this.partySiteNumber = value; } /** * Gets the value of the lastUpdatedBy property. * * @return * possible object is * {@link String } * */ public String getLastUpdatedBy() { return lastUpdatedBy; } /** * Sets the value of the lastUpdatedBy property. * * @param value * allowed object is * {@link String } * */ public void setLastUpdatedBy(String value) { this.lastUpdatedBy = value; } /** * Gets the value of the creationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreationDate() { return creationDate; } /** * Sets the value of the creationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreationDate(XMLGregorianCalendar value) { this.creationDate = value; } /** * Gets the value of the createdBy property. * * @return * possible object is * {@link String } * */ public String getCreatedBy() { return createdBy; } /** * Sets the value of the createdBy property. * * @param value * allowed object is * {@link String } * */ public void setCreatedBy(String value) { this.createdBy = value; } /** * Gets the value of the lastUpdateLogin property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getLastUpdateLogin() { return lastUpdateLogin; } /** * Sets the value of the lastUpdateLogin property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setLastUpdateLogin(JAXBElement<String> value) { this.lastUpdateLogin = ((JAXBElement<String> ) value); } /** * Gets the value of the requestId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getRequestId() { return requestId; } /** * Sets the value of the requestId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setRequestId(JAXBElement<Long> value) { this.requestId = ((JAXBElement<Long> ) value); } /** * Gets the value of the origSystemReference property. * * @return * possible object is * {@link String } * */ public String getOrigSystemReference() { return origSystemReference; } /** * Sets the value of the origSystemReference property. * * @param value * allowed object is * {@link String } * */ public void setOrigSystemReference(String value) { this.origSystemReference = value; } /** * Gets the value of the startDateActive property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getStartDateActive() { return startDateActive; } /** * Sets the value of the startDateActive property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setStartDateActive(XMLGregorianCalendar value) { this.startDateActive = value; } /** * Gets the value of the endDateActive property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getEndDateActive() { return endDateActive; } /** * Sets the value of the endDateActive property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setEndDateActive(JAXBElement<XMLGregorianCalendar> value) { this.endDateActive = ((JAXBElement<XMLGregorianCalendar> ) value); } /** * Gets the value of the mailstop property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getMailstop() { return mailstop; } /** * Sets the value of the mailstop property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setMailstop(JAXBElement<String> value) { this.mailstop = ((JAXBElement<String> ) value); } /** * Gets the value of the identifyingAddressFlag property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIdentifyingAddressFlag() { return identifyingAddressFlag; } /** * Sets the value of the identifyingAddressFlag property. * * @param value * allowed object is * {@link Boolean } * */ public void setIdentifyingAddressFlag(Boolean value) { this.identifyingAddressFlag = value; } /** * Gets the value of the language property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getLanguage() { return language; } /** * Sets the value of the language property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setLanguage(JAXBElement<String> value) { this.language = ((JAXBElement<String> ) value); } /** * Gets the value of the status property. * * @return * possible object is * {@link String } * */ public String getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link String } * */ public void setStatus(String value) { this.status = value; } /** * Gets the value of the partySiteName property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPartySiteName() { return partySiteName; } /** * Sets the value of the partySiteName property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPartySiteName(JAXBElement<String> value) { this.partySiteName = ((JAXBElement<String> ) value); } /** * Gets the value of the addressee property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getAddressee() { return addressee; } /** * Sets the value of the addressee property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setAddressee(JAXBElement<String> value) { this.addressee = ((JAXBElement<String> ) value); } /** * Gets the value of the objectVersionNumber property. * * @return * possible object is * {@link Integer } * */ public Integer getObjectVersionNumber() { return objectVersionNumber; } /** * Sets the value of the objectVersionNumber property. * * @param value * allowed object is * {@link Integer } * */ public void setObjectVersionNumber(Integer value) { this.objectVersionNumber = value; } /** * Gets the value of the createdByModule property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getCreatedByModule() { return createdByModule; } /** * Sets the value of the createdByModule property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setCreatedByModule(JAXBElement<String> value) { this.createdByModule = ((JAXBElement<String> ) value); } /** * Gets the value of the globalLocationNumber property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getGlobalLocationNumber() { return globalLocationNumber; } /** * Sets the value of the globalLocationNumber property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setGlobalLocationNumber(JAXBElement<String> value) { this.globalLocationNumber = ((JAXBElement<String> ) value); } /** * Gets the value of the dunsNumberC property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getDUNSNumberC() { return dunsNumberC; } /** * Sets the value of the dunsNumberC property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setDUNSNumberC(JAXBElement<String> value) { this.dunsNumberC = ((JAXBElement<String> ) value); } /** * Gets the value of the comments property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getComments() { return comments; } /** * Sets the value of the comments property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setComments(JAXBElement<String> value) { this.comments = ((JAXBElement<String> ) value); } /** * Gets the value of the partySiteType property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPartySiteType() { return partySiteType; } /** * Sets the value of the partySiteType property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPartySiteType(JAXBElement<String> value) { this.partySiteType = ((JAXBElement<String> ) value); } /** * Gets the value of the partyNameDba property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPartyNameDba() { return partyNameDba; } /** * Sets the value of the partyNameDba property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPartyNameDba(JAXBElement<String> value) { this.partyNameDba = ((JAXBElement<String> ) value); } /** * Gets the value of the partyNameDivision property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPartyNameDivision() { return partyNameDivision; } /** * Sets the value of the partyNameDivision property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPartyNameDivision(JAXBElement<String> value) { this.partyNameDivision = ((JAXBElement<String> ) value); } /** * Gets the value of the partyNameLegal property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPartyNameLegal() { return partyNameLegal; } /** * Sets the value of the partyNameLegal property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPartyNameLegal(JAXBElement<String> value) { this.partyNameLegal = ((JAXBElement<String> ) value); } /** * Gets the value of the relationshipId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getRelationshipId() { return relationshipId; } /** * Sets the value of the relationshipId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setRelationshipId(JAXBElement<Long> value) { this.relationshipId = ((JAXBElement<Long> ) value); } /** * Gets the value of the partyUsageCode property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPartyUsageCode() { return partyUsageCode; } /** * Sets the value of the partyUsageCode property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPartyUsageCode(JAXBElement<String> value) { this.partyUsageCode = ((JAXBElement<String> ) value); } /** * Gets the value of the overallPrimaryFlag property. * * @return * possible object is * {@link Boolean } * */ public Boolean isOverallPrimaryFlag() { return overallPrimaryFlag; } /** * Sets the value of the overallPrimaryFlag property. * * @param value * allowed object is * {@link Boolean } * */ public void setOverallPrimaryFlag(Boolean value) { this.overallPrimaryFlag = value; } /** * Gets the value of the partySiteUse 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 partySiteUse property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPartySiteUse().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PartySiteUse } * * */ public List<PartySiteUse> getPartySiteUse() { if (partySiteUse == null) { partySiteUse = new ArrayList<PartySiteUse>(); } return this.partySiteUse; } /** * Gets the value of the phone 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 phone property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPhone().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Phone } * * */ public List<Phone> getPhone() { if (phone == null) { phone = new ArrayList<Phone>(); } return this.phone; } /** * Gets the value of the originalSystemReference 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 originalSystemReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOriginalSystemReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OriginalSystemReference } * * */ public List<OriginalSystemReference> getOriginalSystemReference() { if (originalSystemReference == null) { originalSystemReference = new ArrayList<OriginalSystemReference>(); } return this.originalSystemReference; } /** * Gets the value of the contactPreference 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 contactPreference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContactPreference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ContactPreference } * * */ public List<ContactPreference> getContactPreference() { if (contactPreference == null) { contactPreference = new ArrayList<ContactPreference>(); } return this.contactPreference; } /** * Gets the value of the personPartySiteInformation property. * * @return * possible object is * {@link PartySiteInformation } * */ public PartySiteInformation getPersonPartySiteInformation() { return personPartySiteInformation; } /** * Sets the value of the personPartySiteInformation property. * * @param value * allowed object is * {@link PartySiteInformation } * */ public void setPersonPartySiteInformation(PartySiteInformation value) { this.personPartySiteInformation = value; } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots.impl; import com.intellij.ProjectTopics; import com.intellij.ide.lightEdit.LightEdit; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.*; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.components.impl.stores.BatchUpdateListener; import com.intellij.openapi.components.impl.stores.IProjectStore; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.fileTypes.FileTypeEvent; import com.intellij.openapi.fileTypes.FileTypeListener; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.impl.ModuleEx; import com.intellij.openapi.project.DumbModeTask; import com.intellij.openapi.project.DumbServiceImpl; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.impl.VirtualFilePointerContainerImpl; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.project.ProjectKt; import com.intellij.ui.GuiUtils; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.annotations.RequiresEdt; import com.intellij.util.containers.CollectionFactory; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.FileBasedIndexImpl; import com.intellij.util.indexing.FileBasedIndexProjectHandler; import com.intellij.util.indexing.UnindexedFilesUpdater; import com.intellij.util.messages.MessageBusConnection; import com.intellij.workspaceModel.ide.WorkspaceModel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; /** * ProjectRootManager extended with ability to watch events. */ public class ProjectRootManagerComponent extends ProjectRootManagerImpl implements ProjectComponent, Disposable { private static final Logger LOG = Logger.getInstance(ProjectRootManagerComponent.class); private static final boolean LOG_CACHES_UPDATE = ApplicationManager.getApplication().isInternal() && !ApplicationManager.getApplication().isUnitTestMode(); private final static ExtensionPointName<WatchedRootsProvider> WATCHED_ROOTS_PROVIDER_EP_NAME = new ExtensionPointName<>("com.intellij.roots.watchedRootsProvider"); private final ExecutorService myExecutor = ApplicationManager.getApplication().isUnitTestMode() ? ConcurrencyUtil.newSameThreadExecutorService() : AppExecutorUtil.createBoundedApplicationPoolExecutor("Project Root Manager", 1); private @NotNull Future<?> myCollectWatchRootsFuture = CompletableFuture.completedFuture(null); // accessed in EDT only private final OnlyOnceExceptionLogger myRootsChangedLogger = new OnlyOnceExceptionLogger(LOG); private boolean myPointerChangesDetected; private int myInsideWriteAction; private @NotNull Set<LocalFileSystem.WatchRequest> myRootsToWatch = CollectionFactory.createSmallMemoryFootprintSet(); private Disposable myRootPointersDisposable = Disposer.newDisposable(); // accessed in EDT public ProjectRootManagerComponent(@NotNull Project project) { super(project); if (!myProject.isDefault()) { registerListeners(); } } private void registerListeners() { MessageBusConnection connection = myProject.getMessageBus().connect(this); connection.subscribe(FileTypeManager.TOPIC, new FileTypeListener() { @Override public void beforeFileTypesChanged(@NotNull FileTypeEvent event) { myFileTypesChanged.beforeRootsChanged(); } @Override public void fileTypesChanged(@NotNull FileTypeEvent event) { myFileTypesChanged.rootsChanged(); } }); if (!LightEdit.owns(myProject)) { VirtualFileManager.getInstance().addVirtualFileManagerListener(new VirtualFileManagerListener() { @Override public void afterRefreshFinish(boolean asynchronous) { doUpdateOnRefresh(); } }, this); } StartupManager.getInstance(myProject).registerStartupActivity(() -> { myStartupActivityPerformed = true; }); connection.subscribe(BatchUpdateListener.TOPIC, new BatchUpdateListener() { @Override public void onBatchUpdateStarted() { myRootsChanged.levelUp(); myFileTypesChanged.levelUp(); } @Override public void onBatchUpdateFinished() { myRootsChanged.levelDown(); myFileTypesChanged.levelDown(); } }); Runnable rootsExtensionPointListener = () -> ApplicationManager.getApplication().invokeLater(() -> { WriteAction.run(() -> { makeRootsChange(EmptyRunnable.getInstance(), false, true); }); }); AdditionalLibraryRootsProvider.EP_NAME.addChangeListener(rootsExtensionPointListener, this); OrderEnumerationHandler.EP_NAME.addChangeListener(rootsExtensionPointListener, this); } @Override public void projectOpened() { addRootsToWatch(); ApplicationManager.getApplication().addApplicationListener(new AppListener(), myProject); } @Override public void projectClosed() { LocalFileSystem.getInstance().removeWatchedRoots(myRootsToWatch); } @RequiresEdt private void addRootsToWatch() { if (myProject.isDefault()) return; ApplicationManager.getApplication().assertIsWriteThread(); Disposable oldDisposable = myRootPointersDisposable; Disposable newDisposable = Disposer.newDisposable(); myCollectWatchRootsFuture.cancel(false); myCollectWatchRootsFuture = myExecutor.submit(() -> { Pair<Set<String>, Set<String>> watchRoots = ReadAction.compute(() -> myProject.isDisposed() ? null : collectWatchRoots(newDisposable)); GuiUtils.invokeLaterIfNeeded(() -> { if (myProject.isDisposed()) return; myRootPointersDisposable = newDisposable; // dispose after the re-creating container to keep VFPs from disposing and re-creating back; // instead, just increment/decrement their usage count Disposer.dispose(oldDisposable); myRootsToWatch = LocalFileSystem.getInstance().replaceWatchedRoots(myRootsToWatch, watchRoots.first, watchRoots.second); }, ModalityState.any()); }); } private void doUpdateOnRefresh() { if (ApplicationManager.getApplication().isUnitTestMode() && (!myStartupActivityPerformed || myProject.isDisposed())) { return; // in test mode suppress addition to a queue unless project is properly initialized } if (LOG_CACHES_UPDATE || LOG.isDebugEnabled()) { LOG.debug("refresh"); } FileBasedIndexProjectHandler.scheduleReindexingInDumbMode(myProject); } @Override protected void fireBeforeRootsChangeEvent(boolean fileTypes) { isFiringEvent = true; try { myProject.getMessageBus().syncPublisher(ProjectTopics.PROJECT_ROOTS).beforeRootsChange(new ModuleRootEventImpl(myProject, fileTypes)); } finally { isFiringEvent = false; } } @Override protected void fireRootsChangedEvent(boolean fileTypes, @Nullable ProjectRootManagerImpl.RootsChangeType changeType) { isFiringEvent = true; try { myProject.getMessageBus().syncPublisher(ProjectTopics.PROJECT_ROOTS).rootsChanged(new ModuleRootEventImpl(myProject, fileTypes)); } finally { isFiringEvent = false; } synchronizeRoots(changeType); addRootsToWatch(); } private @NotNull Pair<Set<String>, Set<String>> collectWatchRoots(@NotNull Disposable disposable) { ApplicationManager.getApplication().assertReadAccessAllowed(); Set<String> recursivePathsToWatch = CollectionFactory.createFilePathSet(); Set<String> flatPaths = CollectionFactory.createFilePathSet(); IProjectStore store = ProjectKt.getStateStore(myProject); Path projectFilePath = store.getProjectFilePath(); if (!Project.DIRECTORY_STORE_FOLDER.equals(projectFilePath.getParent().getFileName().toString())) { flatPaths.add(FileUtil.toSystemIndependentName(projectFilePath.toString())); flatPaths.add(FileUtil.toSystemIndependentName(store.getWorkspacePath().toString())); } for (AdditionalLibraryRootsProvider extension : AdditionalLibraryRootsProvider.EP_NAME.getExtensionList()) { Collection<VirtualFile> toWatch = extension.getRootsToWatch(myProject); if (!toWatch.isEmpty()) { for (VirtualFile file : toWatch) { recursivePathsToWatch.add(file.getPath()); } } } for (WatchedRootsProvider extension : WATCHED_ROOTS_PROVIDER_EP_NAME.getExtensionList()) { Set<String> toWatch = extension.getRootsToWatch(myProject); if (!toWatch.isEmpty()) { for (String path : toWatch) { recursivePathsToWatch.add(FileUtil.toSystemIndependentName(path)); } } } Set<String> excludedUrls = CollectionFactory.createSmallMemoryFootprintSet(); // changes in files provided by this method should be watched manually because no-one's bothered to set up correct pointers for them for (DirectoryIndexExcludePolicy excludePolicy : DirectoryIndexExcludePolicy.EP_NAME.getExtensionList(myProject)) { Collections.addAll(excludedUrls, excludePolicy.getExcludeUrlsForProject()); } // avoid creating empty unnecessary container if (!WorkspaceModel.isEnabled() && (!flatPaths.isEmpty() || !excludedUrls.isEmpty())) { Disposer.register(this, disposable); // creating a container with these URLs with the sole purpose to get events to getRootsValidityChangedListener() when these roots change VirtualFilePointerContainer container = VirtualFilePointerManager.getInstance().createContainer(disposable, getRootsValidityChangedListener()); flatPaths.forEach(path -> container.add(VfsUtilCore.pathToUrl(path))); ((VirtualFilePointerContainerImpl)container).addAll(excludedUrls); } // module roots already fire validity change events, see usages of ProjectRootManagerComponent.getRootsValidityChangedListener collectModuleWatchRoots(recursivePathsToWatch, flatPaths); return new Pair<>(recursivePathsToWatch, flatPaths); } private void collectModuleWatchRoots(@NotNull Set<? super String> recursivePaths, @NotNull Set<? super String> flatPaths) { Set<String> urls = CollectionFactory.createFilePathSet(); for (Module module : ModuleManager.getInstance(myProject).getModules()) { ModuleRootManager rootManager = ModuleRootManager.getInstance(module); ContainerUtil.addAll(urls, rootManager.getContentRootUrls()); rootManager.orderEntries().withoutModuleSourceEntries().withoutDepModules().forEach(entry -> { for (OrderRootType type : OrderRootType.getAllTypes()) { ContainerUtil.addAll(urls, entry.getUrls(type)); } return true; }); } for (String url : urls) { String protocol = VirtualFileManager.extractProtocol(url); if (protocol == null || StandardFileSystems.FILE_PROTOCOL.equals(protocol)) { recursivePaths.add(extractLocalPath(url)); } else if (StandardFileSystems.JAR_PROTOCOL.equals(protocol)) { flatPaths.add(extractLocalPath(url)); } else if (StandardFileSystems.JRT_PROTOCOL.equals(protocol)) { recursivePaths.add(extractLocalPath(url)); } } } private void synchronizeRoots(@Nullable ProjectRootManagerImpl.RootsChangeType changeType) { if (!myStartupActivityPerformed) return; if (changeType == RootsChangeType.ROOTS_REMOVED) { logRootChanges("some project roots were removed"); return; } logRootChanges("project roots have changed"); DumbServiceImpl dumbService = DumbServiceImpl.getInstance(myProject); if (FileBasedIndex.getInstance() instanceof FileBasedIndexImpl) { dumbService.queueTask(new UnindexedFilesUpdater(myProject)); } } private void logRootChanges(@NotNull String message) { if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.info(message); } else { myRootsChangedLogger.info(message, new Throwable()); } } @Override protected void clearScopesCaches() { super.clearScopesCaches(); LibraryScopeCache libraryScopeCache = myProject.getServiceIfCreated(LibraryScopeCache.class); if (libraryScopeCache != null) { libraryScopeCache.clear(); } } @Override public void clearScopesCachesForModules() { super.clearScopesCachesForModules(); Module[] modules = ModuleManager.getInstance(myProject).getModules(); for (Module module : modules) { ((ModuleEx)module).clearScopesCache(); } } @Override public void markRootsForRefresh() { Set<String> paths = CollectionFactory.createFilePathSet(); collectModuleWatchRoots(paths, paths); LocalFileSystem fs = LocalFileSystem.getInstance(); for (String path : paths) { VirtualFile root = fs.findFileByPath(path); if (root instanceof NewVirtualFile) { ((NewVirtualFile)root).markDirtyRecursively(); } } } @Override public void dispose() { myCollectWatchRootsFuture.cancel(false); myExecutor.shutdownNow(); } private class AppListener implements ApplicationListener { @Override public void beforeWriteActionStart(@NotNull Object action) { myInsideWriteAction++; } @Override public void writeActionFinished(@NotNull Object action) { if (--myInsideWriteAction == 0 && myPointerChangesDetected) { myPointerChangesDetected = false; myRootsChanged.levelDown(); } } } private final VirtualFilePointerListener myRootsChangedListener = new VirtualFilePointerListener() { @NotNull private ProjectRootManagerImpl.RootsChangeType getPointersChanges(VirtualFilePointer @NotNull [] pointers) { RootsChangeType result = null; for (VirtualFilePointer pointer : pointers) { if (pointer.isValid()) { if (result == null) { result = RootsChangeType.ROOTS_ADDED; } else if (result != RootsChangeType.ROOTS_ADDED) { return RootsChangeType.GENERIC; } } else { if (result == null) { result = RootsChangeType.ROOTS_REMOVED; } else if (result != RootsChangeType.ROOTS_REMOVED) { return RootsChangeType.GENERIC; } } } return ObjectUtils.notNull(result, RootsChangeType.GENERIC); } @Override public void beforeValidityChanged(VirtualFilePointer @NotNull [] pointers) { if (myProject.isDisposed()) { return; } if (!isInsideWriteAction() && !myPointerChangesDetected) { myPointerChangesDetected = true; //this is the first pointer changing validity myRootsChanged.levelUp(); } myRootsChanged.beforeRootsChanged(); if (LOG_CACHES_UPDATE || LOG.isTraceEnabled()) { LOG.trace(new Throwable(pointers.length > 0 ? pointers[0].getPresentableUrl() : "")); } } @Override public void validityChanged(VirtualFilePointer @NotNull [] pointers) { RootsChangeType changeType = getPointersChanges(pointers); if (myProject.isDisposed()) { return; } if (isInsideWriteAction()) { myRootsChanged.rootsChanged(changeType); } else { clearScopesCaches(); } } private boolean isInsideWriteAction() { return myInsideWriteAction == 0; } }; @Override public @NotNull VirtualFilePointerListener getRootsValidityChangedListener() { return myRootsChangedListener; } }
/* * 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.action.admin.indices.analyze; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; public class DetailAnalyzeResponse implements Streamable, ToXContent { DetailAnalyzeResponse() { } private boolean customAnalyzer = false; private AnalyzeTokenList analyzer; private CharFilteredText[] charfilters; private AnalyzeTokenList tokenizer; private AnalyzeTokenList[] tokenfilters; public DetailAnalyzeResponse(AnalyzeTokenList analyzer) { this(false, analyzer, null, null, null); } public DetailAnalyzeResponse(CharFilteredText[] charfilters, AnalyzeTokenList tokenizer, AnalyzeTokenList[] tokenfilters) { this(true, null, charfilters, tokenizer, tokenfilters); } public DetailAnalyzeResponse(boolean customAnalyzer, AnalyzeTokenList analyzer, CharFilteredText[] charfilters, AnalyzeTokenList tokenizer, AnalyzeTokenList[] tokenfilters) { this.customAnalyzer = customAnalyzer; this.analyzer = analyzer; this.charfilters = charfilters; this.tokenizer = tokenizer; this.tokenfilters = tokenfilters; } public AnalyzeTokenList analyzer() { return this.analyzer; } public DetailAnalyzeResponse analyzer(AnalyzeTokenList analyzer) { this.analyzer = analyzer; return this; } public CharFilteredText[] charfilters() { return this.charfilters; } public DetailAnalyzeResponse charfilters(CharFilteredText[] charfilters) { this.charfilters = charfilters; return this; } public AnalyzeTokenList tokenizer() { return tokenizer; } public DetailAnalyzeResponse tokenizer(AnalyzeTokenList tokenizer) { this.tokenizer = tokenizer; return this; } public AnalyzeTokenList[] tokenfilters() { return tokenfilters; } public DetailAnalyzeResponse tokenfilters(AnalyzeTokenList[] tokenfilters) { this.tokenfilters = tokenfilters; return this; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field(Fields.CUSTOM_ANALYZER, customAnalyzer); if (analyzer != null) { builder.startObject(Fields.ANALYZER); analyzer.toXContentWithoutObject(builder, params); builder.endObject(); } if (charfilters != null) { builder.startArray(Fields.CHARFILTERS); for (CharFilteredText charfilter : charfilters) { charfilter.toXContent(builder, params); } builder.endArray(); } if (tokenizer != null) { builder.startObject(Fields.TOKENIZER); tokenizer.toXContentWithoutObject(builder, params); builder.endObject(); } if (tokenfilters != null) { builder.startArray(Fields.TOKENFILTERS); for (AnalyzeTokenList tokenfilter : tokenfilters) { tokenfilter.toXContent(builder, params); } builder.endArray(); } return builder; } static final class Fields { static final String NAME = "name"; static final String FILTERED_TEXT = "filtered_text"; static final String CUSTOM_ANALYZER = "custom_analyzer"; static final String ANALYZER = "analyzer"; static final String CHARFILTERS = "charfilters"; static final String TOKENIZER = "tokenizer"; static final String TOKENFILTERS = "tokenfilters"; } @Override public void readFrom(StreamInput in) throws IOException { this.customAnalyzer = in.readBoolean(); if (customAnalyzer) { tokenizer = AnalyzeTokenList.readAnalyzeTokenList(in); int size = in.readVInt(); if (size > 0) { charfilters = new CharFilteredText[size]; for (int i = 0; i < size; i++) { charfilters[i] = CharFilteredText.readCharFilteredText(in); } } size = in.readVInt(); if (size > 0) { tokenfilters = new AnalyzeTokenList[size]; for (int i = 0; i < size; i++) { tokenfilters[i] = AnalyzeTokenList.readAnalyzeTokenList(in); } } } else { analyzer = AnalyzeTokenList.readAnalyzeTokenList(in); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeBoolean(customAnalyzer); if (customAnalyzer) { tokenizer.writeTo(out); if (charfilters != null) { out.writeVInt(charfilters.length); for (CharFilteredText charfilter : charfilters) { charfilter.writeTo(out); } } else { out.writeVInt(0); } if (tokenfilters != null) { out.writeVInt(tokenfilters.length); for (AnalyzeTokenList tokenfilter : tokenfilters) { tokenfilter.writeTo(out); } } else { out.writeVInt(0); } } else { analyzer.writeTo(out); } } public static class AnalyzeTokenList implements Streamable, ToXContent { private String name; private AnalyzeResponse.AnalyzeToken[] tokens; AnalyzeTokenList() { } public AnalyzeTokenList(String name, AnalyzeResponse.AnalyzeToken[] tokens) { this.name = name; this.tokens = tokens; } public String getName() { return name; } public AnalyzeResponse.AnalyzeToken[] getTokens() { return tokens; } public static AnalyzeTokenList readAnalyzeTokenList(StreamInput in) throws IOException { AnalyzeTokenList list = new AnalyzeTokenList(); list.readFrom(in); return list; } public XContentBuilder toXContentWithoutObject(XContentBuilder builder, Params params) throws IOException { builder.field(Fields.NAME, this.name); builder.startArray(AnalyzeResponse.Fields.TOKENS); for (AnalyzeResponse.AnalyzeToken token : tokens) { token.toXContent(builder, params); } builder.endArray(); return builder; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(Fields.NAME, this.name); builder.startArray(AnalyzeResponse.Fields.TOKENS); for (AnalyzeResponse.AnalyzeToken token : tokens) { token.toXContent(builder, params); } builder.endArray(); builder.endObject(); return builder; } @Override public void readFrom(StreamInput in) throws IOException { name = in.readString(); int size = in.readVInt(); if (size > 0) { tokens = new AnalyzeResponse.AnalyzeToken[size]; for (int i = 0; i < size; i++) { tokens[i] = AnalyzeResponse.AnalyzeToken.readAnalyzeToken(in); } } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); if (tokens != null) { out.writeVInt(tokens.length); for (AnalyzeResponse.AnalyzeToken token : tokens) { token.writeTo(out); } } else { out.writeVInt(0); } } } public static class CharFilteredText implements Streamable, ToXContent { private String name; private String[] texts; CharFilteredText() { } public CharFilteredText(String name, String[] texts) { this.name = name; if (texts != null) { this.texts = texts; } else { this.texts = Strings.EMPTY_ARRAY; } } public String getName() { return name; } public String[] getTexts() { return texts; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(Fields.NAME, name); builder.array(Fields.FILTERED_TEXT, texts); builder.endObject(); return builder; } public static CharFilteredText readCharFilteredText(StreamInput in) throws IOException { CharFilteredText text = new CharFilteredText(); text.readFrom(in); return text; } @Override public void readFrom(StreamInput in) throws IOException { name = in.readString(); texts = in.readStringArray(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); out.writeStringArray(texts); } } }
/* * Copyright (c) 2016, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com 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 HOLDER 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. */ package com.salesforce.dva.argus.service.tsdb; import static com.salesforce.dva.argus.system.SystemAssert.requireArgument; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.IntUnaryOperator; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.apache.commons.lang.StringUtils; import com.salesforce.dva.argus.entity.MetatagsRecord; import com.salesforce.dva.argus.entity.MetricSchemaRecord; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.inject.Inject; import com.salesforce.dva.argus.entity.Annotation; import com.salesforce.dva.argus.entity.Metric; import com.salesforce.dva.argus.service.DefaultService; import com.salesforce.dva.argus.service.MonitorService; import com.salesforce.dva.argus.service.TSDBService; import com.salesforce.dva.argus.system.SystemConfiguration; import com.salesforce.dva.argus.system.SystemException; /** * TSDB abstract class, where the put methods are implemented, and the get methods are overridden by specific implementation. * * @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com) */ public class AbstractTSDBService extends DefaultService implements TSDBService { //~ Static fields/initializers ******************************************************************************************************************* private static final int CHUNK_SIZE = 50; private static final int TSDB_DATAPOINTS_WRITE_MAX_SIZE = 100; private static final String QUERY_LATENCY_COUNTER = "query.latency"; private static final String QUERY_COUNT_COUNTER = "query.count"; static final String DELIMITER = "-__-"; //~ Instance fields ****************************************************************************************************************************** private final ObjectMapper _mapper; protected final Logger _logger = LoggerFactory.getLogger(getClass()); private final String[] _writeEndpoints; protected CloseableHttpClient _writeHttpClient; protected final List<String> _readEndPoints; protected final List<String> _readBackupEndPoints; protected Map<String, CloseableHttpClient> _readPortMap = new HashMap<>(); protected final Map<String, String> _readBackupEndPointsMap = new HashMap<>(); /** Round robin iterator for write endpoints. * We will cycle through this iterator to select an endpoint from the set of available endpoints */ private final Iterator<String> _roundRobinIterator; protected final ExecutorService _executorService; protected final MonitorService _monitorService; private final int RETRY_COUNT; /* Given a key for an annotation, we cache its tuid obtained from TSDB when storing the metric portion of annotation. Annotations cannot directly be stored as metric_name and tags. You need to store the metric_name with tags, get the generated tuid and store the annotation using the tuid. Feature request to fix this is mentioned below. https://github.com/OpenTSDB/opentsdb/issues/913 */ private Cache<String, String> _keyUidCache; //~ Constructors ********************************************************************************************************************************* /** * Creates a new Default TSDB Service having an equal number of read and write routes. * * @param config The system _configuration used to configure the service. * @param monitorService The monitor service used to collect query time window counters. Cannot be null. * @throws SystemException If an error occurs configuring the service. */ @Inject public AbstractTSDBService(SystemConfiguration config, MonitorService monitorService) { super(config); requireArgument(config != null, "System configuration cannot be null."); requireArgument(monitorService != null, "Monitor service cannot be null."); _monitorService = monitorService; _mapper = getMapper(); int connCount = Integer.parseInt(config.getValue(Property.TSD_CONNECTION_COUNT.getName(), Property.TSD_CONNECTION_COUNT.getDefaultValue())); int connTimeout = Integer.parseInt(config.getValue(Property.TSD_ENDPOINT_CONNECTION_TIMEOUT.getName(), Property.TSD_ENDPOINT_CONNECTION_TIMEOUT.getDefaultValue())); int socketTimeout = Integer.parseInt(config.getValue(Property.TSD_ENDPOINT_SOCKET_TIMEOUT.getName(), Property.TSD_ENDPOINT_SOCKET_TIMEOUT.getDefaultValue())); int tsdbConnectionReuseCount=Integer.parseInt(config.getValue(Property.TSDB_READ_CONNECTION_REUSE_COUNT.getName(), Property.TSDB_READ_CONNECTION_REUSE_COUNT.getDefaultValue())); _readEndPoints = Arrays.asList(config.getValue(Property.TSD_ENDPOINT_READ.getName(), Property.TSD_ENDPOINT_READ.getDefaultValue()).split(",")); requireArgument(_readEndPoints.size() > 0, "At least one TSD read endpoint required"); for(String readEndPoint : _readEndPoints) { requireArgument((readEndPoint != null) && (!readEndPoint.isEmpty()), "Illegal read endpoint URL."); } _readBackupEndPoints = Arrays.asList(config.getValue(Property.TSD_ENDPOINT_BACKUP_READ.getName(), Property.TSD_ENDPOINT_BACKUP_READ.getDefaultValue()).split(",")); if(_readBackupEndPoints.size() < _readEndPoints.size()){ for(int i=0; i< _readEndPoints.size() - _readBackupEndPoints.size();i++) _readBackupEndPoints.add(""); } _writeEndpoints = config.getValue(Property.TSD_ENDPOINT_WRITE.getName(), Property.TSD_ENDPOINT_WRITE.getDefaultValue()).split(","); requireArgument(_writeEndpoints.length > 0, "At least one TSD write endpoint required"); RETRY_COUNT = Integer.parseInt(config.getValue(Property.TSD_RETRY_COUNT.getName(), Property.TSD_RETRY_COUNT.getDefaultValue())); for(String writeEndpoint : _writeEndpoints) { requireArgument((writeEndpoint != null) && (!writeEndpoint.isEmpty()), "Illegal write endpoint URL."); } requireArgument(connCount >= 2, "At least two connections are required."); requireArgument(connTimeout >= 1, "Timeout must be greater than 0."); _keyUidCache = CacheBuilder.newBuilder() .maximumSize(1000000) .expireAfterAccess(1, TimeUnit.HOURS) .build(); try { int index = 0; for (String readEndpoint : _readEndPoints) { _readPortMap.put(readEndpoint, getClient(connCount / 2, connTimeout, socketTimeout, tsdbConnectionReuseCount ,readEndpoint)); _readBackupEndPointsMap.put(readEndpoint, _readBackupEndPoints.get(index)); index ++; } for (String readBackupEndpoint : _readBackupEndPoints) { if (!readBackupEndpoint.isEmpty()) _readPortMap.put(readBackupEndpoint, getClient(connCount / 2, connTimeout, socketTimeout, tsdbConnectionReuseCount, readBackupEndpoint)); } _writeHttpClient = getClient(connCount / 2, connTimeout, socketTimeout,tsdbConnectionReuseCount, _writeEndpoints); _roundRobinIterator = constructCyclingIterator(_writeEndpoints); _executorService = Executors.newFixedThreadPool(connCount); } catch (MalformedURLException ex) { throw new SystemException("Error initializing the TSDB HTTP Client.", ex); } } //~ Methods ************************************************************************************************************************************** /* Used in tests to mock Tsdb clients. */ void SetTsdbClients(CloseableHttpClient writeHttpClient, CloseableHttpClient readHttpClient) { _writeHttpClient = writeHttpClient; for(String key : _readPortMap.keySet()) { _readPortMap.put(key, readHttpClient); } } Iterator<String> constructCyclingIterator(String[] endpoints) { // Return repeating, non-blocking iterator if single element if (endpoints.length == 1) { return new Iterator<String>() { String item = endpoints[0]; @Override public boolean hasNext() { return true; } @Override public String next() { return item; } }; } return new Iterator<String>() { AtomicInteger index = new AtomicInteger(0); List<String> items = Arrays.asList(endpoints); IntUnaryOperator updater = (operand) -> { if (operand == items.size() - 1) { return 0; } else { return operand + 1; } }; @Override public boolean hasNext() { return true; } @Override public String next() { return items.get(index.getAndUpdate(updater)); } }; } /* Generates the metric names for metrics used for annotations. */ static String toAnnotationKey(String scope, String metric, String type, Map<String, String> tags) { int hash = 7; hash = 71 * hash + (scope != null ? scope.hashCode() : 0); hash = 71 * hash + (metric != null ? metric.hashCode() : 0); hash = 71 * hash + (type != null ? type.hashCode() : 0); hash = 71 * hash + (tags != null ? tags.hashCode() : 0); StringBuilder sb = new StringBuilder(); sb.append(scope).append(".").append(Integer.toHexString(hash)); return sb.toString(); } private static String toAnnotationKey(Annotation annotation) { String scope = annotation.getScope(); String metric = annotation.getMetric(); String type = annotation.getType(); Map<String, String> tags = annotation.getTags(); return toAnnotationKey(scope, metric, type, tags); } /** * We construct OpenTSDB metric name as a combination of Argus metric, scope and namespace as follows: * * metric(otsdb) = metric(argus)&lt;DELIMITER&gt;scope(argus)&lt;DELIMITER&gt;namespace(argus) * * @param metric The metric * @return OpenTSDB metric name constructed from scope, metric and namespace. */ public static String constructTSDBMetricName(Metric metric) { StringBuilder sb = new StringBuilder(); sb.append(metric.getMetric()).append(DELIMITER).append(metric.getScope()); if (metric.getNamespace() != null && !metric.getNamespace().isEmpty()) { sb.append(DELIMITER).append(metric.getNamespace()); } return sb.toString(); } /** * Given otsdb metric name, return argus metric. * We construct OpenTSDB metric name as a combination of Argus metric, scope and namespace as follows: * * metric(otsdb) = metric(argus)&lt;DELIMITER&gt;scope(argus)&lt;DELIMITER&gt;namespace(argus) * * * @param tsdbMetricName The TSDB metric name * @return Argus metric name. */ public static String getMetricFromTSDBMetric(String tsdbMetricName) { return tsdbMetricName.split(DELIMITER)[0]; } /** * Given otsdb metric name, return argus scope. * We construct OpenTSDB metric name as a combination of Argus metric, scope and namespace as follows: * * metric(otsdb) = metric(argus)&lt;DELIMITER&gt;scope(argus)&lt;DELIMITER&gt;namespace(argus) * * * @param tsdbMetricName The TSDB metric name * @return Argus scope. */ public static String getScopeFromTSDBMetric(String tsdbMetricName) { return tsdbMetricName.split(DELIMITER)[1]; } /** * Given otsdb metric name, return argus namespace. * We construct OpenTSDB metric name as a combination of Argus metric, scope and namespace as follows: * * metric(otsdb) = metric(argus)&lt;DELIMITER&gt;scope(argus)&lt;DELIMITER&gt;namespace(argus) * * * @param tsdbMetricName The TSDB metric name * @return Argus namespace. */ public static String getNamespaceFromTSDBMetric(String tsdbMetricName) { String[] splits = tsdbMetricName.split(DELIMITER); return (splits.length == 3) ? splits[2] : null; } //~ Methods ************************************************************************************************************************************** /** @see TSDBService#dispose() */ @Override public void dispose() { } /** @see TSDBService#putMetrics(java.util.List) */ @Override public void putMetrics(List<Metric> metrics) { requireNotDisposed(); requireArgument(TSDB_DATAPOINTS_WRITE_MAX_SIZE > 0, "Max Chunk size can not be less than 1"); requireArgument(metrics != null, "Metrics can not be null"); String endpoint = _roundRobinIterator.next(); _logger.debug("Pushing {} metrics to TSDB using endpoint {}.", metrics.size(), endpoint); List<Metric> fracturedList = new ArrayList<>(); for (Metric metric : metrics) { MetatagsRecord metatagsRecord = metric.getMetatagsRecord(); if (metatagsRecord != null) { //remove this special metatag to prevent it from going to TSDB metatagsRecord.removeMetatag(MetricSchemaRecord.RETENTION_DISCOVERY); } if (metric.getDatapoints().size() <= TSDB_DATAPOINTS_WRITE_MAX_SIZE) { fracturedList.add(metric); } else { fracturedList.addAll(fractureMetric(metric)); } } try { put(fracturedList, endpoint + "/api/put", HttpMethod.POST, CHUNK_SIZE); } catch(Exception ex) { _logger.warn("Failure while trying to push metrics", ex); _retry(fracturedList, _roundRobinIterator, "/api/put", HttpMethod.POST, CHUNK_SIZE); } } public <T> void _retry(List<T> objects, Iterator<String> endPointIterator, String urlPath, HttpMethod httpMethod, int chunkSize) { for(int i=0;i<RETRY_COUNT;i++) { try { String endpoint = endPointIterator.next(); _logger.info("Retrying using endpoint {}.", endpoint); put(objects, endpoint + urlPath, httpMethod, chunkSize); return; } catch(Exception ex) { _logger.info("Failed while trying to push data. We will retry for {} more times", RETRY_COUNT-i); } } _logger.error("Retried for {} times and we still failed. Dropping this chunk of data.", RETRY_COUNT); } /** @see TSDBService#putAnnotations(java.util.List) */ @Override public void putAnnotations(List<Annotation> annotations) { requireNotDisposed(); if (annotations != null) { // Dictionary of annotation key and the annotation Map<String, Annotation> keyAnnotationMap = new HashMap<>(); // List of Dictionary of annotation uid and annotation wrapper // We observed occasional failures with tsdb when we are updating same annotation uid in a batch. // To address that we maintain a list of dictionaries where each dictionary represents a batch that is updated. // If we have multiple annotations with same uid, they get added to different dictionaries // and get updated in multiple batches. List<Map<String, AnnotationWrapper>> wrapperList = new ArrayList<>(); for(Annotation annotation : annotations) { String key = toAnnotationKey(annotation); String uid = _keyUidCache.getIfPresent(key); if(StringUtils.isEmpty(uid)) { // Not in cache, populate keyAnnotationMap so that we can query TSDB. keyAnnotationMap.put(key, annotation); } else { // If we find uid in the cache, we construct the AnnotationWrapper object. AnnotationWrapper wrapper = new AnnotationWrapper(uid, annotation); addToWrapperList(wrapperList, wrapper); } } if(!keyAnnotationMap.isEmpty()) { // query TSDB to get uids for annotations. Map<String, String> keyUidMap = getUidMapFromTsdb(keyAnnotationMap); for (Map.Entry<String, String> keyUidEntry : keyUidMap.entrySet()) { // We add new uids to the cache and create AnnotationWrapper objects. _keyUidCache.put(keyUidEntry.getKey(), keyUidEntry.getValue()); AnnotationWrapper wrapper = new AnnotationWrapper(keyUidEntry.getValue(), keyAnnotationMap.get(keyUidEntry.getKey())); addToWrapperList(wrapperList, wrapper); } } _logger.debug("putAnnotations CacheStats hitCount {} requestCount {} " + "evictionCount {} annotationsCount {}", _keyUidCache.stats().hitCount(), _keyUidCache.stats().requestCount(), _keyUidCache.stats().evictionCount(), annotations.size()); String endpoint = _roundRobinIterator.next(); for(Map<String, AnnotationWrapper> wrapperMap : wrapperList) { List<AnnotationWrapper> wrappers = new ArrayList<AnnotationWrapper>(wrapperMap.values()); try { put(wrappers, endpoint + "/api/annotation/bulk", HttpMethod.POST, CHUNK_SIZE); } catch (Exception ex) { _logger.warn("Exception while trying to push annotations", ex); _retry(wrappers, _roundRobinIterator, "/api/annotation/bulk", HttpMethod.POST, CHUNK_SIZE); } } } } static void addToWrapperList(List<Map<String, AnnotationWrapper>> wrapperList, AnnotationWrapper wrapper) { Boolean addedWrapper = false; for(Map<String, AnnotationWrapper> wrapperMap : wrapperList) { if(!wrapperMap.containsKey(wrapper._uid)) { wrapperMap.put(wrapper._uid, wrapper); addedWrapper = true; break; } } if(!addedWrapper) { Map<String, AnnotationWrapper> wrapperMap = new HashMap<>(); wrapperMap.put(wrapper._uid, wrapper); wrapperList.add(wrapperMap); addedWrapper = true; } } private Map<String, String> getUidMapFromTsdb(Map<String, Annotation> keyAnnotationMap) { List<MetricQuery> queries = new ArrayList<>(); List<Metric> metrics = new ArrayList<>(); Map<Long, Double> datapoints = new HashMap<>(); datapoints.put(1L, 0.0); for(Map.Entry<String, Annotation> annotationEntry : keyAnnotationMap.entrySet()) { String annotationKey = annotationEntry.getKey(); Annotation annotation = annotationEntry.getValue(); String type = annotation.getType(); Map<String, String> tags = annotation.getTags(); Metric metric = new Metric(annotationKey, type); metric.setDatapoints(datapoints); metric.setTags(tags); metrics.add(metric); MetricQuery query = new MetricQuery(annotationKey, type, tags, 0L, 2L); queries.add(query); } putMetrics(metrics); long backOff = 500L; for (int attempts = 0; attempts < 3; attempts++) { try { Thread.sleep(backOff); } catch (InterruptedException ex) { // We continue if interrupted. } try { Map<String, String> keyUidMap = new HashMap<>(); Map<MetricQuery, List<Metric>> metricMap = getMetrics(queries); for(List<Metric> getMetrics : metricMap.values()) { Metric firstMetric = getMetrics.get(0); keyUidMap.put(firstMetric.getScope(), firstMetric.getUid()); } return keyUidMap; } catch (Exception e) { _logger.warn("Exception while trying to get uids for annotations", e); backOff += 500L; } } throw new SystemException("Failed to create new annotation metric."); } private ObjectMapper getMapper() { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(Metric.class, new MetricTransform.Serializer()); module.addDeserializer(ResultSet.class, new MetricTransform.MetricListDeserializer()); module.addSerializer(AnnotationWrapper.class, new AnnotationTransform.Serializer()); module.addDeserializer(AnnotationWrappers.class, new AnnotationTransform.Deserializer()); module.addSerializer(MetricQuery.class, new MetricQueryTransform.Serializer()); mapper.registerModule(module); return mapper; } /* gets objects in chunks. public Map<MetricQuery, List<Metric>> get(List<MetricQuery> queries) throws IOException { requireNotDisposed(); requireArgument(queries != null, "Metric Queries cannot be null."); Map<MetricQuery, List<Metric>> metricsMap = new HashMap<>(); Map<MetricQuery, Future<List<Metric>>> futures = new HashMap<>(); Map<MetricQuery, Long> queryStartExecutionTime = new HashMap<>(); // Only one endpoint for AbstractTSDBService String requestUrl = _readEndPoints.get(0) + "/api/query"; int chunkEnd = 0; while (chunkEnd < queries.size()) { int chunkStart = chunkEnd; long start = System.currentTimeMillis(); chunkEnd = Math.min(queries.size(), chunkStart + CHUNK_SIZE); String requestBody = fromEntity(queries.subList(chunkStart, chunkEnd)); _logger.info("requestUrl {} requestBody {}", requestUrl, requestBody); HttpResponse response = executeHttpRequest(HttpMethod.POST, requestUrl, _readPortMap.get(requestUrl), new StringEntity(requestBody)); List<Metric> metrics = toEntity(extractResponse(response), new TypeReference<ResultSet>() { }).getMetrics(); } for (Map.Entry<MetricQuery, Future<List<Metric>>> entry : futures.entrySet()) { try { List<Metric> m = entry.getValue().get(); List<Metric> metrics = new ArrayList<>(); if (m != null) { for (Metric metric : m) { if (metric != null) { metric.setQuery(entry.getKey()); metrics.add(metric); } } } instrumentQueryLatency(_monitorService, entry.getKey(), queryStartExecutionTime.get(entry.getKey()), "metrics"); metricsMap.put(entry.getKey(), metrics); } catch (InterruptedException | ExecutionException e) { throw new SystemException("Failed to get metrics. The query was: " + entry.getKey() + "\\n", e); } } _logger.info("Time to get Metrics = " + (System.currentTimeMillis() - start)); return metricsMap; } */ /* Writes objects in chunks. */ private <T> void put(List<T> objects, String endpoint, HttpMethod method, int chunkSize) throws IOException { if (objects != null) { int chunkEnd = 0; while (chunkEnd < objects.size()) { int chunkStart = chunkEnd; chunkEnd = Math.min(objects.size(), chunkStart + chunkSize); try { String createBody = fromEntity(objects.subList(chunkStart, chunkEnd)); StringEntity entity = new StringEntity(createBody); _logger.debug("createUrl {} createBody {}", endpoint, createBody); HttpResponse response = executeHttpRequest(method, endpoint, _writeHttpClient, entity); extractResponse(response); } catch (UnsupportedEncodingException ex) { throw new SystemException("Error posting data", ex); } } } } /* Helper to create the read and write clients. */ protected CloseableHttpClient getClient(int connCount, int connTimeout, int socketTimeout, int connectionReuseCount, String...endpoints) throws MalformedURLException { PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(); connMgr.setMaxTotal(connCount); for(String endpoint : endpoints) { URL url = new URL(endpoint); int port = url.getPort(); requireArgument(port != -1, "TSDB endpoint must include explicit port."); HttpHost host = new HttpHost(url.getHost(), url.getPort()); connMgr.setMaxPerRoute(new HttpRoute(host), connCount / endpoints.length); } RequestConfig reqConfig = RequestConfig.custom().setConnectionRequestTimeout(connTimeout).setConnectTimeout(connTimeout).setSocketTimeout( socketTimeout).build(); if(connectionReuseCount>0) { return HttpClients.custom().setConnectionManager(connMgr).setConnectionReuseStrategy(new TSDBReadConnectionReuseStrategy(connectionReuseCount)).setDefaultRequestConfig(reqConfig).build(); }else { return HttpClients.custom().setConnectionManager(connMgr).setDefaultRequestConfig(reqConfig).build(); } } /* * Helper method to extract the HTTP response and close the client connection. Please note that <tt>ByteArrayOutputStreams</tt> do not require to * be closed. */ private String extractStringResponse(HttpResponse content) { requireArgument(content != null, "Response content is null."); String result; HttpEntity entity = null; try { entity = content.getEntity(); if (entity == null) { result = ""; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); entity.writeTo(baos); result = baos.toString("UTF-8"); } return result; } catch (IOException ex) { throw new SystemException(ex); } finally { if (entity != null) { try { EntityUtils.consume(entity); } catch (IOException ex) { _logger.warn("Failed to close entity stream.", ex); } } } } /* Helper method to convert JSON String representation to the corresponding Java entity. */ protected <T> T toEntity(String content, TypeReference<T> type) { try { return _mapper.readValue(content, type); } catch (IOException ex) { throw new SystemException(ex); } } /* Helper method to convert a Java entity to a JSON string. */ protected <T> String fromEntity(T type) { try { return _mapper.writeValueAsString(type); } catch (JsonProcessingException ex) { throw new SystemException(ex); } } /* Helper to process the response. */ protected String extractResponse(HttpResponse response) { if (response != null) { int status = response.getStatusLine().getStatusCode(); if ((status < HttpStatus.SC_OK) || (status >= HttpStatus.SC_MULTIPLE_CHOICES)) { Map<String, Map<String, String>> errorMap = toEntity(extractStringResponse(response), new TypeReference<Map<String, Map<String, String>>>() { }); if (errorMap != null) { throw new SystemException("Error : " + errorMap.toString()); } else { throw new SystemException("Status code: " + status + " . Unknown error occurred. "); } } else { return extractStringResponse(response); } } return null; } /* Execute a request given by type requestType. */ protected HttpResponse executeHttpRequest(HttpMethod requestType, String url, CloseableHttpClient client, StringEntity entity) throws IOException { HttpResponse httpResponse = null; if (entity != null) { entity.setContentType("application/json"); } try { switch (requestType) { case POST: HttpPost post = new HttpPost(url); post.setEntity(entity); httpResponse = client.execute(post); break; case GET: HttpGet httpGet = new HttpGet(url); httpResponse = client.execute(httpGet); break; case DELETE: HttpDelete httpDelete = new HttpDelete(url); httpResponse = client.execute(httpDelete); break; case PUT: HttpPut httpput = new HttpPut(url); httpput.setEntity(entity); httpResponse = client.execute(httpput); break; default: throw new MethodNotSupportedException(requestType.toString()); } } catch (MethodNotSupportedException ex) { throw new SystemException(ex); } return httpResponse; } /** * This method partitions data points of a given metric. * * @param metric - metric whose data points to be fractured * * @return - list of chunks in descending order so that the last chunk will be of size of "firstChunkSize" */ private List<Metric> fractureMetric(Metric metric) { List<Metric> result = new ArrayList<>(); if (metric.getDatapoints().size() <= TSDB_DATAPOINTS_WRITE_MAX_SIZE) { result.add(metric); return result; } Metric tempMetric = new Metric(metric); Map<Long, Double> dataPoints = new LinkedHashMap<>(); int tempChunkSize = TSDB_DATAPOINTS_WRITE_MAX_SIZE; for (Map.Entry<Long, Double> dataPoint : metric.getDatapoints().entrySet()) { dataPoints.put(dataPoint.getKey(), dataPoint.getValue()); if (--tempChunkSize == 0) { tempMetric.setDatapoints(dataPoints); result.add(tempMetric); tempMetric = new Metric(metric); tempChunkSize = TSDB_DATAPOINTS_WRITE_MAX_SIZE; dataPoints = new LinkedHashMap<>(); } } if (!dataPoints.isEmpty()) { tempMetric.setDatapoints(dataPoints); result.add(tempMetric); } return result; } //~ Enums **************************************************************************************************************************************** /** * Enumerates the implementation specific configuration properties. * * @author Tom Valine (tvaline@salesforce.com) */ public enum Property { /** The TSDB read endpoint. */ TSD_ENDPOINT_READ("service.property.tsdb.endpoint.read", "http://localhost:4466,http://localhost:4467"), /** The TSDB write endpoint. */ TSD_ENDPOINT_WRITE("service.property.tsdb.endpoint.write", "http://localhost:4477,http://localhost:4488"), /** The TSDB connection timeout. */ TSD_ENDPOINT_CONNECTION_TIMEOUT("service.property.tsdb.endpoint.connection.timeout", "10000"), /** The TSDB socket connection timeout. */ TSD_ENDPOINT_SOCKET_TIMEOUT("service.property.tsdb.endpoint.socket.timeout", "10000"), /** The TSDB connection count. */ TSD_CONNECTION_COUNT("service.property.tsdb.connection.count", "2"), TSD_RETRY_COUNT("service.property.tsdb.retry.count", "3"), /** The TSDB backup read endpoint. */ TSD_ENDPOINT_BACKUP_READ("service.property.tsdb.endpoint.backup.read", "http://localhost:4466,http://localhost:4467"), TSDB_READ_CONNECTION_REUSE_COUNT("service.property.tsdb.read.connection.reuse.count", "2000"); private final String _name; private final String _defaultValue; private Property(String name, String defaultValue) { _name = name; _defaultValue = defaultValue; } /** * Returns the property name. * * @return The property name. */ public String getName() { return _name; } /** * Returns the default value for the property. * * @return The default value. */ public String getDefaultValue() { return _defaultValue; } } protected void instrumentQueryLatency(final MonitorService monitorService, final AnnotationQuery query, final long start, final String measurementType) { String timeWindow = QueryTimeWindow.getWindow(query.getEndTimestamp() - query.getStartTimestamp()); Map<String, String> tags = new HashMap<String, String>(); tags.put("type", measurementType); tags.put("timeWindow", timeWindow); tags.put("cached", "false"); monitorService.modifyCustomCounter(QUERY_LATENCY_COUNTER, (System.currentTimeMillis() - start), tags); monitorService.modifyCustomCounter(QUERY_COUNT_COUNTER, 1, tags); } /** * Enumeration of supported HTTP methods. * * @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com) */ protected enum HttpMethod { /** POST operation. */ POST, /** GET operation. */ GET, /** DELETE operation. */ DELETE, /** PUT operation. */ PUT; } //~ Inner Classes ******************************************************************************************************************************** /** * Helper entity to wrap multiple Annotation entities into a form closer to the TSDB metric form. * * @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com) */ static class AnnotationWrapper { String _uid; Annotation _annotation; AnnotationWrapper(String uid, Annotation annotation) { _uid = uid; _annotation = annotation; } Annotation getAnnotation() { return _annotation; } String getUid() { return _uid; } String getAnnotationKey() { return _annotation.getSource() + "." + _annotation.getId(); } public void setUid(String uid) { _uid = uid; } public void setAnnotation(Annotation annotation) { _annotation = annotation; } } /** * Helper entity to facilitate de-serialization. * * @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com) */ static class AnnotationWrappers extends ArrayList<AnnotationWrapper> { /** Comment for <code>serialVersionUID.</code> */ private static final long serialVersionUID = 1L; } /** * Helper class used to parallelize query execution. * * @author Bhinav Sura (bhinav.sura@salesforce.com) */ class QueryWorker implements Callable<List<Metric>> { private final String _requestUrl; private final String _requestEndPoint; private final String _requestBody; /** * Creates a new QueryWorker object. * * @param requestUrl The URL to which the request will be issued. * @param requestEndPoint The endpoint to which the request will be issued. * @param requestBody The request body. */ public QueryWorker(String requestUrl, String requestEndPoint, String requestBody) { this._requestUrl = requestUrl; this._requestEndPoint = requestEndPoint; this._requestBody = requestBody; } @Override public List<Metric> call() { _logger.debug("TSDB requestUrl {} requestBody {}", _requestUrl, _requestBody); try { HttpResponse response = executeHttpRequest(HttpMethod.POST, _requestUrl, _readPortMap.get(_requestEndPoint), new StringEntity(_requestBody)); List<Metric> metrics = toEntity(extractResponse(response), new TypeReference<ResultSet>() { }).getMetrics(); return metrics; } catch (IOException e) { throw new SystemException("Failed to retrieve metrics.", e); } } } @Override public Properties getServiceProperties() { throw new UnsupportedOperationException("This method should be overriden by a specific implementation."); } @Override public Map<MetricQuery, List<Metric>> getMetrics(List<MetricQuery> queries) { throw new UnsupportedOperationException("This method should be overriden by a specific implementation."); } @Override public List<Annotation> getAnnotations(List<AnnotationQuery> queries) { throw new UnsupportedOperationException("This method should be overriden by a specific implementation."); } /** * Used to close http connections after reusing the same connection for certain number of times * @author rsarkapally * */ class TSDBReadConnectionReuseStrategy implements ConnectionReuseStrategy{ int connectionReuseCount; AtomicInteger numOfTimesReused = new AtomicInteger(1); public TSDBReadConnectionReuseStrategy(int connectionReuseCount) { this.connectionReuseCount=connectionReuseCount; } @Override public boolean keepAlive(HttpResponse response, HttpContext context) { HttpClientContext httpContext = (HttpClientContext) context; _logger.debug("http connection {} reused for {} times", httpContext.getConnection(), httpContext.getConnection().getMetrics().getRequestCount()); if (numOfTimesReused.getAndIncrement() % connectionReuseCount == 0) { numOfTimesReused.set(1); return false; } return true; } } } /* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Iterator; import javax.annotation.Nullable; /** * A function from {@code A} to {@code B} with an associated <i>reverse</i> function from {@code B} * to {@code A}; used for converting back and forth between <i>different representations of the same * information</i>. * * <h3>Invertibility</h3> * * <p>The reverse operation <b>may</b> be a strict <i>inverse</i> (meaning that {@code * converter.reverse().convert(converter.convert(a)).equals(a)} is always true). However, it is * very common (perhaps <i>more</i> common) for round-trip conversion to be <i>lossy</i>. Consider * an example round-trip using {@link com.google.common.primitives.Doubles#stringConverter}: * * <ol> * <li>{@code stringConverter().convert("1.00")} returns the {@code Double} value {@code 1.0} * <li>{@code stringConverter().reverse().convert(1.0)} returns the string {@code "1.0"} -- * <i>not</i> the same string ({@code "1.00"}) we started with * </ol> * * <p>Note that it should still be the case that the round-tripped and original objects are * <i>similar</i>. * * <h3>Nullability</h3> * * <p>A converter always converts {@code null} to {@code null} and non-null references to non-null * references. It would not make sense to consider {@code null} and a non-null reference to be * "different representations of the same information", since one is distinguishable from * <i>missing</i> information and the other is not. The {@link #convert} method handles this null * behavior for all converters; implementations of {@link #doForward} and {@link #doBackward} are * guaranteed to never be passed {@code null}, and must never return {@code null}. * * <h3>Common ways to use</h3> * * <p>Getting a converter: * * <ul> * <li>Use a provided converter implementation, such as {@link Enums#stringConverter}, {@link * com.google.common.primitives.Ints#stringConverter Ints.stringConverter} or the {@linkplain * #reverse reverse} views of these. * <li>Convert between specific preset values using {@link * com.google.common.collect.Maps#asConverter Maps.asConverter}. For example, use this to create * a "fake" converter for a unit test. It is unnecessary (and confusing) to <i>mock</i> the * {@code Converter} type using a mocking framework. * <li>Otherwise, extend this class and implement its {@link #doForward} and {@link #doBackward} * methods. * </ul> * * <p>Using a converter: * * <ul> * <li>Convert one instance in the "forward" direction using {@code converter.convert(a)}. * <li>Convert multiple instances "forward" using {@code converter.convertAll(as)}. * <li>Convert in the "backward" direction using {@code converter.reverse().convert(b)} or {@code * converter.reverse().convertAll(bs)}. * <li>Use {@code converter} or {@code converter.reverse()} anywhere a {@link Function} is accepted * <li><b>Do not</b> call {@link #doForward} or {@link #doBackward} directly; these exist only to be * overridden. * </ul> * * @author Mike Ward * @author Kurt Alfred Kluever * @author Gregory Kick * @since 16.0 */ @Beta @GwtCompatible public abstract class Converter<A, B> implements Function<A, B> { private final boolean handleNullAutomatically; // We lazily cache the reverse view to avoid allocating on every call to reverse(). private transient Converter<B, A> reverse; /** Constructor for use by subclasses. */ protected Converter() { this(true); } /** * Constructor used only by {@code LegacyConverter} to suspend automatic null-handling. */ Converter(boolean handleNullAutomatically) { this.handleNullAutomatically = handleNullAutomatically; } // SPI methods (what subclasses must implement) /** * Returns a representation of {@code a} as an instance of type {@code B}. If {@code a} cannot be * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. * * @param a the instance to convert; will never be null * @return the converted instance; <b>must not</b> be null */ protected abstract B doForward(A a); /** * Returns a representation of {@code b} as an instance of type {@code A}. If {@code b} cannot be * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. * * @param b the instance to convert; will never be null * @return the converted instance; <b>must not</b> be null * @throws UnsupportedOperationException if backward conversion is not implemented; this should be * very rare. Note that if backward conversion is not only unimplemented but * unimplement<i>able</i> (for example, consider a {@code Converter<Chicken, ChickenNugget>}), * then this is not logically a {@code Converter} at all, and should just implement {@link * Function}. */ protected abstract A doBackward(B b); // API (consumer-side) methods /** * Returns a representation of {@code a} as an instance of type {@code B}. * * @return the converted value; is null <i>if and only if</i> {@code a} is null */ @Nullable public final B convert(@Nullable A a) { return correctedDoForward(a); } @Nullable B correctedDoForward(@Nullable A a) { if (handleNullAutomatically) { // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? return a == null ? null : checkNotNull(doForward(a)); } else { return doForward(a); } } @Nullable A correctedDoBackward(@Nullable B b) { if (handleNullAutomatically) { // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? return b == null ? null : checkNotNull(doBackward(b)); } else { return doBackward(b); } } /** * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The * conversion is done lazily. * * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding * element. */ public Iterable<B> convertAll(final Iterable<? extends A> fromIterable) { checkNotNull(fromIterable, "fromIterable"); return new Iterable<B>() { @Override public Iterator<B> iterator() { return new Iterator<B>() { private final Iterator<? extends A> fromIterator = fromIterable.iterator(); @Override public boolean hasNext() { return fromIterator.hasNext(); } @Override public B next() { return convert(fromIterator.next()); } @Override public void remove() { fromIterator.remove(); } }; } }; } /** * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a * value roughly equivalent to {@code a}. * * <p>The returned converter is serializable if {@code this} converter is. */ // TODO(user): Make this method final public Converter<B, A> reverse() { Converter<B, A> result = reverse; return (result == null) ? reverse = new ReverseConverter<A, B>(this) : result; } private static final class ReverseConverter<A, B> extends Converter<B, A> implements Serializable { final Converter<A, B> original; ReverseConverter(Converter<A, B> original) { this.original = original; } /* * These gymnastics are a little confusing. Basically this class has neither legacy nor * non-legacy behavior; it just needs to let the behavior of the backing converter shine * through. So, we override the correctedDo* methods, after which the do* methods should never * be reached. */ @Override protected A doForward(B b) { throw new AssertionError(); } @Override protected B doBackward(A a) { throw new AssertionError(); } @Override @Nullable A correctedDoForward(@Nullable B b) { return original.correctedDoBackward(b); } @Override @Nullable B correctedDoBackward(@Nullable A a) { return original.correctedDoForward(a); } @Override public Converter<A, B> reverse() { return original; } @Override public boolean equals(@Nullable Object object) { if (object instanceof ReverseConverter) { ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object; return this.original.equals(that.original); } return false; } @Override public int hashCode() { return ~original.hashCode(); } @Override public String toString() { return original + ".reverse()"; } private static final long serialVersionUID = 0L; } /** * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result * of this converter. Its {@code reverse} method applies the converters in reverse order. * * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter} * are. */ public <C> Converter<A, C> andThen(Converter<B, C> secondConverter) { return new ConverterComposition<A, B, C>(this, checkNotNull(secondConverter)); } private static final class ConverterComposition<A, B, C> extends Converter<A, C> implements Serializable { final Converter<A, B> first; final Converter<B, C> second; ConverterComposition(Converter<A, B> first, Converter<B, C> second) { this.first = first; this.second = second; } /* * These gymnastics are a little confusing. Basically this class has neither legacy nor * non-legacy behavior; it just needs to let the behaviors of the backing converters shine * through (which might even differ from each other!). So, we override the correctedDo* methods, * after which the do* methods should never be reached. */ @Override protected C doForward(A a) { throw new AssertionError(); } @Override protected A doBackward(C c) { throw new AssertionError(); } @Override @Nullable C correctedDoForward(@Nullable A a) { return second.correctedDoForward(first.correctedDoForward(a)); } @Override @Nullable A correctedDoBackward(@Nullable C c) { return first.correctedDoBackward(second.correctedDoBackward(c)); } @Override public boolean equals(@Nullable Object object) { if (object instanceof ConverterComposition) { ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object; return this.first.equals(that.first) && this.second.equals(that.second); } return false; } @Override public int hashCode() { return 31 * first.hashCode() + second.hashCode(); } @Override public String toString() { return first + ".andThen(" + second + ")"; } private static final long serialVersionUID = 0L; } /** * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead. */ @Deprecated @Override @Nullable public final B apply(@Nullable A a) { return convert(a); } /** * Indicates whether another object is equal to this converter. * * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. * However, an implementation may also choose to return {@code true} whenever {@code object} is a * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable" * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false} * result from this method does not imply that the converters are known <i>not</i> to be * interchangeable. */ @Override public boolean equals(@Nullable Object object) { return super.equals(object); } // Static converters /** * Returns a serializable converter that always converts or reverses an object to itself. */ @SuppressWarnings("unchecked") // implementation is "fully variant" public static <T> Converter<T, T> identity() { return (IdentityConverter<T>) IdentityConverter.INSTANCE; } /** * A converter that always converts or reverses an object to itself. Note that T is now a * "pass-through type". */ private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable { static final IdentityConverter INSTANCE = new IdentityConverter(); @Override protected T doForward(T t) { return t; } @Override protected T doBackward(T t) { return t; } @Override public IdentityConverter<T> reverse() { return this; } @Override public <S> Converter<T, S> andThen(Converter<T, S> otherConverter) { return checkNotNull(otherConverter, "otherConverter"); } /* * We *could* override convertAll() to return its input, but it's a rather pointless * optimization and opened up a weird type-safety problem. */ @Override public String toString() { return "Converter.identity()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0L; } }
package com.ctrip.platform.dal.dao.sqlbuilder; import junit.framework.Assert; import org.junit.Test; import java.sql.SQLException; public class AbstractFreeSqlBuilderMeltdownWithSpaceSkipDisabledTest { private static final String logicDbName = "dao_test_sqlsvr_tableShard"; private static final String tableName = "dal_client_test"; @Test public void testEqual() throws SQLException { validate("equal", "[a] = ?"); validate("equalNull", ""); validate("equal AND equal", "[a] = ? AND [a] = ?"); validate("equal AND equalNull", "[a] = ?"); validate("equalNull AND equal", "[a] = ?"); validate("equalNull AND equalNull", ""); validate("( equal )", "( [a] = ? )"); validate("( equalNull )", ""); validate("( equal AND equal )", "( [a] = ? AND [a] = ? )"); validate("( equal AND equalNull )", "( [a] = ? )"); validate("( equalNull AND equal )", "( [a] = ? )"); validate("( equalNull AND equalNull )", ""); } @Test public void testLike() throws SQLException { validate("like", "[a] LIKE ?"); validate("likeNull", ""); validate("like AND like", "[a] LIKE ? AND [a] LIKE ?"); validate("like AND likeNull", "[a] LIKE ?"); validate("likeNull AND like", "[a] LIKE ?"); validate("likeNull AND likeNull", ""); validate("( like )", "( [a] LIKE ? )"); validate("( likeNull )", ""); validate("( like AND like )", "( [a] LIKE ? AND [a] LIKE ? )"); validate("( like AND likeNull )", "( [a] LIKE ? )"); validate("( likeNull AND like )", "( [a] LIKE ? )"); validate("( likeNull AND likeNull )", ""); } @Test public void testBetween() throws SQLException { validate("between", "[a] BETWEEN ? AND ?"); validate("betweenNull", ""); validate("between AND between", "[a] BETWEEN ? AND ? AND [a] BETWEEN ? AND ?"); validate("between AND betweenNull", "[a] BETWEEN ? AND ?"); validate("betweenNull AND between", "[a] BETWEEN ? AND ?"); validate("betweenNull AND betweenNull", ""); validate("( between )", "( [a] BETWEEN ? AND ? )"); validate("( betweenNull )", ""); validate("( between AND between )", "( [a] BETWEEN ? AND ? AND [a] BETWEEN ? AND ? )"); validate("( between AND betweenNull )", "( [a] BETWEEN ? AND ? )"); validate("( betweenNull AND between )", "( [a] BETWEEN ? AND ? )"); validate("( betweenNull AND betweenNull )", ""); } @Test public void testIsNull() throws SQLException { validate("isNull", "[a] IS NULL"); validate("isNull AND isNull", "[a] IS NULL AND [a] IS NULL"); validate("( isNull )", "( [a] IS NULL )"); validate("( isNull AND isNull )", "( [a] IS NULL AND [a] IS NULL )"); } @Test public void testIsNotNull() throws SQLException { validate("isNotNull", "[a] IS NOT NULL"); validate("isNotNull AND isNotNull", "[a] IS NOT NULL AND [a] IS NOT NULL"); validate("( isNotNull )", "( [a] IS NOT NULL )"); validate("( isNotNull AND isNotNull )", "( [a] IS NOT NULL AND [a] IS NOT NULL )"); } @Test public void testIn() throws SQLException { validate("in", "[a] IN ( ? )"); validate("in AND in", "[a] IN ( ? ) AND [a] IN ( ? )"); validate("inNull AND in", "[a] IN ( ? )"); validate("in AND inNull", "[a] IN ( ? )"); validate("in AND inNull OR in AND inNull", "[a] IN ( ? ) OR [a] IN ( ? )"); validate("in AND inNull OR in AND inNull AND in OR inNull", "[a] IN ( ? ) OR [a] IN ( ? ) AND [a] IN ( ? )"); validate("( in AND inNull ) OR ( in AND inNull AND in OR inNull OR in )", "( [a] IN ( ? ) ) OR ( [a] IN ( ? ) AND [a] IN ( ? ) OR [a] IN ( ? ) )"); validate("( in ) OR ( in )", "( [a] IN ( ? ) ) OR ( [a] IN ( ? ) )"); validate("( ( in ) OR in ) OR ( in OR ( in ) )", "( ( [a] IN ( ? ) ) OR [a] IN ( ? ) ) OR ( [a] IN ( ? ) OR ( [a] IN ( ? ) ) )"); validate("( ( in ) OR in AND inNull ) OR ( in OR ( in ) )", "( ( [a] IN ( ? ) ) OR [a] IN ( ? ) ) OR ( [a] IN ( ? ) OR ( [a] IN ( ? ) ) )"); validate("( ( ( in ) OR in AND inNull ) OR ( in OR ( in ) ) )", "( ( ( [a] IN ( ? ) ) OR [a] IN ( ? ) ) OR ( [a] IN ( ? ) OR ( [a] IN ( ? ) ) ) )"); validate("( ( ( in ) OR in AND inNull ) OR ( ( in OR ( in ) ) ) )", "( ( ( [a] IN ( ? ) ) OR [a] IN ( ? ) ) OR ( ( [a] IN ( ? ) OR ( [a] IN ( ? ) ) ) ) )"); } @Test public void testNotIn() throws SQLException { validate("notIn", "[a] NOT IN ( ? )"); validate("notIn AND notIn", "[a] NOT IN ( ? ) AND [a] NOT IN ( ? )"); validate("notInNull AND notIn", "[a] NOT IN ( ? )"); validate("notIn AND notInNull", "[a] NOT IN ( ? )"); validate("notIn AND notInNull OR notIn AND notInNull", "[a] NOT IN ( ? ) OR [a] NOT IN ( ? )"); validate("notIn AND notInNull OR notIn AND notInNull AND notIn OR notInNull", "[a] NOT IN ( ? ) OR [a] NOT IN ( ? ) AND [a] NOT IN ( ? )"); validate("( notIn AND notInNull ) OR ( notIn AND notInNull AND notIn OR notInNull OR notIn )", "( [a] NOT IN ( ? ) ) OR ( [a] NOT IN ( ? ) AND [a] NOT IN ( ? ) OR [a] NOT IN ( ? ) )"); validate("( notIn ) OR ( notIn )", "( [a] NOT IN ( ? ) ) OR ( [a] NOT IN ( ? ) )"); validate("( ( notIn ) OR notIn ) OR ( notIn OR ( notIn ) )", "( ( [a] NOT IN ( ? ) ) OR [a] NOT IN ( ? ) ) OR ( [a] NOT IN ( ? ) OR ( [a] NOT IN ( ? ) ) )"); validate("( ( notIn ) OR notIn AND notInNull ) OR ( notIn OR ( notIn ) )", "( ( [a] NOT IN ( ? ) ) OR [a] NOT IN ( ? ) ) OR ( [a] NOT IN ( ? ) OR ( [a] NOT IN ( ? ) ) )"); validate("( ( ( notIn ) OR notIn AND notInNull ) OR ( notIn OR ( notIn ) ) )", "( ( ( [a] NOT IN ( ? ) ) OR [a] NOT IN ( ? ) ) OR ( [a] NOT IN ( ? ) OR ( [a] NOT IN ( ? ) ) ) )"); validate("( ( ( notIn ) OR notIn AND notInNull ) OR ( ( notIn OR ( notIn ) ) ) )", "( ( ( [a] NOT IN ( ? ) ) OR [a] NOT IN ( ? ) ) OR ( ( [a] NOT IN ( ? ) OR ( [a] NOT IN ( ? ) ) ) ) )"); } @Test public void testNot() throws SQLException { validate("NOT equal", "NOT [a] = ?"); validate("NOT equalNull", ""); validate("NOT NOT NOT equal", "NOT NOT NOT [a] = ?"); validate("NOT NOT NOT equalNull", ""); validate("NOT equal AND NOT equal", "NOT [a] = ? AND NOT [a] = ?"); validate("NOT equal AND NOT equalNull", "NOT [a] = ?"); validate("NOT equalNull AND NOT equal", "NOT [a] = ?"); validate("NOT equalNull AND NOT equalNull", ""); validate("( NOT equal )", "( NOT [a] = ? )"); validate("( NOT NOT NOT equal )", "( NOT NOT NOT [a] = ? )"); validate("( NOT equalNull )", ""); validate("( NOT NOT NOT equalNull )", ""); validate("( NOT equal AND NOT equal )", "( NOT [a] = ? AND NOT [a] = ? )"); validate("( NOT equal AND NOT equalNull )", "( NOT [a] = ? )"); validate("( NOT equalNull AND NOT equal )", "( NOT [a] = ? )"); validate("( NOT equalNull AND NOT equalNull )", ""); } @Test public void testBracket() throws SQLException { validate("( ( equalNull ) )", ""); validate("( ( ( equalNull ) ) )", ""); validate("( ( ( equalNull ) ) ) AND ( ( ( equalNull ) ) )", ""); validate("( ( ( equalNull ) ) ) OR ( ( ( equalNull ) ) )", ""); validate("NOT ( NOT ( NOT ( NOT equalNull ) ) ) OR ( ( ( equalNull ) ) )", ""); } @Test public void testOr() throws SQLException { validate("equal OR equal", "[a] = ? OR [a] = ?"); validate("equal AND ( equal OR equal )", "[a] = ? AND ( [a] = ? OR [a] = ? )"); } public void validate(String exp, String expected) throws SQLException { AbstractFreeSqlBuilder builder = new AbstractFreeSqlBuilder().setLogicDbName(logicDbName); builder.disableSpaceSkipping(); // equal equalNull between betweenNull in inNull like likeNull isNull isNotNull AND OR NOT ( ) String[] tokens = exp.split(" "); for(String token: tokens) { switch (token) { case "equal": builder.equal("a"); break; case "equalNull": builder.equal("a").ignoreNull(null); break; case "like": builder.like("a"); break; case "likeNull": builder.like("a").ignoreNull(null); break; case "isNull": builder.isNull("a"); break; case "isNotNull": builder.isNotNull("a"); break; case "in": builder.in("a"); break; case "notIn": builder.notIn("a"); break; case "inNull": builder.in("a").ignoreNull(null); break; case "notInNull": builder.notIn("a").ignoreNull(null); break; case "between": builder.between("a"); break; case "betweenNull": builder.between("a").ignoreNull(null); break; case "AND": builder.and(); break; case "OR": builder.or(); break; case "NOT": builder.not(); break; case "(": builder.leftBracket(); break; case ")": builder.rightBracket(); break; default: Assert.fail("Unknown token: " + token); } } Assert.assertEquals(expected, builder.build()); } }
// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium; import android.content.Context; import android.content.Intent; import android.net.Proxy; import android.util.ArrayMap; import java.lang.System; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class ChromeProxy extends CordovaPlugin { private static final String LOG_TAG = "ChromeProxy"; private JSONObject config = new JSONObject(); @Override public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException { if ("get".equals(action)) { get(args, callbackContext); return true; } else if ("set".equals(action)) { set(args, callbackContext); return true; } else if ("clear".equals(action)) { clear(args, callbackContext); return true; } return false; } private void get(final CordovaArgs args, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { // Ignoring scope. // Arguably, this should use System.getProperty to see if somehow // the proxy settings were already set... callbackContext.success(config); } }); } private void setHttpProxy(JSONObject rule, String prefix, String nonProxyHosts) throws JSONException { String scheme = rule.getString("scheme"); if (!"http".equals(scheme)) { throw new JSONException("Scheme must be http"); } String host = rule.getString("host"); int port = rule.has("port") ? rule.getInt("port") : 80; String portString = Integer.toString(port); System.setProperty(prefix + ".proxyHost", host); System.setProperty(prefix + ".proxyPort", portString); if (nonProxyHosts != null) { System.setProperty(prefix + ".nonProxyHosts", nonProxyHosts); } } private void set(final CordovaArgs args, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { // Ignoring scope. JSONObject details; try { details = args.getJSONObject(0); } catch (JSONException e) { callbackContext.error("Failed to parse details as JSON"); return; } try { if (details.has("value")) { config = details.getJSONObject("value"); String mode = config.getString("mode"); if (!"fixed_servers".equals(mode) && !"direct".equals(mode)) { callbackContext.error("Mode must be fixed_servers or direct"); return; } if ("direct".equals(mode)) { clear(args, callbackContext); return; } } else { callbackContext.error("Missing value"); } } catch (JSONException e) { callbackContext.error("Failed to parse value as JSON"); } try { JSONObject rules = config.getJSONObject("rules"); String nonProxyHosts = null; if (rules.has("bypassList")) { JSONArray bypassList = rules.getJSONArray("bypassList"); nonProxyHosts = bypassList.join("|"); } if (rules.has("singleProxy")) { JSONObject rule = rules.getJSONObject("singleProxy"); String scheme = rule.getString("scheme"); if ("socks5".equals(scheme)) { if (nonProxyHosts != null) { callbackContext.error("nonProxyHosts not supported with socks"); return; } String host = rule.getString("host"); int port = rule.has("port") ? rule.getInt("port") : 1080; String portString = Integer.toString(port); System.setProperty("socksProxyHost", host); System.setProperty("socksProxyPort", portString); } else if ("http".equals(scheme)) { setHttpProxy(rule, "http", nonProxyHosts); setHttpProxy(rule, "https", nonProxyHosts); setHttpProxy(rule, "ftp", nonProxyHosts); } else { callbackContext.error("Scheme must be socks5 or http"); return; } } else { if (rules.has("proxyForHttp")) { JSONObject rule = rules.getJSONObject("httpProxy"); setHttpProxy(rule, "http", nonProxyHosts); } if (rules.has("proxyForHttps")) { JSONObject rule = rules.getJSONObject("proxyForHttps"); setHttpProxy(rule, "https", nonProxyHosts); } if (rules.has("proxyForFtp")) { JSONObject rule = rules.getJSONObject("proxyForFtp"); setHttpProxy(rule, "ftp", nonProxyHosts); } } onSettingsChanged(); callbackContext.success(); } catch (JSONException e) { callbackContext.error("Failed to parse rule(s) as JSON"); } catch (Exception e) { callbackContext.error("Other error"); } } }); } private void clear(final CordovaArgs args, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { System.clearProperty("socksProxyHost"); System.clearProperty("socksProxyPort"); System.clearProperty("http.proxyHost"); System.clearProperty("http.proxyPort"); System.clearProperty("http.nonProxyHosts"); System.clearProperty("https.proxyHost"); System.clearProperty("https.proxyPort"); System.clearProperty("https.nonProxyHosts"); System.clearProperty("ftp.proxyHost"); System.clearProperty("ftp.proxyPort"); System.clearProperty("ftp.nonProxyHosts"); onSettingsChanged(); } }); } private void onSettingsChanged() { Context appContext = this.cordova.getActivity().getApplicationContext(); // See http://stackoverflow.com/questions/32245972/android-webview-non-fqdn-urls-not-routing-through-proxy-on-lollipop // and https://crbug.com/525945 for the source of this pattern. try { Class<?> applicationClass = Class.forName("android.app.Application"); Field mLoadedApkField = applicationClass.getDeclaredField("mLoadedApk"); mLoadedApkField.setAccessible(true); Object mloadedApk = mLoadedApkField.get(appContext); Class<?> loadedApkClass = Class.forName("android.app.LoadedApk"); Field mReceiversField = loadedApkClass.getDeclaredField("mReceivers"); mReceiversField.setAccessible(true); ArrayMap<?, ?> receivers = (ArrayMap<?, ?>) mReceiversField.get(mloadedApk); for (Object receiverMap : receivers.values()) { for (Object receiver : ((ArrayMap<?, ?>) receiverMap).keySet()) { Class<?> clazz = receiver.getClass(); if (clazz.getName().contains("ProxyChangeListener")) { Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class); Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); onReceiveMethod.invoke(receiver, appContext, intent); } } } } catch (Exception e) { // TODO } } }
package tk.fusselrulezz.ets2editor.util; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.MessageDigest; import java.text.DecimalFormat; import java.text.Normalizer; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtils { public static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray(); private static final char[] NUMBERS = "1234567890".toCharArray(); private static final char[] LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray(); private static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\s"); public static String toString(byte[] bytes, String charset) { return new String(bytes, Charset.forName(charset)); } public static String toString(Object[] array, String splitter, int offset, int stop){ String result = ""; for(int i = offset; i < stop; i++){ result += array[i] + splitter; } return result.substring(0, result.length() - splitter.length()); } public static String toString(Object[] array, String splitter, int offset){ return toString(array, splitter, offset, array.length); } public static String toString(Object[] array, String splitter){ return toString(array, splitter, 0); } public static String toString(Object[] array){ return toString(array, " ", 0); } public static String reverseCases(String string){ String result = ""; for(int i = 0; i < string.length(); i++){ char c = string.charAt(i); if(Character.isLowerCase(c)){ result += Character.toUpperCase(c); } else { result += Character.toLowerCase(c); } } return result; } public static boolean isNumeric(String string){ return string.matches("[+-]?[0-9]+"); } public static int toInteger(String numeric){ return (isNumeric(numeric)) ? Integer.parseInt(numeric) : 0; } public static float toFloat(String numeric){ return Float.parseFloat(numeric); } public static long toLong(String numeric){ return (isNumeric(numeric)) ? Long.parseLong(numeric) : 0; } public static short toShort(String numeric){ return (isNumeric(numeric)) ? Short.parseShort(numeric) : 0; } public static boolean toBoolean(String string) { if(string.equals("1") || string.equals("true")) { return true; } return false; } public static boolean isSurrounded(String string, String sequence){ return (string.startsWith(sequence) && string.endsWith(sequence)); } public static String removeSurroundings(String string, String sequence){ return (isSurrounded(string, sequence)) ? string.substring(sequence.length(), string.length() - sequence.length()) : string; } public static String addSurroundings(String value, String sequence) { return sequence + value + sequence; } public static String formatDecimals(long number){ return new DecimalFormat().format(number); } public static String formatDecimals(long number, char separator){ return new DecimalFormat().format(number).replace(',', separator); } public static String formatDecimals(double number){ return new DecimalFormat().format(number); } public static String formatDecimals(double number, char separator){ return new DecimalFormat().format(number).replace(',', separator); } public static String upperFirstChar(String string){ return Character.toUpperCase(string.charAt(0)) + string.substring(1); } public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_CHARS[v >>> 4]; hexChars[j * 2 + 1] = HEX_CHARS[v & 0x0F]; } return new String(hexChars); } public static String md5(String string) { try { return bytesToHex(MessageDigest.getInstance("md5").digest(string.getBytes("UTF-8"))); } catch (Exception e) { return string; } } public static String addZeros(int number, int length) { String result = String.valueOf(number); while(result.length() < length) result = "0" + result; return result; } public static String replace(String source, String[] oldStrings, String[] newStrings) { if(oldStrings.length == newStrings.length) { for(int i = 0; i < newStrings.length; i++) { source = source.replace(oldStrings[i], newStrings[i]); } } return source; } public static boolean isLetter(char c) { for(int i = 0; i < LETTERS.length; i++) { if(LETTERS[i] == c) return true; } return false; } public static boolean isNumber(char c) { for(int i = 0; i < NUMBERS.length; i++) { if(NUMBERS[i] == c) return true; } return false; } public static boolean isHexChar(char c) { for(int i = 0; i < HEX_CHARS.length; i++) { if(HEX_CHARS[i] == c) return true; } return false; } public static String[] splitSpaces(String subject) { List<String> matchList = new ArrayList<String>(); Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'"); Matcher regexMatcher = regex.matcher(subject); while (regexMatcher.find()) { String group = regexMatcher.group(); if(group.trim().startsWith("\"") && group.trim().endsWith("\"") && matchList.size() > 1) { String before = matchList.get(matchList.size() - 1); matchList.set(matchList.size() - 1, before + group); } else { matchList.add(group); } } return matchList.toArray(new String[0]); } public static String convertCharset(String string, String source, String result) { try { return new String(string.getBytes(source), result); } catch (UnsupportedEncodingException e) { return null; } } public static String normalize(String string) { if(string != null) { Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); String decomposed = Normalizer.normalize(string, Normalizer.Form.NFD); return pattern.matcher(decomposed).replaceAll(""); } else { return null; } } public static boolean requiresQuotationMarks(String string) { return PATTERN_WHITESPACE.matcher(string).find(); } public static String getRandomHexString(int numchars){ Random r = new Random(); StringBuffer sb = new StringBuffer(); while(sb.length() < numchars){ sb.append(Integer.toHexString(r.nextInt())); } return sb.toString().substring(0, numchars).toUpperCase(); } }
/* * 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.trino.sql.planner.iterative.rule; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.trino.sql.planner.iterative.rule.test.BaseRuleTest; import io.trino.sql.planner.iterative.rule.test.PlanBuilder; import io.trino.sql.planner.plan.Assignments; import io.trino.sql.planner.plan.JoinNode; import org.testng.annotations.Test; import java.util.Optional; import static io.trino.spi.type.BigintType.BIGINT; import static io.trino.sql.planner.assertions.PlanMatchPattern.aggregation; import static io.trino.sql.planner.assertions.PlanMatchPattern.assignUniqueId; import static io.trino.sql.planner.assertions.PlanMatchPattern.expression; import static io.trino.sql.planner.assertions.PlanMatchPattern.filter; import static io.trino.sql.planner.assertions.PlanMatchPattern.functionCall; import static io.trino.sql.planner.assertions.PlanMatchPattern.join; import static io.trino.sql.planner.assertions.PlanMatchPattern.project; import static io.trino.sql.planner.assertions.PlanMatchPattern.singleGroupingSet; import static io.trino.sql.planner.assertions.PlanMatchPattern.values; import static io.trino.sql.planner.plan.AggregationNode.Step.SINGLE; import static io.trino.sql.planner.plan.JoinNode.Type.LEFT; public class TestTransformCorrelatedGlobalAggregationWithoutProjection extends BaseRuleTest { @Test public void doesNotFireOnPlanWithoutCorrelatedJoinNode() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.values(p.symbol("a"))) .doesNotFire(); } @Test public void doesNotFireOnCorrelatedWithoutAggregation() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.values(p.symbol("a")))) .doesNotFire(); } @Test public void doesNotFireOnUncorrelated() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(), p.values(p.symbol("a")), p.values(p.symbol("b")))) .doesNotFire(); } @Test public void doesNotFireOnCorrelatedWithNonScalarAggregation() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.aggregation(ab -> ab .source(p.values(p.symbol("a"), p.symbol("b"))) .addAggregation(p.symbol("sum"), PlanBuilder.expression("sum(a)"), ImmutableList.of(BIGINT)) .singleGroupingSet(p.symbol("b"))))) .doesNotFire(); } @Test public void doesNotFireOnMultipleProjections() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.project( Assignments.of(p.symbol("expr_2"), PlanBuilder.expression("expr - 1")), p.project( Assignments.of(p.symbol("expr"), PlanBuilder.expression("sum + 1")), p.aggregation(ab -> ab .source(p.values(p.symbol("a"), p.symbol("b"))) .addAggregation(p.symbol("sum"), PlanBuilder.expression("sum(a)"), ImmutableList.of(BIGINT)) .globalGrouping()))))) .doesNotFire(); } @Test public void rewritesOnSubqueryWithoutProjection() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.aggregation(ab -> ab .source(p.values(p.symbol("a"), p.symbol("b"))) .addAggregation(p.symbol("sum"), PlanBuilder.expression("sum(a)"), ImmutableList.of(BIGINT)) .globalGrouping()))) .matches( project(ImmutableMap.of("sum_1", expression("sum_1"), "corr", expression("corr")), aggregation(ImmutableMap.of("sum_1", functionCall("sum", ImmutableList.of("a"))), join(JoinNode.Type.LEFT, ImmutableList.of(), assignUniqueId("unique", values(ImmutableMap.of("corr", 0))), project(ImmutableMap.of("non_null", expression("true")), values(ImmutableMap.of("a", 0, "b", 1))))))); } @Test public void rewritesOnSubqueryWithProjection() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.project(Assignments.of(p.symbol("expr"), PlanBuilder.expression("sum + 1")), p.aggregation(ab -> ab .source(p.values(p.symbol("a"), p.symbol("b"))) .addAggregation(p.symbol("sum"), PlanBuilder.expression("sum(a)"), ImmutableList.of(BIGINT)) .globalGrouping())))) .doesNotFire(); } @Test public void testSubqueryWithCount() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.aggregation(ab -> ab .source(p.values(p.symbol("a"), p.symbol("b"))) .addAggregation(p.symbol("count_rows"), PlanBuilder.expression("count(*)"), ImmutableList.of()) .addAggregation(p.symbol("count_non_null_values"), PlanBuilder.expression("count(a)"), ImmutableList.of(BIGINT)) .globalGrouping()))) .matches( project( aggregation(ImmutableMap.of( "count_rows", functionCall("count", ImmutableList.of()), "count_non_null_values", functionCall("count", ImmutableList.of("a"))), join(JoinNode.Type.LEFT, ImmutableList.of(), assignUniqueId("unique", values(ImmutableMap.of("corr", 0))), project(ImmutableMap.of("non_null", expression("true")), values(ImmutableMap.of("a", 0, "b", 1))))))); } @Test public void rewritesOnSubqueryWithDistinct() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.aggregation(outerBuilder -> outerBuilder .addAggregation(p.symbol("sum"), PlanBuilder.expression("sum(a)"), ImmutableList.of(BIGINT)) .addAggregation(p.symbol("count"), PlanBuilder.expression("count()"), ImmutableList.of()) .globalGrouping() .source(p.aggregation(innerBuilder -> innerBuilder .singleGroupingSet(p.symbol("a")) .source(p.filter( PlanBuilder.expression("b > corr"), p.values(p.symbol("a"), p.symbol("b"))))))))) .matches( project(ImmutableMap.of("corr", expression("corr"), "sum_agg", expression("sum_agg"), "count_agg", expression("count_agg")), aggregation( singleGroupingSet("corr", "unique"), ImmutableMap.of(Optional.of("sum_agg"), functionCall("sum", ImmutableList.of("a")), Optional.of("count_agg"), functionCall("count", ImmutableList.of())), ImmutableList.of(), ImmutableList.of("non_null"), Optional.empty(), SINGLE, aggregation( singleGroupingSet("corr", "unique", "non_null", "a"), ImmutableMap.of(), Optional.empty(), SINGLE, join( LEFT, ImmutableList.of(), Optional.of("b > corr"), assignUniqueId( "unique", values("corr")), project( ImmutableMap.of("non_null", expression("true")), filter( "true", values("a", "b")))))))); } @Test public void testWithPreexistingMask() { tester().assertThat(new TransformCorrelatedGlobalAggregationWithoutProjection(tester().getPlannerContext())) .on(p -> p.correlatedJoin( ImmutableList.of(p.symbol("corr")), p.values(p.symbol("corr")), p.aggregation(ab -> ab .source(p.values(p.symbol("a"), p.symbol("mask"))) .addAggregation(p.symbol("count_non_null_values"), PlanBuilder.expression("count(a)"), ImmutableList.of(BIGINT), p.symbol("mask")) .globalGrouping()))) .matches( project( aggregation( singleGroupingSet("corr", "unique"), ImmutableMap.of(Optional.of("count_non_null_values"), functionCall("count", ImmutableList.of("a"))), ImmutableList.of(), ImmutableList.of("new_mask"), Optional.empty(), SINGLE, project( ImmutableMap.of("new_mask", expression("mask AND non_null")), join(JoinNode.Type.LEFT, ImmutableList.of(), assignUniqueId("unique", values(ImmutableMap.of("corr", 0))), project(ImmutableMap.of("non_null", expression("true")), values(ImmutableMap.of("a", 0, "mask", 1)))))))); } }
/* * @author Ramesh Lingappa */ package com.jmandrillapi.model.message; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import com.jmandrillapi.utils.ObjectUtils; /** * The Class MandrillMessage. */ public class MandrillMessage { /** The subaccount. */ private String html, text, subject, subaccount; /** The to. */ private List<Recipient> to; /** The tags. */ private List<String> tags; /** The metadata. */ private Map<String, String> headers, metadata; /** The merge. */ private boolean important, merge; /** The images. */ private List<MessageAttachment> attachments, images; /** The from email. */ @JsonProperty("from_email") private String fromEmail; /** The from name. */ @JsonProperty("from_name") private String fromName; /** The track opens. */ @JsonProperty("track_opens") private boolean trackOpens; /** The track clicks. */ @JsonProperty("track_clicks") private boolean trackClicks; /** The auto text. */ @JsonProperty("auto_text") private boolean autoText; /** The auto html. */ @JsonProperty("auto_html") private boolean autoHtml; /** The inline css. */ @JsonProperty("inline_css") private boolean inlineCss; /** The url strip qs. */ @JsonProperty("url_strip_qs") private boolean urlStripQs; /** The preserve recipients. */ @JsonProperty("preserve_recipients") private boolean preserveRecipients; /** The view content link. */ @JsonProperty("view_content_link") private boolean viewContentLink; /** The bcc address. */ @JsonProperty("bcc_address") private String bccAddress; /** The tracking domain. */ @JsonProperty("tracking_domain") private String trackingDomain; /** The signing domain. */ @JsonProperty("signing_domain") private String signingDomain; /** The return path domain. */ @JsonProperty("return_path_domain") private String returnPathDomain; /** The merge language. */ @JsonProperty("merge_language") private String mergeLanguage; /** The global merge vars. */ @JsonProperty("global_merge_vars") private List<MergeVar> globalMergeVars; /** The merge vars. */ @JsonProperty("merge_vars") private List<RecipientMergeVars> mergeVars; /** The google analytics domains. */ @JsonProperty("google_analytics_domains") private List<String> googleAnalyticsDomains; /** The google analytics campaign. */ @JsonProperty("google_analytics_campaign") private String googleAnalyticsCampaign; /** The recipient meta data. */ @JsonProperty("recipient_metadata") private List<RecipientMetadata> recipientMetaData; /** * Instantiates a new mandrill message. */ public MandrillMessage() { } /** * Instantiates a new mandrill message. * * @param fromEmail the from email * @param subject the subject */ public MandrillMessage(String fromEmail, String subject) { super(); this.fromEmail = fromEmail; this.subject = subject; } /** * Gets the html. * * @return the html */ public String getHtml() { return html; } /** * Sets the html. * * @param html the new html */ public void setHtml(String html) { this.html = html; } /** * Gets the text. * * @return the text */ public String getText() { return text; } /** * Sets the text. * * @param text the new text */ public void setText(String text) { this.text = text; } /** * Gets the subject. * * @return the subject */ public String getSubject() { return subject; } /** * Sets the subject. * * @param subject the new subject */ public void setSubject(String subject) { this.subject = subject; } /** * Gets the subaccount. * * @return the subaccount */ public String getSubaccount() { return subaccount; } /** * Sets the subaccount. * * @param subaccount the new subaccount */ public void setSubaccount(String subaccount) { this.subaccount = subaccount; } /** * Gets the to. * * @return the to */ public List<Recipient> getTo() { return to; } /** * Sets the to. * * @param to the new to */ public void setTo(List<Recipient> to) { this.to = to; } /** * Adds the to. * * @param recipient the recipient */ public void addTo(Recipient recipient) { this.to = ObjectUtils.addToList(to, recipient); } /** * Gets the tags. * * @return the tags */ public List<String> getTags() { return tags; } /** * Sets the tags. * * @param tags the new tags */ public void setTags(List<String> tags) { this.tags = tags; } /** * Adds the tags. * * @param tag the tag */ public void addTags(String tag) { this.tags = ObjectUtils.addToList(tags, tag); } /** * Gets the headers. * * @return the headers */ public Map<String, String> getHeaders() { return headers; } /** * Sets the headers. * * @param headers the headers */ public void setHeaders(Map<String, String> headers) { this.headers = headers; } /** * Adds the header. * * @param key the key * @param value the value */ public void addHeader(String key, String value) { this.headers = ObjectUtils.addToMap(this.headers, key, value); } /** * Gets the metadata. * * @return the metadata */ public Map<String, String> getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata the metadata */ public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } /** * Adds the meta data. * * @param key the key * @param value the value */ public void addMetaData(String key, String value) { this.metadata = ObjectUtils.addToMap(this.metadata, key, value); } /** * Checks if is important. * * @return true, if is important */ public boolean isImportant() { return important; } /** * Sets the important. * * @param important the new important */ public void setImportant(boolean important) { this.important = important; } /** * Checks if is merge. * * @return true, if is merge */ public boolean isMerge() { return merge; } /** * Sets the merge. * * @param merge the new merge */ public void setMerge(boolean merge) { this.merge = merge; } /** * Gets the attachments. * * @return the attachments */ public List<MessageAttachment> getAttachments() { return attachments; } /** * Sets the attachments. * * @param attachments the new attachments */ public void setAttachments(List<MessageAttachment> attachments) { this.attachments = attachments; } /** * Adds the attachment. * * @param attachment the attachment */ public void addAttachment(MessageAttachment attachment) { this.attachments = ObjectUtils.addToList(this.attachments, attachment); } /** * Gets the images. * * @return the images */ public List<MessageAttachment> getImages() { return images; } /** * Sets the images. * * @param images the new images */ public void setImages(List<MessageAttachment> images) { this.images = images; } /** * Adds the image. * * @param image the image */ public void addImage(MessageAttachment image) { this.images = ObjectUtils.addToList(this.images, image); } /** * Gets the from email. * * @return the from email */ public String getFromEmail() { return fromEmail; } /** * Sets the from email. * * @param fromEmail the new from email */ public void setFromEmail(String fromEmail) { this.fromEmail = fromEmail; } /** * Gets the from name. * * @return the from name */ public String getFromName() { return fromName; } /** * Sets the from name. * * @param fromName the new from name */ public void setFromName(String fromName) { this.fromName = fromName; } /** * Checks if is track opens. * * @return true, if is track opens */ public boolean isTrackOpens() { return trackOpens; } /** * Sets the track opens. * * @param trackOpens the new track opens */ public void setTrackOpens(boolean trackOpens) { this.trackOpens = trackOpens; } /** * Checks if is track clicks. * * @return true, if is track clicks */ public boolean isTrackClicks() { return trackClicks; } /** * Sets the track clicks. * * @param trackClicks the new track clicks */ public void setTrackClicks(boolean trackClicks) { this.trackClicks = trackClicks; } /** * Checks if is auto text. * * @return true, if is auto text */ public boolean isAutoText() { return autoText; } /** * Sets the auto text. * * @param autoText the new auto text */ public void setAutoText(boolean autoText) { this.autoText = autoText; } /** * Checks if is auto html. * * @return true, if is auto html */ public boolean isAutoHtml() { return autoHtml; } /** * Sets the auto html. * * @param autoHtml the new auto html */ public void setAutoHtml(boolean autoHtml) { this.autoHtml = autoHtml; } /** * Checks if is inline css. * * @return true, if is inline css */ public boolean isInlineCss() { return inlineCss; } /** * Sets the inline css. * * @param inlineCss the new inline css */ public void setInlineCss(boolean inlineCss) { this.inlineCss = inlineCss; } /** * Checks if is url strip qs. * * @return true, if is url strip qs */ public boolean isUrlStripQs() { return urlStripQs; } /** * Sets the url strip qs. * * @param urlStripQs the new url strip qs */ public void setUrlStripQs(boolean urlStripQs) { this.urlStripQs = urlStripQs; } /** * Checks if is preserve recipients. * * @return true, if is preserve recipients */ public boolean isPreserveRecipients() { return preserveRecipients; } /** * Sets the preserve recipients. * * @param preserveRecipients the new preserve recipients */ public void setPreserveRecipients(boolean preserveRecipients) { this.preserveRecipients = preserveRecipients; } /** * Checks if is view content link. * * @return true, if is view content link */ public boolean isViewContentLink() { return viewContentLink; } /** * Sets the view content link. * * @param viewContentLink the new view content link */ public void setViewContentLink(boolean viewContentLink) { this.viewContentLink = viewContentLink; } /** * Gets the bcc address. * * @return the bcc address */ public String getBccAddress() { return bccAddress; } /** * Sets the bcc address. * * @param bccAddress the new bcc address */ public void setBccAddress(String bccAddress) { this.bccAddress = bccAddress; } /** * Gets the tracking domain. * * @return the tracking domain */ public String getTrackingDomain() { return trackingDomain; } /** * Sets the tracking domain. * * @param trackingDomain the new tracking domain */ public void setTrackingDomain(String trackingDomain) { this.trackingDomain = trackingDomain; } /** * Gets the signing domain. * * @return the signing domain */ public String getSigningDomain() { return signingDomain; } /** * Sets the signing domain. * * @param signingDomain the new signing domain */ public void setSigningDomain(String signingDomain) { this.signingDomain = signingDomain; } /** * Gets the return path domain. * * @return the return path domain */ public String getReturnPathDomain() { return returnPathDomain; } /** * Sets the return path domain. * * @param returnPathDomain the new return path domain */ public void setReturnPathDomain(String returnPathDomain) { this.returnPathDomain = returnPathDomain; } /** * Gets the merge language. * * @return the merge language */ public String getMergeLanguage() { return mergeLanguage; } /** * Sets the merge language. * * @param mergeLanguage the new merge language */ public void setMergeLanguage(String mergeLanguage) { this.mergeLanguage = mergeLanguage; } /** * Gets the global merge vars. * * @return the global merge vars */ public List<MergeVar> getGlobalMergeVars() { return globalMergeVars; } /** * Sets the global merge vars. * * @param globalMergeVars the new global merge vars */ public void setGlobalMergeVars(List<MergeVar> globalMergeVars) { this.globalMergeVars = globalMergeVars; } /** * Adds the global merge var. * * @param var the var */ public void addGlobalMergeVar(MergeVar var) { this.globalMergeVars = ObjectUtils.addToList(this.globalMergeVars, var); } /** * Gets the merge vars. * * @return the merge vars */ public List<RecipientMergeVars> getMergeVars() { return mergeVars; } /** * Sets the merge vars. * * @param mergeVars the new merge vars */ public void setMergeVars(List<RecipientMergeVars> mergeVars) { this.mergeVars = mergeVars; } /** * Adds the merge var. * * @param mergeVar the merge var */ public void addMergeVar(RecipientMergeVars mergeVar) { this.mergeVars = ObjectUtils.addToList(this.mergeVars, mergeVar); } /** * Gets the google analytics domains. * * @return the google analytics domains */ public List<String> getGoogleAnalyticsDomains() { return googleAnalyticsDomains; } /** * Sets the google analytics domains. * * @param googleAnalyticsDomains the new google analytics domains */ public void setGoogleAnalyticsDomains(List<String> googleAnalyticsDomains) { this.googleAnalyticsDomains = googleAnalyticsDomains; } /** * Adds the google analytics domain. * * @param googleAnalyticsDomain the google analytics domain */ public void addGoogleAnalyticsDomain(String googleAnalyticsDomain) { this.googleAnalyticsDomains = ObjectUtils.addToList(this.googleAnalyticsDomains, googleAnalyticsDomain); } /** * Gets the google analytics campaign. * * @return the google analytics campaign */ public String getGoogleAnalyticsCampaign() { return googleAnalyticsCampaign; } /** * Sets the google analytics campaign. * * @param googleAnalyticsCampaign the new google analytics campaign */ public void setGoogleAnalyticsCampaign(String googleAnalyticsCampaign) { this.googleAnalyticsCampaign = googleAnalyticsCampaign; } /** * Gets the recipient meta data. * * @return the recipient meta data */ public List<RecipientMetadata> getRecipientMetaData() { return recipientMetaData; } /** * Sets the recipient meta data. * * @param recipientMetaData the new recipient meta data */ public void setRecipientMetaData(List<RecipientMetadata> recipientMetaData) { this.recipientMetaData = recipientMetaData; } /** * Adds the recipient meta data. * * @param recipientMetaData the recipient meta data */ public void addRecipientMetaData(RecipientMetadata recipientMetaData) { this.recipientMetaData = ObjectUtils.addToList(this.recipientMetaData, recipientMetaData); } }
package apron.constraint; // Generated from Constraint.g4 by ANTLR 4.0 import org.antlr.v4.runtime.tree.*; import org.antlr.v4.runtime.Token; public interface ConstraintListener extends ParseTreeListener { void enterBoolean_expr(ConstraintParser.Boolean_exprContext ctx); void exitBoolean_expr(ConstraintParser.Boolean_exprContext ctx); void enterFieldS(ConstraintParser.FieldSContext ctx); void exitFieldS(ConstraintParser.FieldSContext ctx); void enterPriorityMin(ConstraintParser.PriorityMinContext ctx); void exitPriorityMin(ConstraintParser.PriorityMinContext ctx); void enterFieldM(ConstraintParser.FieldMContext ctx); void exitFieldM(ConstraintParser.FieldMContext ctx); void enterBind(ConstraintParser.BindContext ctx); void exitBind(ConstraintParser.BindContext ctx); void enterSwitchLevel(ConstraintParser.SwitchLevelContext ctx); void exitSwitchLevel(ConstraintParser.SwitchLevelContext ctx); void enterAssertExpr(ConstraintParser.AssertExprContext ctx); void exitAssertExpr(ConstraintParser.AssertExprContext ctx); void enterPhysicalTopo(ConstraintParser.PhysicalTopoContext ctx); void exitPhysicalTopo(ConstraintParser.PhysicalTopoContext ctx); void enterActions(ConstraintParser.ActionsContext ctx); void exitActions(ConstraintParser.ActionsContext ctx); void enterStatisticsS(ConstraintParser.StatisticsSContext ctx); void exitStatisticsS(ConstraintParser.StatisticsSContext ctx); void enterAssertStmtM(ConstraintParser.AssertStmtMContext ctx); void exitAssertStmtM(ConstraintParser.AssertStmtMContext ctx); void enterFlowLevel(ConstraintParser.FlowLevelContext ctx); void exitFlowLevel(ConstraintParser.FlowLevelContext ctx); void enterFilterTermFactor(ConstraintParser.FilterTermFactorContext ctx); void exitFilterTermFactor(ConstraintParser.FilterTermFactorContext ctx); void enterVarPerm(ConstraintParser.VarPermContext ctx); void exitVarPerm(ConstraintParser.VarPermContext ctx); void enterPermS(ConstraintParser.PermSContext ctx); void exitPermS(ConstraintParser.PermSContext ctx); void enterOwnFlows(ConstraintParser.OwnFlowsContext ctx); void exitOwnFlows(ConstraintParser.OwnFlowsContext ctx); void enterFilterExprAndTerm(ConstraintParser.FilterExprAndTermContext ctx); void exitFilterExprAndTerm(ConstraintParser.FilterExprAndTermContext ctx); void enterAssertExclusive(ConstraintParser.AssertExclusiveContext ctx); void exitAssertExclusive(ConstraintParser.AssertExclusiveContext ctx); void enterBindList(ConstraintParser.BindListContext ctx); void exitBindList(ConstraintParser.BindListContext ctx); void enterModifyEventOrder(ConstraintParser.ModifyEventOrderContext ctx); void exitModifyEventOrder(ConstraintParser.ModifyEventOrderContext ctx); void enterMaxPriority(ConstraintParser.MaxPriorityContext ctx); void exitMaxPriority(ConstraintParser.MaxPriorityContext ctx); void enterPermListM(ConstraintParser.PermListMContext ctx); void exitPermListM(ConstraintParser.PermListMContext ctx); void enterAllPathsAsLinks(ConstraintParser.AllPathsAsLinksContext ctx); void exitAllPathsAsLinks(ConstraintParser.AllPathsAsLinksContext ctx); void enterPermListS(ConstraintParser.PermListSContext ctx); void exitPermListS(ConstraintParser.PermListSContext ctx); void enterFileDeny(ConstraintParser.FileDenyContext ctx); void exitFileDeny(ConstraintParser.FileDenyContext ctx); void enterPortLevel(ConstraintParser.PortLevelContext ctx); void exitPortLevel(ConstraintParser.PortLevelContext ctx); void enterExclusive(ConstraintParser.ExclusiveContext ctx); void exitExclusive(ConstraintParser.ExclusiveContext ctx); void enterEventInterception(ConstraintParser.EventInterceptionContext ctx); void exitEventInterception(ConstraintParser.EventInterceptionContext ctx); void enterAllSwitches(ConstraintParser.AllSwitchesContext ctx); void exitAllSwitches(ConstraintParser.AllSwitchesContext ctx); void enterBooleanExpr(ConstraintParser.BooleanExprContext ctx); void exitBooleanExpr(ConstraintParser.BooleanExprContext ctx); void enterDrop(ConstraintParser.DropContext ctx); void exitDrop(ConstraintParser.DropContext ctx); void enterValIp(ConstraintParser.ValIpContext ctx); void exitValIp(ConstraintParser.ValIpContext ctx); void enterSingleBigSwitch(ConstraintParser.SingleBigSwitchContext ctx); void exitSingleBigSwitch(ConstraintParser.SingleBigSwitchContext ctx); void enterAssertNot(ConstraintParser.AssertNotContext ctx); void exitAssertNot(ConstraintParser.AssertNotContext ctx); void enterSwIdxList(ConstraintParser.SwIdxListContext ctx); void exitSwIdxList(ConstraintParser.SwIdxListContext ctx); void enterAssertStmtS(ConstraintParser.AssertStmtSContext ctx); void exitAssertStmtS(ConstraintParser.AssertStmtSContext ctx); void enterBorderSwitches(ConstraintParser.BorderSwitchesContext ctx); void exitBorderSwitches(ConstraintParser.BorderSwitchesContext ctx); void enterPhysical_topo(ConstraintParser.Physical_topoContext ctx); void exitPhysical_topo(ConstraintParser.Physical_topoContext ctx); void enterPermM(ConstraintParser.PermMContext ctx); void exitPermM(ConstraintParser.PermMContext ctx); void enterLink_idx(ConstraintParser.Link_idxContext ctx); void exitLink_idx(ConstraintParser.Link_idxContext ctx); void enterBindApp(ConstraintParser.BindAppContext ctx); void exitBindApp(ConstraintParser.BindAppContext ctx); void enterValInt(ConstraintParser.ValIntContext ctx); void exitValInt(ConstraintParser.ValIntContext ctx); void enterAssertOr(ConstraintParser.AssertOrContext ctx); void exitAssertOr(ConstraintParser.AssertOrContext ctx); void enterPermExprUnion(ConstraintParser.PermExprUnionContext ctx); void exitPermExprUnion(ConstraintParser.PermExprUnionContext ctx); void enterOthersFlows(ConstraintParser.OthersFlowsContext ctx); void exitOthersFlows(ConstraintParser.OthersFlowsContext ctx); void enterField(ConstraintParser.FieldContext ctx); void exitField(ConstraintParser.FieldContext ctx); void enterLinkListS(ConstraintParser.LinkListSContext ctx); void exitLinkListS(ConstraintParser.LinkListSContext ctx); void enterVirtualTopo(ConstraintParser.VirtualTopoContext ctx); void exitVirtualTopo(ConstraintParser.VirtualTopoContext ctx); void enterFilterExprTerm(ConstraintParser.FilterExprTermContext ctx); void exitFilterExprTerm(ConstraintParser.FilterExprTermContext ctx); void enterLinkListM(ConstraintParser.LinkListMContext ctx); void exitLinkListM(ConstraintParser.LinkListMContext ctx); void enterVirtualSwitchSetS(ConstraintParser.VirtualSwitchSetSContext ctx); void exitVirtualSwitchSetS(ConstraintParser.VirtualSwitchSetSContext ctx); void enterWildcard(ConstraintParser.WildcardContext ctx); void exitWildcard(ConstraintParser.WildcardContext ctx); void enterBindExpr(ConstraintParser.BindExprContext ctx); void exitBindExpr(ConstraintParser.BindExprContext ctx); void enterForward(ConstraintParser.ForwardContext ctx); void exitForward(ConstraintParser.ForwardContext ctx); void enterNetworkDeny(ConstraintParser.NetworkDenyContext ctx); void exitNetworkDeny(ConstraintParser.NetworkDenyContext ctx); void enterLinkM(ConstraintParser.LinkMContext ctx); void exitLinkM(ConstraintParser.LinkMContext ctx); void enterVirtualSwitchSetM(ConstraintParser.VirtualSwitchSetMContext ctx); void exitVirtualSwitchSetM(ConstraintParser.VirtualSwitchSetMContext ctx); void enterLinkS(ConstraintParser.LinkSContext ctx); void exitLinkS(ConstraintParser.LinkSContext ctx); void enterVirtual_topo(ConstraintParser.Virtual_topoContext ctx); void exitVirtual_topo(ConstraintParser.Virtual_topoContext ctx); void enterFieldMask(ConstraintParser.FieldMaskContext ctx); void exitFieldMask(ConstraintParser.FieldMaskContext ctx); void enterFlowTableB(ConstraintParser.FlowTableBContext ctx); void exitFlowTableB(ConstraintParser.FlowTableBContext ctx); void enterFlowTableA(ConstraintParser.FlowTableAContext ctx); void exitFlowTableA(ConstraintParser.FlowTableAContext ctx); void enterSystemS(ConstraintParser.SystemSContext ctx); void exitSystemS(ConstraintParser.SystemSContext ctx); void enterFileAllow(ConstraintParser.FileAllowContext ctx); void exitFileAllow(ConstraintParser.FileAllowContext ctx); void enterCmp_operator(ConstraintParser.Cmp_operatorContext ctx); void exitCmp_operator(ConstraintParser.Cmp_operatorContext ctx); void enterVar_perm(ConstraintParser.Var_permContext ctx); void exitVar_perm(ConstraintParser.Var_permContext ctx); void enterAssertAnd(ConstraintParser.AssertAndContext ctx); void exitAssertAnd(ConstraintParser.AssertAndContext ctx); void enterProgram(ConstraintParser.ProgramContext ctx); void exitProgram(ConstraintParser.ProgramContext ctx); void enterSwIdxListS(ConstraintParser.SwIdxListSContext ctx); void exitSwIdxListS(ConstraintParser.SwIdxListSContext ctx); void enterFieldVal(ConstraintParser.FieldValContext ctx); void exitFieldVal(ConstraintParser.FieldValContext ctx); void enterPktOut(ConstraintParser.PktOutContext ctx); void exitPktOut(ConstraintParser.PktOutContext ctx); void enterFilterTermOrFactor(ConstraintParser.FilterTermOrFactorContext ctx); void exitFilterTermOrFactor(ConstraintParser.FilterTermOrFactorContext ctx); void enterSwIdxListM(ConstraintParser.SwIdxListMContext ctx); void exitSwIdxListM(ConstraintParser.SwIdxListMContext ctx); void enterTopology(ConstraintParser.TopologyContext ctx); void exitTopology(ConstraintParser.TopologyContext ctx); void enterAllFlows(ConstraintParser.AllFlowsContext ctx); void exitAllFlows(ConstraintParser.AllFlowsContext ctx); void enterNetworkAllow(ConstraintParser.NetworkAllowContext ctx); void exitNetworkAllow(ConstraintParser.NetworkAllowContext ctx); void enterApp_name(ConstraintParser.App_nameContext ctx); void exitApp_name(ConstraintParser.App_nameContext ctx); void enterPktOutAllow(ConstraintParser.PktOutAllowContext ctx); void exitPktOutAllow(ConstraintParser.PktOutAllowContext ctx); void enterFlowTable(ConstraintParser.FlowTableContext ctx); void exitFlowTable(ConstraintParser.FlowTableContext ctx); void enterOwnershipS(ConstraintParser.OwnershipSContext ctx); void exitOwnershipS(ConstraintParser.OwnershipSContext ctx); void enterFilterFactorNotFactor(ConstraintParser.FilterFactorNotFactorContext ctx); void exitFilterFactorNotFactor(ConstraintParser.FilterFactorNotFactorContext ctx); void enterFilterFactorNot(ConstraintParser.FilterFactorNotContext ctx); void exitFilterFactorNot(ConstraintParser.FilterFactorNotContext ctx); void enterVirtualSwitchSet(ConstraintParser.VirtualSwitchSetContext ctx); void exitVirtualSwitchSet(ConstraintParser.VirtualSwitchSetContext ctx); void enterFilterExpr(ConstraintParser.FilterExprContext ctx); void exitFilterExpr(ConstraintParser.FilterExprContext ctx); void enterPathM(ConstraintParser.PathMContext ctx); void exitPathM(ConstraintParser.PathMContext ctx); void enterAssertList(ConstraintParser.AssertListContext ctx); void exitAssertList(ConstraintParser.AssertListContext ctx); void enterPathS(ConstraintParser.PathSContext ctx); void exitPathS(ConstraintParser.PathSContext ctx); void enterProcessAllow(ConstraintParser.ProcessAllowContext ctx); void exitProcessAllow(ConstraintParser.ProcessAllowContext ctx); void enterModify(ConstraintParser.ModifyContext ctx); void exitModify(ConstraintParser.ModifyContext ctx); void enterAllDriectLinks(ConstraintParser.AllDriectLinksContext ctx); void exitAllDriectLinks(ConstraintParser.AllDriectLinksContext ctx); void enterPriorityMax(ConstraintParser.PriorityMaxContext ctx); void exitPriorityMax(ConstraintParser.PriorityMaxContext ctx); void enterPerm_name(ConstraintParser.Perm_nameContext ctx); void exitPerm_name(ConstraintParser.Perm_nameContext ctx); void enterSw_idx(ConstraintParser.Sw_idxContext ctx); void exitSw_idx(ConstraintParser.Sw_idxContext ctx); void enterModifyField(ConstraintParser.ModifyFieldContext ctx); void exitModifyField(ConstraintParser.ModifyFieldContext ctx); void enterPktOutDeny(ConstraintParser.PktOutDenyContext ctx); void exitPktOutDeny(ConstraintParser.PktOutDenyContext ctx); void enterProcessDeny(ConstraintParser.ProcessDenyContext ctx); void exitProcessDeny(ConstraintParser.ProcessDenyContext ctx); void enterLinkList(ConstraintParser.LinkListContext ctx); void exitLinkList(ConstraintParser.LinkListContext ctx); void enterNotificationS(ConstraintParser.NotificationSContext ctx); void exitNotificationS(ConstraintParser.NotificationSContext ctx); void enterFlowPredicate(ConstraintParser.FlowPredicateContext ctx); void exitFlowPredicate(ConstraintParser.FlowPredicateContext ctx); }
package org.apache.ctakes.temporal.ae; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.ctakes.relationextractor.ae.RelationExtractorAnnotator; import org.apache.ctakes.relationextractor.ae.features.PartOfSpeechFeaturesExtractor; import org.apache.ctakes.relationextractor.ae.features.RelationFeaturesExtractor; import org.apache.ctakes.temporal.ae.feature.CheckSpecialWordRelationExtractor; //import org.apache.ctakes.temporal.ae.feature.DeterminerRelationFeaturesExtractor; import org.apache.ctakes.temporal.ae.feature.EventArgumentPropertyExtractor; import org.apache.ctakes.temporal.ae.feature.EventPositionRelationFeaturesExtractor; import org.apache.ctakes.temporal.ae.feature.EventTimeRelationFeatureExtractor; import org.apache.ctakes.temporal.ae.feature.NumberOfEventTimeBetweenCandidatesExtractor; import org.apache.ctakes.temporal.ae.feature.OverlappedHeadFeaturesExtractor; import org.apache.ctakes.temporal.ae.feature.SRLRelationFeaturesExtractor; import org.apache.ctakes.temporal.ae.feature.SectionHeaderRelationExtractor; import org.apache.ctakes.temporal.ae.feature.TimeXRelationFeaturesExtractor; //import org.apache.ctakes.temporal.ae.feature.TemporalAttributeForMixEventTimeExtractor; import org.apache.ctakes.temporal.ae.feature.UmlsFeatureExtractor; import org.apache.ctakes.temporal.ae.feature.UnexpandedTokenFeaturesExtractor; import org.apache.ctakes.typesystem.type.relation.BinaryTextRelation; import org.apache.ctakes.typesystem.type.relation.RelationArgument; import org.apache.ctakes.typesystem.type.relation.TemporalTextRelation; //import org.apache.ctakes.typesystem.type.syntax.WordToken; import org.apache.ctakes.typesystem.type.textsem.EventMention; import org.apache.ctakes.typesystem.type.textsem.IdentifiedAnnotation; import org.apache.ctakes.typesystem.type.textspan.Segment; //import org.apache.ctakes.typesystem.type.textspan.Paragraph; import org.apache.ctakes.typesystem.type.textspan.Sentence; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.jcas.tcas.DocumentAnnotation; import org.apache.uima.resource.ResourceInitializationException; import org.cleartk.ml.CleartkAnnotator; import org.cleartk.ml.DataWriter; import org.cleartk.ml.jar.DefaultDataWriterFactory; import org.cleartk.ml.jar.DirectoryDataWriterFactory; import org.cleartk.ml.jar.GenericJarClassifierFactory; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.util.JCasUtil; import com.google.common.collect.Lists; public class ConsecutiveSentencesEventEventRelationAnnotator extends RelationExtractorAnnotator { public static AnalysisEngineDescription createDataWriterDescription( Class<? extends DataWriter<String>> dataWriterClass, File outputDirectory, double probabilityOfKeepingANegativeExample) throws ResourceInitializationException { return AnalysisEngineFactory.createPrimitiveDescription( ConsecutiveSentencesEventEventRelationAnnotator.class, CleartkAnnotator.PARAM_IS_TRAINING, true, DefaultDataWriterFactory.PARAM_DATA_WRITER_CLASS_NAME, dataWriterClass, DirectoryDataWriterFactory.PARAM_OUTPUT_DIRECTORY, outputDirectory, RelationExtractorAnnotator.PARAM_PROBABILITY_OF_KEEPING_A_NEGATIVE_EXAMPLE, // not sure why this has to be cast; something funny going on in uimaFIT maybe? (float) probabilityOfKeepingANegativeExample); } public static AnalysisEngineDescription createAnnotatorDescription(File modelDirectory) throws ResourceInitializationException { return AnalysisEngineFactory.createPrimitiveDescription( ConsecutiveSentencesEventEventRelationAnnotator.class, CleartkAnnotator.PARAM_IS_TRAINING, false, GenericJarClassifierFactory.PARAM_CLASSIFIER_JAR_PATH, new File(modelDirectory, "model.jar")); } @Override protected List<RelationFeaturesExtractor> getFeatureExtractors() { return Lists.newArrayList( new UnexpandedTokenFeaturesExtractor() //use unexpanded version for i2b2 data , new OverlappedHeadFeaturesExtractor() , new EventArgumentPropertyExtractor() , new PartOfSpeechFeaturesExtractor() , new NumberOfEventTimeBetweenCandidatesExtractor() , new UmlsFeatureExtractor() , new SRLRelationFeaturesExtractor() , new SectionHeaderRelationExtractor() , new TimeXRelationFeaturesExtractor() , new EventPositionRelationFeaturesExtractor() , new CheckSpecialWordRelationExtractor() , new EventTimeRelationFeatureExtractor() // , new DeterminerRelationFeaturesExtractor() ); } @Override protected Class<? extends Annotation> getCoveringClass() { return DocumentAnnotation.class; } @SuppressWarnings("null") @Override public List<IdentifiedAnnotationPair> getCandidateRelationArgumentPairs( JCas jCas, Annotation document) { List<IdentifiedAnnotationPair> pairs = Lists.newArrayList(); Collection<Segment> segments = JCasUtil.select(jCas, Segment.class); List<Segment> segList = Lists.newArrayList(); for(Segment seg: segments){ if (!seg.getId().equals("SIMPLE_SEGMENT")){//remove simple segment segList.add(seg); } } for(Segment segment : segList){ List<Sentence> sentList = JCasUtil.selectCovered(jCas, Sentence.class, segment); int sentListLength = sentList.size(); if( sentListLength >=2){ for (int i=0; i<sentListLength-1; i++ ) { Sentence currentSent = sentList.get(i); Sentence nextSent = sentList.get(i+1); List<EventMention> currentEvents = JCasUtil.selectCovered(jCas, EventMention.class, currentSent); List<EventMention> nextEvents = JCasUtil.selectCovered(jCas, EventMention.class, nextSent); //filtering events List<EventMention> realEvents = new ArrayList<>(); //filtering events for(EventMention event : currentEvents){ // filter out ctakes events if(event.getClass().equals(EventMention.class)){ realEvents.add(event); } } currentEvents = realEvents; realEvents = new ArrayList<>(); //filtering events for(EventMention event : nextEvents){ // filter out ctakes events if(event.getClass().equals(EventMention.class)){ realEvents.add(event); } } nextEvents = realEvents; //scheme2 : pairing major events + time int currentSize = currentEvents == null ? 0 : currentEvents.size(); int nextSize = nextEvents == null ? 0 : nextEvents.size(); if( currentSize == 0 || nextSize ==0){ continue; } EventMention currentFirst = null; EventMention currentLast = null; EventMention nextFirst = null; EventMention nextLast = null; if( currentSize ==1 ){ currentFirst = currentEvents.get(0); }else if(currentSize > 1){ currentFirst = currentEvents.get(0); currentLast = currentEvents.get(currentSize-1); } if( nextSize == 1){ nextFirst = nextEvents.get(0); }else if( nextSize > 1 ){ nextFirst = nextEvents.get(0); nextLast = nextEvents.get(nextSize-1); } //pair them up if(currentFirst != null){ if(nextFirst != null){ pairs.add(new IdentifiedAnnotationPair(nextFirst, currentFirst)); } if( nextLast != null){ pairs.add(new IdentifiedAnnotationPair(nextLast, currentFirst)); } } if( currentLast != null ){ if(nextFirst != null){ pairs.add(new IdentifiedAnnotationPair(nextFirst, currentLast)); } if( nextLast != null){ pairs.add(new IdentifiedAnnotationPair(nextLast, currentLast)); } } } } } return pairs; } // private static boolean hasOverlapTokens(JCas jCas, EventMention event1, EventMention event2) { // List<WordToken> currentTokens = JCasUtil.selectCovered(jCas, WordToken.class, event1); // int tokenSize1 = currentTokens.size(); // List<WordToken> nextTokens = JCasUtil.selectCovered(jCas, WordToken.class, event2); // int tokenSize2 = nextTokens.size(); // int tokenSize = Math.min(tokenSize1, tokenSize2); // int matches = 0; // for(WordToken t1: currentTokens){ // for(WordToken t2: nextTokens){ // if(t1.getCoveredText().toLowerCase().equals(t2.getCoveredText().toLowerCase())){ // matches++; // } // } // } // float matchRatio = (float)matches/tokenSize; // if( matchRatio >= 0.5) // return true; // return false; // } @Override protected void createRelation(JCas jCas, IdentifiedAnnotation arg1, IdentifiedAnnotation arg2, String predictedCategory) { RelationArgument relArg1 = new RelationArgument(jCas); relArg1.setArgument(arg1); relArg1.setRole("Arg1"); relArg1.addToIndexes(); RelationArgument relArg2 = new RelationArgument(jCas); relArg2.setArgument(arg2); relArg2.setRole("Arg2"); relArg2.addToIndexes(); TemporalTextRelation relation = new TemporalTextRelation(jCas); relation.setArg1(relArg1); relation.setArg2(relArg2); relation.setCategory(predictedCategory); relation.addToIndexes(); } @Override protected String getRelationCategory( Map<List<Annotation>, BinaryTextRelation> relationLookup, IdentifiedAnnotation arg1, IdentifiedAnnotation arg2) { BinaryTextRelation relation = relationLookup.get(Arrays.asList(arg1, arg2)); String category = null; if (relation != null) { category = relation.getCategory(); } else { relation = relationLookup.get(Arrays.asList(arg2, arg1)); if (relation != null) { if(relation.getCategory().equals("OVERLAP")){ category = relation.getCategory(); }else if (relation.getCategory().equals("BEFORE")){ category = "AFTER"; }else if (relation.getCategory().equals("AFTER")){ category = "BEFORE"; } // else{ // category = relation.getCategory() + "-1"; // } } } if (category == null && coin.nextDouble() <= this.probabilityOfKeepingANegativeExample) { category = NO_RELATION_CATEGORY; } return category; } }
package jeffaschenk.commons.frameworks.cnxidx.resiliency.ldap; import jeffaschenk.commons.frameworks.cnxidx.utility.ldap.idxCMDReturnCodes; import jeffaschenk.commons.frameworks.cnxidx.utility.logging.FrameworkLogger; import jeffaschenk.commons.frameworks.cnxidx.utility.logging.FrameworkLoggerLevel; import jeffaschenk.commons.frameworks.cnxidx.utility.security.FrameworkDirectoryUser; import java.util.*; import java.io.*; /** * Java Service Driver for the IRRLogRestoreDriver. * * @author jeff.schenk * @version 4.4 $Revision * Developed 2005 */ public class IRRChangeLogRestoreService implements idxCMDReturnCodes { // ******************************* // Version Information. public static final String VERSION = "4.4 2005-12-06"; // *********************************** // Globals Default Property File Name public static final String FRAMEWORK_CONFIG_PROPERTIES = "framework.config"; public static final String DEFAULT_PROPERTIES_FILENAME = "service.properties"; // ******************************** // Global Property Names public static final String IRR_HOST_URL_PNAME = "IRR.HOST.URL"; public static final String IRR_PRINCIPAL_PNAME = "IRR.PRINCIPAL"; public static final String IRR_CREDENTIALS_PNAME = "IRR.CREDENTIALS"; public static final String IRR_IDU_PNAME = "IRR.IDU"; public static final String INPUT_PATH_PNAME = "RESILIENCY.INPUT.FILE.PATH"; public static final String PUBLISHER_EXCLUDE_PATH_PNAME = "RESILIENCY.PUBLISH.EXCLUDE.FILTER.FILE.PATH"; public static final String RESTORE_EXCLUDE_PATH_PNAME = "RESILIENCY.RESTORE.EXCLUDE.FILTER.FILE.PATH"; public static final String OPERTIONAL_MODE_PNAME = "RESILIENCY.OPERATIONAL.MODE"; public static final String WEBADMIN_PORT_PNAME = "RESILIENCY.WEBADMIN.PORT"; public static final String WEBADMIN_ALLOW_LIST_PNAME = "RESILIENCY.WEBADMIN.ALLOW.LIST"; public static final String MULTICAST_ADDRESS_PNAME = "RESILIENCY.MULTICAST.ADDRESS"; public static final String MULTICAST_PORT_PNAME = "RESILIENCY.MULTICAST.PORT"; public static final String GROUPNAME_PNAME = "RESILIENCY.GROUP.NAME"; // ******************************* // Common Logging Facility. public static final String CLASSNAME = IRRChangeLogRestoreService.class.getName(); /** * Main * * @param args Incoming Argument Array. * */ public static void main(String[] args) { // **************************************** // Local Objects Properties RunConfig = new Properties(); String IRRHost = null; String IRRPrincipal = null; String IRRCredentials = null; String IRRIDU = null; String INPUT_PATH = null; String PUBLISH_EXCLUDE_DN_FILTER_FILE = null; String RESTORE_EXCLUDE_DN_FILTER_FILE = null; int WEBADMIN_PORT = 0; String WEBADMIN_ALLOW_LIST = null; String OPERATIONAL_MODE = null; String GROUPNAME = null; String MULTICAST_ADDRESS = null; String MULTICAST_PORT = null; String METHODNAME = "main"; // **************************************** // Send the Greeting. FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.INFO, MessageConstants.SERVICE_VERSION, new String[]{VERSION}); FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.INFO, MessageConstants.SERVICE_CONFIGURATION); // **************************************** // Obtain the RunTime Properties from // a local Property file. FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.INFO, MessageConstants.SERVICE_CONFIGURATION); String PFileName = System.getProperty(FRAMEWORK_CONFIG_PROPERTIES, DEFAULT_PROPERTIES_FILENAME); File PF = new File(PFileName); try { if (!PF.exists()) { FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.SEVERE, ErrorConstants.SERVICE_UNABLE_TO_READ_PROPERTIES, new String[]{PFileName.toString()}); System.exit(EXIT_GENERIC_FAILURE); } // End of If. // ************************************* // Try to load the Properties. RunConfig.load(new FileInputStream(PF)); FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.INFO, MessageConstants.SERVICE_PROPERTIES_OBTAINED, new String[]{PF.getAbsoluteFile().toString()}); } catch (Exception e) { FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.SEVERE, ErrorConstants.SERVICE_UNABLE_TO_OBTAIN_PROPERTIES, new String[]{PFileName.toString(), e.getMessage().toString()}); System.exit(EXIT_GENERIC_FAILURE); } // End of Exception. // ***************************************** // Obtain the Properties and formulate into // our variables. IRRHost = RunConfig.getProperty(IRR_HOST_URL_PNAME); IRRPrincipal = RunConfig.getProperty(IRR_PRINCIPAL_PNAME); IRRCredentials = RunConfig.getProperty(IRR_CREDENTIALS_PNAME); IRRIDU = RunConfig.getProperty(IRR_IDU_PNAME); // INPUT_PATH = RunConfig.getProperty(INPUT_PATH_PNAME); // PUBLISH_EXCLUDE_DN_FILTER_FILE = RunConfig.getProperty(PUBLISHER_EXCLUDE_PATH_PNAME); RESTORE_EXCLUDE_DN_FILTER_FILE = RunConfig.getProperty(RESTORE_EXCLUDE_PATH_PNAME); OPERATIONAL_MODE = RunConfig.getProperty(OPERTIONAL_MODE_PNAME); // MULTICAST_ADDRESS = RunConfig.getProperty(MULTICAST_ADDRESS_PNAME); MULTICAST_PORT = RunConfig.getProperty(MULTICAST_PORT_PNAME); GROUPNAME = RunConfig.getProperty(GROUPNAME_PNAME); // try { WEBADMIN_PORT = Integer.parseInt( RunConfig.getProperty(WEBADMIN_PORT_PNAME, "0")); } catch (NumberFormatException nfe) { WEBADMIN_PORT = 0; } // End of Exception processing. // WEBADMIN_ALLOW_LIST = RunConfig.getProperty(WEBADMIN_ALLOW_LIST_PNAME); // ********************************************************************* // ********************************************************************* // Verify all the properties are present and available to continue. FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.INFO, MessageConstants.SERVICE_VERIFYING_PROPERTIES); // ****************** // Check IRRHost if ((IRRHost == null) || (IRRHost.equalsIgnoreCase(""))) { FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.SEVERE, ErrorConstants.SERVICE_IRR_HOST_URL_NOT_SPECIFIED); System.exit(EXIT_GENERIC_FAILURE); } // End of If. // ****************** // Check IRRIDU if ((IRRIDU != null) && (!IRRIDU.equalsIgnoreCase(""))) { // ***************************** // We have an IDU Specified, // try to obtain Principal // and Credentials. // try { FrameworkDirectoryUser idu = new FrameworkDirectoryUser(IRRIDU); IRRPrincipal = idu.getDN(); IRRCredentials = idu.getPassword(); } catch (Exception e) { FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.SEVERE, ErrorConstants.SERVICE_UNABLE_TO_OBTAIN_AUTHENTICATION_DATA, new String[]{e.getMessage()}); System.exit(EXIT_GENERIC_FAILURE); } // End of Exception. } // End of If. // ****************** // Check IRRPrincipal if ((IRRPrincipal == null) || (IRRPrincipal.equalsIgnoreCase(""))) { FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.SEVERE, ErrorConstants.SERVICE_UNABLE_TO_OBTAIN_IRRPRINCIPAL_PROPERTY); System.exit(EXIT_GENERIC_FAILURE); } // End of If. // ****************** // Check IRRCredentials if ((IRRCredentials == null) || (IRRCredentials.equalsIgnoreCase(""))) { FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.SEVERE, ErrorConstants.SERVICE_UNABLE_TO_OBTAIN_IRRCREDENTIALS_PROPERTY); System.exit(EXIT_GENERIC_FAILURE); } // End of If. // ******************** // Check INPUT_PATH if ((INPUT_PATH == null) || (INPUT_PATH.equalsIgnoreCase(""))) { FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.SEVERE, ErrorConstants.SERVICE_PROPERTY_NOT_SPECIFIED, new String[]{INPUT_PATH_PNAME}); System.exit(EXIT_GENERIC_FAILURE); } // End of If. // ******************** // Check the Paths // Existence. File EIP = new File(INPUT_PATH); if ((!EIP.exists()) || (!EIP.isDirectory()) || (!EIP.canRead()) || (!EIP.canWrite())) { FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.SEVERE, ErrorConstants.SERVICE_PROPERTY_FILENAME_NOT_ACCESSIBLE, new String[]{INPUT_PATH_PNAME, INPUT_PATH}); System.exit(EXIT_GENERIC_FAILURE); } // End of If. // ********************************************************* // Now determine which Constructor to use. If any MCAST or // our groupname specified, then use the correct constructor. Thread controlThread = null; if ((MULTICAST_ADDRESS != null) || (MULTICAST_PORT != null) || (GROUPNAME != null)) { // ********************************************************* // Now create a Control Thread to Boot up the Service. controlThread = new IRRChangeLogRestoreServiceControlThread( IRRHost, IRRPrincipal, IRRCredentials, INPUT_PATH, PUBLISH_EXCLUDE_DN_FILTER_FILE, RESTORE_EXCLUDE_DN_FILTER_FILE, WEBADMIN_PORT, OPERATIONAL_MODE, GROUPNAME, MULTICAST_ADDRESS, MULTICAST_PORT, WEBADMIN_ALLOW_LIST); } else { // ********************************************************* // Now create a Control Thread to Boot up the Service. controlThread = new IRRChangeLogRestoreServiceControlThread( IRRHost, IRRPrincipal, IRRCredentials, INPUT_PATH, PUBLISH_EXCLUDE_DN_FILTER_FILE, RESTORE_EXCLUDE_DN_FILTER_FILE, WEBADMIN_PORT, OPERATIONAL_MODE); } // End of Else . // ************************** // Start the Thread. FrameworkLogger.log(CLASSNAME, METHODNAME, FrameworkLoggerLevel.INFO, MessageConstants.SERVICE_BOOTING); controlThread.start(); // ************************** // Attach a Shutdown Hook // Thread. Runtime.getRuntime().addShutdownHook( new IRRChangeLogRestoreServiceShutdownThread(controlThread)); } // End of Main } // End of Class IRRChangeLogRestoreService
// Expression.java // (C) 2016 Masato Kokubo package org.lightsleep.component; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.lightsleep.Sql; import org.lightsleep.database.Database; import org.lightsleep.helper.ColumnInfo; import org.lightsleep.helper.EntityInfo; import org.lightsleep.helper.MissingPropertyException; import org.lightsleep.helper.Resource; import org.lightsleep.helper.SqlEntityInfo; /** * Configures an expression with a string content and an array of argument objects embedded in the string. * * @since 1.0.0 * @author Masato Kokubo */ public class Expression implements Condition { // Class resources private static final Resource resource = new Resource(Expression.class); private static final String messageLessArguments = resource.getString("messageLessArguments"); private static final String messageMoreArguments = resource.getString("messageMoreArguments"); private static final String messageMissingProperty = resource.getString("messageMissingProperty"); private static final String messageMissingProperties = resource.getString("messageMissingProperties"); /** The empty expression */ public static final Expression EMPTY = new Expression(""); // The content private final String content; // The arguments private final Object[] arguments; /** * Constructs a new <b>Expression</b>. * * @param content the content of the expression * @param arguments the arguments of the expression * * @throws NullPointerException <b>content</b> or <b>arguments</b> is <b>null</b> */ public Expression(String content, Object... arguments) { this.content = Objects.requireNonNull(content, "content is null"); this.arguments = Objects.requireNonNull(arguments, "arguments is null"); } /** * Returns the content of the expression. * * @return the content */ public String content() { return content; } /** * Returns the arguments. * * @return the arguments */ public Object[] arguments() { return arguments; } @Override public boolean isEmpty() { return content.isEmpty(); } /** * <table class="additional"> * <caption><span>Conversion Process</span></caption> * <tr> * <th>String before convert</th> * <th>String after convert</th> * </tr> * <tr> * <td>{}</td> * <td>An element of <b>arguments</b></td> * </tr> * <tr> * <td>{<i>Property Name</i>}</td> * <td>Column Name</td> * </tr> * <tr> * <td>{<i>Table Alias</i>.<i>Property Name</i>}</td> * <td>Table Alias.Column Name</td> * </tr> * <tr> * <td>{<i>Table Alias</i>_<i>Property Name</i>}</td> * <td>Column Alias</td> * </tr> * <tr> * <td>{#<i>Property Name</i>}</td> * <td>Property Value of the entity</td> * </tr> * </table> * * @throws MissingArgumentsException if the number of arguments does not match the number of placements in the expression * @throws MissingPropertyException if a property that does not exist in the expression is referenced */ @Override public <E> String toString(Database database, Sql<E> sql, List<Object> parameters) { Objects.requireNonNull(database, "database is null"); Objects.requireNonNull(sql, "sql is null"); Objects.requireNonNull(parameters, "parameters is null"); EntityInfo<E> entityInfo = sql.entityInfo(); E entity = sql.entity(); StringBuilder buff = new StringBuilder(content.length()); StringBuilder tempBuff = new StringBuilder(); boolean inBrace = false; boolean escaped = false; boolean referEntity = false; int argIndex = 0; for (int index = 0; index < content.length(); ++index) { char ch = content.charAt(index); if (escaped) { // In escaping escaped = false; } else { // Not in escaping if (ch == '\\') { // Escape character escaped = true; continue; } if (inBrace) { // in {} if (Character.isWhitespace(ch)) continue; if (ch != '}') { if (tempBuff.length() == 0) { if (ch == '#' && !referEntity) { referEntity = true; continue; } } tempBuff.append(ch); continue; } inBrace = false; String propertyName = tempBuff.toString(); if (propertyName.length() == 0 || referEntity) { // Replaces an argument or refer the entity value Object value = null; if (propertyName.length() == 0) { // Replaces an argument if (argIndex >= arguments.length) { // Argument shortage throw new MissingArgumentsException(MessageFormat.format( messageLessArguments, content, arguments.length)); } value = arguments[argIndex++]; } else { // Refers the entity value Objects.requireNonNull(entity, "sql.entity is null"); value = entityInfo.accessor().getValue(entity, propertyName); ColumnInfo columnInfo = entityInfo.getColumnInfo(propertyName); Class<?> columnType = columnInfo.columnType(); if (columnType != null) value = database.convert(value, columnType); } if (value == null) buff.append("NULL"); else { SqlString sqlString = database.convert(value, SqlString.class); buff.append(sqlString.toString()); parameters.addAll(Arrays.asList(sqlString.parameters())); } } else { appendsColumnName(buff, sql, entityInfo, propertyName); } continue; } if (ch == '{') { // { start inBrace = true; referEntity = false; tempBuff.setLength(0); continue; } } buff.append(ch); } if (argIndex < arguments.length) throw new MissingArgumentsException(MessageFormat.format( messageMoreArguments, content, arguments.length)); return buff.toString(); } private static char[] delimiterChars = {'.', '_'}; // Appends a column name private <E> void appendsColumnName(StringBuilder buff, Sql<E> sql, EntityInfo<E> entityInfo, String propertyName) { List<String> propertyNames = new ArrayList<>(); try { // Converts to a column name ColumnInfo columnInfo = entityInfo.getColumnInfo(propertyName); buff.append(columnInfo.getColumnName(sql.tableAlias())); return; } catch (IllegalArgumentException e) { propertyNames.add(propertyName); } // Try with the table alias and column alias for (char delimiterChar : delimiterChars) { int chIndex = propertyName.indexOf(delimiterChar); if (chIndex >= 1) { String tableAlias = propertyName.substring(0, chIndex); SqlEntityInfo<?> sqlEntityInfo = sql.getSqlEntityInfo(tableAlias); if (sqlEntityInfo != null) { // Found an entity information with the table alias or column alias String propertyName2 = propertyName.substring(chIndex + 1); try { ColumnInfo columnInfo = sqlEntityInfo.entityInfo().getColumnInfo(propertyName2); if (delimiterChar == '.') buff.append(columnInfo.getColumnName(sqlEntityInfo.tableAlias())); else buff.append(columnInfo.getColumnAlias(sqlEntityInfo.tableAlias())); return; } catch (IllegalArgumentException e) { propertyNames.add(propertyName2); } } } } propertyNames = propertyNames.stream().map(name -> '"' + name + '"').collect(Collectors.toList()); throw new MissingPropertyException(propertyNames.size() == 1 ? MessageFormat.format(messageMissingProperty, entityInfo.entityClass().getName(), propertyNames.get(0)) : MessageFormat.format(messageMissingProperties, entityInfo.entityClass().getName(), '[' + String.join(", ", propertyNames) + ']') ); } /** * @since 1.9.1 */ @Override public int hashCode() { return 31 * content.hashCode() + Arrays.hashCode(arguments); } /** * @since 1.9.1 */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Expression other = (Expression)obj; if (!content.equals(other.content)) return false; if (!Arrays.equals(arguments, other.arguments)) return false; return true; } }
/* * Copyright 2013-2020 Grzegorz Slowikowski (gslowikowski at gmail dot com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.google.code.play2.plugin; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.codehaus.plexus.util.DirectoryScanner; import com.google.code.play2.provider.api.Play2JavaEnhancer; import com.google.code.play2.provider.api.Play2Provider; import com.google.code.sbt.compiler.api.Analysis; import com.google.code.sbt.compiler.api.AnalysisProcessor; /** * Enhance Java classes * * @author <a href="mailto:gslowikowski@gmail.com">Grzegorz Slowikowski</a> * @since 1.0.0 */ @Mojo( name = "enhance", defaultPhase = LifecyclePhase.PROCESS_CLASSES, requiresDependencyResolution = ResolutionScope.COMPILE ) public class Play2EnhanceClassesMojo extends AbstractPlay2EnhanceMojo { private static final String DEFAULT_TEMPLATES_TARGET_DIRECTORY_NAME = "src_managed"; /** * Project classpath. */ @Parameter( defaultValue = "${project.compileClasspathElements}", readonly = true, required = true ) private List<String> classpathElements; @Override protected void internalExecute() throws MojoExecutionException, MojoFailureException, IOException { File analysisCacheFile = getAnalysisCacheFile(); if ( !analysisCacheFile.exists() ) { throw new MojoExecutionException( String.format( "Analysis cache file \"%s\" not found", analysisCacheFile.getAbsolutePath() ) ); } if ( !analysisCacheFile.isFile() ) { throw new MojoExecutionException( String.format( "Analysis cache \"%s\" is not a file", analysisCacheFile.getAbsolutePath() ) ); } List<File> classpathFiles = new ArrayList<File>( classpathElements.size() ); for ( String path : classpathElements ) { classpathFiles.add( new File( path ) ); } AnalysisProcessor sbtAnalysisProcessor = getSbtAnalysisProcessor(); Analysis analysis = sbtAnalysisProcessor.readFromFile( analysisCacheFile ); Play2Provider play2Provider = getProvider(); Play2JavaEnhancer enhancer = play2Provider.getEnhancer(); try { enhancer.setClasspathFiles( classpathFiles ); File timestampFile = new File( getAnalysisCacheFile().getParentFile(), "play_instrumentation" ); long lastEnhanced = 0L; if ( timestampFile.exists() ) { String line = readFileFirstLine( timestampFile, "ASCII" ); lastEnhanced = Long.parseLong( line ); } List<String> compileSourceRoots = project.getCompileSourceRoots(); Set<File> sourcesToGenerageAccessors = null; for ( String sourceRoot : compileSourceRoots ) { if ( !sourceRoot.startsWith( project.getBuild().getDirectory() ) ) // unmanaged { File scannerBaseDir = new File( sourceRoot ); if ( scannerBaseDir.isDirectory() ) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( scannerBaseDir ); scanner.setIncludes( new String[] { "**/*.java" } ); scanner.addDefaultExcludes(); scanner.scan(); String[] javaSources = scanner.getIncludedFiles(); if ( sourcesToGenerageAccessors == null ) { sourcesToGenerageAccessors = toFiles( scannerBaseDir, javaSources ); } else { sourcesToGenerageAccessors.addAll( toFiles( scannerBaseDir, javaSources ) ); } } } } if ( sourcesToGenerageAccessors == null || sourcesToGenerageAccessors.isEmpty() ) { getLog().info( "No Java classes to enhance" ); return; } Set<File> sourcesToRewriteAccess = null; if ( playVersion.compareTo( "2.4" ) < 0 ) { // Play 2.1.x, 2.2.x, 2.3.x sourcesToRewriteAccess = new HashSet<File>( sourcesToGenerageAccessors ); File targetDirectory = new File( project.getBuild().getDirectory() ); String templatesOutputDirectoryName = play2Provider.getTemplatesCompiler().getCustomOutputDirectoryName(); if ( templatesOutputDirectoryName == null ) { templatesOutputDirectoryName = DEFAULT_TEMPLATES_TARGET_DIRECTORY_NAME; } File scannerBaseDir = new File( targetDirectory, templatesOutputDirectoryName + "/main" ); if ( scannerBaseDir.isDirectory() ) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( scannerBaseDir ); scanner.setIncludes( new String[] { "**/*.template.scala" } ); scanner.addDefaultExcludes(); scanner.scan(); String[] scalaTemplateSources = scanner.getIncludedFiles(); sourcesToRewriteAccess.addAll( toFiles( scannerBaseDir, scalaTemplateSources ) ); } } else { // Play 2.4.x for ( String sourceRoot : compileSourceRoots ) { File scannerBaseDir = new File( sourceRoot ); if ( scannerBaseDir.isDirectory() ) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( scannerBaseDir ); scanner.setIncludes( new String[] { "**/*.java", "**/*.scala" } ); scanner.addDefaultExcludes(); scanner.scan(); String[] files = scanner.getIncludedFiles(); if ( sourcesToRewriteAccess == null ) { sourcesToRewriteAccess = toFiles( scannerBaseDir, files ); } else { sourcesToRewriteAccess.addAll( toFiles( scannerBaseDir, files ) ); } } } } boolean accessorsGeneratedInJavaClasses = generateAccessors( sourcesToGenerageAccessors, lastEnhanced, analysis, enhancer ); boolean accessRewritten = false; if ( sourcesToRewriteAccess != null ) { accessRewritten = rewriteAccess( sourcesToRewriteAccess, lastEnhanced, analysis, enhancer ); } if ( accessorsGeneratedInJavaClasses || accessRewritten ) { if ( analysis != null ) { analysis.writeToFile( analysisCacheFile ); } writeToFile( timestampFile, "ASCII", Long.toString( System.currentTimeMillis() ) ); } } catch ( IOException e ) { throw e; } catch ( Exception e ) { throw new MojoExecutionException( "Enhancement exception", e ); } } private Set<File> toFiles( File baseDir, String[] fileNames ) { Set<File> result = new HashSet<File>( fileNames.length ); for ( String fileName : fileNames ) { result.add( new File( baseDir, fileName ) ); } return result; } private boolean generateAccessors( Set<File> javaSources, long lastEnhanced, Analysis analysis, Play2JavaEnhancer enhancer ) throws Exception { int processedFiles = 0; int enhancedFiles = 0; if ( javaSources.size() > 0 ) { for ( File sourceFile : javaSources ) { if ( analysis.getCompilationTime( sourceFile ) > lastEnhanced ) { Set<File> javaClasses = analysis.getProducts( sourceFile ); for ( File classFile : javaClasses ) { processedFiles++; if ( enhancer.generateAccessors( classFile ) || enhancer.rewriteAccess( classFile ) ) { enhancedFiles++; getLog().debug( String.format( "\"%s\" enhanced", classFile.getPath() ) ); //if ( sbtAnalysisProcessor.areClassFileTimestampsSupported() ) //{ analysis.updateClassFileTimestamp( classFile ); //} } else { getLog().debug( String.format( "\"%s\" skipped", classFile.getPath() ) ); } } } } } if ( processedFiles > 0 ) { getLog().info( String.format( "Generate accessors - %d Java %s processed, %d enhanced", Integer.valueOf( processedFiles ), processedFiles > 1 ? "classes" : "class", Integer.valueOf( enhancedFiles ) ) ); } else { getLog().info( "Generate accessors - no Java classes to process" ); } return enhancedFiles > 0; } private boolean rewriteAccess( Set<File> sourceFilesToEnhance, long lastEnhanced, Analysis analysis, Play2JavaEnhancer enhancer ) throws Exception { int processedFiles = 0; int enhancedFiles = 0; if ( sourceFilesToEnhance.size() > 0 ) { for ( File sourceFile : sourceFilesToEnhance ) { if ( analysis.getCompilationTime( sourceFile ) > lastEnhanced ) { Set<File> templateClasses = analysis.getProducts( sourceFile ); for ( File classFile : templateClasses ) { processedFiles++; if ( enhancer.rewriteAccess( classFile ) ) { enhancedFiles++; getLog().debug( String.format( "\"%s\" enhanced", classFile.getPath() ) ); analysis.updateClassFileTimestamp( classFile ); } else { getLog().debug( String.format( "\"%s\" skipped", classFile.getPath() ) ); } } } } } if ( processedFiles > 0 ) { getLog().info( String.format( "Rewrite access - %d %s processed, %d enhanced", Integer.valueOf( processedFiles ), processedFiles > 1 ? "classes" : "class", Integer.valueOf( enhancedFiles ) ) ); } else { getLog().info( "Rewrite access - no classes to process" ); } return enhancedFiles > 0; } }
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.net.InetAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Client { /** * @param args */ private static int clientID; private static HashMap<Integer,Integer> quorumset; private static int clockcounter=0; private static boolean canSendRequestMessage=true; private static int MessageCounter=40; private static boolean LOCKED=false; private static String CurrentLockedMessage=""; private static boolean Semaphore=false; private static boolean sentInquire=false; public static int countREQUEST=0; public static int countLOCKED=0; public static int countRELEASE=0; public static int countRELINQUISH=0; public static int countFAILED=0; public static int countINQUIRE=0; private ArrayList<String> INQUIRELIST=new ArrayList<String>(); public static Client clientnd; public static void main(String[] args) { // TODO Auto-generated method stub int delay=0; String ipadd=""; try { ipadd = InetAddress.getLocalHost().getHostName(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Client cl=null; /*if(ipadd.equals("net01.utdallas.edu")){ clientnd=new Client(1); delay=8000; }else if(ipadd.equals("net02.utdallas.edu")){ clientnd=new Client(2); delay=7500; }else if(ipadd.equals("net03.utdallas.edu")){ clientnd=new Client(3); delay=7000; }else if(ipadd.equals("net04.utdallas.edu")){ clientnd=new Client(4); delay=6500; }else if(ipadd.equals("net05.utdallas.edu")){ clientnd=new Client(5); delay=6000; }else if(ipadd.equals("net06.utdallas.edu")){ clientnd=new Client(6); delay=5500; }else if(ipadd.equals("net07.utdallas.edu")){ clientnd=new Client(7); delay=5000; }*/ clientnd=new Client(2); delay=1000; clientnd.createServer(); try { Thread.currentThread().sleep(delay); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(MessageCounter!=0){ clientnd.SendRequestMessage(); MessageCounter--; } /*new Thread() { public void run() { while(true){ //System.out.println("Thread for processing Messages started"); clientnd.processMessageQueue(); } } }.start();*/ } public Client(int id){ clientID=id; if(clientID==1){ quorumset= new HashMap<Integer,Integer>(3); }else if(clientID==2){ quorumset= new HashMap<Integer,Integer>(4); }else if(clientID==3){ quorumset= new HashMap<Integer,Integer>(3); }else if(clientID==4){ quorumset= new HashMap<Integer,Integer>(4); }else if(clientID==5){ quorumset= new HashMap<Integer,Integer>(4); }else if(clientID==6){ quorumset= new HashMap<Integer,Integer>(3); }else if(clientID==7){ quorumset= new HashMap<Integer,Integer>(4); } } public void createServer(){ int portnum=NodeConfig.getClientport(clientID); new clientServer(portnum).start(); } public void connectClient(String message){ String hostname=""; int portnum=0; hostname=NodeConfig.getclienthostname(clientID); //Connect to Self portnum=NodeConfig.getClientport(clientID); new clientConnection(hostname,portnum,message).start(); if(clientID==1){ hostname=NodeConfig.getclienthostname(clientID+1); //Connect to Client2 portnum=NodeConfig.getClientport(clientID+1); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID+3); //Connect to Client4 portnum=NodeConfig.getClientport(clientID+3); new clientConnection(hostname,portnum,message).start(); }else if(clientID==2){ hostname=NodeConfig.getclienthostname(clientID+1); //Connect to Client3 portnum=NodeConfig.getClientport(clientID+1); //Change the value clientID+1 new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID+2); //Connect to Client4 portnum=NodeConfig.getClientport(clientID+2); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID+5); //Connect to Client7 portnum=NodeConfig.getClientport(clientID+5); new clientConnection(hostname,portnum,message).start(); }else if(clientID==3){ hostname=NodeConfig.getclienthostname(clientID-2); //Connect to Client1 portnum=NodeConfig.getClientport(clientID-2); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID+4); //Connect to Client7 portnum=NodeConfig.getClientport(clientID+4); new clientConnection(hostname,portnum,message).start(); }else if(clientID==4){ hostname=NodeConfig.getclienthostname(clientID+1); //Connect to Client5 portnum=NodeConfig.getClientport(clientID+1); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID+2); //Connect to Client6 portnum=NodeConfig.getClientport(clientID+2); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID+3); //Connect to Client7 portnum=NodeConfig.getClientport(clientID+3); new clientConnection(hostname,portnum,message).start(); }else if(clientID==5){ hostname=NodeConfig.getclienthostname(clientID-3); //Connect to Client2 portnum=NodeConfig.getClientport(clientID-3); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID-2); //Connect to Client3 portnum=NodeConfig.getClientport(clientID-2); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID+1); //Connect to Client6 portnum=NodeConfig.getClientport(clientID+1); new clientConnection(hostname,portnum,message).start(); }else if(clientID==6){ hostname=NodeConfig.getclienthostname(clientID-5); //Connect to Client1 portnum=NodeConfig.getClientport(clientID-5); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID-3); //Connect to Client3 portnum=NodeConfig.getClientport(clientID-3); new clientConnection(hostname,portnum,message).start(); }else if(clientID==7){ hostname=NodeConfig.getclienthostname(clientID-4); //Connect to Client3 portnum=NodeConfig.getClientport(clientID-4); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID-3); //Connect to Client4 portnum=NodeConfig.getClientport(clientID-3); new clientConnection(hostname,portnum,message).start(); hostname=NodeConfig.getclienthostname(clientID-2); //Connect to Client5 portnum=NodeConfig.getClientport(clientID-2); new clientConnection(hostname,portnum,message).start(); } } public HashMap<Integer,Integer> getQuorumState(int ClientID){ return quorumset; } //Added synchronization public synchronized void setQuorumState(String message){ int clientno=getClientID(message); String messagetype= getMessageType(message); int state=0; //System.out.println("setting QuorumState for incoming message "+ message); // In case Locked message is received state will be 1 and if FAILED TYPE is RECEIVED state will be -1 if(messagetype.equals(NodeConfig.LOCKED)){ state=1; }else if(messagetype.equals(NodeConfig.FAILED)){ state=-1; } //System.out.println("setQuorumState: ClientID "+ clientno+ "State"+ state); //quorumset.put(clientno, state); if(clientID==1){ if(clientno==1||clientno==2||clientno==4){ quorumset.put(clientno, state); } }else if(clientID==2){ if(clientno==2||clientno==3||clientno==4||clientno==7){ quorumset.put(clientno, state); } }else if(clientID==3){ if(clientno==1||clientno==3||clientno==7){ quorumset.put(clientno, state); } }else if(clientID==4){ if(clientno==4||clientno==5||clientno==6||clientno==7){ quorumset.put(clientno, state); } }else if(clientID==5){ if(clientno==2||clientno==3||clientno==5||clientno==6){ quorumset.put(clientno, state); } }else if(clientID==6){ if(clientno==1||clientno==3||clientno==6){ quorumset.put(clientno, state); } }else if(clientID==7){ if(clientno==3||clientno==4||clientno==5||clientno==7){ quorumset.put(clientno, state); } } } //Synchronization is not req here private boolean CheckClientFailedResponse(){ int num=0; boolean response=false; Log.write("CheckClientFailedResponse quorum" + quorumset.values()); for (Integer value : quorumset.values()) { if(value==-1){ response=true; break; } } Log.write("CheckClientFailedResponse response" + response); return response; } private boolean CanEnterCriticalSection(){ int num=0; boolean response=false; Log.write("CanEnterCriticalSection quorum" + quorumset.values()); int MAXSIZE=getquorumsetsize(); for (Integer value : quorumset.values()) { if(value==1){ response=true; num++; }else{ response=false; break; } } //check if the quorum size has been reached it max //num++; if(num<MAXSIZE){ response=false; } //System.out.println("CheckingCriticalSectionEntry:"+ num); Log.write("CanEnterCriticalSection response: " + response); return response; } //Get the size of the each of the quorum set based on the clientID private int getquorumsetsize(){ int SIZE=0; if(clientID==1){ //SIZE=2; SIZE=3; }else if(clientID==2){ SIZE=4; //SIZE=2; }else if(clientID==3){ SIZE=3; }else if(clientID==4){ SIZE=4; }else if(clientID==5){ SIZE=4; }else if(clientID==6){ SIZE=3; }else if(clientID==7){ SIZE=4; } return SIZE; } //Send a message public synchronized void SendMessage(String output_message, int whichclient){ String senderhostname=NodeConfig.getclienthostname(whichclient); //Connect to Client6 int clientportnum=NodeConfig.getClientport(whichclient); new clientConnection(senderhostname,clientportnum,output_message).start(); } // Send a Request Message public void SendRequestMessage(){ String reqmsg=getMessageFormat(NodeConfig.REQUEST,clientID); connectClient(reqmsg); } public synchronized void ProcessIncomingMessage(String Message_IN){ String Message_TYPE=this.getMessageType(Message_IN); int Message_Clock=this.getClockvalue(Message_IN); int Message_ClientID=this.getClientID(Message_IN); this.setClockCounter(Message_Clock); if(Message_TYPE.equals(NodeConfig.REQUEST)){ int pos=PriorityQueue.add(Message_IN); countREQUEST++; if(!LOCKED){ LOCKED=true; CurrentLockedMessage=PriorityQueue.poll(); int getclientID=getClientID(CurrentLockedMessage); SendMessage(getMessageFormat(NodeConfig.LOCKED, clientID),getclientID); Log.write("Sent LOCKED Message to client "+ getclientID); }else{ int isPreceding=PriorityQueue.CompareMessage(CurrentLockedMessage, Message_IN); if(isPreceding==0){ String sendFailedMsg=this.getMessageFormat(NodeConfig.FAILED, clientID); this.SendMessage(sendFailedMsg, Message_ClientID); Log.write("Sent FAILED Message to current waiting due to higher incoming message client "+ Message_ClientID); }else{ if(!sentInquire){ sentInquire=true; int getclientID=getClientID(CurrentLockedMessage); //This can also be store in a static variable String sendInquireMsg=this.getMessageFormat(NodeConfig.INQUIRE, clientID); this.SendMessage(sendInquireMsg, getclientID); Log.write("Sent INQUIRY Message to client "+ getclientID); }else{ if(pos==0){ String sendFailedMsg=this.getMessageFormat(NodeConfig.FAILED, clientID); for(int i=1;i<PriorityQueue.size();i++){ int clientid=getClientID(PriorityQueue.get(i)); this.SendMessage(sendFailedMsg, clientid); Log.write("Sent FAILED Message to current waiting message due to higher incoming message client "+ clientid); } } } } } }else if(Message_TYPE.equals(NodeConfig.LOCKED)){ countLOCKED++; setQuorumState(Message_IN); if(CanEnterCriticalSection()){ Writer output; try { output = new BufferedWriter(new FileWriter("input.txt",true)); output.append("ClientID "+InetAddress.getLocalHost().getHostName()+" MessageCount: "+MessageCounter+"\n"); output.append("REQUEST:"+countREQUEST+"\n"); output.append("LOCKED:"+countLOCKED+"\n"); output.append("RELEASED:"+countRELEASE+"\n"); output.append("FAILED:"+countFAILED+"\n"); output.append("RELINQUISH:"+countRELINQUISH+"\n"); output.append("INQUIRE:"+countINQUIRE+"\n"); output.close(); //finishedCriticalSection=true; quorumset.clear(); //Send Release message to all the client in the quorum String releasemessage=getMessageFormat(NodeConfig.RELEASE,clientID); connectClient(releasemessage); resetMessageCounts(); // the place to count messages //Thread.currentThread().sleep(1000); Log.write("Sent RELEASE Message to all clients "); if(MessageCounter!=0){ clientnd.SendRequestMessage(); MessageCounter--; Log.write("Sent REQUEST Message to all clients in quorum "); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }else if(Message_TYPE.equals(NodeConfig.FAILED)){ countFAILED++; setQuorumState(Message_IN); for(String message : INQUIRELIST) { int clientnum= getClientID(message); SendMessage(getMessageFormat(NodeConfig.RELINQUISH,clientID),clientnum); Log.write("Sent RELINQUISH Message to client " +clientnum ); } INQUIRELIST.clear(); }else if(Message_TYPE.equals(NodeConfig.INQUIRE)){ countINQUIRE++; int clientnum=getClientID(Message_IN); if(CheckClientFailedResponse()){ SendMessage(getMessageFormat(NodeConfig.RELINQUISH,clientID),clientnum); Log.write("Sent RELINQUISH Message to client " +clientnum ); }else{ INQUIRELIST.add(Message_IN); } }else if(Message_TYPE.equals(NodeConfig.RELEASE)){ countRELEASE++; sentInquire=false; if(!PriorityQueue.isEmpty()){ CurrentLockedMessage=PriorityQueue.poll(); int clientnum=getClientID(CurrentLockedMessage); SendMessage(getMessageFormat(NodeConfig.LOCKED,clientID),clientnum); LOCKED=true; Log.write("Sent LOCKED Message to client "+ clientnum + "after getting RELEASE message from client " + Message_ClientID); }else{ LOCKED=false; CurrentLockedMessage=""; } }else if(Message_TYPE.equals(NodeConfig.RELINQUISH)){ countRELINQUISH++; sentInquire=false; PriorityQueue.add(CurrentLockedMessage); CurrentLockedMessage=PriorityQueue.poll(); int clientnum=getClientID(CurrentLockedMessage); SendMessage(getMessageFormat(NodeConfig.LOCKED,clientID),clientnum); Log.write("Sent LOCKED Message to client "+ clientnum + "after getting reliquish message from client " + Message_ClientID); } } public int getClockvalue(String msg){ // message format "REQUEST:TIME_STAMP:CLIENTID" StringTokenizer message_token = new StringTokenizer(msg, ":"); String tokens[] = new String[message_token.countTokens()]; int i=0; while (message_token.hasMoreTokens()) { tokens[i] = message_token.nextToken(); //System.out.println(tokens[i]); i++; } return Integer.parseInt(tokens[1]); } public int getClientID(String msg){ // message format "REQUEST:TIME_STAMP:CLIENTID" StringTokenizer message_token = new StringTokenizer(msg, ":"); String tokens[] = new String[message_token.countTokens()]; int i=0; while (message_token.hasMoreTokens()) { tokens[i] = message_token.nextToken(); //System.out.println(tokens[i]); i++; } return Integer.parseInt(tokens[2]); } public String getMessageType(String msg){ // message format "REQUEST:TIME_STAMP:CLIENTID" StringTokenizer message_token = new StringTokenizer(msg, ":"); String tokens[] = new String[message_token.countTokens()]; int i=0; while (message_token.hasMoreTokens()) { tokens[i] = message_token.nextToken(); //System.out.println(tokens[i]); i++; } return tokens[0]; } //Create the message format public synchronized String getMessageFormat(String requesttype,int Clientnum){ int clck=setClockCounter(0); String message=requesttype+":"+clck+":"+Clientnum; return message; } public int getClockCounter(){ return clockcounter; } public synchronized int setClockCounter(int remoteClock){ if((remoteClock+1)>(clockcounter+1)){ clockcounter=remoteClock+1; }else clockcounter++; return clockcounter; } public void resetMessageCounts(){ countREQUEST=0; countLOCKED=0; countRELEASE=0; countRELINQUISH=0; countFAILED=0; countINQUIRE=0; } public void processMessageQueue() { System.out.println("checking Message present in MESSAGEQUEUE :" + MessageQueue.isEmpty() ); if(MessageQueue.isEmpty()){ try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; }else{ //Just check here if there is any synchronization problem String inmsg=MessageQueue.poll(); System.out.println("processing Message from MESSAGEQUEUE :" + inmsg ); Log.write("processing Message from MESSAGEQUEUE :" + inmsg); ProcessIncomingMessage(inmsg); System.out.println("Finished processing Message from MESSAGEQUEUE: " + inmsg); Log.write("Finished processing Message from MESSAGEQUEUE: " + inmsg); return; } } }
/* * $Id$ * * Copyright 2000-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.struts.action; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.DynaClass; import org.apache.commons.beanutils.DynaProperty; import org.apache.struts.config.FormBeanConfig; import org.apache.struts.config.FormPropertyConfig; /** * <p>Specialized subclass of <code>ActionForm</code> that allows the creation * of form beans with dynamic sets of properties, without requiring the * developer to create a Java class for each type of form bean.</p> * * <p><strong>USAGE NOTE</strong> - Since Struts 1.1, the * <code>reset</code> method no longer initializes property values to those * specified in <code>&lt;form-property&gt;</code> elements in the Struts * module configuration file. If you wish to utilize that behavior, the * simplest solution is to subclass <code>DynaActionForm</code> and call * the <code>initialize</code> method inside it.</p> * * @version $Rev$ $Date$ * @since Struts 1.1 */ public class DynaActionForm extends ActionForm implements DynaBean { // ----------------------------------------------------- Instance Variables /** * <p>The <code>DynaActionFormClass</code> with which we are associated. * </p> */ protected DynaActionFormClass dynaClass = null; /** * <p>The set of property values for this <code>DynaActionForm</code>, * keyed by property name.</p> */ protected HashMap dynaValues = new HashMap(); // ----------------------------------------------------- ActionForm Methods /** * <p>Initialize all bean properties to their initial values, as specified * in the {@link FormPropertyConfig} elements associated with the * definition of this <code>DynaActionForm</code>.</p> * * @param mapping The mapping used to select this instance */ public void initialize(ActionMapping mapping) { String name = mapping.getName(); if (name == null) { return; } FormBeanConfig config = mapping.getModuleConfig().findFormBeanConfig(name); if (config == null) { return; } initialize(config); } public void initialize(FormBeanConfig config) { FormPropertyConfig props[] = config.findFormPropertyConfigs(); for (int i = 0; i < props.length; i++) { set(props[i].getName(), props[i].initial()); } } // :FIXME: Is there any point in retaining these reset methods // since they now simply replicate the superclass behavior? /** * <p>Reset bean properties to their default state, as needed. * This method is called before the properties are repopulated by * the controller.</p> * * <p>The default implementation attempts to forward to the HTTP * version of this method.</p> * * @param mapping The mapping used to select this instance * @param request The servlet request we are processing */ public void reset(ActionMapping mapping, ServletRequest request) { super.reset(mapping,request); } /** * <p>Reset bean properties to their default state, as needed. This method is * called before the properties are repopulated by the controller.</p> * * <p>The default implementation (since Struts 1.1) does nothing. * Subclasses may override this method to reset bean properties to * default values, or the <code>initialize</code> method may be used to * initialize property values to those provided in the form property * configuration information (which was the behavior of * this method in some release candidates).</p> * * @param mapping The mapping used to select this instance * @param request The servlet request we are processing */ public void reset(ActionMapping mapping, HttpServletRequest request) { super.reset(mapping,request); } // ------------------------------------------------------- DynaBean Methods /** * <p>Indicates if the specified mapped property contain a value for the * specified key value.</p> * * @param name Name of the property to check * @param key Name of the key to check * * @exception IllegalArgumentException if there is no property * of the specified name */ public boolean contains(String name, String key) { Object value = dynaValues.get(name); if (value == null) { throw new NullPointerException ("No mapped value for '" + name + "(" + key + ")'"); } else if (value instanceof Map) { return (((Map) value).containsKey(key)); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'"); } } /** * <p>Return the value of a simple property with the specified name.</p> * * @param name Name of the property whose value is to be retrieved * * @exception IllegalArgumentException if there is no property * of the specified name * @exception NullPointerException if the type specified for the * property is invalid */ public Object get(String name) { // Return any non-null value for the specified property Object value = dynaValues.get(name); if (value != null) { return (value); } // Return a null value for a non-primitive property Class type = getDynaProperty(name).getType(); if (type == null) { throw new NullPointerException ("The type for property " + name + " is invalid"); } if (!type.isPrimitive()) { return (value); } // Manufacture default values for primitive properties if (type == Boolean.TYPE) { return (Boolean.FALSE); } else if (type == Byte.TYPE) { return (new Byte((byte) 0)); } else if (type == Character.TYPE) { return (new Character((char) 0)); } else if (type == Double.TYPE) { return (new Double(0.0)); } else if (type == Float.TYPE) { return (new Float((float) 0.0)); } else if (type == Integer.TYPE) { return (new Integer(0)); } else if (type == Long.TYPE) { return (new Long(0)); } else if (type == Short.TYPE) { return (new Short((short) 0)); } else { return (null); } } /** * <p>Return the value of an indexed property with the specified name. * </p> * * @param name Name of the property whose value is to be retrieved * @param index Index of the value to be retrieved * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property * @exception NullPointerException if no array or List has been * initialized for this property */ public Object get(String name, int index) { Object value = dynaValues.get(name); if (value == null) { throw new NullPointerException ("No indexed value for '" + name + "[" + index + "]'"); } else if (value.getClass().isArray()) { return (Array.get(value, index)); } else if (value instanceof List) { return ((List) value).get(index); } else { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]'"); } } /** * <p>Return the value of a mapped property with the specified name, * or <code>null</code> if there is no value for the specified key. * </p> * * @param name Name of the property whose value is to be retrieved * @param key Key of the value to be retrieved * * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public Object get(String name, String key) { Object value = dynaValues.get(name); if (value == null) { throw new NullPointerException ("No mapped value for '" + name + "(" + key + ")'"); } else if (value instanceof Map) { return (((Map) value).get(key)); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'"); } } /** * <p>Return the value of a <code>String</code> property with the specified * name. This is equivalent to calling * <code>(String) dynaForm.get(name)</code>.</p> * * @param name Name of the property whose value is to be retrieved * * @throws IllegalArgumentException if there is no property * of the specified name * @throws NullPointerException if the type specified for the * property is invalid * @throws ClassCastException if the property is not a String. * @since Struts 1.2 */ public String getString(String name) { return (String) this.get(name); } /** * <p>Return the value of a <code>String[]</code> property with the * specified name. This is equivalent to calling * <code>(String[]) dynaForm.get(name)</code>.</p> * * @param name Name of the property whose value is to be retrieved * * @throws IllegalArgumentException if there is no property * of the specified name * @throws NullPointerException if the type specified for the * property is invalid * @throws ClassCastException if the property is not a String[]. * @since Struts 1.2 */ public String[] getStrings(String name) { return (String[]) this.get(name); } /** * <p>Return the <code>DynaClass</code> instance that describes the set * of properties available for this <code>DynaBean</code>.</p> */ public DynaClass getDynaClass() { return (this.dynaClass); } /** * <p>Returns the <code>Map</code> containing the property values. This is * done mostly to facilitate accessing the <code>DynaActionForm</code> * through JavaBeans accessors, in order to use the JavaServer Pages * Standard Tag Library (JSTL).</p> * * <p>For instance, the normal JSTL EL syntax for accessing an * <code>ActionForm</code> would be something like this: * <pre> * ${formbean.prop}</pre> * The JSTL EL syntax for accessing a <code>DynaActionForm</code> looks * something like this (because of the presence of this * <code>getMap()</code> method): * <pre> * ${dynabean.map.prop}</pre> * </p> */ public Map getMap() { return (dynaValues); } /** * <p>Remove any existing value for the specified key on the * specified mapped property.</p> * * @param name Name of the property for which a value is to * be removed * @param key Key of the value to be removed * * @exception IllegalArgumentException if there is no property * of the specified name */ public void remove(String name, String key) { Object value = dynaValues.get(name); if (value == null) { throw new NullPointerException ("No mapped value for '" + name + "(" + key + ")'"); } else if (value instanceof Map) { ((Map) value).remove(key); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'"); } } /** * <p>Set the value of a simple property with the specified name.</p> * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception NullPointerException if the type specified for the * property is invalid * @exception NullPointerException if an attempt is made to set a * primitive property to null */ public void set(String name, Object value) { DynaProperty descriptor = getDynaProperty(name); if (descriptor.getType() == null) { throw new NullPointerException ("The type for property " + name + " is invalid"); } if (value == null) { if (descriptor.getType().isPrimitive()) { throw new NullPointerException ("Primitive value for '" + name + "'"); } } else if (!isDynaAssignable(descriptor.getType(), value.getClass())) { throw new ConversionException ("Cannot assign value of type '" + value.getClass().getName() + "' to property '" + name + "' of type '" + descriptor.getType().getName() + "'"); } dynaValues.put(name, value); } /** * <p>Set the value of an indexed property with the specified name.</p> * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property */ public void set(String name, int index, Object value) { Object prop = dynaValues.get(name); if (prop == null) { throw new NullPointerException ("No indexed value for '" + name + "[" + index + "]'"); } else if (prop.getClass().isArray()) { Array.set(prop, index, value); } else if (prop instanceof List) { try { ((List) prop).set(index, value); } catch (ClassCastException e) { throw new ConversionException(e.getMessage()); } } else { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]'"); } } /** * <p>Set the value of a mapped property with the specified name.</p> * * @param name Name of the property whose value is to be set * @param key Key of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not mapped */ public void set(String name, String key, Object value) { Object prop = dynaValues.get(name); if (prop == null) { throw new NullPointerException ("No mapped value for '" + name + "(" + key + ")'"); } else if (prop instanceof Map) { ((Map) prop).put(key, value); } else { throw new IllegalArgumentException ("Non-mapped property for '" + name + "(" + key + ")'"); } } // --------------------------------------------------------- Public Methods /** * <p>Render a String representation of this object.</p> */ public String toString() { StringBuffer sb = new StringBuffer("DynaActionForm[dynaClass="); DynaClass dynaClass = getDynaClass(); if (dynaClass == null) { return sb.append("null]").toString(); } sb.append(dynaClass.getName()); DynaProperty props[] = dynaClass.getDynaProperties(); if (props == null) { props = new DynaProperty[0]; } for (int i = 0; i < props.length; i++) { sb.append(','); sb.append(props[i].getName()); sb.append('='); Object value = get(props[i].getName()); if (value == null) { sb.append("<NULL>"); } else if (value.getClass().isArray()) { int n = Array.getLength(value); sb.append("{"); for (int j = 0; j < n; j++) { if (j > 0) { sb.append(','); } sb.append(Array.get(value, j)); } sb.append("}"); } else if (value instanceof List) { int n = ((List) value).size(); sb.append("{"); for (int j = 0; j < n; j++) { if (j > 0) { sb.append(','); } sb.append(((List) value).get(j)); } sb.append("}"); } else if (value instanceof Map) { int n = 0; Iterator keys = ((Map) value).keySet().iterator(); sb.append("{"); while (keys.hasNext()) { if (n > 0) { sb.append(','); } n++; Object key = keys.next(); sb.append(key); sb.append('='); sb.append(((Map) value).get(key)); } sb.append("}"); } else { sb.append(value); } } sb.append("]"); return (sb.toString()); } // -------------------------------------------------------- Package Methods /** * <p>Set the <code>DynaActionFormClass</code> instance with which we are * associated.</p> * * @param dynaClass The DynaActionFormClass instance for this bean */ void setDynaActionFormClass(DynaActionFormClass dynaClass) { this.dynaClass = dynaClass; } // ------------------------------------------------------ Protected Methods /** * <p>Return the property descriptor for the specified property name.</p> * * @param name Name of the property for which to retrieve the descriptor * * @exception IllegalArgumentException if this is not a valid property * name for our DynaClass */ protected DynaProperty getDynaProperty(String name) { DynaProperty descriptor = getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new IllegalArgumentException ("Invalid property name '" + name + "'"); } return (descriptor); } /** * <p>Indicates if an object of the source class is assignable to the * destination class.</p> * * @param dest Destination class * @param source Source class */ protected boolean isDynaAssignable(Class dest, Class source) { if (dest.isAssignableFrom(source) || ((dest == Boolean.TYPE) && (source == Boolean.class)) || ((dest == Byte.TYPE) && (source == Byte.class)) || ((dest == Character.TYPE) && (source == Character.class)) || ((dest == Double.TYPE) && (source == Double.class)) || ((dest == Float.TYPE) && (source == Float.class)) || ((dest == Integer.TYPE) && (source == Integer.class)) || ((dest == Long.TYPE) && (source == Long.class)) || ((dest == Short.TYPE) && (source == Short.class))) { return (true); } else { return (false); } } }
/** * The MIT License (MIT) * * Copyright (c) 2011-2016 Incapture Technologies LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package rapture.structured; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.junit.Ignore; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import rapture.common.PluginConfig; import rapture.common.PluginTransportItem; import rapture.common.RaptureURI; import rapture.common.Scheme; import rapture.common.StoredProcedureParams; import rapture.common.StructuredRepoConfig; import rapture.common.client.HttpAdminApi; import rapture.common.client.HttpBlobApi; import rapture.common.client.HttpDocApi; import rapture.common.client.HttpLoginApi; import rapture.common.client.HttpPluginApi; import rapture.common.client.HttpScriptApi; import rapture.common.client.HttpSearchApi; import rapture.common.client.HttpSeriesApi; import rapture.common.client.HttpStructuredApi; import rapture.common.client.HttpUserApi; import rapture.common.impl.jackson.JacksonUtil; import rapture.common.impl.jackson.MD5Utils; import rapture.helper.IntegrationTestHelper; import rapture.plugin.install.PluginSandbox; import rapture.plugin.install.PluginSandboxItem; import rapture.plugin.util.PluginUtils; public class StructuredApiIntegrationTests { private IntegrationTestHelper helper; private HttpLoginApi raptureLogin = null; private HttpUserApi userApi = null; private HttpStructuredApi structApi = null; private HttpSeriesApi seriesApi = null; private HttpScriptApi scriptApi = null; private HttpSearchApi searchApi = null; private HttpDocApi docApi = null; private HttpBlobApi blobApi = null; private IntegrationTestHelper helper2; private HttpUserApi userApi2 = null; private HttpDocApi docApi2 = null; private HttpLoginApi raptureLogin2 = null; private HttpAdminApi admin = null; private HttpPluginApi pluginApi = null; private RaptureURI repoUri = null; private static final String user = "User"; /** * Setup TestNG method to create Rapture login object and objects. * * @param RaptureURL * Passed in from <env>_testng.xml suite file * @param RaptureUser * Passed in from <env>_testng.xml suite file * @param RapturePassword * Passed in from <env>_testng.xml suite file * @return none */ @BeforeClass(groups = { "structured", "postgres","nightly" }) @Parameters({ "RaptureURL", "RaptureUser", "RapturePassword" }) public void setUp(@Optional("http://localhost:8665/rapture") String url, @Optional("rapture") String username, @Optional("rapture") String password) { // If running from eclipse set env var -Penv=docker or use the following // url variable settings: // url="http://192.168.99.101:8665/rapture"; //docker // url="http://localhost:8665/rapture"; helper = new IntegrationTestHelper(url, username, password); raptureLogin = helper.getRaptureLogin(); structApi = helper.getStructApi(); userApi = helper.getUserApi(); seriesApi = helper.getSeriesApi(); scriptApi = helper.getScriptApi(); docApi = helper.getDocApi(); blobApi = helper.getBlobApi(); searchApi = helper.getSearchApi(); admin = helper.getAdminApi(); pluginApi = helper.getPluginApi(); if (!admin.doesUserExist(user)) { admin.addUser(user, "Another User", MD5Utils.hash16(user), "user@incapture.net"); } helper2 = new IntegrationTestHelper(url, user, user); userApi2 = helper2.getUserApi(); docApi2 = helper2.getDocApi(); repoUri = helper.getRandomAuthority(Scheme.DOCUMENT); helper.configureTestRepo(repoUri, "MONGODB"); // TODO Make this configurable } @Test(groups = { "structured", "postgres","nightly" }) public void testDeleteNonExistingRow() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { marvin=\"paranoid\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); row.put("id", 43); row.put("name", "Don't Panic Now"); structApi.insertRow(table, row); row.put("id", 44); row.put("name", "Don't Panic Now Again"); structApi.insertRow(table, row); structApi.deleteRows(table, "id=45"); List<Map<String, Object>> contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.size(), 3); } @Test(groups = { "structured", "postgres","nightly" }) public void testDeleteByTextColumn() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { marvin=\"paranoid\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "AAA"); structApi.insertRow(table, row); row.put("id", 43); row.put("name", "AAB"); structApi.insertRow(table, row); row.put("id", 44); row.put("name", "BAA"); structApi.insertRow(table, row); row.put("id", 45); row.put("name", "BAAB"); structApi.insertRow(table, row); row.put("id", 46); row.put("name", "AACCA"); structApi.insertRow(table, row); row.put("id", 47); row.put("name", "AAC"); structApi.insertRow(table, row); structApi.deleteRows(table, "name LIKE 'AA%'"); List<Map<String, Object>> contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.get(0), ImmutableMap.of("id", new Integer(44),"name","BAA")); Assert.assertEquals(contents.get(1), ImmutableMap.of("id", new Integer(45),"name","BAAB")); structApi.deleteRows(table, "name LIKE '%AA'"); contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.get(0), ImmutableMap.of("id", new Integer(45),"name","BAAB")); } @Test(groups = { "structured", "postgres","nightly" }) public void testBasicStructuredRepo() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { marvin=\"paranoid\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); List<Map<String, Object>> contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.size(), 1); Assert.assertEquals(contents.get(0), row); // Batch insert List<Map<String, Object>> batch = new ArrayList<>(); for (String s : ImmutableList.of("Ford Prefect", "Zaphod Beeblebrox", "Arthur Dent", "Slartibartfast", "Trillian")) { int cha = s.charAt(0); batch.add(ImmutableMap.<String, Object> of("id", cha, "name", s)); } structApi.insertRows(table, batch); contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.size(), batch.size() + 1); structApi.deleteRows(table, "id=42"); contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.size(), batch.size()); for (Map<String, Object> m : batch) Assert.assertTrue(contents.contains(m)); Assert.assertTrue(contents.contains(ImmutableMap.<String, Object> of("id", new Integer('Z'), "name", "Zaphod Beeblebrox"))); // Update a row structApi.updateRows(table, ImmutableMap.<String, Object> of("id", new Integer('Z'), "name", "Zarniwoop"), "id=" + new Integer('Z')); contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.size(), batch.size()); Assert.assertTrue(contents.contains(ImmutableMap.<String, Object> of("id", new Integer('Z'), "name", "Zarniwoop"))); Assert.assertFalse(contents.contains(ImmutableMap.<String, Object> of("id", new Integer('Z'), "name", "Zaphod Beeblebrox"))); System.out.println(JacksonUtil.prettyfy(JacksonUtil.jsonFromObject(contents))); structApi.deleteRows(table, "name like 'Zarniwoop'"); contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertFalse(contents.contains(ImmutableMap.<String, Object> of("id", new Integer('Z'), "name", "Zarniwoop"))); structApi.dropTable(table); try { contents = structApi.selectRows(table, null, null, null, null, -1); Assert.fail("Expected an exception to be thrown"); } catch (Exception e) { // Expected } // Good enough. Delete the repo. structApi.deleteStructuredRepo(repoStr); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist any more"); } // Verify that ascending/descending works for strings and integers @Test(groups = { "structured", "postgres","nightly" }) public void testAscending() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { planet=\"magrathea\" }"; if (!structApi.structuredRepoExists(repoStr)) structApi.createStructuredRepo(repoStr, config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); List<Map<String, Object>> contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.size(), 1); Assert.assertEquals(contents.get(0), row); // Batch insert List<Map<String, Object>> batch = new ArrayList<>(); for (String s : ImmutableList.of("Roosta", "Hotblack Desiato", "Ford Prefect", "Zaphod Beeblebrox", "Arthur Dent", "Slartibartfast", "Trillian")) { int cha = s.hashCode() % 131; batch.add(ImmutableMap.<String, Object> of("id", cha, "name", s)); } structApi.insertRows(table, batch); contents = structApi.selectRows(table, null, "id != 42", ImmutableList.of("name"), true, -1); System.out.println(JacksonUtil.prettyfy(JacksonUtil.jsonFromObject(contents))); Assert.assertEquals(contents.size(), batch.size()); String last = "AAAA"; for (Map<String, Object> map : contents) { String next = map.get("name").toString(); Assert.assertTrue(next.compareTo(last) > 0); last = next; } contents = structApi.selectRows(table, null, "id != 42", ImmutableList.of("name"), false, -1); System.out.println(JacksonUtil.prettyfy(JacksonUtil.jsonFromObject(contents))); Assert.assertEquals(contents.size(), batch.size()); last = "Zz"; for (Map<String, Object> map : contents) { String next = map.get("name").toString(); Assert.assertTrue(last.compareTo(next) > 0, last + " > " + next); last = next; } contents = structApi.selectRows(table, null, "id != 42", ImmutableList.of("id"), true, -1); Assert.assertEquals(contents.size(), batch.size()); Integer lasti = Integer.MIN_VALUE; for (Map<String, Object> map : contents) { Integer nexti = (Integer) map.get("id"); Assert.assertTrue(nexti.compareTo(lasti) > 0); lasti = nexti; } contents = structApi.selectRows(table, null, "id != 42", ImmutableList.of("id"), false, -1); System.out.println(JacksonUtil.prettyfy(JacksonUtil.jsonFromObject(contents))); Assert.assertEquals(contents.size(), batch.size()); lasti = Integer.MAX_VALUE; for (Map<String, Object> map : contents) { Integer nexti = (Integer) map.get("id"); Assert.assertTrue(lasti.compareTo(nexti) > 0, lasti + " > " + nexti); lasti = nexti; } // Good enough. Delete the repo. structApi.deleteStructuredRepo(repoStr); Assert.assertFalse(structApi.structuredRepoExists(repoStr), "Repo does not exist any more"); } @Test(groups = { "structured", "postgres","nightly" }) public void testSqlGeneration() { String foo = "Don\'t Panic"; String bar = foo.replace("\'", "''"); Assert.assertEquals("Don''t Panic", bar); RaptureURI repo = new RaptureURI("structured://hhgg"); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { planet=\"magrathea\" }"; try { if (!structApi.structuredRepoExists(repoStr)) structApi.createStructuredRepo(repoStr, config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); boolean pass = false; String sql = structApi.getDdl(table, true); for (String s : sql.split("\n")) { if (s.contains("INSERT")) { Assert.assertEquals("INSERT INTO hhgg.table (id, name) VALUES ('42', 'Don''t Panic')", s); pass = true; } } Assert.assertTrue(pass); } finally { if (structApi.structuredRepoExists(repoStr)) structApi.deleteStructuredRepo(repoStr); } } @Test(groups = { "structured", "postgres", "nightly" }) public void testSqlSequenceGeneration() { RaptureURI repo = new RaptureURI("structured://hhgg"); String repoStr = repo.toString(); String table = "hhgg/ford"; String config = "STRUCTURED { } USING POSTGRES { planet=\"magrathea\" }"; try { if (!structApi.structuredRepoExists(repoStr)) structApi.createStructuredRepo(repoStr, config); // It would appear to be a restriction that the sequence name be structApi.createProcedureCallUsingSql(repoStr + "/fordseq", "DROP SEQUENCE ford_ident_seq;"); StoredProcedureParams params = new StoredProcedureParams(); structApi.callProcedure(repoStr + "/fordseq", params); structApi.createProcedureCallUsingSql(repoStr + "/fordseq", "CREATE SEQUENCE ford_ident_seq;"); structApi.callProcedure(repoStr + "/fordseq", params); String sql = "CREATE TABLE hhgg.ford ( ident INTEGER NOT NULL UNIQUE DEFAULT nextval('ford_ident_seq'), name TEXT);"; structApi.createTableUsingSql(repoStr, sql); structApi.insertRow(table, ImmutableMap.of("name", "Dentarthurdent")); structApi.insertRow(table, ImmutableMap.of("name", "Tricia McMillan")); boolean pass = false; String ddl = structApi.getDdl(table, true); ddl = ddl.substring(0, ddl.indexOf('/')); Assert.assertEquals(ddl, "CREATE SEQUENCE ford_ident_seq;\n\nCREATE TABLE hhgg.ford\n(\n ident INTEGER NOT NULL UNIQUE DEFAULT nextval('ford_ident_seq'),\n name TEXT\n);\n\n" + "INSERT INTO hhgg.ford (ident, name) VALUES ('1', 'Dentarthurdent')\nINSERT INTO hhgg.ford (ident, name) VALUES ('2', 'Tricia McMillan')\n"); } finally { if (structApi.structuredRepoExists(repoStr)) structApi.deleteStructuredRepo(repoStr); } } // Test used in conjunction with manually running plugin installer to verify that it works. // Could possibly be expanded to invoke the PI but more hassle than it's worth. // The preceding test verifies the code in question, though it doesn't exercise the executeDdl method // as that's a trusted method on the server @Ignore @Test(groups = { "structured", "postgres","nightly" }, enabled=false) public void manualTestPlugin() { RaptureURI repo = new RaptureURI("structured://hhgg"); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { planet=\"magrathea\" }"; if (!structApi.structuredRepoExists(repoStr)) structApi.createStructuredRepo(repoStr, config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); List<Map<String, Object>> contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.size(), 1); Assert.assertEquals(contents.get(0), row); // Batch insert List<Map<String, Object>> batch = new ArrayList<>(); for (String s : ImmutableList.of("Roosta", "Hotblack Desiato", "Ford Prefect", "Zaphod Beeblebrox", "Arthur Dent", "Slartibartfast", "Trillian")) { int cha = s.hashCode() % 131; batch.add(ImmutableMap.<String, Object> of("id", cha, "name", s)); } structApi.insertRows(table, batch); // Now export the plug-in // Put a breakpoint here // Delete the repo structApi.deleteStructuredRepo(repoStr); Assert.assertFalse(structApi.structuredRepoExists(repoStr), "Repo does not exist any more"); // Now install the plug-in // Put a breakpoint here Assert.assertTrue(structApi.structuredRepoExists(repoStr), "Repo created"); contents = structApi.selectRows(table, null, "id = 42", ImmutableList.of("id"), true, -1); Assert.assertEquals(1, contents.size()); // Good enough. Delete the repo. structApi.deleteStructuredRepo(repoStr); Assert.assertFalse(structApi.structuredRepoExists(repoStr), "Repo does not exist any more"); } @Test(groups = { "structured", "postgres","nightly" }) public void testInsertExistingRow() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { douglas=\"adams\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 43); row.put("name", "Don't Panic More"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 44); row.put("name", "Don't Panic Even More"); structApi.insertRow(table, row); try { structApi.insertRow(table, row); Assert.fail(); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("duplicate key value violates")); } } @Test(groups = { "structured", "postgres","nightly" }) public void testUpdateNonExistingRow() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { douglas=\"adams\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 43); row.put("name", "Don't Panic More"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 44); row.put("name", "Don't Panic Even More"); structApi.insertRow(table, row); structApi.updateRows(table, ImmutableMap.of("name", "bob"), "id=400"); List<Map<String, Object>> contents = structApi.selectRows(table, null, null, null, null, -1); Assert.assertEquals(contents.get(0), ImmutableMap.of("id", new Integer(42),"name","Don't Panic")); Assert.assertEquals(contents.get(1), ImmutableMap.of("id", new Integer(43),"name","Don't Panic More")); Assert.assertEquals(contents.get(2), ImmutableMap.of("id", new Integer(44),"name","Don't Panic Even More")); } @Test(groups = { "structured", "postgres","nightly" }) public void testSelectWithWhereClause() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { douglas=\"adams\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 43); row.put("name", "Don't Panic More"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 44); row.put("name", "Don't Panic Even More"); structApi.insertRow(table, row); List<Map<String, Object>> contents = structApi.selectRows(table, null, "id<43", null, null, -1); Assert.assertEquals(contents.size(), 1); Assert.assertEquals(contents.get(0), ImmutableMap.of("id", new Integer(42),"name","Don't Panic")); } @Test(groups = { "structured", "postgres","nightly" }) public void testSelectWithInvalidWhereClause() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { douglas=\"adams\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); try { structApi.selectRows(table, null, "id*43", null, null, -1); Assert.fail("Select statement should have failed from invalid where clause"); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Failed to parse where clause")); } } @Test(groups = { "structured", "postgres","nightly" }) public void testSelectColumns() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { douglas=\"adams\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 43); row.put("name", "Don't Panic More"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 44); row.put("name", "Don't Panic Even More"); structApi.insertRow(table, row); List<Map<String, Object>> contents = structApi.selectRows(table, ImmutableList.of("id"), null, null, null, -1); Assert.assertEquals(contents.get(0), ImmutableMap.of("id", new Integer(42))); Assert.assertEquals(contents.get(1), ImmutableMap.of("id", new Integer(43))); Assert.assertEquals(contents.get(2), ImmutableMap.of("id", new Integer(44))); } @Test(groups = { "structured", "postgres","nightly" }) public void testSelectColumnsDecending() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { douglas=\"adams\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Don't Panic"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 43); row.put("name", "Don't Panic More"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 44); row.put("name", "Don't Panic Even More"); structApi.insertRow(table, row); List<Map<String, Object>> contents = structApi.selectRows(table, ImmutableList.of("id"), null, ImmutableList.of("id"), Boolean.FALSE, -1); Assert.assertEquals(contents.get(0), ImmutableMap.of("id", new Integer(44))); Assert.assertEquals(contents.get(1), ImmutableMap.of("id", new Integer(43))); Assert.assertEquals(contents.get(2), ImmutableMap.of("id", new Integer(42))); } @Test(groups = { "structured", "postgres","nightly" }) public void testSelectColumnsOrdering() { RaptureURI repo = helper.getRandomAuthority(Scheme.STRUCTURED); String repoStr = repo.toString(); String config = "STRUCTURED { } USING POSTGRES { douglas=\"adams\" }"; // Create a repo Boolean repoExists = structApi.structuredRepoExists(repoStr); Assert.assertFalse(repoExists, "Repo does not exist yet"); structApi.createStructuredRepo(repoStr, config); repoExists = structApi.structuredRepoExists(repoStr); Assert.assertTrue(repoExists, "Repo should exist now"); // Verify the config StructuredRepoConfig rc = structApi.getStructuredRepoConfig(repoStr); Assert.assertEquals(rc.getConfig(), config); // Create a table. Add and remove data String table = "//" + repo.getAuthority() + "/table"; structApi.createTable(table, ImmutableMap.of("id", "int", "name", "varchar(255), PRIMARY KEY (id)")); Map<String, Object> row = new HashMap<>(); row.put("id", 42); row.put("name", "Evan"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 43); row.put("name", "Aaron"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 44); row.put("name", "Carl"); structApi.insertRow(table, row); row = new HashMap<>(); row.put("id", 45); row.put("name", "Bob"); structApi.insertRow(table, row); List<Map<String, Object>> contents = structApi.selectRows(table, null, null, ImmutableList.of("name"), null, -1); Assert.assertEquals(contents.get(0), ImmutableMap.of("id", new Integer(43),"name","Aaron")); Assert.assertEquals(contents.get(1), ImmutableMap.of("id", new Integer(45),"name","Bob")); Assert.assertEquals(contents.get(2), ImmutableMap.of("id", new Integer(44),"name","Carl")); Assert.assertEquals(contents.get(3), ImmutableMap.of("id", new Integer(42),"name","Evan")); } @Test(groups = { "plugin", "nightly" }) public void testInstallStructuredPlugin() throws Exception { String zipFilename = "resources/teststructcreate.zip"; File f = new File(zipFilename); if (!f.exists()) { Assert.fail(f.getAbsolutePath()); } String pluginName; PluginSandbox sandbox; ZipFile in = null; try { in = new ZipFile(zipFilename); PluginConfig plugin = new PluginUtils().getPluginConfigFromZip(zipFilename); if (plugin == null) { Assert.fail("CAnnot read " + f.getAbsolutePath()); } sandbox = new PluginSandbox(); sandbox.setConfig(plugin); sandbox.setStrict(true); pluginName = plugin.getPlugin(); sandbox.setRootDir(new File(f.getParent(), pluginName)); Enumeration<? extends ZipEntry> entries = in.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } sandbox.makeItemFromZipEntry(in, entry); } } finally { in.close(); } Map<String, PluginTransportItem> payload = Maps.newLinkedHashMap(); for (PluginSandboxItem item : sandbox.getItems(null)) { PluginTransportItem payloadItem = item.makeTransportItem(); payload.put(item.getURI().toString(), payloadItem); } pluginApi.installPlugin(sandbox.makeManifest(null), payload); System.out.println("db=" + helper.getStructApi().structuredRepoExists("structured://structtest")); pluginApi.uninstallPlugin(pluginName); boolean installed = false; for (PluginConfig c : pluginApi.getInstalledPlugins()) if (c.getPlugin().compareTo(pluginName) == 0) installed = true; Assert.assertFalse(installed, "Plugin did not uninstall"); } }
package org.apache.jdbm; import java.io.*; import java.util.AbstractMap; import java.util.ArrayList; public class SerialClassInfoTest extends TestCaseWithTestFile { static class Bean1 implements Serializable { public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Bean1 bean1 = (Bean1) o; if (Double.compare(bean1.doubleField, doubleField) != 0) return false; if (Float.compare(bean1.floatField, floatField) != 0) return false; if (intField != bean1.intField) return false; if (longField != bean1.longField) return false; if (field1 != null ? !field1.equals(bean1.field1) : bean1.field1 != null) return false; if (field2 != null ? !field2.equals(bean1.field2) : bean1.field2 != null) return false; return true; } protected String field1 = null; protected String field2 = null; protected int intField = Integer.MAX_VALUE; protected long longField = Long.MAX_VALUE; protected double doubleField = Double.MAX_VALUE; protected float floatField = Float.MAX_VALUE; transient int getCalled = 0; transient int setCalled = 0; public String getField2() { getCalled++; return field2; } public void setField2(String field2) { setCalled++; this.field2 = field2; } Bean1(String field1, String field2) { this.field1 = field1; this.field2 = field2; } Bean1() { } } static class Bean2 extends Bean1 { public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Bean2 bean2 = (Bean2) o; if (field3 != null ? !field3.equals(bean2.field3) : bean2.field3 != null) return false; return true; } @Override public int hashCode() { return field3 != null ? field3.hashCode() : 0; } private String field3 = null; Bean2(String field1, String field2, String field3) { super(field1, field2); this.field3 = field3; } Bean2() { } } SerialClassInfo s; public void setUp() throws IOException { s = new Serialization(); } Bean1 b = new Bean1("aa", "bb"); Bean2 b2 = new Bean2("aa", "bb", "cc"); public void testGetFieldValue1() throws Exception { assertEquals("aa", s.getFieldValue("field1", b)); } public void testGetFieldValue2() throws Exception { assertEquals("bb", s.getFieldValue("field2", b)); assertEquals(1, b.getCalled); } public void testGetFieldValue3() throws Exception { assertEquals("aa", s.getFieldValue("field1", b2)); } public void testGetFieldValue4() throws Exception { assertEquals("bb", s.getFieldValue("field2", b2)); assertEquals(1, b2.getCalled); } public void testGetFieldValue5() throws Exception { assertEquals("cc", s.getFieldValue("field3", b2)); } public void testSetFieldValue1() { s.setFieldValue("field1", b, "zz"); assertEquals("zz", b.field1); } public void testSetFieldValue2() { s.setFieldValue("field2", b, "zz"); assertEquals("zz", b.field2); assertEquals(1, b.setCalled); } public void testSetFieldValue3() { s.setFieldValue("field1", b2, "zz"); assertEquals("zz", b2.field1); } public void testSetFieldValue4() { s.setFieldValue("field2", b2, "zz"); assertEquals("zz", b2.field2); assertEquals(1, b2.setCalled); } public void testSetFieldValue5() { s.setFieldValue("field3", b2, "zz"); assertEquals("zz", b2.field3); } public void testGetPrimitiveField() { assertEquals(Integer.MAX_VALUE, s.getFieldValue("intField", b2)); assertEquals(Long.MAX_VALUE, s.getFieldValue("longField", b2)); assertEquals(Double.MAX_VALUE, s.getFieldValue("doubleField", b2)); assertEquals(Float.MAX_VALUE, s.getFieldValue("floatField", b2)); } public void testSetPrimitiveField() { s.setFieldValue("intField", b2, -1); assertEquals(-1, s.getFieldValue("intField", b2)); s.setFieldValue("longField", b2, -1L); assertEquals(-1L, s.getFieldValue("longField", b2)); s.setFieldValue("doubleField", b2, -1D); assertEquals(-1D, s.getFieldValue("doubleField", b2)); s.setFieldValue("floatField", b2, -1F); assertEquals(-1F, s.getFieldValue("floatField", b2)); } <E> E serialize(E e) throws ClassNotFoundException, IOException { Serialization s2 = new Serialization(); ByteArrayOutputStream out = new ByteArrayOutputStream(); s2.serialize(new DataOutputStream(out), e); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); return (E) s2.deserialize(new DataInputStream(in)); } public void testSerializable() throws Exception { assertEquals(serialize(b), b); } public void testRecursion() throws Exception { AbstractMap.SimpleEntry b = new AbstractMap.SimpleEntry("abcd", null); b.setValue(b.getKey()); AbstractMap.SimpleEntry bx = serialize(b); assertEquals(bx, b); assert (bx.getKey() == bx.getValue()); } public void testRecursion2() throws Exception { AbstractMap.SimpleEntry b = new AbstractMap.SimpleEntry("abcd", null); b.setValue(b); AbstractMap.SimpleEntry bx = serialize(b); assertTrue(bx == bx.getValue()); assertEquals(bx.getKey(), "abcd"); } public void testRecursion3() throws Exception { ArrayList l = new ArrayList(); l.add("123"); l.add(l); ArrayList l2 = serialize(l); assertTrue(l.size() == 2); assertEquals(l.get(0), "123"); assertTrue(l.get(1) == l); } public void testPersistedSimple() throws Exception { String f = newTestFile(); DBAbstract r1 = (DBAbstract) DBMaker.openFile(f).make(); long recid = r1.insert("AA"); r1.commit(); r1.close(); DBAbstract r2 = (DBAbstract) DBMaker.openFile(f).make(); String a2 = r2.fetch(recid); r2.close(); assertEquals("AA", a2); } public void testPersisted() throws Exception { Bean1 b1 = new Bean1("abc", "dcd"); String f = newTestFile(); DBAbstract r1 = (DBAbstract) DBMaker.openFile(f).make() ; long recid = r1.insert(b1); r1.commit(); r1.close(); DBAbstract r2 = (DBAbstract) DBMaker.openFile(f).make(); Bean1 b2 = (Bean1) r2.fetch(recid); r2.close(); assertEquals(b1, b2); } }
/* * 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.cloudwatchevents.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Information about the EC2 instances that are to be sent the command, specified as key-value pairs. Each * <code>RunCommandTarget</code> block can include only one key, but this key may specify multiple values. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/RunCommandTarget" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RunCommandTarget implements Serializable, Cloneable, StructuredPojo { /** * <p> * Can be either <code>tag:</code> <i>tag-key</i> or <code>InstanceIds</code>. * </p> */ private String key; /** * <p> * If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. * </p> */ private java.util.List<String> values; /** * <p> * Can be either <code>tag:</code> <i>tag-key</i> or <code>InstanceIds</code>. * </p> * * @param key * Can be either <code>tag:</code> <i>tag-key</i> or <code>InstanceIds</code>. */ public void setKey(String key) { this.key = key; } /** * <p> * Can be either <code>tag:</code> <i>tag-key</i> or <code>InstanceIds</code>. * </p> * * @return Can be either <code>tag:</code> <i>tag-key</i> or <code>InstanceIds</code>. */ public String getKey() { return this.key; } /** * <p> * Can be either <code>tag:</code> <i>tag-key</i> or <code>InstanceIds</code>. * </p> * * @param key * Can be either <code>tag:</code> <i>tag-key</i> or <code>InstanceIds</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public RunCommandTarget withKey(String key) { setKey(key); return this; } /** * <p> * If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. * </p> * * @return If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. */ public java.util.List<String> getValues() { return values; } /** * <p> * If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. * </p> * * @param values * If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. */ public void setValues(java.util.Collection<String> values) { if (values == null) { this.values = null; return; } this.values = new java.util.ArrayList<String>(values); } /** * <p> * If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setValues(java.util.Collection)} or {@link #withValues(java.util.Collection)} if you want to override the * existing values. * </p> * * @param values * If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. * @return Returns a reference to this object so that method calls can be chained together. */ public RunCommandTarget withValues(String... values) { if (this.values == null) { setValues(new java.util.ArrayList<String>(values.length)); } for (String ele : values) { this.values.add(ele); } return this; } /** * <p> * If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. * </p> * * @param values * If <code>Key</code> is <code>tag:</code> <i>tag-key</i>, <code>Values</code> is a list of tag values. If * <code>Key</code> is <code>InstanceIds</code>, <code>Values</code> is a list of Amazon EC2 instance IDs. * @return Returns a reference to this object so that method calls can be chained together. */ public RunCommandTarget withValues(java.util.Collection<String> values) { setValues(values); 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 (getKey() != null) sb.append("Key: ").append(getKey()).append(","); if (getValues() != null) sb.append("Values: ").append(getValues()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RunCommandTarget == false) return false; RunCommandTarget other = (RunCommandTarget) obj; if (other.getKey() == null ^ this.getKey() == null) return false; if (other.getKey() != null && other.getKey().equals(this.getKey()) == false) return false; if (other.getValues() == null ^ this.getValues() == null) return false; if (other.getValues() != null && other.getValues().equals(this.getValues()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getKey() == null) ? 0 : getKey().hashCode()); hashCode = prime * hashCode + ((getValues() == null) ? 0 : getValues().hashCode()); return hashCode; } @Override public RunCommandTarget clone() { try { return (RunCommandTarget) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.cloudwatchevents.model.transform.RunCommandTargetMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.core.impl.localsearch.decider.acceptor.stepcountinghillclimbing; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import org.junit.jupiter.api.Test; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.core.config.localsearch.decider.acceptor.stepcountinghillclimbing.StepCountingHillClimbingType; import org.optaplanner.core.impl.localsearch.decider.acceptor.AbstractAcceptorTest; import org.optaplanner.core.impl.localsearch.scope.LocalSearchMoveScope; import org.optaplanner.core.impl.localsearch.scope.LocalSearchPhaseScope; import org.optaplanner.core.impl.localsearch.scope.LocalSearchStepScope; import org.optaplanner.core.impl.solver.scope.SolverScope; import org.optaplanner.core.impl.testdata.domain.TestdataSolution; public class StepCountingHillClimbingAcceptorTest extends AbstractAcceptorTest { @Test public void typeStep() { StepCountingHillClimbingAcceptor acceptor = new StepCountingHillClimbingAcceptor(2, StepCountingHillClimbingType.STEP); SolverScope<TestdataSolution> solverScope = new SolverScope<>(); solverScope.setBestScore(SimpleScore.of(-1000)); LocalSearchPhaseScope<TestdataSolution> phaseScope = new LocalSearchPhaseScope<>(solverScope); LocalSearchStepScope<TestdataSolution> lastCompletedStepScope = new LocalSearchStepScope<>(phaseScope, -1); lastCompletedStepScope.setScore(solverScope.getBestScore()); phaseScope.setLastCompletedStepScope(lastCompletedStepScope); acceptor.phaseStarted(phaseScope); // thresholdScore = -1000, lastCompletedStepScore = Integer.MIN_VALUE LocalSearchStepScope<TestdataSolution> stepScope0 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope0 = buildMoveScope(stepScope0, -500); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); assertThat(acceptor.isAccepted(moveScope0)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -800))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -1000))).isTrue(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); stepScope0.setStep(moveScope0.getMove()); stepScope0.setScore(moveScope0.getScore()); solverScope.setBestScore(moveScope0.getScore()); acceptor.stepEnded(stepScope0); phaseScope.setLastCompletedStepScope(stepScope0); // thresholdScore = -1000, lastCompletedStepScore = -500 LocalSearchStepScope<TestdataSolution> stepScope1 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope1 = buildMoveScope(stepScope1, -700); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -900))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -2000))).isFalse(); assertThat(acceptor.isAccepted(moveScope1)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -1000))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -1001))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); stepScope1.setStep(moveScope1.getMove()); stepScope1.setScore(moveScope1.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope1); phaseScope.setLastCompletedStepScope(stepScope1); // thresholdScore = -700, lastCompletedStepScore = -700 LocalSearchStepScope<TestdataSolution> stepScope2 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope2 = buildMoveScope(stepScope1, -400); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -700))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -701))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -600))).isTrue(); assertThat(acceptor.isAccepted(moveScope2)).isTrue(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -700))).isTrue(); stepScope2.setStep(moveScope2.getMove()); stepScope2.setScore(moveScope2.getScore()); solverScope.setBestScore(moveScope2.getScore()); acceptor.stepEnded(stepScope2); phaseScope.setLastCompletedStepScope(stepScope2); // thresholdScore = -700, lastCompletedStepScore = -400 LocalSearchStepScope<TestdataSolution> stepScope3 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope3 = buildMoveScope(stepScope1, -400); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -900))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -700))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -701))).isFalse(); assertThat(acceptor.isAccepted(moveScope3)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -2000))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isFalse(); stepScope3.setStep(moveScope3.getMove()); stepScope3.setScore(moveScope3.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope3); phaseScope.setLastCompletedStepScope(stepScope3); // thresholdScore = -400 (not the best score of -200!), lastCompletedStepScore = -400 LocalSearchStepScope<TestdataSolution> stepScope4 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope4 = buildMoveScope(stepScope1, -300); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -400))).isTrue(); assertThat(acceptor.isAccepted(moveScope4)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -500))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -401))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -400))).isTrue(); stepScope4.setStep(moveScope4.getMove()); stepScope4.setScore(moveScope4.getScore()); solverScope.setBestScore(moveScope4.getScore()); acceptor.stepEnded(stepScope4); phaseScope.setLastCompletedStepScope(stepScope4); // thresholdScore = -400, lastCompletedStepScore = -300 LocalSearchStepScope<TestdataSolution> stepScope5 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope5 = buildMoveScope(stepScope1, -300); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -301))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -400))).isTrue(); assertThat(acceptor.isAccepted(moveScope5)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -600))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -301))).isTrue(); stepScope5.setStep(moveScope5.getMove()); stepScope5.setScore(moveScope5.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope5); phaseScope.setLastCompletedStepScope(stepScope5); acceptor.phaseEnded(phaseScope); } @Test public void typeEqualOrImprovingStep() { StepCountingHillClimbingAcceptor acceptor = new StepCountingHillClimbingAcceptor(2, StepCountingHillClimbingType.EQUAL_OR_IMPROVING_STEP); SolverScope<TestdataSolution> solverScope = new SolverScope<>(); solverScope.setBestScore(SimpleScore.of(-1000)); LocalSearchPhaseScope<TestdataSolution> phaseScope = new LocalSearchPhaseScope<>(solverScope); LocalSearchStepScope<TestdataSolution> lastCompletedStepScope = new LocalSearchStepScope<>(phaseScope, -1); lastCompletedStepScope.setScore(solverScope.getBestScore()); phaseScope.setLastCompletedStepScope(lastCompletedStepScope); acceptor.phaseStarted(phaseScope); // thresholdScore = -1000, lastCompletedStepScore = Integer.MIN_VALUE LocalSearchStepScope<TestdataSolution> stepScope0 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope0 = buildMoveScope(stepScope0, -500); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); assertThat(acceptor.isAccepted(moveScope0)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -800))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -1000))).isTrue(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); stepScope0.setStep(moveScope0.getMove()); stepScope0.setScore(moveScope0.getScore()); solverScope.setBestScore(moveScope0.getScore()); acceptor.stepEnded(stepScope0); phaseScope.setLastCompletedStepScope(stepScope0); // thresholdScore = -1000, lastCompletedStepScore = -500 LocalSearchStepScope<TestdataSolution> stepScope1 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope1 = buildMoveScope(stepScope1, -700); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -900))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -2000))).isFalse(); assertThat(acceptor.isAccepted(moveScope1)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -1000))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -1001))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); stepScope1.setStep(moveScope1.getMove()); stepScope1.setScore(moveScope1.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope1); phaseScope.setLastCompletedStepScope(stepScope1); // thresholdScore = -1000, lastCompletedStepScore = -700 LocalSearchStepScope<TestdataSolution> stepScope2 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope2 = buildMoveScope(stepScope1, -400); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -700))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, 1000))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -1001))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -600))).isTrue(); assertThat(acceptor.isAccepted(moveScope2)).isTrue(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -700))).isTrue(); stepScope2.setStep(moveScope2.getMove()); stepScope2.setScore(moveScope2.getScore()); solverScope.setBestScore(moveScope2.getScore()); acceptor.stepEnded(stepScope2); phaseScope.setLastCompletedStepScope(stepScope2); // thresholdScore = -400, lastCompletedStepScore = -400 LocalSearchStepScope<TestdataSolution> stepScope3 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope3 = buildMoveScope(stepScope1, -400); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -900))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -401))).isFalse(); assertThat(acceptor.isAccepted(moveScope3)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -2000))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isFalse(); stepScope3.setStep(moveScope3.getMove()); stepScope3.setScore(moveScope3.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope3); phaseScope.setLastCompletedStepScope(stepScope3); // thresholdScore = -400, lastCompletedStepScore = -400 LocalSearchStepScope<TestdataSolution> stepScope4 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope4 = buildMoveScope(stepScope1, -300); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -400))).isTrue(); assertThat(acceptor.isAccepted(moveScope4)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -500))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -401))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -400))).isTrue(); stepScope4.setStep(moveScope4.getMove()); stepScope4.setScore(moveScope4.getScore()); solverScope.setBestScore(moveScope4.getScore()); acceptor.stepEnded(stepScope4); phaseScope.setLastCompletedStepScope(stepScope4); // thresholdScore = -300, lastCompletedStepScore = -300 LocalSearchStepScope<TestdataSolution> stepScope5 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope5 = buildMoveScope(stepScope1, -300); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -301))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -400))).isFalse(); assertThat(acceptor.isAccepted(moveScope5)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -600))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -301))).isFalse(); stepScope5.setStep(moveScope5.getMove()); stepScope5.setScore(moveScope5.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope5); phaseScope.setLastCompletedStepScope(stepScope5); acceptor.phaseEnded(phaseScope); } @Test public void typeImprovingStep() { StepCountingHillClimbingAcceptor acceptor = new StepCountingHillClimbingAcceptor(2, StepCountingHillClimbingType.IMPROVING_STEP); SolverScope<TestdataSolution> solverScope = new SolverScope<>(); solverScope.setBestScore(SimpleScore.of(-1000)); LocalSearchPhaseScope<TestdataSolution> phaseScope = new LocalSearchPhaseScope<>(solverScope); LocalSearchStepScope<TestdataSolution> lastCompletedStepScope = new LocalSearchStepScope<>(phaseScope, -1); lastCompletedStepScope.setScore(solverScope.getBestScore()); phaseScope.setLastCompletedStepScope(lastCompletedStepScope); acceptor.phaseStarted(phaseScope); // thresholdScore = -1000, lastCompletedStepScore = Integer.MIN_VALUE LocalSearchStepScope<TestdataSolution> stepScope0 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope0 = buildMoveScope(stepScope0, -500); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); assertThat(acceptor.isAccepted(moveScope0)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -800))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -1000))).isTrue(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); stepScope0.setStep(moveScope0.getMove()); stepScope0.setScore(moveScope0.getScore()); solverScope.setBestScore(moveScope0.getScore()); acceptor.stepEnded(stepScope0); phaseScope.setLastCompletedStepScope(stepScope0); // thresholdScore = -1000, lastCompletedStepScore = -500 LocalSearchStepScope<TestdataSolution> stepScope1 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope1 = buildMoveScope(stepScope1, -700); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -900))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -2000))).isFalse(); assertThat(acceptor.isAccepted(moveScope1)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -1000))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope1, -1001))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isTrue(); stepScope1.setStep(moveScope1.getMove()); stepScope1.setScore(moveScope1.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope1); phaseScope.setLastCompletedStepScope(stepScope1); // thresholdScore = -1000, lastCompletedStepScore = -700 LocalSearchStepScope<TestdataSolution> stepScope2 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope2 = buildMoveScope(stepScope1, -400); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -700))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, 1000))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -1001))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope2, -600))).isTrue(); assertThat(acceptor.isAccepted(moveScope2)).isTrue(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -700))).isTrue(); stepScope2.setStep(moveScope2.getMove()); stepScope2.setScore(moveScope2.getScore()); solverScope.setBestScore(moveScope2.getScore()); acceptor.stepEnded(stepScope2); phaseScope.setLastCompletedStepScope(stepScope2); // thresholdScore = -400, lastCompletedStepScore = -400 LocalSearchStepScope<TestdataSolution> stepScope3 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope3 = buildMoveScope(stepScope1, -400); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -900))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -401))).isFalse(); assertThat(acceptor.isAccepted(moveScope3)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope3, -2000))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -900))).isFalse(); stepScope3.setStep(moveScope3.getMove()); stepScope3.setScore(moveScope3.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope3); phaseScope.setLastCompletedStepScope(stepScope3); // thresholdScore = -400, lastCompletedStepScore = -400 LocalSearchStepScope<TestdataSolution> stepScope4 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope4 = buildMoveScope(stepScope1, -300); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -400))).isTrue(); assertThat(acceptor.isAccepted(moveScope4)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -500))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope4, -401))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -400))).isTrue(); stepScope4.setStep(moveScope4.getMove()); stepScope4.setScore(moveScope4.getScore()); solverScope.setBestScore(moveScope4.getScore()); acceptor.stepEnded(stepScope4); phaseScope.setLastCompletedStepScope(stepScope4); // thresholdScore = -400, lastCompletedStepScore = -300 LocalSearchStepScope<TestdataSolution> stepScope5 = new LocalSearchStepScope<>(phaseScope); LocalSearchMoveScope<TestdataSolution> moveScope5 = buildMoveScope(stepScope1, -300); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -301))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -400))).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -401))).isFalse(); assertThat(acceptor.isAccepted(moveScope5)).isTrue(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -2000))).isFalse(); assertThat(acceptor.isAccepted(buildMoveScope(stepScope5, -600))).isFalse(); // Repeated call assertThat(acceptor.isAccepted(buildMoveScope(stepScope0, -301))).isTrue(); stepScope5.setStep(moveScope5.getMove()); stepScope5.setScore(moveScope5.getScore()); // bestScore unchanged acceptor.stepEnded(stepScope5); phaseScope.setLastCompletedStepScope(stepScope5); acceptor.phaseEnded(phaseScope); } @Test public void zeroStepCountingHillClimbingSize() { assertThatIllegalArgumentException() .isThrownBy(() -> new StepCountingHillClimbingAcceptor(0, StepCountingHillClimbingType.STEP)); } @Test public void negativeStepCountingHillClimbingSize() { assertThatIllegalArgumentException() .isThrownBy(() -> new StepCountingHillClimbingAcceptor(-1, StepCountingHillClimbingType.STEP)); } }
/* * 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.execution; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.junit.JUnitConfiguration; import com.intellij.execution.junit.JUnitConfigurationProducer; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.module.StdModuleTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ModuleRootModificationUtil; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.IdeaTestCase; import com.intellij.testFramework.MapDataContext; import com.intellij.testFramework.PsiTestUtil; import com.intellij.testFramework.TempFiles; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public abstract class BaseConfigurationTestCase extends IdeaTestCase { protected TempFiles myTempFiles; private final List<Module> myModulesToDispose = new ArrayList<Module>(); protected static final String MOCK_JUNIT = "mock JUnit"; @Override protected void setUp() throws Exception { super.setUp(); myTempFiles = new TempFiles(myFilesToDelete); } protected void addModule(String path) throws IOException { addModule(path, true); } protected void addModule(String path, boolean addSource) throws IOException { VirtualFile module1Content = findFile(path); createModule(module1Content, addSource); } protected void createModule(VirtualFile module1Content, boolean addSource) throws IOException { Module module = createEmptyModule(); if (addSource) { PsiTestUtil.addSourceRoot(module, module1Content, true); } else { PsiTestUtil.addContentRoot(module, module1Content); } VirtualFile mockJUnit = findFile(MOCK_JUNIT); ModuleRootModificationUtil.addModuleLibrary(module, mockJUnit.getUrl()); ModuleRootModificationUtil.setModuleSdk(module, ModuleRootManager.getInstance(myModule).getSdk()); GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module); VirtualFile testCase = mockJUnit.findFileByRelativePath("junit/framework/TestCase.java"); assertNotNull(testCase); assertTrue(scope.contains(testCase)); Module missingModule = createTempModule(); addDependency(module, missingModule); ModuleManager.getInstance(myProject).disposeModule(missingModule); } protected Module createEmptyModule() throws IOException { Module module = createTempModule(); myModulesToDispose.add(module); return module; } private Module createTempModule() { return createTempModule(myTempFiles, myProject); } @NotNull public static Module createTempModule(TempFiles tempFiles, final Project project) { final String tempPath = tempFiles.createTempFile("xxx").getAbsolutePath(); return ApplicationManager.getApplication().runWriteAction(new Computable<Module>() { @Override public Module compute() { Module result = ModuleManager.getInstance(project).newModule(tempPath, StdModuleTypes.JAVA.getId()); project.save(); return result; } }); } protected static VirtualFile findFile(String path) { String filePath = PathManagerEx.getTestDataPath() + File.separator + "junit" + File.separator + "configurations" + File.separator + path; return LocalFileSystem.getInstance().findFileByPath(filePath.replace(File.separatorChar, '/')); } @Override protected void tearDown() throws Exception { myModulesToDispose.clear(); super.tearDown(); } protected void disposeModule(Module module) { assertTrue(myModulesToDispose.remove(module)); ModuleManager.getInstance(myProject).disposeModule(module); } protected Module getModule1() { return getModule(0); } protected Module getModule(int index) { return myModulesToDispose.get(index); } protected Module getModule2() { return getModule(1); } protected Module getModule4() { return getModule(3); } protected Module getModule3() { return getModule(2); } protected PsiClass findClass(Module module, String qualifiedName) { return findClass(qualifiedName, GlobalSearchScope.moduleScope(module)); } protected PsiClass findClass(String qualifiedName, GlobalSearchScope scope) { return JavaPsiFacade.getInstance(myProject).findClass(qualifiedName, scope); } protected JUnitConfiguration createJUnitConfiguration(@NotNull PsiElement psiElement, @NotNull Class<? extends JUnitConfigurationProducer> producerClass, @NotNull MapDataContext dataContext) { ConfigurationContext context = createContext(psiElement, dataContext); RunConfigurationProducer producer = RunConfigurationProducer.getInstance(producerClass); assert producer != null; ConfigurationFromContext fromContext = producer.createConfigurationFromContext(context); assertNotNull(fromContext); return (JUnitConfiguration)fromContext.getConfiguration(); } protected final <T extends RunConfiguration> T createConfiguration(@NotNull PsiElement psiElement) { return createConfiguration(psiElement, new MapDataContext()); } protected <T extends RunConfiguration> T createConfiguration(@NotNull PsiElement psiElement, @NotNull MapDataContext dataContext) { ConfigurationContext context = createContext(psiElement, dataContext); RunnerAndConfigurationSettings settings = context.getConfiguration(); @SuppressWarnings("unchecked") T configuration = settings == null ? null : (T)settings.getConfiguration(); return configuration; } public ConfigurationContext createContext(@NotNull PsiElement psiClass) { MapDataContext dataContext = new MapDataContext(); return createContext(psiClass, dataContext); } public ConfigurationContext createContext(@NotNull PsiElement psiClass, @NotNull MapDataContext dataContext) { dataContext.put(CommonDataKeys.PROJECT, myProject); if (LangDataKeys.MODULE.getData(dataContext) == null) { dataContext.put(LangDataKeys.MODULE, ModuleUtilCore.findModuleForPsiElement(psiClass)); } dataContext.put(Location.DATA_KEY, PsiLocation.fromPsiElement(psiClass)); return ConfigurationContext.getFromContext(dataContext); } protected void addDependency(Module module, Module dependency) { ModuleRootModificationUtil.addDependency(module, dependency); } protected void checkPackage(String packageName, JUnitConfiguration configuration) { assertEquals(packageName, configuration.getPersistentData().getPackageName()); } protected void checkClassName(String className, JUnitConfiguration configuration) { assertEquals(className, configuration.getPersistentData().getMainClassName()); } protected void checkMethodName(String methodName, JUnitConfiguration configuration) { assertEquals(methodName, configuration.getPersistentData().getMethodName()); } protected void checkTestObject(String testObjectKey, JUnitConfiguration configuration) { assertEquals(testObjectKey, configuration.getPersistentData().TEST_OBJECT); } }