repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
winningsix/hive
ql/src/java/org/apache/hadoop/hive/ql/optimizer/GlobalLimitOptimizer.java
8347
/** * 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.hive.ql.optimizer; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.Context; import org.apache.hadoop.hive.ql.exec.FilterOperator; import org.apache.hadoop.hive.ql.exec.GroupByOperator; import org.apache.hadoop.hive.ql.exec.LimitOperator; import org.apache.hadoop.hive.ql.exec.Operator; import org.apache.hadoop.hive.ql.exec.OperatorUtils; import org.apache.hadoop.hive.ql.exec.ReduceSinkOperator; import org.apache.hadoop.hive.ql.exec.TableScanOperator; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.optimizer.ppr.PartitionPruner; import org.apache.hadoop.hive.ql.parse.GlobalLimitCtx; import org.apache.hadoop.hive.ql.parse.ParseContext; import org.apache.hadoop.hive.ql.parse.PrunedPartitionList; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.parse.SplitSample; import org.apache.hadoop.hive.ql.plan.ExprNodeDesc; import org.apache.hadoop.hive.ql.plan.FilterDesc; import org.apache.hadoop.hive.ql.plan.GroupByDesc; import org.apache.hadoop.hive.ql.plan.OperatorDesc; import org.apache.hadoop.hive.ql.plan.ReduceSinkDesc; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; /** * This optimizer is used to reduce the input size for the query for queries which are * specifying a limit. * <p/> * For eg. for a query of type: * <p/> * select expr from T where <filter> limit 100; * <p/> * Most probably, the whole table T need not be scanned. * Chances are that even if we scan the first file of T, we would get the 100 rows * needed by this query. * This optimizer step populates the GlobalLimitCtx which is used later on to prune the inputs. */ public class GlobalLimitOptimizer implements Transform { private final Log LOG = LogFactory.getLog(GlobalLimitOptimizer.class.getName()); public ParseContext transform(ParseContext pctx) throws SemanticException { Context ctx = pctx.getContext(); Map<String, Operator<? extends OperatorDesc>> topOps = pctx.getTopOps(); GlobalLimitCtx globalLimitCtx = pctx.getGlobalLimitCtx(); Map<TableScanOperator, ExprNodeDesc> opToPartPruner = pctx.getOpToPartPruner(); Map<String, SplitSample> nameToSplitSample = pctx.getNameToSplitSample(); // determine the query qualifies reduce input size for LIMIT // The query only qualifies when there are only one top operator // and there is no transformer or UDTF and no block sampling // is used. if (ctx.getTryCount() == 0 && topOps.size() == 1 && !globalLimitCtx.ifHasTransformOrUDTF() && nameToSplitSample.isEmpty()) { // Here we recursively check: // 1. whether there are exact one LIMIT in the query // 2. whether there is no aggregation, group-by, distinct, sort by, // distributed by, or table sampling in any of the sub-query. // The query only qualifies if both conditions are satisfied. // // Example qualified queries: // CREATE TABLE ... AS SELECT col1, col2 FROM tbl LIMIT .. // INSERT OVERWRITE TABLE ... SELECT col1, hash(col2), split(col1) // FROM ... LIMIT... // SELECT * FROM (SELECT col1 as col2 (SELECT * FROM ...) t1 LIMIT ...) t2); // TableScanOperator ts = (TableScanOperator) topOps.values().toArray()[0]; Integer tempGlobalLimit = checkQbpForGlobalLimit(ts); // query qualify for the optimization if (tempGlobalLimit != null && tempGlobalLimit != 0) { Table tab = ts.getConf().getTableMetadata(); if (!tab.isPartitioned()) { Set<FilterOperator> filterOps = OperatorUtils.findOperators(ts, FilterOperator.class); if (filterOps.size() == 0) { globalLimitCtx.enableOpt(tempGlobalLimit); } } else { // check if the pruner only contains partition columns if (PartitionPruner.onlyContainsPartnCols(tab, opToPartPruner.get(ts))) { PrunedPartitionList partsList; try { String alias = (String) topOps.keySet().toArray()[0]; partsList = PartitionPruner.prune(ts, pctx, alias); } catch (HiveException e) { // Has to use full name to make sure it does not conflict with // org.apache.commons.lang.StringUtils LOG.error(org.apache.hadoop.util.StringUtils.stringifyException(e)); throw new SemanticException(e.getMessage(), e); } // If there is any unknown partition, create a map-reduce job for // the filter to prune correctly if (!partsList.hasUnknownPartitions()) { globalLimitCtx.enableOpt(tempGlobalLimit); } } } if (globalLimitCtx.isEnable()) { LOG.info("Qualify the optimize that reduces input size for 'limit' for limit " + globalLimitCtx.getGlobalLimit()); } } } return pctx; } /** * Check the limit number in all sub queries * * @return if there is one and only one limit for all subqueries, return the limit * if there is no limit, return 0 * otherwise, return null */ private static Integer checkQbpForGlobalLimit(TableScanOperator ts) { Set<Class<? extends Operator<?>>> searchedClasses = new ImmutableSet.Builder<Class<? extends Operator<?>>>() .add(ReduceSinkOperator.class) .add(GroupByOperator.class) .add(FilterOperator.class) .add(LimitOperator.class) .build(); Multimap<Class<? extends Operator<?>>, Operator<?>> ops = OperatorUtils.classifyOperators(ts, searchedClasses); // To apply this optimization, in the input query: // - There cannot exist any order by/sort by clause, // thus existsOrdering should be false. // - There cannot exist any distribute by clause, thus // existsPartitioning should be false. // - There cannot exist any cluster by clause, thus // existsOrdering AND existsPartitioning should be false. for (Operator<?> op : ops.get(ReduceSinkOperator.class)) { ReduceSinkDesc reduceSinkConf = ((ReduceSinkOperator) op).getConf(); if (reduceSinkConf.isOrdering() || reduceSinkConf.isPartitioning()) { return null; } } // - There cannot exist any (distinct) aggregate. for (Operator<?> op : ops.get(GroupByOperator.class)) { GroupByDesc groupByConf = ((GroupByOperator) op).getConf(); if (groupByConf.isAggregate() || groupByConf.isDistinct()) { return null; } } // - There cannot exist any sampling predicate. for (Operator<?> op : ops.get(FilterOperator.class)) { FilterDesc filterConf = ((FilterOperator) op).getConf(); if (filterConf.getIsSamplingPred()) { return null; } } // If there is one and only one limit starting at op, return the limit // If there is no limit, return 0 // Otherwise, return null Collection<Operator<?>> limitOps = ops.get(LimitOperator.class); if (limitOps.size() == 1) { return ((LimitOperator) limitOps.iterator().next()).getConf().getLimit(); } else if (limitOps.size() == 0) { return 0; } return null; } }
apache-2.0
luciofm/AndroidSalao
src/com/luciofm/presentation/androidsalao/DisplayService.java
175
package com.luciofm.presentation.androidsalao; public interface DisplayService { void connection(boolean connetion); void next(); void previous(); void advance(); }
apache-2.0
yongjhih/kaif-android
app/src/main/java/io/kaif/mobile/app/BaseFragment.java
438
package io.kaif.mobile.app; import rx.Observable; import rx.android.app.support.RxFragment; import rx.android.lifecycle.LifecycleObservable; import rx.android.schedulers.AndroidSchedulers; public class BaseFragment extends RxFragment { protected <T> Observable<T> bind(Observable<T> observable) { return LifecycleObservable.bindFragmentLifecycle(lifecycle(), observable.observeOn(AndroidSchedulers.mainThread())); } }
apache-2.0
state-hiu/geowave
geowave-accumulo/src/main/java/mil/nga/giat/geowave/accumulo/AccumuloRowId.java
2604
package mil.nga.giat.geowave.accumulo; import java.nio.ByteBuffer; import java.util.Arrays; import org.apache.accumulo.core.data.Key; /** * This class encapsulates the elements that compose the row ID in Accumulo, and * can serialize and deserialize the individual elements to/from the row ID. The * row ID consists of the index ID, followed by an adapter ID, followed by a * data ID, followed by data ID length and adapter ID length, and lastly the * number of duplicate row IDs for this entry. The data ID must be unique for an * adapter, so the combination of adapter ID and data ID is intended to * guarantee uniqueness for this row ID. * */ public class AccumuloRowId { private final byte[] indexId; private final byte[] dataId; private final byte[] adapterId; private final int numberOfDuplicates; public AccumuloRowId( final Key key ) { this( key.getRow().copyBytes()); } public AccumuloRowId( final byte[] accumuloRowId ) { final byte[] metadata = Arrays.copyOfRange( accumuloRowId, accumuloRowId.length - 12, accumuloRowId.length); final ByteBuffer metadataBuf = ByteBuffer.wrap(metadata); final int adapterIdLength = metadataBuf.getInt(); final int dataIdLength = metadataBuf.getInt(); final int numberOfDuplicates = metadataBuf.getInt(); final ByteBuffer buf = ByteBuffer.wrap( accumuloRowId, 0, accumuloRowId.length - 12); final byte[] indexId = new byte[accumuloRowId.length - 12 - adapterIdLength - dataIdLength]; final byte[] adapterId = new byte[adapterIdLength]; final byte[] dataId = new byte[dataIdLength]; buf.get(indexId); buf.get(adapterId); buf.get(dataId); this.indexId = indexId; this.dataId = dataId; this.adapterId = adapterId; this.numberOfDuplicates = numberOfDuplicates; } public AccumuloRowId( final byte[] indexId, final byte[] dataId, final byte[] adapterId, final int numberOfDuplicates ) { this.indexId = indexId; this.dataId = dataId; this.adapterId = adapterId; this.numberOfDuplicates = numberOfDuplicates; } public byte[] getRowId() { final ByteBuffer buf = ByteBuffer.allocate(12 + dataId.length + adapterId.length + indexId.length); buf.put(indexId); buf.put(adapterId); buf.put(dataId); buf.putInt(adapterId.length); buf.putInt(dataId.length); buf.putInt(numberOfDuplicates); return buf.array(); } public byte[] getIndexId() { return indexId; } public byte[] getDataId() { return dataId; } public byte[] getAdapterId() { return adapterId; } public int getNumberOfDuplicates() { return numberOfDuplicates; } }
apache-2.0
alibaba/Sentinel
sentinel-dashboard/src/test/java/com/alibaba/csp/sentinel/dashboard/rule/zookeeper/ZookeeperConfigUtil.java
1381
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.dashboard.rule.zookeeper; import org.apache.commons.lang.StringUtils; public class ZookeeperConfigUtil { public static final String RULE_ROOT_PATH = "/sentinel_rule_config"; public static final int RETRY_TIMES = 3; public static final int SLEEP_TIME = 1000; public static String getPath(String appName) { StringBuilder stringBuilder = new StringBuilder(RULE_ROOT_PATH); if (StringUtils.isBlank(appName)) { return stringBuilder.toString(); } if (appName.startsWith("/")) { stringBuilder.append(appName); } else { stringBuilder.append("/") .append(appName); } return stringBuilder.toString(); } }
apache-2.0
gzsombor/ranger
ranger-elasticsearch-plugin-shim/src/main/java/org/apache/ranger/authorization/elasticsearch/authorizer/RangerElasticsearchAuthorizer.java
3996
/* * 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.ranger.authorization.elasticsearch.authorizer; import java.util.List; import org.apache.logging.log4j.Logger; import org.apache.ranger.plugin.classloader.RangerPluginClassLoader; import org.elasticsearch.common.logging.ESLoggerFactory; public class RangerElasticsearchAuthorizer { private static final Logger LOG = ESLoggerFactory.getLogger(RangerElasticsearchAuthorizer.class); private static final String RANGER_PLUGIN_TYPE = "elasticsearch"; private static final String RANGER_ELASTICSEARCH_AUTHORIZER_IMPL_CLASSNAME = "org.apache.ranger.authorization.elasticsearch.authorizer.RangerElasticsearchAuthorizer"; private static RangerPluginClassLoader rangerPluginClassLoader = null; private static ClassLoader esClassLoader = null; private RangerElasticsearchAccessControl rangerElasticsearchAccessControl = null; public RangerElasticsearchAuthorizer() { if (LOG.isDebugEnabled()) { LOG.debug("==> RangerElasticsearchAuthorizer.RangerElasticsearchAuthorizer()"); } this.init(); if (LOG.isDebugEnabled()) { LOG.debug("<== RangerElasticsearchAuthorizer.RangerElasticsearchAuthorizer()"); } } public void init() { if (LOG.isDebugEnabled()) { LOG.debug("==> RangerElasticsearchAuthorizer.init()"); } try { // In elasticsearch this.getClass().getClassLoader() is FactoryURLClassLoader, // but Thread.currentThread().getContextClassLoader() is AppClassLoader. esClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); rangerPluginClassLoader = RangerPluginClassLoader.getInstance(RANGER_PLUGIN_TYPE, this.getClass()); Thread.currentThread().setContextClassLoader(esClassLoader); @SuppressWarnings("unchecked") Class<RangerElasticsearchAccessControl> cls = (Class<RangerElasticsearchAccessControl>) Class .forName(RANGER_ELASTICSEARCH_AUTHORIZER_IMPL_CLASSNAME, true, rangerPluginClassLoader); activatePluginClassLoader(); rangerElasticsearchAccessControl = cls.newInstance(); } catch (Exception e) { LOG.error("Error Enabling RangerElasticsearchAuthorizer", e); } finally { deactivatePluginClassLoader(); } if (LOG.isDebugEnabled()) { LOG.debug("<== RangerElasticsearchAuthorizer.init()"); } } public boolean checkPermission(String user, List<String> groups, String index, String action, String clientIPAddress) { boolean ret = false; if (LOG.isDebugEnabled()) { LOG.debug("==> RangerElasticsearchAuthorizer.checkPermission()"); } try { activatePluginClassLoader(); ret = rangerElasticsearchAccessControl.checkPermission(user, groups, index, action, clientIPAddress); } finally { deactivatePluginClassLoader(); } if (LOG.isDebugEnabled()) { LOG.debug("<== RangerElasticsearchAuthorizer.checkPermission()"); } return ret; } private void activatePluginClassLoader() { if (rangerPluginClassLoader != null) { Thread.currentThread().setContextClassLoader(rangerPluginClassLoader); } } private void deactivatePluginClassLoader() { if (esClassLoader != null) { Thread.currentThread().setContextClassLoader(esClassLoader); } } }
apache-2.0
jbqueyrie/TPOpenCompare
src/test/java/org/opencompare/StatisticsPlusPlusTest.java
11353
package org.opencompare; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.junit.Test; import org.opencompare.api.java.Cell; import org.opencompare.api.java.Feature; import org.opencompare.api.java.PCM; import org.opencompare.api.java.PCMContainer; import org.opencompare.api.java.Product; import org.opencompare.api.java.Value; import org.opencompare.api.java.impl.io.KMFJSONLoader; import org.opencompare.api.java.io.PCMLoader; import org.opencompare.api.java.value.BooleanValue; import org.opencompare.api.java.value.IntegerValue; import org.opencompare.api.java.value.RealValue; import org.opencompare.api.java.value.StringValue; public class StatisticsPlusPlusTest { @Test public void DSLtest() throws IOException { //On lit le fichier de paramètres .fact crée avec le DSL : //Initialisation des paramètres : double threshold= 0.9; //Si threshold est <0.5, on le met à 0.5 if(threshold<0.5){ threshold=0.5; } int maxFacts=5; ArrayList<String> features = new ArrayList<String>(); features.add("number"); features.add("string"); features.add("boolean"); //On vérifie les valeurs présentes dans la liste features du fichier de paramètres : //On initialise tout à false : boolean feature_nombre = false; boolean feature_string = false; boolean feature_boolean = false; //number : Si l'utilisateur veut les quantiles if (isIn("number",features)){ feature_nombre = true; } //string : Si l'utilisateur les modalités les plus présentes if (isIn("string",features)){ feature_string=true; } //boolean : Si l'utilisateur veut les booleans les plus présents if (isIn("boolean",features)){ feature_boolean=true; } //Initialisation du chemin pour créer le dossier txt: String path = "/home/nicolasd/Bureau/OpenCompare_data/data"; String path_txt = "/home/nicolasd/Bureau/OpenCompare_data/txt"; File theDir = new File(path_txt); // if the directory does not exist, create it if (!theDir.exists()) { System.out.println("creating directory txt :"); boolean result = false; try{ theDir.mkdir(); result = true; } catch(SecurityException se){ //handle it } if(result) { System.out.println("DIR created"); } } File pcmFile = new File(path); File[] filesInDir = pcmFile.listFiles(); PCMLoader loader = new KMFJSONLoader(); for (File f : filesInDir) { List<PCMContainer> pcmContainers = loader.load(f); //Récupération du nom de fichier String name = f.getName(); name = name.substring(0,name.length()-4); //Création des fichiers dans lesquels on stocke les faits File file = new File(path_txt + "/" + name + ".txt"); file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); for (PCMContainer pcmContainer : pcmContainers ) { System.out.println("--------------------------------------"); writer.write("--------------------------------------"); writer.newLine(); System.out.println("Fichier : "+f.getName()); writer.write("Fichier : "+f.getName()); writer.newLine(); System.out.println("--------------------------------------"); writer.write("--------------------------------------"); System.out.println("\n\n"); writer.newLine(); // Get the PCM PCM pcm = pcmContainer.getPcm(); ArrayList<String> facts = new ArrayList<String>(); // On parcourt les colonnes for (Feature feature : pcm.getConcreteFeatures()) { //On repère le nom de la colonne String nom_variable = feature.getName(); //On initialise des booleens pour pouvoir connaitre le type des variables boolean nombre = true; boolean chaine_caract = true; boolean bool = true; ArrayList<Cell> colonne = new ArrayList<Cell>(); // On parcourt les lignes for (Product product : pcm.getProducts()) { // Find the cell corresponding to the current feature and product Cell cell = product.findCell(feature); Value interp = cell.getInterpretation(); //On vérifie le type de la colonne if (!(interp instanceof IntegerValue || interp instanceof RealValue)){ nombre=false; } if (!(interp instanceof StringValue)){ chaine_caract=false; } if (!(interp instanceof BooleanValue)){ bool=false; } //On stocke les variables dans une liste colonne.add(cell); } // Si la clonne contient des entiers, on fait un calcul des quantiles si l'utilisateur l'a demandé if (nombre & feature_nombre){ //On stocke le contenu de la colonne dans un tableau de Doubles double[] valeurs = new double[colonne.size()]; for (int i=0;i<colonne.size();i++){ if(colonne.get(i).getInterpretation() instanceof IntegerValue){ valeurs[i]= Integer.parseInt(colonne.get(i).getContent()); } else if(colonne.get(i).getInterpretation() instanceof RealValue){ valeurs[i]= Double.parseDouble(colonne.get(i).getContent()); } else{ System.out.println("Problème de type"); writer.write("Problème de type"); writer.newLine(); } } double quant = quantile(valeurs,threshold); if (!(quant==-1)){ String fact = "Plus de "+(threshold*100)+"% des produits ont une valeur de " +nom_variable+" supérieure à "+quant; //On vérifie si le nombre max de faits est atteint if(facts.size()>=maxFacts){ //System.out.println("Le nombre de faits max pour la matrice est atteint."); } else{ facts.add(fact); } } } //Si la colonne contient des chaînes de caractères, on fait un compte par catégorie si l'utilisateur l'a demandé if(chaine_caract & feature_string){ //On stocke le contenu de la colonne dans un tableau de Strings ArrayList<String> valeurs = new ArrayList<String>(); for (int i=0;i<colonne.size();i++){ valeurs.add(colonne.get(i).getContent()); } ArrayList<String> categoriePrincipale = categorie(valeurs,threshold); if (categoriePrincipale.size() != 0){ String fact = "Plus de "+(threshold*100)+"% des produits ont une valeur de " +nom_variable+" égale à "; fact+= categoriePrincipale.get(0); if(categoriePrincipale.size()>1){ for (int i=1;i<categoriePrincipale.size()-1;i++){ fact+= ", " +categoriePrincipale.get(i); } fact+= " et "+categoriePrincipale.get(categoriePrincipale.size()-1); } //On vérifie si le nombre max de faits est atteint if(facts.size()>=maxFacts){ //System.out.println("Le nombre de faits max pour la matrice est atteint."); } else{ facts.add(fact); } } } // Si la clonne contient des booleens, on regarde le pourcentae de true et false if (bool & feature_boolean){ //On stocke le contenu de la colonne dans un tableau de booleens boolean[] valeurs = new boolean[colonne.size()]; for (int i=0;i<colonne.size();i++){ if(colonne.get(i).getInterpretation() instanceof BooleanValue){ valeurs[i]= Boolean.parseBoolean(colonne.get(i).getContent()); } else{ System.out.println("Problème de type"); writer.write("Problème de type"); writer.newLine(); } } String bool_value = pourcentage(valeurs,threshold); if (!(bool_value.equals(""))){ String fact = "Plus de "+(threshold*100)+"% des produits ont une valeur de " +nom_variable+" égale à "+bool_value; //On vérifie si le nombre max de faits est atteint if(facts.size()>=maxFacts){ //System.out.println("Le nombre de faits max pour la matrice est atteint."); } else{ facts.add(fact); } } } } if(facts.size()!=0){ for (int i=0;i<facts.size();i++){ System.out.println(facts.get(i)); writer.write(facts.get(i)); writer.newLine(); } } else{ System.out.println("La matrice ne contient pas de fait intéressant d'après les features demandées."); writer.write("La matrice ne contient pas de fait intéressant d'après les features demandées."); writer.newLine(); } System.out.println("\n\n"); writer.newLine(); writer.newLine(); } writer.close(); } } public static double quantile(double[] values, double threshold) { double res = -1; //On vérifie que la matrice a une ligne if (!(values == null || values.length == 0)) { // Tri des valeurs et calcul du quantile double[] v = new double[values.length]; System.arraycopy(values, 0, v, 0, values.length); Arrays.sort(v); int n = (int) Math.round(v.length * threshold / 100); res = v[n]; } return res; } public static ArrayList<String> categorie(ArrayList<String> values, double threshold) { ArrayList<String> res = new ArrayList<String>(); if (!(values == null || values.size() == 0)) { //On récupère toutes les différentes modalités HashSet<String> uniqueValues = new HashSet<String>(values); //On transforme le set en liste List<String> modalites = new ArrayList<>(uniqueValues); //On initialise un tableau vide qui contiendra les occurences de chaque modalité double[] occurences = new double[modalites.size()]; for (int i=0;i<occurences.length;i++){ occurences[i]=0; } //On parcourt chaque valeur de la colonne for (int i=0;i<values.size();i++){ //On la stocke dans une valeur temporaire String temp = values.get(i); //On incrémente la modalité reliée for (int j=0;j<modalites.size();j++) { if(temp.equals(modalites.get(j))){ occurences[j]++; } } } //On regarde si une modalité est présente dans plus de threshold % des cas for (int k=0;k<occurences.length;k++){ double percent = occurences[k]/values.size(); if(percent>=threshold){ //Si la modalité est une chaine vide, on ne la prend pas en compte if(!(modalites.get(k).equals(""))){ res.add(modalites.get(k)); } } } } return res; } public static String pourcentage(boolean[] values, double threshold) { String res = ""; //On vérifie que la matrice a une ligne if (!(values == null || values.length == 0)) { double nb_bool=0; //On parcours le tableau de booleans et on calcule le pourcentage de true et false for (int i=0;i<values.length;i++){ if(values[i]){ nb_bool++; } } //On regarde la valeur du pourcentage pour regarder la valeur à retourner double percent = nb_bool/values.length; if(percent>=threshold){ res="True"; } else{ res="False"; } } return res; } //Fonction qui vérifie si une chaine de caractères est présente dans une liste : public boolean isIn(String element, ArrayList<String> liste){ boolean res=false; for (int i=0;i<liste.size();i++){ if(element.equals(liste.get(i))){ res=true; } } return res; } }
apache-2.0
AlanJager/zstack
plugin/flatNetworkProvider/src/main/java/org/zstack/network/service/flat/FlatDhcpAcquireDhcpServerIpReply.java
1199
package org.zstack.network.service.flat; import org.zstack.header.message.MessageReply; import org.zstack.header.network.l3.IpRangeInventory; import org.zstack.header.network.l3.UsedIpInventory; /** * Created by frank on 10/11/2015. */ public class FlatDhcpAcquireDhcpServerIpReply extends MessageReply { private String ip; private String netmask; private String usedIpUuid; private UsedIpInventory usedIp; private IpRangeInventory ipr; public String getNetmask() { return netmask; } public void setNetmask(String netmask) { this.netmask = netmask; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getUsedIpUuid() { return usedIpUuid; } public void setUsedIpUuid(String usedIpUuid) { this.usedIpUuid = usedIpUuid; } public UsedIpInventory getUsedIp() { return usedIp; } public void setUsedIp(UsedIpInventory usedIp) { this.usedIp = usedIp; } public IpRangeInventory getIpr() { return ipr; } public void setIpr(IpRangeInventory ipr) { this.ipr = ipr; } }
apache-2.0
yijia1992/coolweather
app/src/main/java/com/example/coolweather/MainActivity.java
1121
package com.example.coolweather; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
apache-2.0
Guardiola31337/HexGrid
hexgrid/src/main/java/com/pguardiola/HexagonViewNorthSouth.java
3676
/* * Copyright (C) 2016 Pablo Guardiola Sánchez. * * 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.pguardiola; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Path; import android.graphics.Region; import android.util.AttributeSet; import android.view.View; public class HexagonViewNorthSouth extends View { private Path hexagonPath; private Path hexagonBorderPath; private float radius; private float width, height; private int maskColor; public HexagonViewNorthSouth(Context context) { super(context); init(); } public HexagonViewNorthSouth(Context context, AttributeSet attrs) { super(context, attrs); init(); } public HexagonViewNorthSouth(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void setRadius(float r) { this.radius = r; calculatePath(); } public void setMaskColor(int color) { this.maskColor = color; invalidate(); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = MeasureSpec.getSize(widthMeasureSpec); height = MeasureSpec.getSize(heightMeasureSpec); radius = height / 2; calculatePath(); } @Override public void onDraw(Canvas c) { super.onDraw(c); c.clipPath(hexagonBorderPath, Region.Op.DIFFERENCE); c.drawColor(Color.WHITE); c.save(); c.clipPath(hexagonPath, Region.Op.DIFFERENCE); c.drawColor(maskColor); c.save(); } private void init() { hexagonPath = new Path(); hexagonBorderPath = new Path(); maskColor = 0xFFb2c311; } private void calculatePath() { float centerX = width / 2; float centerY = height / 2; float adjacent = (float) (Math.sqrt(3) * radius / 2); float opposite = radius / 2; float hypotenuse = radius; // North-South hexagonPath.moveTo(centerX, centerY + hypotenuse); hexagonPath.lineTo(centerX - adjacent, centerY + opposite); hexagonPath.lineTo(centerX - adjacent, centerY - opposite); hexagonPath.lineTo(centerX, centerY - hypotenuse); hexagonPath.lineTo(centerX + adjacent, centerY - opposite); hexagonPath.lineTo(centerX + adjacent, centerY + opposite); hexagonPath.moveTo(centerX, centerY + hypotenuse); float radiusBorder = radius - 5; float adjacentBorder = (float) (Math.sqrt(3) * radiusBorder / 2); float oppositeBorder = radiusBorder / 2; float hypotenuseBorder = radiusBorder; // North-South hexagonBorderPath.moveTo(centerX, centerY + hypotenuseBorder); hexagonBorderPath.lineTo(centerX - adjacentBorder, centerY + oppositeBorder); hexagonBorderPath.lineTo(centerX - adjacentBorder, centerY - oppositeBorder); hexagonBorderPath.lineTo(centerX, centerY - hypotenuseBorder); hexagonBorderPath.lineTo(centerX + adjacentBorder, centerY - oppositeBorder); hexagonBorderPath.lineTo(centerX + adjacentBorder, centerY + oppositeBorder); hexagonBorderPath.moveTo(centerX, centerY + hypotenuseBorder); invalidate(); } }
apache-2.0
yongxu16/agile-test
src/test/java/configuration/ConfigurationTest.java
787
package configuration; import org.agle4j.framework.constant.ConfigConstant; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.junit.Test; /** * commons-configuration 包测试 * 一个java应用程序的配置管理类库 * * @author hanyx * @since */ public class ConfigurationTest { @Test public void testConfiguration() { try { PropertiesConfiguration config = new PropertiesConfiguration(ConfigConstant.CONFIG_FILE) ; config.setProperty("colors.background", "#000000"); config.save(); Integer num = config.getInt("app.upload_limit") ; System.out.println(num); } catch (ConfigurationException e) { e.printStackTrace(); } } }
apache-2.0
planoAccess/clonedONOS
apps/vtn/vtnweb/src/main/java/org/onosproject/vtnweb/web/FlowClassifierCodec.java
6133
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.vtnweb.web; import static com.google.common.base.Preconditions.checkNotNull; import static org.onlab.util.Tools.nullIsIllegal; import org.onlab.packet.IpPrefix; import org.onosproject.codec.CodecContext; import org.onosproject.codec.JsonCodec; import org.onosproject.vtnrsc.DefaultFlowClassifier; import org.onosproject.vtnrsc.FlowClassifier; import org.onosproject.vtnrsc.FlowClassifierId; import org.onosproject.vtnrsc.TenantId; import org.onosproject.vtnrsc.VirtualPortId; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Flow Classifier JSON codec. */ public final class FlowClassifierCodec extends JsonCodec<FlowClassifier> { private static final String FLOW_CLASSIFIER_ID = "id"; private static final String TENANT_ID = "tenant_id"; private static final String NAME = "name"; private static final String DESCRIPTION = "description"; private static final String ETHER_TYPE = "ethertype"; private static final String PROTOCOL = "protocol"; private static final String MIN_SRC_PORT_RANGE = "source_port_range_min"; private static final String MAX_SRC_PORT_RANGE = "source_port_range_max"; private static final String MIN_DST_PORT_RANGE = "destination_port_range_min"; private static final String MAX_DST_PORT_RANGE = "destination_port_range_max"; private static final String SRC_IP_PREFIX = "source_ip_prefix"; private static final String DST_IP_PREFIX = "destination_ip_prefix"; private static final String SRC_PORT = "logical_source_port"; private static final String DST_PORT = "logical_destination_port"; private static final String MISSING_MEMBER_MESSAGE = " member is required in Flow Classifier."; @Override public FlowClassifier decode(ObjectNode json, CodecContext context) { if (json == null || !json.isObject()) { return null; } FlowClassifier.Builder resultBuilder = new DefaultFlowClassifier.Builder(); String flowClassifierId = nullIsIllegal(json.get(FLOW_CLASSIFIER_ID), FLOW_CLASSIFIER_ID + MISSING_MEMBER_MESSAGE).asText(); resultBuilder.setFlowClassifierId(FlowClassifierId.of(flowClassifierId)); String tenantId = nullIsIllegal(json.get(TENANT_ID), TENANT_ID + MISSING_MEMBER_MESSAGE).asText(); resultBuilder.setTenantId(TenantId.tenantId(tenantId)); String flowClassiferName = nullIsIllegal(json.get(NAME), NAME + MISSING_MEMBER_MESSAGE).asText(); resultBuilder.setName(flowClassiferName); String flowClassiferDescription = (json.get(DESCRIPTION)).asText(); resultBuilder.setDescription(flowClassiferDescription); String etherType = nullIsIllegal(json.get(ETHER_TYPE), ETHER_TYPE + MISSING_MEMBER_MESSAGE).asText(); resultBuilder.setEtherType(etherType); String protocol = (json.get(PROTOCOL)).asText(); resultBuilder.setProtocol(protocol); int minSrcPortRange = (json.get(MIN_SRC_PORT_RANGE)).asInt(); resultBuilder.setMinSrcPortRange(minSrcPortRange); int maxSrcPortRange = (json.get(MAX_SRC_PORT_RANGE)).asInt(); resultBuilder.setMaxSrcPortRange(maxSrcPortRange); int minDstPortRange = (json.get(MIN_DST_PORT_RANGE)).asInt(); resultBuilder.setMinDstPortRange(minDstPortRange); int maxDstPortRange = (json.get(MAX_DST_PORT_RANGE)).asInt(); resultBuilder.setMaxDstPortRange(maxDstPortRange); String srcIpPrefix = (json.get(SRC_IP_PREFIX)).asText(); if (!srcIpPrefix.isEmpty()) { resultBuilder.setSrcIpPrefix(IpPrefix.valueOf(srcIpPrefix)); } String dstIpPrefix = (json.get(DST_IP_PREFIX)).asText(); if (!dstIpPrefix.isEmpty()) { resultBuilder.setDstIpPrefix(IpPrefix.valueOf(dstIpPrefix)); } String srcPort = json.get(SRC_PORT) != null ? (json.get(SRC_PORT)).asText() : ""; if (!srcPort.isEmpty()) { resultBuilder.setSrcPort(VirtualPortId.portId(srcPort)); } String dstPort = json.get(DST_PORT) != null ? (json.get(DST_PORT)).asText() : ""; if (!dstPort.isEmpty()) { resultBuilder.setDstPort(VirtualPortId.portId(dstPort)); } return resultBuilder.build(); } @Override public ObjectNode encode(FlowClassifier flowClassifier, CodecContext context) { checkNotNull(flowClassifier, "flowClassifier cannot be null"); ObjectNode result = context.mapper().createObjectNode() .put(FLOW_CLASSIFIER_ID, flowClassifier.flowClassifierId().toString()) .put(TENANT_ID, flowClassifier.tenantId().toString()) .put(NAME, flowClassifier.name()) .put(DESCRIPTION, flowClassifier.description()) .put(ETHER_TYPE, flowClassifier.etherType()) .put(PROTOCOL, flowClassifier.protocol()) .put(MIN_SRC_PORT_RANGE, flowClassifier.minSrcPortRange()) .put(MAX_SRC_PORT_RANGE, flowClassifier.maxSrcPortRange()) .put(MIN_DST_PORT_RANGE, flowClassifier.minDstPortRange()) .put(MAX_DST_PORT_RANGE, flowClassifier.maxDstPortRange()) .put(SRC_IP_PREFIX, flowClassifier.srcIpPrefix().toString()) .put(DST_IP_PREFIX, flowClassifier.dstIpPrefix().toString()) .put(SRC_PORT, flowClassifier.srcPort().toString()) .put(DST_PORT, flowClassifier.dstPort().toString()); return result; } }
apache-2.0
CaMnter/SaveVolley
volley-comments/src/main/java/com/android/volley/NetworkDispatcher.java
10456
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley; import android.annotation.TargetApi; import android.net.TrafficStats; import android.os.Build; import android.os.Process; import android.os.SystemClock; import java.util.concurrent.BlockingQueue; /** * Provides a thread for performing network dispatch from a queue of requests. * * Requests added to the specified queue are processed from the network via a * specified {@link Network} interface. Responses are committed to cache, if * eligible, using a specified {@link Cache} interface. Valid responses and * errors are posted back to the caller via a {@link ResponseDelivery}. */ /* * NetworkDispatcher 是用于处理 Volley 中的网络请求 的 网络线程。 会将 网络 Request 队列的 Request 逐个抽出 * 然后进行网络请求: * 1. 成功,拿到数据进行解析,然后将 Response 进行硬盘缓存,缓存成 Cache.Entry 的形式,最后 * 传递 Request 和 Response * 2. 失败,失败的话,一般会抛出异常,然后进行 记录请求时长 和 传递错误( VolleyError ) */ public class NetworkDispatcher extends Thread { /** The queue of requests to service. */ /* * 保存 网络 Request,因为这里会涉及到 并发 * 所以,采用 BlockingQueue */ private final BlockingQueue<Request<?>> mQueue; /** The network interface for processing requests. */ /* * 用于执行 网络请求 的 Network 接口 * HttpClientStack 或 HurlStack */ private final Network mNetwork; /** The cache to write to. */ /* * 这里的 Cache 其实是一个 DiskBasedCache 缓存 * 用于将网络请求 回调的 Response 数据进行缓存 */ private final Cache mCache; /** For posting responses and errors. */ /* * 1. 用于 传递网络请求成功后的 Request 和 Response * 2. 用于 传递网络请求失败后的 只有 error 的 Response */ private final ResponseDelivery mDelivery; /** Used for telling us to die. */ // 结束标记,标记这个 NetworkDispatcher 线程是否结束 private volatile boolean mQuit = false; /** * Creates a new network dispatcher thread. You must call {@link #start()} * in order to begin processing. * * @param queue Queue of incoming requests for triage * @param network Network interface to use for performing requests * @param cache Cache interface to use for writing responses to cache * @param delivery Delivery interface to use for posting responses */ public NetworkDispatcher(BlockingQueue<Request<?>> queue, Network network, Cache cache, ResponseDelivery delivery) { mQueue = queue; mNetwork = network; mCache = cache; mDelivery = delivery; } /** * Forces this dispatcher to quit immediately. If any requests are still in * the queue, they are not guaranteed to be processed. */ /* * 线程结束 */ public void quit() { // 设置 结束标记 mQuit = true; // 线程中断,run() 内会抛出一个 InterruptedException interrupt(); } /* * 使用 Android 4.0 以后,DDMS 中的 Network Traffic Tool * * 这里为 NetworkDispatcher 的打上 Traffic 的 tag * 实时地监测网络的使用情况 */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void addTrafficStatsTag(Request<?> request) { // Tag the request (if API >= 14) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { /* * 设置 该线程 的 监测网络的使用情况 * 在 Network Traffic Tool 工具中查到 */ TrafficStats.setThreadStatsTag(request.getTrafficStatsTag()); } } @Override public void run() { // 设置 该线程优先级为 THREAD_PRIORITY_BACKGROUND Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { /* * 记录 循环开始时的时间 * 代指 一个 请求开始时的时间 */ long startTimeMs = SystemClock.elapsedRealtime(); Request<?> request; try { // Take a request from the queue. // 从 网络 Request 队列中拿出一个 Request request = mQueue.take(); } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. // 查看 结束标记 是否为 true if (mQuit) { // 退出 循环体 return; } // 结束标记 为 false,跳过此次,然后继续循环 continue; } try { // 为请求添加一个 "cache-queue-take" MarkLog request.addMarker("network-queue-take"); // If the request was cancelled already, do not perform the // network request. // 如果 Request 已经被取消了 if (request.isCanceled()) { // 关闭请求,打印 请求中的 MarkLog request.finish("network-discard-cancelled"); // 跳过此次,然后继续循环 continue; } // 为 NetworkDispatcher 的打上 Traffic 的 tag addTrafficStatsTag(request); // Perform the network request. /* * 用于执行 网络请求 的 Network 接口 * 调用 Network 接口( HttpClientStack 或 HurlStack )去请求网络 * 但是 HttpStack 处理后,都返回 Apache 的请求结果( HttpResponse ) * performRequest(...) 接下来会将:Apache HttpResponse -> Volley NetworkResponse 进行转化 */ NetworkResponse networkResponse = mNetwork.performRequest(request); // 为请求添加一个 "network-http-complete" MarkLog request.addMarker("network-http-complete"); // If the server returned 304 AND we delivered a response already, // we're done -- don't deliver a second identical response. /* * 状态码 304: Not Modified 并且 该请求的请求结果 Response ( 响应 )已经被传递 */ if (networkResponse.notModified && request.hasHadResponseDelivered()) { // 关闭请求,打印 请求中的 MarkLog request.finish("not-modified"); // 跳过此次,然后继续循环 continue; } // Parse the response here on the worker thread. // 解析 请求结果 Response( 响应 ) Response<?> response = request.parseNetworkResponse(networkResponse); // 为请求添加一个 "network-parse-complete" MarkLog request.addMarker("network-parse-complete"); // Write to cache if applicable. // TODO: Only update cache metadata instead of entire record for 304s. /* * response.cacheEntry:会在 parseNetworkResponse(...) 的时候 执行 * Response<T> success(T result, Cache.Entry cacheEntry) 方法 构造一个 * Response<T> 对象,并且设置上 cacheEntry * * 所以这里判断了 * 1. 请求是否需要缓存 * 2. 请求结果 Response( 响应 )的 cacheEntry 是否存在 */ if (request.shouldCache() && response.cacheEntry != null) { // 在 DiskBasedCache 上添加缓存,即要缓存到硬盘中 mCache.put(request.getCacheKey(), response.cacheEntry); // 为请求添加一个 "network-cache-written" MarkLog request.addMarker("network-cache-written"); } // Post the response back. // 修改 传递标识,标识已经被传递了( 下面就开始传递 ) request.markDelivered(); // 传递 Request 和 Response mDelivery.postResponse(request, response); } catch (VolleyError volleyError) { /* * performRequest(Request<?> request) throws VolleyError * 会抛出一个 VolleyError * 所以这里被理解为 请求网络 的时候发生错误 */ // 设置 请求时长 volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); // 解析 并 传递 网络错误 parseAndDeliverNetworkError(request, volleyError); } catch (Exception e) { VolleyLog.e(e, "Unhandled exception %s", e.toString()); // 其他异常的话,也会实例化一个 VolleyError VolleyError volleyError = new VolleyError(e); // 设置 请求时长 volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); // 开始传递 错误 mDelivery.postError(request, volleyError); } } } /* * 解析 并 传递 网络错误 * 会封装成一个 VolleyError */ private void parseAndDeliverNetworkError(Request<?> request, VolleyError error) { error = request.parseNetworkError(error); mDelivery.postError(request, error); } }
apache-2.0
equella/Equella
Source/Plugins/Core/com.equella.base/src/com/tle/common/harvester/HarvesterProfileSettings.java
2776
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0, (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tle.common.harvester; import com.tle.beans.entity.LanguageBundle; import java.util.Map; public abstract class HarvesterProfileSettings { private LanguageBundle name; private Map<String, String> attributes; public HarvesterProfileSettings() { super(); } public HarvesterProfileSettings(HarvesterProfile gateway) { this(); load(gateway); } public void load(HarvesterProfile gateway1) { this.attributes = gateway1.getAttributes(); this.name = gateway1.getName(); _load(); } public void save(HarvesterProfile gateway1) { gateway1.setType(getType()); this.attributes = gateway1.getAttributes(); gateway1.setName(name); _save(); for (Map.Entry<String, String> entry : attributes.entrySet()) { gateway1.setAttribute(entry.getKey(), entry.getValue()); } } public String get(String key, String defaultValue) { String value = attributes.get(key); if (value == null) { value = defaultValue; } return value; } public boolean get(String key, boolean defaultValue) { String value = attributes.get(key); boolean v; if (value == null) { v = defaultValue; } else { v = Boolean.valueOf(value); } return v; } public int get(String key, int defaultValue) { String value = attributes.get(key); int v; if (value != null) { try { v = Integer.parseInt(value); } catch (Exception e) { v = defaultValue; } } else { v = defaultValue; } return v; } public void put(String key, Object value) { attributes.put(key, value.toString()); } public void put(String key, String value) { attributes.put(key, value); } protected abstract String getType(); protected abstract void _load(); protected abstract void _save(); public LanguageBundle getName() { return name; } public void setName(LanguageBundle name) { this.name = name; } }
apache-2.0
wamdue/agorbunov
chapter_005/src/main/java/ru/job4j/list/SimpleQueue.java
2235
package ru.job4j.list; /** * Created on 24.07.17. * Simple queue realization. * @author Wamdue * @version 1.0 * @param <E> - class to store. */ public class SimpleQueue<E> extends SimpleLinkedList<E> { /** * Link to the first element. */ private Node<E> first = null; /** * Link to the last element. */ private Node<E> last = null; /** * Size. */ private int size = 0; /** * Removes first element from list, and returns it. * @return - first element, or null if size == 0. */ public E poll() { E temp = this.first.item; if (this.size > 0) { this.first = this.first.next; this.size--; } return temp; } /** * Removes first element from list, and returns it. * @return - first element, or null if size == 0. */ public E remove() { return this.poll(); } /** * Returns first element from the list, without deleting. * @return first element from the list. */ public E peek() { return first.item; } /** * adding element to the end of the list. * @param e - element to add. */ public void offer(E e) { Node<E> l = last; Node<E> newNode = new Node<>(e, l, null); if (l == null) { first = newNode; last = newNode; } else { l.next = newNode; last = l.next; } size++; } /** * Private class to store elements in list. * @param <E> - class to store. */ private class Node<E> { /** * main element. */ private E item; /** * Link to previous item. */ private Node<E> previous; /** * link ot next item. */ private Node<E> next; /** * Main constructor. * @param item - main item. * @param previous - link to previous item. * @param next - link to next item. */ Node(E item, Node<E> previous, Node<E> next) { this.item = item; this.previous = previous; this.next = next; } } }
apache-2.0
dwdyer/uncommons-maths
core/src/java/test/org/uncommons/maths/random/PoissonGeneratorTest.java
3742
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // 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.uncommons.maths.random; import java.util.Random; import org.testng.annotations.Test; import org.uncommons.maths.Maths; import org.uncommons.maths.number.AdjustableNumberGenerator; import org.uncommons.maths.number.NumberGenerator; import org.uncommons.maths.statistics.DataSet; /** * Unit test for the Poisson number generator. * @author Daniel Dyer */ public class PoissonGeneratorTest { private final Random rng = new MersenneTwisterRNG(); /** * Check that the observed mean and standard deviation are consistent * with the specified distribution parameters. */ @Test(groups = "non-deterministic") public void testDistribution() { final double mean = 19; NumberGenerator<Integer> generator = new PoissonGenerator(mean, rng); checkDistribution(generator, mean); } @Test(groups = "non-deterministic") public void testDynamicParameters() { final double initialMean = 19; AdjustableNumberGenerator<Double> meanGenerator = new AdjustableNumberGenerator<Double>(initialMean); NumberGenerator<Integer> generator = new PoissonGenerator(meanGenerator, rng); checkDistribution(generator, initialMean); // Adjust parameters and ensure that the generator output conforms to this new // distribution. final double adjustedMean = 13; meanGenerator.setValue(adjustedMean); checkDistribution(generator, adjustedMean); } /** * The mean must be greater than zero to be useful. This test ensures * that an appropriate exception is thrown if the mean is not positive. Not * throwing an exception is an error because it permits undetected bugs in * programs that use {@link PoissonGenerator}. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testMeanTooLow() { new PoissonGenerator(0d, rng); } private void checkDistribution(NumberGenerator<Integer> generator, double expectedMean) { // Variance of a Possion distribution equals its mean. final double expectedStandardDeviation = Math.sqrt(expectedMean); final int iterations = 10000; DataSet data = new DataSet(iterations); for (int i = 0; i < iterations; i++) { int value = generator.nextValue(); assert value >= 0 : "Value must be non-negative: " + value; data.addValue(value); } assert Maths.approxEquals(data.getArithmeticMean(), expectedMean, 0.02) : "Observed mean outside acceptable range: " + data.getArithmeticMean(); assert Maths.approxEquals(data.getSampleStandardDeviation(), expectedStandardDeviation, 0.02) : "Observed standard deviation outside acceptable range: " + data.getSampleStandardDeviation(); } }
apache-2.0
GwtMaterialDesign/gwt-material-addins
src/test/java/gwt/material/design/addins/client/ui/MaterialSplitPanelTest.java
4086
/* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2017 GwtMaterialDesign * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gwt.material.design.addins.client.ui; import gwt.material.design.addins.client.ui.base.AddinsWidgetTestCase; import gwt.material.design.addins.client.splitpanel.MaterialSplitPanel; import gwt.material.design.addins.client.splitpanel.constants.Dock; import gwt.material.design.client.constants.Axis; import gwt.material.design.client.ui.MaterialPanel; /** * Test case for splitpanel component * * @author kevzlou7979 */ public class MaterialSplitPanelTest extends AddinsWidgetTestCase<MaterialSplitPanel> { @Override protected MaterialSplitPanel createWidget() { return new MaterialSplitPanel(); } public void testStructure() { // UiBinder // given MaterialSplitPanel splitPanel = getWidget(false); MaterialPanel leftPanel = new MaterialPanel(); MaterialPanel rightPanel = new MaterialPanel(); splitPanel.add(leftPanel); splitPanel.add(rightPanel); // when / then checkStructure(splitPanel, leftPanel, rightPanel); // Standard // given attachWidget(); // when / then checkStructure(splitPanel, leftPanel, rightPanel); } protected void checkStructure(MaterialSplitPanel splitPanel, MaterialPanel leftPanel, MaterialPanel rightPanel) { assertEquals(leftPanel, splitPanel.getWidget(0)); assertEquals(rightPanel, splitPanel.getWidget(1)); } public void testProperties() { // UiBinder // given MaterialSplitPanel splitPanel = getWidget(false); // when / then checkProperties(splitPanel); // Standard // given attachWidget(); // when / then checkProperties(splitPanel); } protected void checkProperties(MaterialSplitPanel splitPanel) { splitPanel.setBarPosition(20); assertEquals(0.2, splitPanel.getBarPosition()); splitPanel.setLeftMin(10); assertEquals(Double.valueOf(10), splitPanel.getLeftMin()); splitPanel.setLeftMax(40); assertEquals(Double.valueOf(40), splitPanel.getLeftMax()); splitPanel.setBottomMax(20); assertEquals(Double.valueOf(20), splitPanel.getBottomMax()); splitPanel.setBottomMin(30); assertEquals(Double.valueOf(30), splitPanel.getBottomMin()); splitPanel.setTopMax(20); assertEquals(Double.valueOf(20), splitPanel.getTopMax()); splitPanel.setTopMin(30); assertEquals(Double.valueOf(30), splitPanel.getTopMin()); splitPanel.setRightMax(20); assertEquals(Double.valueOf(20), splitPanel.getRightMax()); splitPanel.setRightMin(30); assertEquals(Double.valueOf(30), splitPanel.getRightMin()); splitPanel.setDock(Dock.RIGHT); assertEquals(Dock.RIGHT, splitPanel.getDock()); splitPanel.setDock(Dock.BOTTOM); assertEquals(Dock.BOTTOM, splitPanel.getDock()); splitPanel.setDock(Dock.LEFT); assertEquals(Dock.LEFT, splitPanel.getDock()); splitPanel.setDock(Dock.TOP); assertEquals(Dock.TOP, splitPanel.getDock()); splitPanel.setAxis(Axis.HORIZONTAL); assertEquals(Axis.HORIZONTAL, splitPanel.getAxis()); splitPanel.setAxis(Axis.VERTICAL); assertEquals(Axis.VERTICAL, splitPanel.getAxis()); splitPanel.setThickness(200); assertEquals(Double.valueOf(200), splitPanel.getThickness()); } }
apache-2.0
jakubnabrdalik/spring-workshops
src/main/groovy/eu/solidcraft/starter/examples/example2/repository/springdatajpa/SpringDataVisitRepository.java
1116
/* * Copyright 2002-2013 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 eu.solidcraft.starter.examples.example2.repository.springdatajpa; import eu.solidcraft.starter.examples.example2.model.Visit; import eu.solidcraft.starter.examples.example2.repository.VisitRepository; import org.springframework.data.repository.Repository; /** * Spring Data JPA specialization of the {@link VisitRepository} interface * * @author Michael Isvy * @since 15.1.2013 */ public interface SpringDataVisitRepository extends VisitRepository, Repository<Visit, Integer> { }
apache-2.0
Jason-Chen-2017/restfeel
src/main/java/com/restfeel/entity/RfRequest.java
3393
/* * Copyright 2014 Ranjan Kumar * * 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.restfeel.entity; import java.util.ArrayList; import java.util.List; import org.springframework.data.mongodb.core.mapping.DBRef; public class RfRequest extends NamedEntity { private static final long serialVersionUID = 1L; private String apiUrl; private String methodType; private String apiBody; private List<RfHeader> rfHeaders = new ArrayList<RfHeader>(); private List<RfCookie> rfCookies; private List<UrlParam> urlParams; private List<FormParam> formParams; private BasicAuth basicAuth; private DigestAuth digestAuth; private OAuth2 oAuth2; private String conversationId; private String evaluatedApiUrl; @DBRef private Assertion assertion; public String getMethodType() { return methodType; } public void setMethodType(String methodType) { this.methodType = methodType; } public List<RfHeader> getRfHeaders() { return rfHeaders; } public void setRfHeaders(List<RfHeader> rfHeaders) { this.rfHeaders = rfHeaders; } public List<RfCookie> getRfCookies() { return rfCookies; } public void setRfCookies(List<RfCookie> rfCookies) { this.rfCookies = rfCookies; } public List<UrlParam> getUrlParams() { return urlParams; } public void setUrlParams(List<UrlParam> urlParams) { this.urlParams = urlParams; } public List<FormParam> getFormParams() { return formParams; } public void setFormParams(List<FormParam> formParams) { this.formParams = formParams; } public BasicAuth getBasicAuth() { return basicAuth; } public void setBasicAuth(BasicAuth basicAuth) { this.basicAuth = basicAuth; } public DigestAuth getDigestAuth() { return digestAuth; } public void setDigestAuth(DigestAuth digestAuth) { this.digestAuth = digestAuth; } public OAuth2 getoAuth2() { return oAuth2; } public void setoAuth2(OAuth2 oAuth2) { this.oAuth2 = oAuth2; } public Assertion getAssertion() { return assertion; } public void setAssertion(Assertion assertion) { this.assertion = assertion; } public String getConversationId() { return conversationId; } public void setConversationId(String conversationId) { this.conversationId = conversationId; } public String getApiUrl() { return apiUrl; } public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } public String getApiBody() { return apiBody; } public void setApiBody(String apiBody) { this.apiBody = apiBody; } public String getEvaluatedApiUrl() { return evaluatedApiUrl; } public void setEvaluatedApiUrl(String evaluatedApiUrl) { this.evaluatedApiUrl = evaluatedApiUrl; } }
apache-2.0
jjmeyer0/nifi
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/test/java/org/apache/nifi/integration/accesscontrol/ITConnectionAccessControl.java
15790
/* * 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.integration.accesscontrol; import com.sun.jersey.api.client.ClientResponse; import org.apache.nifi.connectable.ConnectableType; import org.apache.nifi.integration.util.NiFiTestAuthorizer; import org.apache.nifi.integration.util.NiFiTestUser; import org.apache.nifi.web.api.dto.ConnectableDTO; import org.apache.nifi.web.api.dto.ConnectionDTO; import org.apache.nifi.web.api.dto.RevisionDTO; import org.apache.nifi.web.api.dto.flow.FlowDTO; import org.apache.nifi.web.api.entity.ConnectionEntity; import org.apache.nifi.web.api.entity.ProcessGroupFlowEntity; import org.apache.nifi.web.api.entity.ProcessorEntity; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import static org.apache.nifi.integration.accesscontrol.AccessControlHelper.NONE_CLIENT_ID; import static org.apache.nifi.integration.accesscontrol.AccessControlHelper.READ_CLIENT_ID; import static org.apache.nifi.integration.accesscontrol.AccessControlHelper.READ_WRITE_CLIENT_ID; import static org.apache.nifi.integration.accesscontrol.AccessControlHelper.WRITE_CLIENT_ID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Access control test for connections. */ public class ITConnectionAccessControl { private static AccessControlHelper helper; @BeforeClass public static void setup() throws Exception { helper = new AccessControlHelper(); } /** * Ensures the READ user can get a connection. * * @throws Exception ex */ @Test public void testReadUserGetConnection() throws Exception { final ConnectionEntity entity = getRandomConnection(helper.getReadUser()); assertTrue(entity.getPermissions().getCanRead()); assertFalse(entity.getPermissions().getCanWrite()); assertNotNull(entity.getComponent()); } /** * Ensures the READ WRITE user can get a connection. * * @throws Exception ex */ @Test public void testReadWriteUserGetConnection() throws Exception { final ConnectionEntity entity = getRandomConnection(helper.getReadWriteUser()); assertTrue(entity.getPermissions().getCanRead()); assertTrue(entity.getPermissions().getCanWrite()); assertNotNull(entity.getComponent()); } /** * Ensures the WRITE user can get a connection. * * @throws Exception ex */ @Test public void testWriteUserGetConnection() throws Exception { final ConnectionEntity entity = getRandomConnection(helper.getWriteUser()); assertFalse(entity.getPermissions().getCanRead()); assertTrue(entity.getPermissions().getCanWrite()); assertNull(entity.getComponent()); } /** * Ensures the NONE user can get a connection. * * @throws Exception ex */ @Test public void testNoneUserGetConnection() throws Exception { final ConnectionEntity entity = getRandomConnection(helper.getNoneUser()); assertFalse(entity.getPermissions().getCanRead()); assertFalse(entity.getPermissions().getCanWrite()); assertNull(entity.getComponent()); } /** * Ensures the READ user cannot put a connection. * * @throws Exception ex */ @Test public void testReadUserPutConnection() throws Exception { final ConnectionEntity entity = getRandomConnection(helper.getReadUser()); assertTrue(entity.getPermissions().getCanRead()); assertFalse(entity.getPermissions().getCanWrite()); assertNotNull(entity.getComponent()); // attempt update the name entity.getRevision().setClientId(READ_CLIENT_ID); entity.getComponent().setName("Updated Name"); // perform the request final ClientResponse response = updateConnection(helper.getReadUser(), entity); // ensure forbidden response assertEquals(403, response.getStatus()); } /** * Ensures the READ_WRITE user can put a connection. * * @throws Exception ex */ @Test public void testReadWriteUserPutConnection() throws Exception { final ConnectionEntity entity = getRandomConnection(helper.getReadWriteUser()); assertTrue(entity.getPermissions().getCanRead()); assertTrue(entity.getPermissions().getCanWrite()); assertNotNull(entity.getComponent()); final String updatedName = "Updated Name"; // attempt to update the name final long version = entity.getRevision().getVersion(); entity.getRevision().setClientId(AccessControlHelper.READ_WRITE_CLIENT_ID); entity.getComponent().setName(updatedName); // perform the request final ClientResponse response = updateConnection(helper.getReadWriteUser(), entity); // ensure successful response assertEquals(200, response.getStatus()); // get the response final ConnectionEntity responseEntity = response.getEntity(ConnectionEntity.class); // verify assertEquals(READ_WRITE_CLIENT_ID, responseEntity.getRevision().getClientId()); assertEquals(version + 1, responseEntity.getRevision().getVersion().longValue()); assertEquals(updatedName, responseEntity.getComponent().getName()); } /** * Ensures the READ_WRITE user can put a connection. * * @throws Exception ex */ @Test public void testReadWriteUserPutConnectionThroughInheritedPolicy() throws Exception { final ConnectionEntity entity = createConnection(NiFiTestAuthorizer.NO_POLICY_COMPONENT_NAME); final String updatedName = "Updated name"; // attempt to update the name final long version = entity.getRevision().getVersion(); entity.getRevision().setClientId(READ_WRITE_CLIENT_ID); entity.getComponent().setName(updatedName); // perform the request final ClientResponse response = updateConnection(helper.getReadWriteUser(), entity); // ensure successful response assertEquals(200, response.getStatus()); // get the response final ConnectionEntity responseEntity = response.getEntity(ConnectionEntity.class); // verify assertEquals(AccessControlHelper.READ_WRITE_CLIENT_ID, responseEntity.getRevision().getClientId()); assertEquals(version + 1, responseEntity.getRevision().getVersion().longValue()); assertEquals(updatedName, responseEntity.getComponent().getName()); } /** * Ensures the WRITE user can put a connection. * * @throws Exception ex */ @Test public void testWriteUserPutConnection() throws Exception { final ConnectionEntity entity = getRandomConnection(helper.getWriteUser()); assertFalse(entity.getPermissions().getCanRead()); assertTrue(entity.getPermissions().getCanWrite()); assertNull(entity.getComponent()); final String updatedName = "Updated Name"; // attempt to update the name final ConnectionDTO requestDto = new ConnectionDTO(); requestDto.setId(entity.getId()); requestDto.setName(updatedName); final long version = entity.getRevision().getVersion(); final RevisionDTO requestRevision = new RevisionDTO(); requestRevision.setVersion(version); requestRevision.setClientId(AccessControlHelper.WRITE_CLIENT_ID); final ConnectionEntity requestEntity = new ConnectionEntity(); requestEntity.setId(entity.getId()); requestEntity.setRevision(requestRevision); requestEntity.setComponent(requestDto); // perform the request final ClientResponse response = updateConnection(helper.getWriteUser(), requestEntity); // ensure successful response assertEquals(200, response.getStatus()); // get the response final ConnectionEntity responseEntity = response.getEntity(ConnectionEntity.class); // verify assertEquals(WRITE_CLIENT_ID, responseEntity.getRevision().getClientId()); assertEquals(version + 1, responseEntity.getRevision().getVersion().longValue()); } /** * Ensures the NONE user cannot put a connection. * * @throws Exception ex */ @Test public void testNoneUserPutConnection() throws Exception { final ConnectionEntity entity = getRandomConnection(helper.getNoneUser()); assertFalse(entity.getPermissions().getCanRead()); assertFalse(entity.getPermissions().getCanWrite()); assertNull(entity.getComponent()); final String updatedName = "Updated Name"; // attempt to update the name final ConnectionDTO requestDto = new ConnectionDTO(); requestDto.setId(entity.getId()); requestDto.setName(updatedName); final long version = entity.getRevision().getVersion(); final RevisionDTO requestRevision = new RevisionDTO(); requestRevision.setVersion(version); requestRevision.setClientId(AccessControlHelper.NONE_CLIENT_ID); final ConnectionEntity requestEntity = new ConnectionEntity(); requestEntity.setId(entity.getId()); requestEntity.setRevision(requestRevision); requestEntity.setComponent(requestDto); // perform the request final ClientResponse response = updateConnection(helper.getNoneUser(), requestEntity); // ensure forbidden response assertEquals(403, response.getStatus()); } /** * Ensures the READ user cannot delete a connection. * * @throws Exception ex */ @Test public void testReadUserDeleteConnection() throws Exception { verifyDelete(helper.getReadUser(), AccessControlHelper.READ_CLIENT_ID, 403); } /** * Ensures the READ WRITE user can delete a connection. * * @throws Exception ex */ @Test public void testReadWriteUserDeleteConnection() throws Exception { verifyDelete(helper.getReadWriteUser(), AccessControlHelper.READ_WRITE_CLIENT_ID, 200); } /** * Ensures the WRITE user can delete a connection. * * @throws Exception ex */ @Test public void testWriteUserDeleteConnection() throws Exception { verifyDelete(helper.getWriteUser(), AccessControlHelper.WRITE_CLIENT_ID, 200); } /** * Ensures the NONE user can delete a connection. * * @throws Exception ex */ @Test public void testNoneUserDeleteConnection() throws Exception { verifyDelete(helper.getNoneUser(), NONE_CLIENT_ID, 403); } private ConnectionEntity getRandomConnection(final NiFiTestUser user) throws Exception { final String url = helper.getBaseUrl() + "/flow/process-groups/root"; // get the connections final ClientResponse response = user.testGet(url); // ensure the response was successful assertEquals(200, response.getStatus()); // unmarshal final ProcessGroupFlowEntity flowEntity = response.getEntity(ProcessGroupFlowEntity.class); final FlowDTO flowDto = flowEntity.getProcessGroupFlow().getFlow(); final Set<ConnectionEntity> connections = flowDto.getConnections(); // ensure the correct number of connection assertFalse(connections.isEmpty()); // use the first connection as the target Iterator<ConnectionEntity> connectionIter = connections.iterator(); assertTrue(connectionIter.hasNext()); return connectionIter.next(); } private ClientResponse updateConnection(final NiFiTestUser user, final ConnectionEntity entity) throws Exception { final String url = helper.getBaseUrl() + "/connections/" + entity.getId(); // perform the request return user.testPut(url, entity); } private ConnectionEntity createConnection(final String name) throws Exception { String url = helper.getBaseUrl() + "/process-groups/root/connections"; // get two processors final ProcessorEntity one = ITProcessorAccessControl.createProcessor(helper, "one"); final ProcessorEntity two = ITProcessorAccessControl.createProcessor(helper, "two"); // create the source connectable ConnectableDTO source = new ConnectableDTO(); source.setId(one.getId()); source.setGroupId(one.getComponent().getParentGroupId()); source.setType(ConnectableType.PROCESSOR.name()); // create the target connectable ConnectableDTO target = new ConnectableDTO(); target.setId(two.getId()); target.setGroupId(two.getComponent().getParentGroupId()); target.setType(ConnectableType.PROCESSOR.name()); // create the relationships Set<String> relationships = new HashSet<>(); relationships.add("success"); // create the connection ConnectionDTO connection = new ConnectionDTO(); connection.setName(name); connection.setSource(source); connection.setDestination(target); connection.setSelectedRelationships(relationships); // create the revision final RevisionDTO revision = new RevisionDTO(); revision.setClientId(READ_WRITE_CLIENT_ID); revision.setVersion(0L); // create the entity body ConnectionEntity entity = new ConnectionEntity(); entity.setRevision(revision); entity.setComponent(connection); // perform the request ClientResponse response = helper.getReadWriteUser().testPost(url, entity); // ensure the request is successful assertEquals(201, response.getStatus()); // get the entity body entity = response.getEntity(ConnectionEntity.class); // verify creation connection = entity.getComponent(); assertEquals(name, connection.getName()); // get the connection return entity; } private void verifyDelete(final NiFiTestUser user, final String clientId, final int responseCode) throws Exception { final ConnectionEntity entity = createConnection("Copy"); // create the entity body final Map<String, String> queryParams = new HashMap<>(); queryParams.put("version", String.valueOf(entity.getRevision().getVersion())); queryParams.put("clientId", clientId); // perform the request ClientResponse response = user.testDelete(entity.getUri(), queryParams); // ensure the request is failed with a forbidden status code assertEquals(responseCode, response.getStatus()); } @AfterClass public static void cleanup() throws Exception { helper.cleanup(); } }
apache-2.0
consulo/consulo
modules/base/platform-api/src/main/java/com/intellij/ui/speedSearch/SpeedSearch.java
5838
/* * Copyright 2000-2017 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.ui.speedSearch; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.util.TextRange; import com.intellij.psi.codeStyle.AllOccurrencesMatcher; import com.intellij.psi.codeStyle.FixingLayoutMatcher; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.util.text.Matcher; import com.intellij.util.ui.UIUtil; import kava.beans.PropertyChangeListener; import kava.beans.PropertyChangeSupport; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class SpeedSearch extends SpeedSearchSupply implements KeyListener { public static final String PUNCTUATION_MARKS = "*_-\"'/.#$>: ,;?!@%^&"; private final PropertyChangeSupport myChangeSupport = new PropertyChangeSupport(this); private final boolean myMatchAllOccurrences; private String myString = ""; private boolean myEnabled; private Matcher myMatcher; public SpeedSearch() { this(false); } public SpeedSearch(boolean matchAllOccurrences) { myMatchAllOccurrences = matchAllOccurrences; } public void type(String letter) { updatePattern(myString + letter); } public void backspace() { if (myString.length() > 0) { updatePattern(myString.substring(0, myString.length() - 1)); } } public boolean shouldBeShowing(String string) { return string == null || myString.length() == 0 || (myMatcher != null && myMatcher.matches(string)); } public void processKeyEvent(KeyEvent e) { if (e.isConsumed() || !myEnabled) return; String old = myString; if (e.getID() == KeyEvent.KEY_PRESSED) { if (KeymapUtil.isEventForAction(e, "EditorDeleteToWordStart")) { if (isHoldingFilter()) { while (!myString.isEmpty() && !Character.isWhitespace(myString.charAt(myString.length() - 1))) { backspace(); } e.consume(); } } else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { backspace(); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { if (isHoldingFilter()) { updatePattern(""); e.consume(); } } } else if (e.getID() == KeyEvent.KEY_TYPED) { if (!UIUtil.isReallyTypedEvent(e)) return; // key-char is good only on KEY_TYPED // for example: key-char on ctrl-J PRESSED is \n // see https://en.wikipedia.org/wiki/Control_character char ch = e.getKeyChar(); if (Character.isLetterOrDigit(ch) || !startedWithWhitespace(ch) && PUNCTUATION_MARKS.indexOf(ch) != -1) { type(Character.toString(ch)); e.consume(); } } if (!old.equalsIgnoreCase(myString)) { update(); } } private boolean startedWithWhitespace(char ch) { return !isHoldingFilter() && Character.isWhitespace(ch); } public void update() { } public void noHits() { } public boolean isHoldingFilter() { return myEnabled && myString.length() > 0; } public void setEnabled(boolean enabled) { myEnabled = enabled; } public void reset() { if (isHoldingFilter()) { updatePattern(""); } if (myEnabled) { update(); } } public String getFilter() { return myString; } public void updatePattern(final String string) { String prevString = myString; myString = string; try { String pattern = "*" + string; NameUtil.MatchingCaseSensitivity caseSensitivity = NameUtil.MatchingCaseSensitivity.NONE; String separators = ""; myMatcher = myMatchAllOccurrences ? AllOccurrencesMatcher.create(pattern, caseSensitivity, separators) : new FixingLayoutMatcher(pattern, caseSensitivity, separators); } catch (Exception e) { myMatcher = null; } fireStateChanged(prevString); } @Nullable public Matcher getMatcher() { return myMatcher; } @Nullable @Override public Iterable<TextRange> matchingFragments(@Nonnull String text) { if (myMatcher instanceof MinusculeMatcher) { return ((MinusculeMatcher)myMatcher).matchingFragments(text); } return null; } @Override public void refreshSelection() { } @Override public boolean isPopupActive() { return isHoldingFilter(); } @Nullable @Override public String getEnteredPrefix() { return myString; } @Override public void addChangeListener(@Nonnull PropertyChangeListener listener) { myChangeSupport.addPropertyChangeListener(listener); } @Override public void removeChangeListener(@Nonnull PropertyChangeListener listener) { myChangeSupport.removePropertyChangeListener(listener); } private void fireStateChanged(String prevString) { myChangeSupport.firePropertyChange(SpeedSearchSupply.ENTERED_PREFIX_PROPERTY_NAME, prevString, getEnteredPrefix()); } @Override public void findAndSelectElement(@Nonnull String searchQuery) { } @Override public void keyTyped(KeyEvent e) { processKeyEvent(e); } @Override public void keyPressed(KeyEvent e) { processKeyEvent(e); } @Override public void keyReleased(KeyEvent e) { processKeyEvent(e); } }
apache-2.0
WASdev/standards.jsr352.jbatch
com.ibm.jbatch.container/src/main/java/com/ibm/jbatch/container/jsl/impl/TransitionImpl.java
2254
/* * Copyright 2012 International Business Machines Corp. * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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.ibm.jbatch.container.jsl.impl; import com.ibm.jbatch.container.jsl.TransitionElement; import com.ibm.jbatch.container.jsl.ExecutionElement; import com.ibm.jbatch.container.jsl.Transition; public class TransitionImpl implements Transition { private TransitionElement transitionElement; private ExecutionElement executionElement; boolean finishedTransitioning = false; boolean noTransitionElementMatchedAfterException = false; public TransitionImpl() { super(); } @Override public TransitionElement getTransitionElement() { return transitionElement; } @Override public ExecutionElement getNextExecutionElement() { return executionElement; } @Override public void setTransitionElement(TransitionElement transitionElement) { this.transitionElement = transitionElement; } @Override public void setNextExecutionElement(ExecutionElement executionElement) { this.executionElement = executionElement; } @Override public boolean isFinishedTransitioning() { return finishedTransitioning; } @Override public void setFinishedTransitioning() { this.finishedTransitioning = true; } @Override public void setNoTransitionElementMatchAfterException() { this.noTransitionElementMatchedAfterException = true; } @Override public boolean noTransitionElementMatchedAfterException() { return noTransitionElementMatchedAfterException; } }
apache-2.0
alvinkwekel/camel
components/camel-coap/src/generated/java/org/apache/camel/coap/CoAPEndpointUriFactory.java
2176
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.coap; import java.net.URISyntaxException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.camel.spi.EndpointUriFactory; /** * Generated by camel build tools - do NOT edit this file! */ public class CoAPEndpointUriFactory extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = "coaps+tcp:uri"; private static final String[] SCHEMES = new String[]{"coap", "coaps", "coap+tcp", "coaps+tcp"}; private static final Set<String> PROPERTY_NAMES; static { Set<String> set = new HashSet<>(17); set.add("uri"); set.add("alias"); set.add("cipherSuites"); set.add("clientAuthentication"); set.add("privateKey"); set.add("pskStore"); set.add("publicKey"); set.add("recommendedCipherSuitesOnly"); set.add("sslContextParameters"); set.add("trustedRpkStore"); set.add("bridgeErrorHandler"); set.add("coapMethodRestrict"); set.add("exceptionHandler"); set.add("exchangePattern"); set.add("lazyStartProducer"); set.add("basicPropertyBinding"); set.add("synchronous"); PROPERTY_NAMES = set; } @Override public boolean isEnabled(String scheme) { for (String s : SCHEMES) { if (s.equals(scheme)) { return true; } } return false; } @Override public String buildUri(String scheme, Map<String, Object> properties) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "uri", null, false, copy); uri = buildQueryParameters(uri, copy); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public boolean isLenientProperties() { return false; } }
apache-2.0
loilo-inc/loilo-promise
promise/src/main/java/tv/loilo/promise/UntilParams.java
1081
/* * Copyright (c) 2015-2016 LoiLo 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 tv.loilo.promise; import java.util.concurrent.atomic.AtomicInteger; /** * Parameters that are passed to {@link UntilCallback}. */ public final class UntilParams<T> extends ResultParams<T> { private final AtomicInteger mIndex; public UntilParams(AtomicInteger index, Result<T> result, CloseableStack scope, Object tag) { super(result, scope, tag); mIndex = index; } public AtomicInteger getIndex() { return mIndex; } }
apache-2.0
googleapis/google-cloudevents-java
src/main/java/com/google/events/cloud/cloudbuild/v1/MachineTypeEnum.java
1348
/* * Copyright 2021 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. */ package com.google.events.cloud.cloudbuild.v1; import java.io.IOException; public enum MachineTypeEnum { N1_HIGHCPU_32, N1_HIGHCPU_8, UNSPECIFIED; public String toValue() { switch (this) { case N1_HIGHCPU_32: return "N1_HIGHCPU_32"; case N1_HIGHCPU_8: return "N1_HIGHCPU_8"; case UNSPECIFIED: return "UNSPECIFIED"; } return null; } public static MachineTypeEnum forValue(String value) throws IOException { if (value.equals("N1_HIGHCPU_32")) return N1_HIGHCPU_32; if (value.equals("N1_HIGHCPU_8")) return N1_HIGHCPU_8; if (value.equals("UNSPECIFIED")) return UNSPECIFIED; throw new IOException("Cannot deserialize MachineTypeEnum"); } }
apache-2.0
CLovinr/OftenPorter
Porter-Bridge-Servlet/src/main/java/cn/oftenporter/servlet/JSONHeader.java
176
package cn.oftenporter.servlet; /** * 实现了该接口的对象,被输出时设置内容类型为{@linkplain ContentType#APP_JSON}。 */ public interface JSONHeader { }
apache-2.0
simonbrunner/msnswitch-control
src/main/java/com/simonbrunner/msnswitchctrl/network/SwitchStatus.java
451
package com.simonbrunner.msnswitchctrl.network; /** * Created by simon on 03/01/16. */ public class SwitchStatus { private Boolean plug1; private Boolean plug2; public Boolean getPlug1() { return plug1; } public void setPlug1(Boolean plug1) { this.plug1 = plug1; } public Boolean getPlug2() { return plug2; } public void setPlug2(Boolean plug2) { this.plug2 = plug2; } }
apache-2.0
smanvi-pivotal/geode
geode-core/src/main/java/org/apache/geode/internal/cache/tier/Acceptor.java
2120
/* * 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.geode.internal.cache.tier; import java.io.IOException; import org.apache.geode.internal.Version; import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier; /** * Defines the message listener/acceptor interface which is the GemFire Bridge Server. Multiple * communication stacks may provide implementations for the interfaces defined in this package * * @since GemFire 2.0.2 */ public interface Acceptor { /** * The GFE version of the server. * * @since GemFire 5.7 */ Version VERSION = Version.CURRENT.getGemFireVersion(); /** * Listens for a client to connect and establishes a connection to that client. */ void accept() throws Exception; /** * Starts this acceptor thread */ void start() throws IOException; /** * Returns the port on which this acceptor listens for connections from clients. */ int getPort(); /** * returns the server's name string, including the inet address and port that the server is * listening on */ String getServerName(); /** * Closes this acceptor thread */ void close(); /** * Is this acceptor running (handling connections)? */ boolean isRunning(); /** * Returns the CacheClientNotifier used by this Acceptor. */ CacheClientNotifier getCacheClientNotifier(); }
apache-2.0
witcxc/saiku
saiku-core/saiku-service/src/main/java/org/saiku/service/olap/totals/package-info.java
655
/* * Copyright 2014 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * OLAP Totals. * */ package org.saiku.service.olap.totals;
apache-2.0
fr3anthe/ifedorenko
3.1-Hibernate/3.1.2.2-CarSell/src/main/java/ru/job4j/model/dao/DCarbody.java
888
package ru.job4j.model.dao; import org.slf4j.LoggerFactory; import ru.job4j.model.entities.Carbody; import java.util.List; /** * class DCarbody. * * @author ifedorenko * @since 19.12.2018 */ public class DCarbody extends DAOAbstract<Carbody> { private static final DCarbody INSTANCE = new DCarbody(); /** * Private Constructor */ private DCarbody() { this.logger = LoggerFactory.getLogger(DCarbody.class); } @Override public Carbody getById(int id) { return this.tx(session -> session.get(Carbody.class, id)); } @Override public List<Carbody> getAll() { return this.tx(session -> session.createQuery("from ru.job4j.model.entities.Carbody").getResultList()); } /** * Method getInstance. * @return INSTANCE */ public static DCarbody getInstance() { return INSTANCE; } }
apache-2.0
jituo666/CrazyPic
src/com/xjt/crazypic/edit/pipeline/RenderingRequestCaller.java
138
package com.xjt.crazypic.edit.pipeline; public interface RenderingRequestCaller { public void available(RenderingRequest request); }
apache-2.0
orioncode/orionplatform
orion_data/orion_data_structures/src/main/java/com/orionplatform/data/data_structures/array/ArraySortService.java
1201
package com.orionplatform.data.data_structures.array; import java.util.Arrays; import java.util.Comparator; import com.orionplatform.core.abstraction.OrionService; public class ArraySortService<T> extends OrionService { public static synchronized void sort(byte[] array) { Arrays.sort(array); } public static synchronized void sort(short[] array) { Arrays.sort(array); } public static synchronized void sort(int[] array) { Arrays.sort(array); } public static synchronized void sort(long[] array) { Arrays.sort(array); } public static synchronized void sort(float[] array) { Arrays.sort(array); } public static synchronized void sort(double[] array) { Arrays.sort(array); } public static synchronized void sort(char[] array) { Arrays.sort(array); } public static synchronized <T> void sort(T[] array) { Arrays.sort(array); } public static synchronized <T> void sort(T[] array, Comparator<T> comparator) { Arrays.sort(array, comparator); } }
apache-2.0
pgfox/activemq-artemis
artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java
88749
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.server; /** * Logger Code 22 * * each message id must be 6 digits long starting with 10, the 3rd digit donates the level so * * INF0 1 * WARN 2 * DEBUG 3 * ERROR 4 * TRACE 5 * FATAL 6 * * so an INFO message would be 101000 to 101999 */ import javax.transaction.xa.Xid; import java.io.File; import java.net.SocketAddress; import java.net.URI; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import io.netty.channel.Channel; import org.apache.activemq.artemis.api.core.ActiveMQExceptionType; import org.apache.activemq.artemis.api.core.Pair; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.client.impl.ServerLocatorInternal; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.io.IOCallback; import org.apache.activemq.artemis.core.io.SequentialFile; import org.apache.activemq.artemis.core.paging.cursor.PagePosition; import org.apache.activemq.artemis.core.paging.cursor.PageSubscription; import org.apache.activemq.artemis.core.persistence.OperationContext; import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.BackupReplicationStartFailedMessage; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.server.cluster.Bridge; import org.apache.activemq.artemis.core.server.cluster.impl.BridgeImpl; import org.apache.activemq.artemis.core.server.cluster.impl.ClusterConnectionImpl; import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl; import org.apache.activemq.artemis.core.server.impl.ServerSessionImpl; import org.apache.activemq.artemis.core.server.management.Notification; import org.apache.activemq.artemis.utils.FutureLatch; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.w3c.dom.Node; @MessageLogger(projectCode = "AMQ") public interface ActiveMQServerLogger extends BasicLogger { /** * The default logger. */ ActiveMQServerLogger LOGGER = Logger.getMessageLogger(ActiveMQServerLogger.class, ActiveMQServerLogger.class.getPackage().getName()); @LogMessage(level = Logger.Level.DEBUG) @Message(id = 223000, value = "Received Interrupt Exception whilst waiting for component to shutdown: {0}", format = Message.Format.MESSAGE_FORMAT) void interruptWhilstStoppingComponent(String componentClassName); @LogMessage(level = Logger.Level.INFO) @Message(id = 221000, value = "{0} Message Broker is starting with configuration {1}", format = Message.Format.MESSAGE_FORMAT) void serverStarting(String type, Configuration configuration); @LogMessage(level = Logger.Level.INFO) @Message(id = 221001, value = "Apache ActiveMQ Artemis Message Broker version {0} [{1}, nodeID={2}] {3}", format = Message.Format.MESSAGE_FORMAT) void serverStarted(String fullVersion, String name, SimpleString nodeId, String identity); @LogMessage(level = Logger.Level.INFO) @Message(id = 221002, value = "Apache ActiveMQ Artemis Message Broker version {0} [{1}] stopped, uptime {2}", format = Message.Format.MESSAGE_FORMAT) void serverStopped(String version, SimpleString nodeId, String uptime); @LogMessage(level = Logger.Level.INFO) @Message(id = 221003, value = "Deploying queue {0}", format = Message.Format.MESSAGE_FORMAT) void deployQueue(SimpleString queueName); @LogMessage(level = Logger.Level.INFO) @Message(id = 221004, value = "{0}", format = Message.Format.MESSAGE_FORMAT) void dumpServerInfo(String serverInfo); @LogMessage(level = Logger.Level.INFO) @Message(id = 221005, value = "Deleting pending large message as it was not completed: {0}", format = Message.Format.MESSAGE_FORMAT) void deletingPendingMessage(Pair<Long, Long> msgToDelete); @LogMessage(level = Logger.Level.INFO) @Message(id = 221006, value = "Waiting to obtain live lock", format = Message.Format.MESSAGE_FORMAT) void awaitingLiveLock(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221007, value = "Server is now live", format = Message.Format.MESSAGE_FORMAT) void serverIsLive(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221008, value = "live server wants to restart, restarting server in backup", format = Message.Format.MESSAGE_FORMAT) void awaitFailBack(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221109, value = "Apache ActiveMQ Artemis Backup Server version {0} [{1}] started, waiting live to fail before it gets active", format = Message.Format.MESSAGE_FORMAT) void backupServerStarted(String version, SimpleString nodeID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221010, value = "Backup Server is now live", format = Message.Format.MESSAGE_FORMAT) void backupServerIsLive(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221011, value = "Server {0} is now live", format = Message.Format.MESSAGE_FORMAT) void serverIsLive(String identity); @LogMessage(level = Logger.Level.INFO) @Message(id = 221012, value = "Using AIO Journal", format = Message.Format.MESSAGE_FORMAT) void journalUseAIO(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221013, value = "Using NIO Journal", format = Message.Format.MESSAGE_FORMAT) void journalUseNIO(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221014, value = "{0}% loaded", format = Message.Format.MESSAGE_FORMAT) void percentLoaded(Long percent); @LogMessage(level = Logger.Level.INFO) @Message(id = 221015, value = "Can not find queue {0} while reloading ACKNOWLEDGE_CURSOR, deleting record now", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueReloading(Long queueID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221016, value = "Can not find queue {0} while reloading PAGE_CURSOR_COUNTER_VALUE, deleting record now", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueReloadingPage(Long queueID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221017, value = "Can not find queue {0} while reloading PAGE_CURSOR_COUNTER_INC, deleting record now", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueReloadingPageCursor(Long queueID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221018, value = "Large message: {0} did not have any associated reference, file will be deleted", format = Message.Format.MESSAGE_FORMAT) void largeMessageWithNoRef(Long messageID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221019, value = "Deleting unreferenced message id={0} from the journal", format = Message.Format.MESSAGE_FORMAT) void journalUnreferencedMessage(Long messageID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221020, value = "Started {0} Acceptor at {1}:{2,number,#} for protocols [{3}]", format = Message.Format.MESSAGE_FORMAT) void startedAcceptor(String acceptorType, String host, Integer port, String enabledProtocols); @LogMessage(level = Logger.Level.INFO) @Message(id = 221021, value = "failed to remove connection", format = Message.Format.MESSAGE_FORMAT) void errorRemovingConnection(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221022, value = "unable to start connector service: {0}", format = Message.Format.MESSAGE_FORMAT) void errorStartingConnectorService(@Cause Throwable e, String name); @LogMessage(level = Logger.Level.INFO) @Message(id = 221023, value = "unable to stop connector service: {0}", format = Message.Format.MESSAGE_FORMAT) void errorStoppingConnectorService(@Cause Throwable e, String name); @LogMessage(level = Logger.Level.INFO) @Message(id = 221024, value = "Backup server {0} is synchronized with live-server.", format = Message.Format.MESSAGE_FORMAT) void backupServerSynched(ActiveMQServerImpl server); @LogMessage(level = Logger.Level.INFO) @Message(id = 221025, value = "Replication: sending {0} (size={1}) to replica.", format = Message.Format.MESSAGE_FORMAT) void replicaSyncFile(SequentialFile jf, Long size); @LogMessage(level = Logger.Level.INFO) @Message( id = 221026, value = "Bridge {0} connected to forwardingAddress={1}. {2} does not have any bindings. Messages will be ignored until a binding is created.", format = Message.Format.MESSAGE_FORMAT) void bridgeNoBindings(SimpleString name, SimpleString forwardingAddress, SimpleString address); @LogMessage(level = Logger.Level.INFO) @Message(id = 221027, value = "Bridge {0} is connected", format = Message.Format.MESSAGE_FORMAT) void bridgeConnected(BridgeImpl name); @LogMessage(level = Logger.Level.INFO) @Message(id = 221028, value = "Bridge is stopping, will not retry", format = Message.Format.MESSAGE_FORMAT) void bridgeStopping(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221029, value = "stopped bridge {0}", format = Message.Format.MESSAGE_FORMAT) void bridgeStopped(SimpleString name); @LogMessage(level = Logger.Level.INFO) @Message(id = 221030, value = "paused bridge {0}", format = Message.Format.MESSAGE_FORMAT) void bridgePaused(SimpleString name); @LogMessage(level = Logger.Level.INFO) @Message(id = 221031, value = "backup announced", format = Message.Format.MESSAGE_FORMAT) void backupAnnounced(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221032, value = "Waiting to become backup node", format = Message.Format.MESSAGE_FORMAT) void waitingToBecomeBackup(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221033, value = "** got backup lock", format = Message.Format.MESSAGE_FORMAT) void gotBackupLock(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221034, value = "Waiting {0} to obtain live lock", format = Message.Format.MESSAGE_FORMAT) void waitingToObtainLiveLock(String timeoutMessage); @LogMessage(level = Logger.Level.INFO) @Message(id = 221035, value = "Live Server Obtained live lock", format = Message.Format.MESSAGE_FORMAT) void obtainedLiveLock(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221036, value = "Message with duplicate ID {0} was already set at {1}. Move from {2} being ignored and message removed from {3}", format = Message.Format.MESSAGE_FORMAT) void messageWithDuplicateID(Object duplicateProperty, SimpleString toAddress, SimpleString address, SimpleString simpleString); @LogMessage(level = Logger.Level.INFO) @Message(id = 221037, value = "{0} to become ''live''", format = Message.Format.MESSAGE_FORMAT) void becomingLive(ActiveMQServer server); @LogMessage(level = Logger.Level.INFO) @Message(id = 221038, value = "Configuration option ''{0}'' is deprecated. Consult the manual for details.", format = Message.Format.MESSAGE_FORMAT) void deprecatedConfigurationOption(String deprecatedOption); @LogMessage(level = Logger.Level.INFO) @Message(id = 221039, value = "Restarting as Replicating backup server after live restart", format = Message.Format.MESSAGE_FORMAT) void restartingReplicatedBackupAfterFailback(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221040, value = "Remote group coordinators has not started.", format = Message.Format.MESSAGE_FORMAT) void remoteGroupCoordinatorsNotStarted(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221041, value = "Cannot find queue {0} while reloading PAGE_CURSOR_COMPLETE, deleting record now", format = Message.Format.MESSAGE_FORMAT) void cantFindQueueOnPageComplete(long queueID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221042, value = "Bridge {0} timed out waiting for the completion of {1} messages, we will just shutdown the bridge after 10 seconds wait", format = Message.Format.MESSAGE_FORMAT) void timedOutWaitingCompletions(String bridgeName, long numberOfMessages); @LogMessage(level = Logger.Level.INFO) @Message(id = 221043, value = "Protocol module found: [{1}]. Adding protocol support for: {0}", format = Message.Format.MESSAGE_FORMAT) void addingProtocolSupport(String protocolKey, String moduleName); @LogMessage(level = Logger.Level.INFO) @Message(id = 221045, value = "libaio is not available, switching the configuration into NIO", format = Message.Format.MESSAGE_FORMAT) void switchingNIO(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221046, value = "Unblocking message production on address ''{0}''; size is currently: {1} bytes; max-size-bytes: {2}", format = Message.Format.MESSAGE_FORMAT) void unblockingMessageProduction(SimpleString addressName, long currentSize, long maxSize); @LogMessage(level = Logger.Level.INFO) @Message(id = 221047, value = "Backup Server has scaled down to live server", format = Message.Format.MESSAGE_FORMAT) void backupServerScaledDown(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221048, value = "Consumer {0}:{1} attached to queue ''{2}'' from {3} identified as ''slow.'' Expected consumption rate: {4} msgs/second; actual consumption rate: {5} msgs/second.", format = Message.Format.MESSAGE_FORMAT) void slowConsumerDetected(String sessionID, long consumerID, String queueName, String remoteAddress, float slowConsumerThreshold, float consumerRate); @LogMessage(level = Logger.Level.INFO) @Message(id = 221049, value = "Activating Replica for node: {0}", format = Message.Format.MESSAGE_FORMAT) void activatingReplica(SimpleString nodeID); @LogMessage(level = Logger.Level.INFO) @Message(id = 221050, value = "Activating Shared Store Slave", format = Message.Format.MESSAGE_FORMAT) void activatingSharedStoreSlave(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221051, value = "Populating security roles from LDAP at: {0}", format = Message.Format.MESSAGE_FORMAT) void populatingSecurityRolesFromLDAP(String url); @LogMessage(level = Logger.Level.INFO) @Message(id = 221052, value = "Deploying topic {0}", format = Message.Format.MESSAGE_FORMAT) void deployTopic(SimpleString topicName); @LogMessage(level = Logger.Level.INFO) @Message(id = 221053, value = "Disallowing use of vulnerable protocol ''{0}'' on acceptor ''{1}''. See http://www.oracle.com/technetwork/topics/security/poodlecve-2014-3566-2339408.html for more details.", format = Message.Format.MESSAGE_FORMAT) void disallowedProtocol(String protocol, String acceptorName); @LogMessage(level = Logger.Level.INFO) @Message(id = 221054, value = "libaio was found but the filesystem does not support AIO. Switching the configuration into NIO. Journal path: {0}", format = Message.Format.MESSAGE_FORMAT) void switchingNIOonPath(String journalPath); @LogMessage(level = Logger.Level.INFO) @Message(id = 221055, value = "There were too many old replicated folders upon startup, removing {0}", format = Message.Format.MESSAGE_FORMAT) void removingBackupData(String path); @LogMessage(level = Logger.Level.INFO) @Message(id = 221056, value = "Reloading configuration ...{0}", format = Message.Format.MESSAGE_FORMAT) void reloadingConfiguration(String module); @LogMessage(level = Logger.Level.INFO) @Message(id = 221057, value = "Global Max Size is being adjusted to 1/2 of the JVM max size (-Xmx). being defined as {0}", format = Message.Format.MESSAGE_FORMAT) void usingDefaultPaging(long bytes); @LogMessage(level = Logger.Level.INFO) @Message(id = 221058, value = "resetting Journal File size from {0} to {1} to fit with alignment of {2}", format = Message.Format.MESSAGE_FORMAT) void invalidJournalFileSize(int journalFileSize, int fileSize, int alignment); @LogMessage(level = Logger.Level.INFO) @Message(id = 221059, value = "Deleting old data directory {0} as the max folders is set to 0", format = Message.Format.MESSAGE_FORMAT) void backupDeletingData(String oldPath); @LogMessage(level = Logger.Level.INFO) @Message(id = 221060, value = "Sending quorum vote request to {0}: {1}", format = Message.Format.MESSAGE_FORMAT) void sendingQuorumVoteRequest(String remoteAddress, String vote); @LogMessage(level = Logger.Level.INFO) @Message(id = 221061, value = "Received quorum vote response from {0}: {1}", format = Message.Format.MESSAGE_FORMAT) void receivedQuorumVoteResponse(String remoteAddress, String vote); @LogMessage(level = Logger.Level.INFO) @Message(id = 221062, value = "Received quorum vote request: {0}", format = Message.Format.MESSAGE_FORMAT) void receivedQuorumVoteRequest(String vote); @LogMessage(level = Logger.Level.INFO) @Message(id = 221063, value = "Sending quorum vote response: {0}", format = Message.Format.MESSAGE_FORMAT) void sendingQuorumVoteResponse(String vote); @LogMessage(level = Logger.Level.INFO) @Message(id = 221064, value = "Node {0} found in cluster topology", format = Message.Format.MESSAGE_FORMAT) void nodeFoundInClusterTopology(String nodeId); @LogMessage(level = Logger.Level.INFO) @Message(id = 221065, value = "Node {0} not found in cluster topology", format = Message.Format.MESSAGE_FORMAT) void nodeNotFoundInClusterTopology(String nodeId); @LogMessage(level = Logger.Level.INFO) @Message(id = 221066, value = "Initiating quorum vote: {0}", format = Message.Format.MESSAGE_FORMAT) void initiatingQuorumVote(SimpleString vote); @LogMessage(level = Logger.Level.INFO) @Message(id = 221067, value = "Waiting {0} {1} for quorum vote results.", format = Message.Format.MESSAGE_FORMAT) void waitingForQuorumVoteResults(int timeout, String unit); @LogMessage(level = Logger.Level.INFO) @Message(id = 221068, value = "Received all quorum votes.", format = Message.Format.MESSAGE_FORMAT) void receivedAllQuorumVotes(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221069, value = "Timeout waiting for quorum vote responses.", format = Message.Format.MESSAGE_FORMAT) void timeoutWaitingForQuorumVoteResponses(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221070, value = "Restarting as backup based on quorum vote results.", format = Message.Format.MESSAGE_FORMAT) void restartingAsBackupBasedOnQuorumVoteResults(); @LogMessage(level = Logger.Level.INFO) @Message(id = 221071, value = "Failing over based on quorum vote results.", format = Message.Format.MESSAGE_FORMAT) void failingOverBasedOnQuorumVoteResults(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222000, value = "ActiveMQServer is being finalized and has not been stopped. Please remember to stop the server before letting it go out of scope", format = Message.Format.MESSAGE_FORMAT) void serverFinalisedWIthoutBeingSTopped(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222001, value = "Error closing sessions while stopping server", format = Message.Format.MESSAGE_FORMAT) void errorClosingSessionsWhileStoppingServer(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222002, value = "Timed out waiting for pool to terminate {0}. Interrupting all its threads!", format = Message.Format.MESSAGE_FORMAT) void timedOutStoppingThreadpool(ExecutorService service); @LogMessage(level = Logger.Level.WARN) @Message(id = 222004, value = "Must specify an address for each divert. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void divertWithNoAddress(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222005, value = "Must specify a forwarding address for each divert. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void divertWithNoForwardingAddress(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222006, value = "Binding already exists with name {0}, divert will not be deployed", format = Message.Format.MESSAGE_FORMAT) void divertBindingAlreadyExists(SimpleString bindingName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222007, value = "Security risk! Apache ActiveMQ Artemis is running with the default cluster admin user and default password. Please see the cluster chapter in the ActiveMQ Artemis User Guide for instructions on how to change this.", format = Message.Format.MESSAGE_FORMAT) void clusterSecurityRisk(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222008, value = "unable to restart server, please kill and restart manually", format = Message.Format.MESSAGE_FORMAT) void serverRestartWarning(); @LogMessage(level = Logger.Level.WARN) void serverRestartWarning(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222009, value = "Unable to announce backup for replication. Trying to stop the server.", format = Message.Format.MESSAGE_FORMAT) void replicationStartProblem(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222010, value = "Critical IO Error, shutting down the server. file={1}, message={0}", format = Message.Format.MESSAGE_FORMAT) void ioCriticalIOError(String message, String file, @Cause Throwable code); @LogMessage(level = Logger.Level.WARN) @Message(id = 222011, value = "Error stopping server", format = Message.Format.MESSAGE_FORMAT) void errorStoppingServer(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222012, value = "Timed out waiting for backup activation to exit", format = Message.Format.MESSAGE_FORMAT) void backupActivationProblem(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222013, value = "Error when trying to start replication", format = Message.Format.MESSAGE_FORMAT) void errorStartingReplication(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222014, value = "Error when trying to stop replication", format = Message.Format.MESSAGE_FORMAT) void errorStoppingReplication(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222016, value = "Cannot deploy a connector with no name specified.", format = Message.Format.MESSAGE_FORMAT) void connectorWithNoName(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222017, value = "There is already a connector with name {0} deployed. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void connectorAlreadyDeployed(String name); @LogMessage(level = Logger.Level.WARN) @Message( id = 222018, value = "AIO was not located on this platform, it will fall back to using pure Java NIO. If your platform is Linux, install LibAIO to enable the AIO journal", format = Message.Format.MESSAGE_FORMAT) void AIONotFound(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222019, value = "There is already a discovery group with name {0} deployed. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void discoveryGroupAlreadyDeployed(String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222020, value = "error scanning for URL''s", format = Message.Format.MESSAGE_FORMAT) void errorScanningURLs(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222021, value = "problem undeploying {0}", format = Message.Format.MESSAGE_FORMAT) void problemUndeployingNode(@Cause Exception e, Node node); @LogMessage(level = Logger.Level.WARN) @Message(id = 222022, value = "Timed out waiting for paging cursor to stop {0} {1}", format = Message.Format.MESSAGE_FORMAT) void timedOutStoppingPagingCursor(FutureLatch future, Executor executor); @LogMessage(level = Logger.Level.WARN) @Message(id = 222023, value = "problem cleaning page address {0}", format = Message.Format.MESSAGE_FORMAT) void problemCleaningPageAddress(@Cause Exception e, SimpleString address); @LogMessage(level = Logger.Level.WARN) @Message(id = 222024, value = "Could not complete operations on IO context {0}", format = Message.Format.MESSAGE_FORMAT) void problemCompletingOperations(OperationContext e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222025, value = "Problem cleaning page subscription counter", format = Message.Format.MESSAGE_FORMAT) void problemCleaningPagesubscriptionCounter(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222026, value = "Error on cleaning up cursor pages", format = Message.Format.MESSAGE_FORMAT) void problemCleaningCursorPages(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222027, value = "Timed out flushing executors for paging cursor to stop {0}", format = Message.Format.MESSAGE_FORMAT) void timedOutFlushingExecutorsPagingCursor(PageSubscription pageSubscription); @LogMessage(level = Logger.Level.WARN) @Message(id = 222028, value = "Could not find page cache for page {0} removing it from the journal", format = Message.Format.MESSAGE_FORMAT) void pageNotFound(PagePosition pos); @LogMessage(level = Logger.Level.WARN) @Message(id = 222029, value = "Could not locate page transaction {0}, ignoring message on position {1} on address={2} queue={3}", format = Message.Format.MESSAGE_FORMAT) void pageSubscriptionCouldntLoad(long transactionID, PagePosition position, SimpleString address, SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222030, value = "File {0} being renamed to {1}.invalidPage as it was loaded partially. Please verify your data.", format = Message.Format.MESSAGE_FORMAT) void pageInvalid(String fileName, String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222031, value = "Error while deleting page file", format = Message.Format.MESSAGE_FORMAT) void pageDeleteError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222032, value = "page finalise error", format = Message.Format.MESSAGE_FORMAT) void pageFinaliseError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222033, value = "Page file {0} had incomplete records at position {1} at record number {2}", format = Message.Format.MESSAGE_FORMAT) void pageSuspectFile(String fileName, int position, int msgNumber); @LogMessage(level = Logger.Level.WARN) @Message(id = 222034, value = "Can not delete page transaction id={0}", format = Message.Format.MESSAGE_FORMAT) void pageTxDeleteError(@Cause Exception e, long recordID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222035, value = "Directory {0} did not have an identification file {1}", format = Message.Format.MESSAGE_FORMAT) void pageStoreFactoryNoIdFile(String s, String addressFile); @LogMessage(level = Logger.Level.WARN) @Message(id = 222036, value = "Timed out on waiting PagingStore {0} to shutdown", format = Message.Format.MESSAGE_FORMAT) void pageStoreTimeout(SimpleString address); @LogMessage(level = Logger.Level.WARN) @Message(id = 222037, value = "IO Error, impossible to start paging", format = Message.Format.MESSAGE_FORMAT) void pageStoreStartIOError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222038, value = "Starting paging on address ''{0}''; size is currently: {1} bytes; max-size-bytes: {2}", format = Message.Format.MESSAGE_FORMAT) void pageStoreStart(SimpleString storeName, long addressSize, long maxSize); @LogMessage(level = Logger.Level.WARN) @Message(id = 222039, value = "Messages sent to address ''{0}'' are being dropped; size is currently: {1} bytes; max-size-bytes: {2}", format = Message.Format.MESSAGE_FORMAT) void pageStoreDropMessages(SimpleString storeName, long addressSize, long maxSize); @LogMessage(level = Logger.Level.WARN) @Message(id = 222040, value = "Server is stopped", format = Message.Format.MESSAGE_FORMAT) void serverIsStopped(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222041, value = "Cannot find queue {0} to update delivery count", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueDelCount(Long queueID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222042, value = "Cannot find message {0} to update delivery count", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindMessageDelCount(Long msg); @LogMessage(level = Logger.Level.WARN) @Message(id = 222043, value = "Message for queue {0} which does not exist. This message will be ignored.", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueForMessage(Long queueID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222044, value = "It was not possible to delete message {0}", format = Message.Format.MESSAGE_FORMAT) void journalErrorDeletingMessage(@Cause Exception e, Long messageID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222045, value = "Message in prepared tx for queue {0} which does not exist. This message will be ignored.", format = Message.Format.MESSAGE_FORMAT) void journalMessageInPreparedTX(Long queueID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222046, value = "Failed to remove reference for {0}", format = Message.Format.MESSAGE_FORMAT) void journalErrorRemovingRef(Long messageID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222047, value = "Can not find queue {0} while reloading ACKNOWLEDGE_CURSOR", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueReloadingACK(Long queueID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222048, value = "PAGE_CURSOR_COUNTER_VALUE record used on a prepared statement, invalid state", format = Message.Format.MESSAGE_FORMAT) void journalPAGEOnPrepared(); @LogMessage(level = Logger.Level.WARN) @Message( id = 222049, value = "InternalError: Record type {0} not recognized. Maybe you are using journal files created on a different version", format = Message.Format.MESSAGE_FORMAT) void journalInvalidRecordType(Byte recordType); @LogMessage(level = Logger.Level.WARN) @Message(id = 222050, value = "Can not locate recordType={0} on loadPreparedTransaction//deleteRecords", format = Message.Format.MESSAGE_FORMAT) void journalInvalidRecordTypeOnPreparedTX(Byte recordType); @LogMessage(level = Logger.Level.WARN) @Message(id = 222051, value = "Journal Error", format = Message.Format.MESSAGE_FORMAT) void journalError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222052, value = "error incrementing delay detection", format = Message.Format.MESSAGE_FORMAT) void errorIncrementDelayDeletionCount(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222053, value = "Error on copying large message {0} for DLA or Expiry", format = Message.Format.MESSAGE_FORMAT) void lareMessageErrorCopying(@Cause Exception e, LargeServerMessage largeServerMessage); @LogMessage(level = Logger.Level.WARN) @Message(id = 222054, value = "Error on executing IOCallback", format = Message.Format.MESSAGE_FORMAT) void errorExecutingAIOCallback(@Cause Throwable t); @LogMessage(level = Logger.Level.WARN) @Message(id = 222055, value = "Error on deleting duplicate cache", format = Message.Format.MESSAGE_FORMAT) void errorDeletingDuplicateCache(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222056, value = "Did not route to any bindings for address {0} and sendToDLAOnNoRoute is true but there is no DLA configured for the address, the message will be ignored.", format = Message.Format.MESSAGE_FORMAT) void noDLA(SimpleString address); @LogMessage(level = Logger.Level.WARN) @Message(id = 222057, value = "It was not possible to add references due to an IO error code {0} message = {1}", format = Message.Format.MESSAGE_FORMAT) void ioErrorAddingReferences(Integer errorCode, String errorMessage); @LogMessage(level = Logger.Level.WARN) @Message(id = 222059, value = "Duplicate message detected - message will not be routed. Message information:\n{0}", format = Message.Format.MESSAGE_FORMAT) void duplicateMessageDetected(org.apache.activemq.artemis.api.core.Message message); @LogMessage(level = Logger.Level.WARN) @Message(id = 222060, value = "Error while confirming large message completion on rollback for recordID={0}", format = Message.Format.MESSAGE_FORMAT) void journalErrorConfirmingLargeMessage(@Cause Throwable e, Long messageID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222061, value = "Client connection failed, clearing up resources for session {0}", format = Message.Format.MESSAGE_FORMAT) void clientConnectionFailed(String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222062, value = "Cleared up resources for session {0}", format = Message.Format.MESSAGE_FORMAT) void clearingUpSession(String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222063, value = "Error processing IOCallback code = {0} message = {1}", format = Message.Format.MESSAGE_FORMAT) void errorProcessingIOCallback(Integer errorCode, String errorMessage); @LogMessage(level = Logger.Level.DEBUG) @Message(id = 222065, value = "Client is not being consistent on the request versioning. It just sent a version id={0} while it informed {1} previously", format = Message.Format.MESSAGE_FORMAT) void incompatibleVersionAfterConnect(int version, int clientVersion); @LogMessage(level = Logger.Level.WARN) @Message(id = 222066, value = "Reattach request from {0} failed as there is no confirmationWindowSize configured, which may be ok for your system", format = Message.Format.MESSAGE_FORMAT) void reattachRequestFailed(String remoteAddress); @LogMessage(level = Logger.Level.WARN) @Message(id = 222067, value = "Connection failure has been detected: {0} [code={1}]", format = Message.Format.MESSAGE_FORMAT) void connectionFailureDetected(String message, ActiveMQExceptionType type); @LogMessage(level = Logger.Level.WARN) @Message(id = 222069, value = "error cleaning up stomp connection", format = Message.Format.MESSAGE_FORMAT) void errorCleaningStompConn(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222070, value = "Stomp Transactional acknowledgement is not supported", format = Message.Format.MESSAGE_FORMAT) void stompTXAckNorSupported(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222071, value = "Interrupted while waiting for stomp heartbeat to die", format = Message.Format.MESSAGE_FORMAT) void errorOnStompHeartBeat(@Cause InterruptedException e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222072, value = "Timed out flushing channel on InVMConnection", format = Message.Format.MESSAGE_FORMAT) void timedOutFlushingInvmChannel(); @LogMessage(level = Logger.Level.WARN) @Message(id = 212074, value = "channel group did not completely close", format = Message.Format.MESSAGE_FORMAT) void nettyChannelGroupError(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222075, value = "{0} is still connected to {1}", format = Message.Format.MESSAGE_FORMAT) void nettyChannelStillOpen(Channel channel, SocketAddress remoteAddress); @LogMessage(level = Logger.Level.WARN) @Message(id = 222076, value = "channel group did not completely unbind", format = Message.Format.MESSAGE_FORMAT) void nettyChannelGroupBindError(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222077, value = "{0} is still bound to {1}", format = Message.Format.MESSAGE_FORMAT) void nettyChannelStillBound(Channel channel, SocketAddress remoteAddress); @LogMessage(level = Logger.Level.WARN) @Message(id = 222078, value = "Error instantiating remoting interceptor {0}", format = Message.Format.MESSAGE_FORMAT) void errorCreatingRemotingInterceptor(@Cause Exception e, String interceptorClass); @LogMessage(level = Logger.Level.WARN) @Message(id = 222079, value = "The following keys are invalid for configuring the acceptor: {0} the acceptor will not be started.", format = Message.Format.MESSAGE_FORMAT) void invalidAcceptorKeys(String s); @LogMessage(level = Logger.Level.WARN) @Message(id = 222080, value = "Error instantiating remoting acceptor {0}", format = Message.Format.MESSAGE_FORMAT) void errorCreatingAcceptor(@Cause Exception e, String factoryClassName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222081, value = "Timed out waiting for remoting thread pool to terminate", format = Message.Format.MESSAGE_FORMAT) void timeoutRemotingThreadPool(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222082, value = "error on connection failure check", format = Message.Format.MESSAGE_FORMAT) void errorOnFailureCheck(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222083, value = "The following keys are invalid for configuring the connector service: {0} the connector will not be started.", format = Message.Format.MESSAGE_FORMAT) void connectorKeysInvalid(String s); @LogMessage(level = Logger.Level.WARN) @Message(id = 222084, value = "The following keys are required for configuring the connector service: {0} the connector will not be started.", format = Message.Format.MESSAGE_FORMAT) void connectorKeysMissing(String s); @LogMessage(level = Logger.Level.WARN) @Message(id = 222085, value = "Packet {0} can not be processed by the ReplicationEndpoint", format = Message.Format.MESSAGE_FORMAT) void invalidPacketForReplication(Packet packet); @LogMessage(level = Logger.Level.WARN) @Message(id = 222086, value = "error handling packet {0} for replication", format = Message.Format.MESSAGE_FORMAT) void errorHandlingReplicationPacket(@Cause Exception e, Packet packet); @LogMessage(level = Logger.Level.WARN) @Message(id = 222087, value = "Replication Error while closing the page on backup", format = Message.Format.MESSAGE_FORMAT) void errorClosingPageOnReplication(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222088, value = "Journal comparison mismatch:\n{0}", format = Message.Format.MESSAGE_FORMAT) void journalcomparisonMismatch(String s); @LogMessage(level = Logger.Level.WARN) @Message(id = 222089, value = "Replication Error deleting large message ID = {0}", format = Message.Format.MESSAGE_FORMAT) void errorDeletingLargeMessage(@Cause Exception e, long messageId); @LogMessage(level = Logger.Level.WARN) @Message(id = 222090, value = "Replication Large MessageID {0} is not available on backup server. Ignoring replication message", format = Message.Format.MESSAGE_FORMAT) void largeMessageNotAvailable(long messageId); @LogMessage(level = Logger.Level.WARN) @Message(id = 222091, value = "The backup node has been shut-down, replication will now stop", format = Message.Format.MESSAGE_FORMAT) void replicationStopOnBackupShutdown(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222092, value = "Connection to the backup node failed, removing replication now", format = Message.Format.MESSAGE_FORMAT) void replicationStopOnBackupFail(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222093, value = "Timed out waiting to stop Bridge", format = Message.Format.MESSAGE_FORMAT) void timedOutWaitingToStopBridge(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222094, value = "Bridge unable to send message {0}, will try again once bridge reconnects", format = Message.Format.MESSAGE_FORMAT) void bridgeUnableToSendMessage(@Cause Exception e, MessageReference ref); @LogMessage(level = Logger.Level.WARN) @Message(id = 222095, value = "Connection failed with failedOver={0}", format = Message.Format.MESSAGE_FORMAT) void bridgeConnectionFailed(Boolean failedOver); @LogMessage(level = Logger.Level.WARN) @Message(id = 222096, value = "Error on querying binding on bridge {0}. Retrying in 100 milliseconds", format = Message.Format.MESSAGE_FORMAT) void errorQueryingBridge(@Cause Throwable t, SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222097, value = "Address {0} does not have any bindings, retry #({1})", format = Message.Format.MESSAGE_FORMAT) void errorQueryingBridge(SimpleString address, Integer retryCount); @LogMessage(level = Logger.Level.WARN) @Message(id = 222098, value = "Server is starting, retry to create the session for bridge {0}", format = Message.Format.MESSAGE_FORMAT) void errorStartingBridge(SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222099, value = "Bridge {0} is unable to connect to destination. It will be disabled.", format = Message.Format.MESSAGE_FORMAT) void errorConnectingBridge(@Cause Exception e, Bridge bridge); @LogMessage(level = Logger.Level.WARN) @Message(id = 222100, value = "ServerLocator was shutdown, can not retry on opening connection for bridge", format = Message.Format.MESSAGE_FORMAT) void bridgeLocatorShutdown(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222101, value = "Bridge {0} achieved {1} maxattempts={2} it will stop retrying to reconnect", format = Message.Format.MESSAGE_FORMAT) void bridgeAbortStart(SimpleString name, Integer retryCount, Integer reconnectAttempts); @LogMessage(level = Logger.Level.WARN) @Message(id = 222102, value = "Unexpected exception while trying to reconnect", format = Message.Format.MESSAGE_FORMAT) void errorReConnecting(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222103, value = "transaction with xid {0} timed out", format = Message.Format.MESSAGE_FORMAT) void timedOutXID(Xid xid); @LogMessage(level = Logger.Level.WARN) @Message(id = 222104, value = "IO Error completing the transaction, code = {0}, message = {1}", format = Message.Format.MESSAGE_FORMAT) void ioErrorOnTX(Integer errorCode, String errorMessage); @LogMessage(level = Logger.Level.WARN) @Message(id = 222105, value = "Could not finish context execution in 10 seconds", format = Message.Format.MESSAGE_FORMAT) void errorCompletingContext(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222106, value = "Replacing incomplete LargeMessage with ID={0}", format = Message.Format.MESSAGE_FORMAT) void replacingIncompleteLargeMessage(Long messageID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222107, value = "Cleared up resources for session {0}", format = Message.Format.MESSAGE_FORMAT) void clientConnectionFailedClearingSession(String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222108, value = "unable to send notification when broadcast group is stopped", format = Message.Format.MESSAGE_FORMAT) void broadcastGroupClosed(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222109, value = "Timed out waiting for write lock on consumer. Check the Thread dump", format = Message.Format.MESSAGE_FORMAT) void timeoutLockingConsumer(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222110, value = "no queue IDs defined!, originalMessage = {0}, copiedMessage = {1}, props={2}", format = Message.Format.MESSAGE_FORMAT) void noQueueIdDefined(org.apache.activemq.artemis.api.core.Message message, org.apache.activemq.artemis.api.core.Message messageCopy, SimpleString idsHeaderName); @LogMessage(level = Logger.Level.TRACE) @Message(id = 222111, value = "exception while invoking {0} on {1}", format = Message.Format.MESSAGE_FORMAT) void managementOperationError(@Cause Exception e, String op, String resourceName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222112, value = "exception while retrieving attribute {0} on {1}", format = Message.Format.MESSAGE_FORMAT) void managementAttributeError(@Cause Exception e, String att, String resourceName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222113, value = "On ManagementService stop, there are {0} unexpected registered MBeans: {1}", format = Message.Format.MESSAGE_FORMAT) void managementStopError(Integer size, List<String> unexpectedResourceNames); @LogMessage(level = Logger.Level.WARN) @Message(id = 222114, value = "Unable to delete group binding info {0}", format = Message.Format.MESSAGE_FORMAT) void unableToDeleteGroupBindings(@Cause Exception e, SimpleString groupId); @LogMessage(level = Logger.Level.WARN) @Message(id = 222115, value = "Error closing serverLocator={0}", format = Message.Format.MESSAGE_FORMAT) void errorClosingServerLocator(@Cause Exception e, ServerLocatorInternal clusterLocator); @LogMessage(level = Logger.Level.WARN) @Message(id = 222116, value = "unable to start broadcast group {0}", format = Message.Format.MESSAGE_FORMAT) void unableToStartBroadcastGroup(@Cause Exception e, String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222117, value = "unable to start cluster connection {0}", format = Message.Format.MESSAGE_FORMAT) void unableToStartClusterConnection(@Cause Exception e, SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222118, value = "unable to start Bridge {0}", format = Message.Format.MESSAGE_FORMAT) void unableToStartBridge(@Cause Exception e, SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222119, value = "No connector with name {0}. backup cannot be announced.", format = Message.Format.MESSAGE_FORMAT) void announceBackupNoConnector(String connectorName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222120, value = "no cluster connections defined, unable to announce backup", format = Message.Format.MESSAGE_FORMAT) void announceBackupNoClusterConnections(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222121, value = "Must specify a unique name for each bridge. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void bridgeNotUnique(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222122, value = "Must specify a queue name for each bridge. This one {0} will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void bridgeNoQueue(String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222123, value = "Forward address is not specified on bridge {0}. Will use original message address instead", format = Message.Format.MESSAGE_FORMAT) void bridgeNoForwardAddress(String bridgeName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222124, value = "There is already a bridge with name {0} deployed. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void bridgeAlreadyDeployed(String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222125, value = "No queue found with name {0} bridge {1} will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void bridgeQueueNotFound(String queueName, String bridgeName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222126, value = "No discovery group found with name {0} bridge will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void bridgeNoDiscoveryGroup(String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222127, value = "Must specify a unique name for each cluster connection. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void clusterConnectionNotUnique(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222128, value = "Must specify an address for each cluster connection. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void clusterConnectionNoForwardAddress(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222129, value = "No connector with name {0}. The cluster connection will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void clusterConnectionNoConnector(String connectorName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222130, value = "Cluster Configuration {0} already exists. The cluster connection will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void clusterConnectionAlreadyExists(String connectorName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222131, value = "No discovery group with name {0}. The cluster connection will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void clusterConnectionNoDiscoveryGroup(String discoveryGroupName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222132, value = "There is already a broadcast-group with name {0} deployed. This one will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void broadcastGroupAlreadyExists(String name); @LogMessage(level = Logger.Level.WARN) @Message( id = 222133, value = "There is no connector deployed with name {0}. The broadcast group with name {1} will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void broadcastGroupNoConnector(String connectorName, String bgName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222134, value = "No connector defined with name {0}. The bridge will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void noConnector(String name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222135, value = "Stopping Redistributor, Timed out waiting for tasks to complete", format = Message.Format.MESSAGE_FORMAT) void errorStoppingRedistributor(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222136, value = "IO Error during redistribution, errorCode = {0} message = {1}", format = Message.Format.MESSAGE_FORMAT) void ioErrorRedistributing(Integer errorCode, String errorMessage); @LogMessage(level = Logger.Level.WARN) @Message(id = 222137, value = "Unable to announce backup, retrying", format = Message.Format.MESSAGE_FORMAT) void errorAnnouncingBackup(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222138, value = "Local Member is not set at on ClusterConnection {0}", format = Message.Format.MESSAGE_FORMAT) void noLocalMemborOnClusterConnection(ClusterConnectionImpl clusterConnection); @LogMessage(level = Logger.Level.WARN) @Message(id = 222139, value = "{0}::Remote queue binding {1} has already been bound in the post office. Most likely cause for this is you have a loop in your cluster due to cluster max-hops being too large or you have multiple cluster connections to the same nodes using overlapping addresses", format = Message.Format.MESSAGE_FORMAT) void remoteQueueAlreadyBoundOnClusterConnection(Object messageFlowRecord, SimpleString clusterName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222141, value = "Node Manager can not open file {0}", format = Message.Format.MESSAGE_FORMAT) void nodeManagerCantOpenFile(@Cause Exception e, File file); @LogMessage(level = Logger.Level.WARN) @Message(id = 222142, value = "Error on resetting large message deliver - {0}", format = Message.Format.MESSAGE_FORMAT) void errorResttingLargeMessage(@Cause Throwable e, Object deliverer); @LogMessage(level = Logger.Level.WARN) @Message(id = 222143, value = "Timed out waiting for executor to complete", format = Message.Format.MESSAGE_FORMAT) void errorTransferringConsumer(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222144, value = "Queue could not finish waiting executors. Try increasing the thread pool size", format = Message.Format.MESSAGE_FORMAT) void errorFlushingExecutorsOnQueue(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222145, value = "Error expiring reference {0} 0n queue", format = Message.Format.MESSAGE_FORMAT) void errorExpiringReferencesOnQueue(@Cause Exception e, MessageReference ref); @LogMessage(level = Logger.Level.WARN) @Message(id = 222146, value = "Message has expired. No bindings for Expiry Address {0} so dropping it", format = Message.Format.MESSAGE_FORMAT) void errorExpiringReferencesNoBindings(SimpleString expiryAddress); @LogMessage(level = Logger.Level.WARN) @Message(id = 222147, value = "Messages are being expired on queue{0}. However there is no expiry queue configured, hence messages will be dropped.", format = Message.Format.MESSAGE_FORMAT) void errorExpiringReferencesNoQueue(SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222148, value = "Message {0} has exceeded max delivery attempts. No bindings for Dead Letter Address {1} so dropping it", format = Message.Format.MESSAGE_FORMAT) void messageExceededMaxDelivery(MessageReference ref, SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222149, value = "Message {0} has reached maximum delivery attempts, sending it to Dead Letter Address {1} from {2}", format = Message.Format.MESSAGE_FORMAT) void messageExceededMaxDeliverySendtoDLA(MessageReference ref, SimpleString name, SimpleString simpleString); @LogMessage(level = Logger.Level.WARN) @Message(id = 222150, value = "Message {0} has exceeded max delivery attempts. No Dead Letter Address configured for queue {1} so dropping it", format = Message.Format.MESSAGE_FORMAT) void messageExceededMaxDeliveryNoDLA(MessageReference ref, SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222151, value = "removing consumer which did not handle a message, consumer={0}, message={1}", format = Message.Format.MESSAGE_FORMAT) void removingBadConsumer(@Cause Throwable e, Consumer consumer, MessageReference reference); @LogMessage(level = Logger.Level.WARN) @Message(id = 222152, value = "Unable to decrement reference counting on queue", format = Message.Format.MESSAGE_FORMAT) void errorDecrementingRefCount(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222153, value = "Unable to remove message id = {0} please remove manually", format = Message.Format.MESSAGE_FORMAT) void errorRemovingMessage(@Cause Throwable e, Long messageID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222154, value = "Error checking DLQ", format = Message.Format.MESSAGE_FORMAT) void errorCheckingDLQ(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222155, value = "Failed to register as backup. Stopping the server.", format = Message.Format.MESSAGE_FORMAT) void errorRegisteringBackup(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222156, value = "Less than {0}%\n{1}\nYou are in danger of running out of RAM. Have you set paging parameters on your addresses? (See user manual \"Paging\" chapter)", format = Message.Format.MESSAGE_FORMAT) void memoryError(Integer memoryWarningThreshold, String info); @LogMessage(level = Logger.Level.WARN) @Message(id = 222157, value = "Error completing callback on replication manager", format = Message.Format.MESSAGE_FORMAT) void errorCompletingCallbackOnReplicationManager(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222158, value = "{0} activation thread did not finish.", format = Message.Format.MESSAGE_FORMAT) void activationDidntFinish(ActiveMQServer server); @LogMessage(level = Logger.Level.WARN) @Message(id = 222159, value = "unable to send notification when broadcast group is stopped", format = Message.Format.MESSAGE_FORMAT) void broadcastBridgeStoppedError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222160, value = "unable to send notification when broadcast group is stopped", format = Message.Format.MESSAGE_FORMAT) void notificationBridgeStoppedError(@Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222161, value = "Group Handler timed-out waiting for sendCondition", format = Message.Format.MESSAGE_FORMAT) void groupHandlerSendTimeout(); @LogMessage(level = Logger.Level.INFO) @Message(id = 222162, value = "Moving data directory {0} to {1}", format = Message.Format.MESSAGE_FORMAT) void backupMovingDataAway(String oldPath, String newPath); @LogMessage(level = Logger.Level.WARN) @Message(id = 222163, value = "Server is being completely stopped, since this was a replicated backup there may be journal files that need cleaning up. The Apache ActiveMQ Artemis broker will have to be manually restarted.", format = Message.Format.MESSAGE_FORMAT) void stopReplicatedBackupAfterFailback(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222164, value = "Error when trying to start replication {0}", format = Message.Format.MESSAGE_FORMAT) void errorStartingReplication(BackupReplicationStartFailedMessage.BackupRegistrationProblem problem); @LogMessage(level = Logger.Level.WARN) @Message(id = 222165, value = "No Dead Letter Address configured for queue {0} in AddressSettings", format = Message.Format.MESSAGE_FORMAT) void AddressSettingsNoDLA(SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222166, value = "No Expiry Address configured for queue {0} in AddressSettings", format = Message.Format.MESSAGE_FORMAT) void AddressSettingsNoExpiryAddress(SimpleString name); @LogMessage(level = Logger.Level.WARN) @Message(id = 222167, value = "Group Binding not available so deleting {0} groups from {1}, groups will be bound to another node", format = Message.Format.MESSAGE_FORMAT) void groupingQueueRemoved(int size, SimpleString clusterName); @SuppressWarnings("deprecation") @LogMessage(level = Logger.Level.WARN) @Message(id = 222168, value = "The ''" + TransportConstants.PROTOCOL_PROP_NAME + "'' property is deprecated. If you want this Acceptor to support multiple protocols, use the ''" + TransportConstants.PROTOCOLS_PROP_NAME + "'' property, e.g. with value ''CORE,AMQP,STOMP''", format = Message.Format.MESSAGE_FORMAT) void warnDeprecatedProtocol(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222169, value = "You have old legacy clients connected to the queue {0} and we can''t disconnect them, these clients may just hang", format = Message.Format.MESSAGE_FORMAT) void warnDisconnectOldClient(String queueName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222170, value = "Bridge {0} forwarding address {1} has confirmation-window-size ({2}) greater than address'' max-size-bytes'' ({3})", format = Message.Format.MESSAGE_FORMAT) void bridgeConfirmationWindowTooSmall(String bridgeName, String address, int windowConfirmation, long maxSizeBytes); @LogMessage(level = Logger.Level.WARN) @Message(id = 222171, value = "Bridge {0} forwarding address {1} could not be resolved on address-settings configuration", format = Message.Format.MESSAGE_FORMAT) void bridgeCantFindAddressConfig(String bridgeName, String forwardingAddress); @LogMessage(level = Logger.Level.WARN) @Message(id = 222172, value = "Queue {0} was busy for more than {1} milliseconds. There are possibly consumers hanging on a network operation", format = Message.Format.MESSAGE_FORMAT) void queueBusy(String name, long timeout); @LogMessage(level = Logger.Level.WARN) @Message(id = 222173, value = "Queue {0} is duplicated during reload. This queue will be renamed as {1}", format = Message.Format.MESSAGE_FORMAT) void queueDuplicatedRenaming(String name, String newName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222174, value = "Queue {0}, on address={1}, is taking too long to flush deliveries. Watch out for frozen clients.", format = Message.Format.MESSAGE_FORMAT) void timeoutFlushInTransit(String queueName, String addressName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222175, value = "Bridge {0} could not find configured connectors", format = Message.Format.MESSAGE_FORMAT) void bridgeCantFindConnectors(String bridgeName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222176, value = "A session that was already doing XA work on {0} is replacing the xid by {1} " + ". This was most likely caused from a previous communication timeout", format = Message.Format.MESSAGE_FORMAT) void xidReplacedOnXStart(String xidOriginalToString, String xidReplacedToString); @LogMessage(level = Logger.Level.WARN) @Message(id = 222177, value = "Wrong configuration for role, {0} is not a valid permission", format = Message.Format.MESSAGE_FORMAT) void rolePermissionConfigurationError(String permission); @LogMessage(level = Logger.Level.WARN) @Message(id = 222178, value = "Error during recovery of page counters", format = Message.Format.MESSAGE_FORMAT) void errorRecoveringPageCounter(@Cause Throwable error); @LogMessage(level = Logger.Level.WARN) @Message(id = 222181, value = "Unable to scaleDown messages", format = Message.Format.MESSAGE_FORMAT) void failedToScaleDown(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222182, value = "Missing cluster-configuration for scale-down-clustername {0}", format = Message.Format.MESSAGE_FORMAT) void missingClusterConfigForScaleDown(String scaleDownCluster); @LogMessage(level = Logger.Level.WARN) @Message(id = 222183, value = "Blocking message production on address ''{0}''; size is currently: {1} bytes; max-size-bytes on address: {2}, global-max-size is {3}", format = Message.Format.MESSAGE_FORMAT) void blockingMessageProduction(SimpleString addressName, long currentSize, long maxSize, long globalMaxSize); @LogMessage(level = Logger.Level.WARN) @Message(id = 222184, value = "Unable to recover group bindings in SCALE_DOWN mode, only FULL backup server can do this", format = Message.Format.MESSAGE_FORMAT) void groupBindingsOnRecovery(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222185, value = "no cluster connection for specified replication cluster", format = Message.Format.MESSAGE_FORMAT) void noClusterConnectionForReplicationCluster(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222186, value = "unable to authorise cluster control", format = Message.Format.MESSAGE_FORMAT) void clusterControlAuthfailure(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222187, value = "Failed to activate replicated backup", format = Message.Format.MESSAGE_FORMAT) void activateReplicatedBackupFailed(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222188, value = "Unable to find target queue for node {0}", format = Message.Format.MESSAGE_FORMAT) void unableToFindTargetQueue(String targetNodeID); @LogMessage(level = Logger.Level.WARN) @Message(id = 222189, value = "Failed to activate shared store slave", format = Message.Format.MESSAGE_FORMAT) void activateSharedStoreSlaveFailed(@Cause Throwable e); @LogMessage(level = Logger.Level.WARN) @Message(id = 222191, value = "Could not find any configured role for user {0}.", format = Message.Format.MESSAGE_FORMAT) void cannotFindRoleForUser(String user); @LogMessage(level = Logger.Level.WARN) @Message(id = 222192, value = "Could not delete: {0}", format = Message.Format.MESSAGE_FORMAT) void couldNotDeleteTempFile(String tempFileName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222193, value = "Memory Limit reached. Producer ({0}) stopped to prevent flooding {1} (blocking for {2}s). See http://activemq.apache.org/producer-flow-control.html for more info.", format = Message.Format.MESSAGE_FORMAT) void memoryLimitReached(String producerID, String address, long duration); @LogMessage(level = Logger.Level.WARN) @Message(id = 222194, value = "PageCursorInfo == null on address {0}, pos = {1}, queue = {2}.", format = Message.Format.MESSAGE_FORMAT) void nullPageCursorInfo(String address, String position, long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 222195, value = "Large message {0} wasn''t found when dealing with add pending large message", format = Message.Format.MESSAGE_FORMAT) void largeMessageNotFound(long id); @LogMessage(level = Logger.Level.WARN) @Message(id = 222196, value = "Could not find binding with id={0} on routeFromCluster for message={1} binding = {2}", format = Message.Format.MESSAGE_FORMAT) void bindingNotFound(long id, String message, String binding); @LogMessage(level = Logger.Level.WARN) @Message(id = 222197, value = "Internal error! Delivery logic has identified a non delivery and still handled a consumer!", format = Message.Format.MESSAGE_FORMAT) void nonDeliveryHandled(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222198, value = "Could not flush ClusterManager executor ({0}) in 10 seconds, verify your thread pool size", format = Message.Format.MESSAGE_FORMAT) void couldNotFlushClusterManager(String manager); @LogMessage(level = Logger.Level.WARN) @Message(id = 222199, value = "Thread dump: {0}", format = Message.Format.MESSAGE_FORMAT) void threadDump(String manager); @LogMessage(level = Logger.Level.WARN) @Message(id = 222200, value = "Could not finish executor on {0}", format = Message.Format.MESSAGE_FORMAT) void couldNotFinishExecutor(String clusterConnection); @LogMessage(level = Logger.Level.WARN) @Message(id = 222201, value = "Timed out waiting for activation to exit", format = Message.Format.MESSAGE_FORMAT) void activationTimeout(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222202, value = "{0}: <{1}> should not be set to the same value as <{2}>. " + "If a system is under high load, or there is a minor network delay, " + "there is a high probability of a cluster split/failure due to connection timeout.", format = Message.Format.MESSAGE_FORMAT) void connectionTTLEqualsCheckPeriod(String connectionName, String ttl, String checkPeriod); @LogMessage(level = Logger.Level.WARN) @Message(id = 222203, value = "Classpath lacks a protocol-manager for protocol {0}, Protocol being ignored on acceptor {1}", format = Message.Format.MESSAGE_FORMAT) void noProtocolManagerFound(String protocol, String host); @LogMessage(level = Logger.Level.WARN) @Message(id = 222204, value = "Duplicated Acceptor {0} with parameters {1} classFactory={2} duplicated on the configuration", format = Message.Format.MESSAGE_FORMAT) void duplicatedAcceptor(String name, String parameters, String classFactory); @LogMessage(level = Logger.Level.WARN) @Message(id = 222205, value = "OutOfMemoryError possible! There are currently {0} addresses with a total max-size-bytes of {1} bytes, but the maximum memory available is {2} bytes.", format = Message.Format.MESSAGE_FORMAT) void potentialOOME(long addressCount, long totalMaxSizeBytes, long maxMemory); @LogMessage(level = Logger.Level.WARN) @Message(id = 222206, value = "Connection limit of {0} reached. Refusing connection from {1}.", format = Message.Format.MESSAGE_FORMAT) void connectionLimitReached(long connectionsAllowed, String address); @LogMessage(level = Logger.Level.WARN) @Message(id = 222207, value = "The backup server is not responding promptly introducing latency beyond the limit. Replication server being disconnected now.", format = Message.Format.MESSAGE_FORMAT) void slowReplicationResponse(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222208, value = "SSL handshake failed for client from {0}: {1}.", format = Message.Format.MESSAGE_FORMAT) void sslHandshakeFailed(String clientAddress, String cause); @LogMessage(level = Logger.Level.WARN) @Message(id = 222209, value = "Could not contact group handler coordinator after 10 retries, message being routed without grouping information", format = Message.Format.MESSAGE_FORMAT) void impossibleToRouteGrouped(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222210, value = "Storage usage is beyond max-disk-usage. System will start blocking producers.", format = Message.Format.MESSAGE_FORMAT) void diskBeyondCapacity(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222211, value = "Storage is back to stable now, under max-disk-usage.", format = Message.Format.MESSAGE_FORMAT) void diskCapacityRestored(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222212, value = "Disk Full! Blocking message production on address ''{0}''. Clients will report blocked.", format = Message.Format.MESSAGE_FORMAT) void blockingDiskFull(SimpleString addressName); @LogMessage(level = Logger.Level.WARN) @Message(id = 222213, value = "There was an issue on the network, server is isolated!", format = Message.Format.MESSAGE_FORMAT) void serverIsolatedOnNetwork(); @LogMessage(level = Logger.Level.WARN) @Message(id = 222214, value = "Destination {1} has an inconsistent and negative address size={0}.", format = Message.Format.MESSAGE_FORMAT) void negativeAddressSize(long size, String destination); @LogMessage(level = Logger.Level.WARN) @Message(id = 222215, value = "Global Address Size has negative and inconsistent value as {0}", format = Message.Format.MESSAGE_FORMAT) void negativeGlobalAddressSize(long size); @LogMessage(level = Logger.Level.WARN) @Message(id = 222216, value = "Security problem while creating session: {0}", format = Message.Format.MESSAGE_FORMAT) void securityProblemWhileCreatingSession(String message); @LogMessage(level = Logger.Level.WARN) @Message(id = 222217, value = "Cannot find connector-ref {0}. The cluster-connection {1} will not be deployed.", format = Message.Format.MESSAGE_FORMAT) void connectorRefNotFound(String connectorRef, String clusterConnection); @LogMessage(level = Logger.Level.WARN) @Message(id = 222218, value = "Server disconnecting: {0}", format = Message.Format.MESSAGE_FORMAT) void disconnectCritical(String reason, @Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224000, value = "Failure in initialisation", format = Message.Format.MESSAGE_FORMAT) void initializationError(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224001, value = "Error deploying URI {0}", format = Message.Format.MESSAGE_FORMAT) void errorDeployingURI(@Cause Throwable e, URI uri); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224002, value = "Error deploying URI", format = Message.Format.MESSAGE_FORMAT) void errorDeployingURI(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224003, value = "Error undeploying URI {0}", format = Message.Format.MESSAGE_FORMAT) void errorUnDeployingURI(@Cause Throwable e, URI a); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224005, value = "Unable to deploy node {0}", format = Message.Format.MESSAGE_FORMAT) void unableToDeployNode(@Cause Exception e, Node node); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224006, value = "Invalid filter: {0}", format = Message.Format.MESSAGE_FORMAT) void invalidFilter(SimpleString filter, @Cause Throwable cause); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224007, value = "page subscription = {0} error={1}", format = Message.Format.MESSAGE_FORMAT) void pageSubscriptionError(IOCallback IOCallback, String error); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224008, value = "Failed to store id", format = Message.Format.MESSAGE_FORMAT) void batchingIdError(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224009, value = "Cannot find message {0}", format = Message.Format.MESSAGE_FORMAT) void cannotFindMessage(Long id); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224010, value = "Cannot find queue messages for queueID={0} on ack for messageID={1}", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueue(Long queue, Long id); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224011, value = "Cannot find queue messages {0} for message {1} while processing scheduled messages", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindQueueScheduled(Long queue, Long id); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224012, value = "error releasing resources", format = Message.Format.MESSAGE_FORMAT) void largeMessageErrorReleasingResources(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224013, value = "failed to expire messages for queue", format = Message.Format.MESSAGE_FORMAT) void errorExpiringMessages(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224014, value = "Failed to close session", format = Message.Format.MESSAGE_FORMAT) void errorClosingSession(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224015, value = "Caught XA exception", format = Message.Format.MESSAGE_FORMAT) void caughtXaException(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224016, value = "Caught exception", format = Message.Format.MESSAGE_FORMAT) void caughtException(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224017, value = "Invalid packet {0}", format = Message.Format.MESSAGE_FORMAT) void invalidPacket(Packet packet); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224018, value = "Failed to create session", format = Message.Format.MESSAGE_FORMAT) void failedToCreateSession(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224019, value = "Failed to reattach session", format = Message.Format.MESSAGE_FORMAT) void failedToReattachSession(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224020, value = "Failed to handle create queue", format = Message.Format.MESSAGE_FORMAT) void failedToHandleCreateQueue(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224021, value = "Failed to decode packet", format = Message.Format.MESSAGE_FORMAT) void errorDecodingPacket(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224022, value = "Failed to execute failure listener", format = Message.Format.MESSAGE_FORMAT) void errorCallingFailureListener(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224024, value = "Stomp Error, tx already exist! {0}", format = Message.Format.MESSAGE_FORMAT) void stompErrorTXExists(String txID); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224027, value = "Failed to write to handler on invm connector {0}", format = Message.Format.MESSAGE_FORMAT) void errorWritingToInvmConnector(@Cause Exception e, Runnable runnable); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224028, value = "Failed to stop acceptor {0}", format = Message.Format.MESSAGE_FORMAT) void errorStoppingAcceptor(String name); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224029, value = "large message sync: largeMessage instance is incompatible with it, ignoring data", format = Message.Format.MESSAGE_FORMAT) void largeMessageIncompatible(); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224030, value = "Could not cancel reference {0}", format = Message.Format.MESSAGE_FORMAT) void errorCancellingRefOnBridge(@Cause Exception e, MessageReference ref2); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224031, value = "-------------------------------Stomp begin tx: {0}", format = Message.Format.MESSAGE_FORMAT) void stompBeginTX(String txID); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224032, value = "Failed to pause bridge", format = Message.Format.MESSAGE_FORMAT) void errorPausingBridge(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224033, value = "Failed to broadcast connector configs", format = Message.Format.MESSAGE_FORMAT) void errorBroadcastingConnectorConfigs(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224034, value = "Failed to close consumer", format = Message.Format.MESSAGE_FORMAT) void errorClosingConsumer(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224035, value = "Failed to close cluster connection flow record", format = Message.Format.MESSAGE_FORMAT) void errorClosingFlowRecord(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224036, value = "Failed to update cluster connection topology", format = Message.Format.MESSAGE_FORMAT) void errorUpdatingTopology(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224037, value = "cluster connection Failed to handle message", format = Message.Format.MESSAGE_FORMAT) void errorHandlingMessage(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224038, value = "Failed to ack old reference", format = Message.Format.MESSAGE_FORMAT) void errorAckingOldReference(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224039, value = "Failed to expire message reference", format = Message.Format.MESSAGE_FORMAT) void errorExpiringRef(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224040, value = "Failed to remove consumer", format = Message.Format.MESSAGE_FORMAT) void errorRemovingConsumer(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224041, value = "Failed to deliver", format = Message.Format.MESSAGE_FORMAT) void errorDelivering(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224042, value = "Error while restarting the backup server: {0}", format = Message.Format.MESSAGE_FORMAT) void errorRestartingBackupServer(@Cause Exception e, ActiveMQServer backup); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224043, value = "Failed to send forced delivery message", format = Message.Format.MESSAGE_FORMAT) void errorSendingForcedDelivery(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224044, value = "error acknowledging message", format = Message.Format.MESSAGE_FORMAT) void errorAckingMessage(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224045, value = "Failed to run large message deliverer", format = Message.Format.MESSAGE_FORMAT) void errorRunningLargeMessageDeliverer(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224046, value = "Exception while browser handled from {0}", format = Message.Format.MESSAGE_FORMAT) void errorBrowserHandlingMessage(@Cause Exception e, MessageReference current); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224047, value = "Failed to delete large message file", format = Message.Format.MESSAGE_FORMAT) void errorDeletingLargeMessageFile(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224048, value = "Failed to remove temporary queue {0}", format = Message.Format.MESSAGE_FORMAT) void errorRemovingTempQueue(@Cause Exception e, SimpleString bindingName); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224049, value = "Cannot find consumer with id {0}", format = Message.Format.MESSAGE_FORMAT) void cannotFindConsumer(long consumerID); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224050, value = "Failed to close connection {0}", format = Message.Format.MESSAGE_FORMAT) void errorClosingConnection(ServerSessionImpl serverSession); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224051, value = "Failed to call notification listener", format = Message.Format.MESSAGE_FORMAT) void errorCallingNotifListener(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224052, value = "Unable to call Hierarchical Repository Change Listener", format = Message.Format.MESSAGE_FORMAT) void errorCallingRepoListener(@Cause Throwable e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224053, value = "failed to timeout transaction, xid:{0}", format = Message.Format.MESSAGE_FORMAT) void errorTimingOutTX(@Cause Exception e, Xid xid); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224054, value = "exception while stopping the replication manager", format = Message.Format.MESSAGE_FORMAT) void errorStoppingReplicationManager(@Cause Throwable t); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224055, value = "Bridge Failed to ack", format = Message.Format.MESSAGE_FORMAT) void bridgeFailedToAck(@Cause Throwable t); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224056, value = "Live server will not fail-back automatically", format = Message.Format.MESSAGE_FORMAT) void autoFailBackDenied(); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224057, value = "Backup server that requested fail-back was not announced. Server will not stop for fail-back.", format = Message.Format.MESSAGE_FORMAT) void failbackMissedBackupAnnouncement(); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224058, value = "Stopping ClusterManager. As it failed to authenticate with the cluster: {0}", format = Message.Format.MESSAGE_FORMAT) void clusterManagerAuthenticationError(String msg); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224059, value = "Invalid cipher suite specified. Supported cipher suites are: {0}", format = Message.Format.MESSAGE_FORMAT) void invalidCipherSuite(String validSuites); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224060, value = "Invalid protocol specified. Supported protocols are: {0}", format = Message.Format.MESSAGE_FORMAT) void invalidProtocol(String validProtocols); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224061, value = "Setting both <{0}> and <ha-policy> is invalid. Please use <ha-policy> exclusively as <{0}> is deprecated. Ignoring <{0}> value.", format = Message.Format.MESSAGE_FORMAT) void incompatibleWithHAPolicy(String parameter); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224062, value = "Failed to send SLOW_CONSUMER notification: {0}", format = Message.Format.MESSAGE_FORMAT) void failedToSendSlowConsumerNotification(Notification notification, @Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224063, value = "Failed to close consumer connections for address {0}", format = Message.Format.MESSAGE_FORMAT) void failedToCloseConsumerConnectionsForAddress(String address, @Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224064, value = "Setting <{0}> is invalid with this HA Policy Configuration. Please use <ha-policy> exclusively or remove. Ignoring <{0}> value.", format = Message.Format.MESSAGE_FORMAT) void incompatibleWithHAPolicyChosen(String parameter); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224065, value = "Failed to remove auto-created queue {0}", format = Message.Format.MESSAGE_FORMAT) void errorRemovingAutoCreatedQueue(@Cause Exception e, SimpleString bindingName); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224066, value = "Error opening context for LDAP", format = Message.Format.MESSAGE_FORMAT) void errorOpeningContextForLDAP(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224067, value = "Error populating security roles from LDAP", format = Message.Format.MESSAGE_FORMAT) void errorPopulatingSecurityRolesFromLDAP(@Cause Exception e); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224068, value = "Unable to stop component: {0}", format = Message.Format.MESSAGE_FORMAT) void errorStoppingComponent(@Cause Throwable t, String componentClassName); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224069, value = "Change detected in broker configuration file, but reload failed", format = Message.Format.MESSAGE_FORMAT) void configurationReloadFailed(@Cause Throwable t); @LogMessage(level = Logger.Level.WARN) @Message(id = 224072, value = "Message Counter Sample Period too short: {0}", format = Message.Format.MESSAGE_FORMAT) void invalidMessageCounterPeriod(long value); @LogMessage(level = Logger.Level.INFO) @Message(id = 224073, value = "Using MAPPED Journal", format = Message.Format.MESSAGE_FORMAT) void journalUseMAPPED(); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224074, value = "Failed to purge queue {0} on no consumers", format = Message.Format.MESSAGE_FORMAT) void failedToPurgeQueue(@Cause Exception e, SimpleString bindingName); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224075, value = "Cannot find pageTX id = {0}", format = Message.Format.MESSAGE_FORMAT) void journalCannotFindPageTX(Long id); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224079, value = "The process for the virtual machine will be killed, as component {0} is not responsive", format = Message.Format.MESSAGE_FORMAT) void criticalSystemHalt(Object component); @LogMessage(level = Logger.Level.ERROR) @Message(id = 224080, value = "The server process will now be stopped, as component {0} is not responsive", format = Message.Format.MESSAGE_FORMAT) void criticalSystemShutdown(Object component); @LogMessage(level = Logger.Level.WARN) @Message(id = 224081, value = "The component {0} is not responsive", format = Message.Format.MESSAGE_FORMAT) void criticalSystemLog(Object component); @LogMessage(level = Logger.Level.INFO) @Message(id = 224076, value = "UnDeploying address {0}", format = Message.Format.MESSAGE_FORMAT) void undeployAddress(SimpleString addressName); @LogMessage(level = Logger.Level.INFO) @Message(id = 224077, value = "UnDeploying queue {0}", format = Message.Format.MESSAGE_FORMAT) void undeployQueue(SimpleString queueName); @LogMessage(level = Logger.Level.WARN) @Message(id = 224078, value = "The size of duplicate cache detection (<id_cache-size/>) appears to be too large {0}. It should be no greater than the number of messages that can be squeezed into conformation buffer (<confirmation-window-size/>) {1}.", format = Message.Format.MESSAGE_FORMAT) void duplicateCacheSizeWarning(int idCacheSize, int confirmationWindowSize); }
apache-2.0
deephacks/confit
core/src/main/java/org/deephacks/confit/internal/core/property/typesafe/impl/AbstractConfigValue.java
13671
/** * Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com> */ package org.deephacks.confit.internal.core.property.typesafe.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.deephacks.confit.internal.core.property.typesafe.ConfigMergeable; import org.deephacks.confit.internal.core.property.typesafe.ConfigRenderOptions; import org.deephacks.confit.internal.core.property.typesafe.ConfigException; import org.deephacks.confit.internal.core.property.typesafe.ConfigObject; import org.deephacks.confit.internal.core.property.typesafe.ConfigOrigin; import org.deephacks.confit.internal.core.property.typesafe.ConfigValue; /** * * Trying very hard to avoid a parent reference in typesafe values; when you have * a tree like this, the availability of parent() tends to result in a lot of * improperly-factored and non-modular code. Please don't add parent(). * */ abstract class AbstractConfigValue implements ConfigValue, MergeableValue { final private SimpleConfigOrigin origin; AbstractConfigValue(ConfigOrigin origin) { this.origin = (SimpleConfigOrigin) origin; } @Override public SimpleConfigOrigin origin() { return this.origin; } /** * This exception means that a value is inherently not resolveable, at the * moment the only known cause is a cycle of substitutions. This is a * checked exception since it's internal to the library and we want to be * sure we handle it before passing it out to public API. This is only * supposed to be thrown by the target of a cyclic reference and it's * supposed to be caught by the ConfigReference looking up that reference, * so it should be impossible for an outermost resolve() to throw this. * * Contrast with ConfigException.NotResolved which just means nobody called * resolve(). */ static class NotPossibleToResolve extends Exception { private static final long serialVersionUID = 1L; final private String traceString; NotPossibleToResolve(ResolveContext context) { super("was not possible to resolve"); this.traceString = context.traceString(); } String traceString() { return traceString; } } /** * Called only by ResolveContext.resolve(). * * @param context * state of the current resolve * @return a new value if there were changes, or this if no changes */ AbstractConfigValue resolveSubstitutions(ResolveContext context) throws NotPossibleToResolve { return this; } ResolveStatus resolveStatus() { return ResolveStatus.RESOLVED; } /** * This is used when including one file in another; the included file is * relativized to the path it's included into in the parent file. The point * is that if you include a file at foo.bar in the parent, and the included * file as a substitution ${a.b.c}, the included substitution now needs to * be ${foo.bar.a.b.c} because we resolve substitutions globally only after * parsing everything. * * @param prefix * @return value relativized to the given path or the same value if nothing * to do */ AbstractConfigValue relativized(Path prefix) { return this; } protected interface Modifier { // keyOrNull is null for non-objects AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v) throws Exception; } protected abstract class NoExceptionsModifier implements Modifier { @Override public final AbstractConfigValue modifyChildMayThrow(String keyOrNull, AbstractConfigValue v) throws Exception { try { return modifyChild(keyOrNull, v); } catch (RuntimeException e) { throw e; } catch(Exception e) { throw new ConfigException.BugOrBroken("Unexpected exception", e); } } abstract AbstractConfigValue modifyChild(String keyOrNull, AbstractConfigValue v); } @Override public AbstractConfigValue toFallbackValue() { return this; } protected abstract AbstractConfigValue newCopy(ConfigOrigin origin); // this is virtualized rather than a field because only some subclasses // really need to store the boolean, and they may be able to pack it // with another boolean to save space. protected boolean ignoresFallbacks() { // if we are not resolved, then somewhere in this value there's // a substitution that may need to look at the fallbacks. return resolveStatus() == ResolveStatus.RESOLVED; } protected AbstractConfigValue withFallbacksIgnored() { if (ignoresFallbacks()) return this; else throw new ConfigException.BugOrBroken( "value class doesn't implement forced fallback-ignoring " + this); } // the withFallback() implementation is supposed to avoid calling // mergedWith* if we're ignoring fallbacks. protected final void requireNotIgnoringFallbacks() { if (ignoresFallbacks()) throw new ConfigException.BugOrBroken( "method should not have been called with ignoresFallbacks=true " + getClass().getSimpleName()); } protected AbstractConfigValue constructDelayedMerge(ConfigOrigin origin, List<AbstractConfigValue> stack) { return new ConfigDelayedMerge(origin, stack); } protected final AbstractConfigValue mergedWithTheUnmergeable( Collection<AbstractConfigValue> stack, Unmergeable fallback) { requireNotIgnoringFallbacks(); // if we turn out to be an object, and the fallback also does, // then a merge may be required; delay until we resolve. List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>(); newStack.addAll(stack); newStack.addAll(fallback.unmergedValues()); return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack); } private final AbstractConfigValue delayMerge(Collection<AbstractConfigValue> stack, AbstractConfigValue fallback) { // if we turn out to be an object, and the fallback also does, // then a merge may be required. // if we contain a substitution, resolving it may need to look // back to the fallback. List<AbstractConfigValue> newStack = new ArrayList<AbstractConfigValue>(); newStack.addAll(stack); newStack.add(fallback); return constructDelayedMerge(AbstractConfigObject.mergeOrigins(newStack), newStack); } protected final AbstractConfigValue mergedWithObject(Collection<AbstractConfigValue> stack, AbstractConfigObject fallback) { requireNotIgnoringFallbacks(); if (this instanceof AbstractConfigObject) throw new ConfigException.BugOrBroken("Objects must reimplement mergedWithObject"); return mergedWithNonObject(stack, fallback); } protected final AbstractConfigValue mergedWithNonObject(Collection<AbstractConfigValue> stack, AbstractConfigValue fallback) { requireNotIgnoringFallbacks(); if (resolveStatus() == ResolveStatus.RESOLVED) { // falling back to a non-object doesn't merge anything, and also // prohibits merging any objects that we fall back to later. // so we have to switch to ignoresFallbacks mode. return withFallbacksIgnored(); } else { // if unresolved, we may have to look back to fallbacks as part of // the resolution process, so always delay return delayMerge(stack, fallback); } } protected AbstractConfigValue mergedWithTheUnmergeable(Unmergeable fallback) { requireNotIgnoringFallbacks(); return mergedWithTheUnmergeable(Collections.singletonList(this), fallback); } protected AbstractConfigValue mergedWithObject(AbstractConfigObject fallback) { requireNotIgnoringFallbacks(); return mergedWithObject(Collections.singletonList(this), fallback); } protected AbstractConfigValue mergedWithNonObject(AbstractConfigValue fallback) { requireNotIgnoringFallbacks(); return mergedWithNonObject(Collections.singletonList(this), fallback); } public AbstractConfigValue withOrigin(ConfigOrigin origin) { if (this.origin == origin) return this; else return newCopy(origin); } // this is only overridden to change the return type @Override public AbstractConfigValue withFallback(ConfigMergeable mergeable) { if (ignoresFallbacks()) { return this; } else { ConfigValue other = ((MergeableValue) mergeable).toFallbackValue(); if (other instanceof Unmergeable) { return mergedWithTheUnmergeable((Unmergeable) other); } else if (other instanceof AbstractConfigObject) { return mergedWithObject((AbstractConfigObject) other); } else { return mergedWithNonObject((AbstractConfigValue) other); } } } protected boolean canEqual(Object other) { return other instanceof ConfigValue; } @Override public boolean equals(Object other) { // note that "origin" is deliberately NOT part of equality if (other instanceof ConfigValue) { return canEqual(other) && (this.valueType() == ((ConfigValue) other).valueType()) && ConfigImplUtil.equalsHandlingNull(this.unwrapped(), ((ConfigValue) other).unwrapped()); } else { return false; } } @Override public int hashCode() { // note that "origin" is deliberately NOT part of equality Object o = this.unwrapped(); if (o == null) return 0; else return o.hashCode(); } @Override public final String toString() { StringBuilder sb = new StringBuilder(); render(sb, 0, null /* atKey */, ConfigRenderOptions.concise()); return getClass().getSimpleName() + "(" + sb.toString() + ")"; } protected static void indent(StringBuilder sb, int indent, ConfigRenderOptions options) { if (options.getFormatted()) { int remaining = indent; while (remaining > 0) { sb.append(" "); --remaining; } } } protected void render(StringBuilder sb, int indent, String atKey, ConfigRenderOptions options) { if (atKey != null) { String renderedKey; if (options.getJson()) renderedKey = ConfigImplUtil.renderJsonString(atKey); else renderedKey = ConfigImplUtil.renderStringUnquotedIfPossible(atKey); sb.append(renderedKey); if (options.getJson()) { if (options.getFormatted()) sb.append(" : "); else sb.append(":"); } else { // in non-JSON we can omit the colon or equals before an object if (this instanceof ConfigObject) { if (options.getFormatted()) sb.append(' '); } else { sb.append("="); } } } render(sb, indent, options); } protected void render(StringBuilder sb, int indent, ConfigRenderOptions options) { Object u = unwrapped(); sb.append(u.toString()); } @Override public final String render() { return render(ConfigRenderOptions.defaults()); } @Override public final String render(ConfigRenderOptions options) { StringBuilder sb = new StringBuilder(); render(sb, 0, null, options); return sb.toString(); } // toString() is a debugging-oriented string but this is defined // to create a string that would parse back to the value in JSON. // It only works for primitive values (that would be a single token) // which are auto-converted to strings when concatenating with // other strings or by the DefaultTransformer. String transformToString() { return null; } SimpleConfig atKey(ConfigOrigin origin, String key) { Map<String, AbstractConfigValue> m = Collections.singletonMap(key, this); return (new SimpleConfigObject(origin, m)).toConfig(); } @Override public SimpleConfig atKey(String key) { return atKey(SimpleConfigOrigin.newSimple("atKey(" + key + ")"), key); } SimpleConfig atPath(ConfigOrigin origin, Path path) { Path parent = path.parent(); SimpleConfig result = atKey(origin, path.last()); while (parent != null) { String key = parent.last(); result = result.atKey(origin, key); parent = parent.parent(); } return result; } @Override public SimpleConfig atPath(String pathExpression) { SimpleConfigOrigin origin = SimpleConfigOrigin.newSimple("atPath(" + pathExpression + ")"); return atPath(origin, Path.newPath(pathExpression)); } }
apache-2.0
far-edge/EdgeInfrastructure
Clients/dataRoutingClient/src/main/java/eu/sensap/farEdge/dataRoutingClient/registry/RegistryClient.java
10728
/*** *Sensap contribution * @author George * */ package eu.sensap.farEdge.dataRoutingClient.registry; import java.io.IOException; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import eu.faredge.edgeInfrastructure.registry.messages.RegistrationResult; import eu.faredge.edgeInfrastructure.registry.messages.RegistrationResultStatusEnum; import eu.faredge.edgeInfrastructure.registry.models.dsm.DSM; //import eu.faredge.edgeInfrastructure.registry.models.DataSourceManifest; import eu.sensap.farEdge.dataRoutingClient.interfaces.DeviceRegisterInterface; import eu.sensap.farEdge.dataRoutingClient.models.Credentials; //import eu.sensap.farEdge.dataRoutingClient.models.RegistrationResult; /*** * This class supports the basic registry operations * There are three operations: * 1. Registers a device with a specific UUID, Credentials, and Configuration Environments * 2. Unregisters e registered device * 3. Asks if a device is registered */ public class RegistryClient implements DeviceRegisterInterface { private final Logger log = LoggerFactory.getLogger(this.getClass()); private Credentials credentials; //Credentials for registry connection private String registryUri; //the end point from registry service private DSM dsm; //Data source Manifest for the device //TODO to be deleted // private ConfigurationEnv configurationEnv; //configuration environmental values for registry and message bus connection // private String dsd; //Data source definition for the data source // private String macAddress; // device macAddress @Override public void create(String registryUri) { this.setRegistryUri(registryUri); // this.setCredentials(credentials); } public RegistryClient(String registryUri) { create(registryUri); } // The public registration method @Override public RegistrationResult registerDevice(DSM dsm, Credentials credentials) { log.debug(" +--Request for registration for DSM with URI =" + dsm.getUri()); this.setDsm(dsm); this.setCredentials(credentials); //call post Method to connect with registry RegistrationResult result= this.postResource(this.registryUri, dsm, credentials); log.debug(" +--Registration returned status " + result.getStatus()); return result; } //the public method for unregister @Override public RegistrationResult unRegisterDevice(String id, Credentials credentials) { log.debug("Request for registration for DSM with id =" + id); // System.out.println("client:registryclient:unRegisterDevice==>dsmUri=" + uri + " registryUri=" + this.getRegistryUri()); // call post Method RegistrationResult result = this.deleteResource(this.registryUri, id,credentials); // System.out.println("Client:RegistryCLient:unregister response=" + result.getResult()); log.debug("Unregister returned status " + result.getStatus()); return result; } // public method for returning the registration status (true false) @Override public boolean isRegistered(DSM dsm, Credentials credentials) { log.debug("check if DSM is registered with id=" + dsm.getId()); // call post Method RegistrationResult result = this.postResource(this.registryUri, dsm,credentials); log.debug("Registration status for dsm_id=" + dsm.getId() + " is " + result.getStatus()); if (result.getStatus()==RegistrationResultStatusEnum.SUCCESS) return true; else return false; } // postResource posts postData data to the specific Rest (URI) private <T> RegistrationResult postResource (String uri, T postData, Credentials credentials) { log.debug(" +--Request for post to uri=" + uri); try { // create and initialize client for REST call Client client = Client.create(); client.addFilter(new HTTPBasicAuthFilter(credentials.getUser(),credentials.getPassword())); WebResource webResource = client.resource(uri); // serialize 'postData' Object to String ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); String request = mapper.writeValueAsString(postData); log.debug(" +--dsm=" + request); // call resource and get Results ClientResponse response = webResource.type("application/json").post(ClientResponse.class,request); //TODO why do I need this? if (response.getStatus() != 201) { log.debug("Response from rest{" + uri + "} has status " + response.getStatus()); client.destroy(); } //Get results as registration results RegistrationResult results = this.getRegistrationResults(response); //destroy client client.destroy(); log.debug(" +--Response from rest{" + uri + "} has status " + results.getStatus()); return results; } catch (Exception e) { // TODO only for skipping registry //e.printStackTrace(); RegistrationResult results = new RegistrationResult(); results.setStatus(RegistrationResultStatusEnum.SUCCESS); results.setBody(this.getFakeDsmId()); results.setStatusMessage("Get a fake registration"); log.debug(" +--Getting Fake registration"); return results; } // catch (Exception e) // { // e.printStackTrace(); // RegistrationResult results = new RegistrationResult(); // results.setStatus(RegistrationResultStatusEnum.FAIL); // results.setStatusMessage("Error creating-initializing-calling resource or parsing the response"); // // log.debug("Error creating-initializing-calling resource or parsing the response"); // // return results; // } } private String getFakeDsmId() { UUID id = UUID.randomUUID(); return "dsm://"+id.toString(); } private <T> RegistrationResult deleteResource (String uri, String postData, Credentials credentials) { log.debug("Request for delete to uri=" + uri + ". Delete the id:" + postData); try { // create and initialize client for REST call Client client = Client.create(); client.addFilter(new HTTPBasicAuthFilter(credentials.getUser(),credentials.getPassword())); WebResource webResource = client.resource(uri).queryParam("id", postData); // call resource and get Results ClientResponse response = webResource.type("application/json").delete(ClientResponse.class); //TODO why do I need this? if (response.getStatus() != 200) { client.destroy(); //throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } //Get results as registration results RegistrationResult results = this.getRegistrationResults(response); //destroy client.destroy(); log.debug("Response from rest{" + uri + "} has status " + results.getStatus()); return results; } catch (Exception e) { e.printStackTrace(); RegistrationResult results = new RegistrationResult(); results.setStatus(RegistrationResultStatusEnum.FAIL); results.setStatusMessage("Error creating-initializing-calling resource or parsing the response"); log.debug("Error creating-initializing-calling resource or parsing the response"); return results; } } private RegistrationResult getRegistrationResults(ClientResponse response) { ObjectMapper mapper = new ObjectMapper(); String createresponseString = response.getEntity(String.class); RegistrationResult res = new RegistrationResult(); try { res = mapper.readValue(createresponseString, res.getClass()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } // TODO: Transformations from Client Response to Registration Result Class // RegistrationResult res = new RegistrationResult(); if (response.getStatus()== 400) { res.setStatus(RegistrationResultStatusEnum.NOTFOUND); } else { res.setStatus(RegistrationResultStatusEnum.SUCCESS); } res.setStatusMessage(Integer.toString(response.getStatus())); return res; } // // private void createDsm() // { // dsm = new DSM(); // dsm.setDataSourceDefinitionReferenceID(dsd); // dsm.setMacAddress(macAddress); // dsm.setUri(configurationEnv.getEdgeUri()+ macAddress); // dsm.setDataSourceDefinitionInterfaceParameters(createDsdIp()); // } // // // private DataSourceDefinitionInterfaceParameters createDsdIp () // { // DataSourceDefinitionInterfaceParameters dsdip = new DataSourceDefinitionInterfaceParameters(); // Set<Parameter> paramSet = null; // // dsdip.setDescr(configurationEnv.getTopic()); // // Parameter top = new Parameter(); // top.setKey("topic"); // top.setValue(configurationEnv.getTopic()); // paramSet.add(top); // // Set<String> keys = configurationEnv.getKafkaProps().stringPropertyNames(); // for (String key : keys) { // Parameter e = new Parameter(); // e.setKey(key); // e.setValue(configurationEnv.getKafkaProps().getProperty(key)); // paramSet.add(e); // System.out.println(key + " : " + configurationEnv.getKafkaProps().getProperty(key)); // } // // dsdip.setParameter(paramSet); // // return dsdip; // } // // Getters and setters public Credentials getCredentials() { return credentials; } public void setCredentials(Credentials credentials) { this.credentials = credentials; } public DSM getDsm() { return dsm; } public void setDsm(DSM dsm) { this.dsm = dsm; } public String getRegistryUri() { return registryUri; } public void setRegistryUri(String registryUri) { this.registryUri = registryUri; } // public String getDsd() { // return dsd; // } // // public void setDsd(String dsd) { // this.dsd = dsd; // } // // public String getMacAddress() { // return macAddress; // } // // public void setMacAddress(String macAddress) { // this.macAddress = macAddress; // } // // public ConfigurationEnv getConfigurationEnv() // { // return configurationEnv; // } // // public void setConfigurationEnv(ConfigurationEnv configurationEnv) // { // this.configurationEnv = configurationEnv; // } }
apache-2.0
nfet/cxf-rest
src/main/java/com/lagnada/demo/cxfrest/rest/MyInterceptor.java
725
package com.lagnada.demo.cxfrest.rest; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Message; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.apache.cxf.security.SecurityContext; import java.security.Principal; public class MyInterceptor extends AbstractPhaseInterceptor<Message> { public MyInterceptor() { super(Phase.PRE_INVOKE); } @Override public void handleMessage(Message message) throws Fault { SecurityContext securityContext = (SecurityContext) message.get("org.apache.cxf.security.SecurityContext"); Principal userPrincipal = securityContext.getUserPrincipal(); "".toString(); } }
apache-2.0
Coreoz/Plume
plume-web-jersey/src/main/java/com/coreoz/plume/jersey/security/permission/PermissionRequestProvider.java
729
package com.coreoz.plume.jersey.security.permission; import java.util.Collection; import javax.ws.rs.container.ContainerRequestContext; /** * Extract permissions from the user corresponding to the current HTTP request */ public interface PermissionRequestProvider { /** * Fetch user permissions corresponding to the current HTTP request. * If the user has no permission or if no user is attached to the HTTP request, * then an empty collection must be returned. */ Collection<String> correspondingPermissions(ContainerRequestContext requestContext); /** * Fetch user information. It will be used to monitor or debug unauthorized access */ String userInformation(ContainerRequestContext requestContext); }
apache-2.0
Skullabs/kikaha
kikaha-modules/kikaha-urouting/source/kikaha/urouting/ConverterFactoryLoader.java
2325
package kikaha.urouting; import java.util.*; import java.util.function.Function; import javax.annotation.PostConstruct; import javax.enterprise.inject.Produces; import javax.enterprise.inject.*; import javax.inject.*; import kikaha.core.util.Lang; import kikaha.urouting.api.*; @Singleton @SuppressWarnings("rawtypes") public class ConverterFactoryLoader { @Inject @Typed( AbstractConverter.class ) Iterable<AbstractConverter> availableConverters; ConverterFactory factory; @PostConstruct public void onStartup() { factory = new ConverterFactory( loadAllConverters() ); } @Produces public ConverterFactory produceFactory(){ return factory; } public Map<String, AbstractConverter<?>> loadAllConverters() { final Map<String, AbstractConverter<?>> converters = loadPrimitiveConverters(); for ( final AbstractConverter converter : availableConverters ){ final String canonicalName = converter.getGenericClass().getCanonicalName(); converters.put(canonicalName, converter); } return converters; } static private Map<String, AbstractConverter<?>> loadPrimitiveConverters(){ final Map<String, AbstractConverter<?>> primitiveConverters = new HashMap<>(); converterFrom( primitiveConverters, int.class, 0, Integer::parseInt ); converterFrom( primitiveConverters, byte.class, (byte)0, Byte::parseByte ); converterFrom( primitiveConverters, float.class, 0f, Float::parseFloat ); converterFrom( primitiveConverters, double.class, 0.0, Double::parseDouble ); converterFrom( primitiveConverters, long.class, 0L, Long::parseLong ); converterFrom( primitiveConverters, short.class, (short)0, Short::parseShort ); converterFrom( primitiveConverters, boolean.class, Boolean.FALSE, Boolean::parseBoolean ); return primitiveConverters; } static private <T> void converterFrom( Map<String, AbstractConverter<?>> primitiveConverters, Class<T> primitiveType, T defaultValue, Function<String, T> converter) { primitiveConverters.put( primitiveType.getCanonicalName(), new AbstractConverter<T>() { @Override public T convert(String value) throws ConversionException { if (Lang.isUndefined(value)) return defaultValue; return converter.apply(value); } @Override public Class<T> getGenericClass() { return primitiveType; } } ); } }
apache-2.0
metaborg/nabl
nabl2.terms/src/main/java/mb/nabl2/util/graph/alg/misc/IGraphPathFinder.java
2933
/******************************************************************************* * Copyright (c) 2010-2013, Abel Hegedus, Istvan Rath and Daniel Varro * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-v20.html. * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package mb.nabl2.util.graph.alg.misc; import java.util.Deque; import java.util.Set; import mb.nabl2.util.graph.igraph.ITcDataSource; /** * The path finder provides methods for retrieving paths in a graph between a source node and one or more target nodes. * Use {@link ITcDataSource#getPathFinder()} for instantiating. * * @author Abel Hegedus * * @param <V> the node type of the graph */ public interface IGraphPathFinder<V> { /** * Returns an arbitrary path from the source node to the target node (if such exists). If there is no path * between them, an empty collection is returned. * * @param sourceNode the source node of the path * @param targetNode the target node of the path * @return the path from the source to the target, or empty collection if target is not reachable from source. */ Deque<V> getPath(V sourceNode, V targetNode); /** * Returns the collection of shortest paths from the source node to the target node (if such exists). If there is no path * between them, an empty collection is returned. * * @param sourceNode the source node of the path * @param targetNode the target node of the path * @return the collection of shortest paths from the source to the target, or empty collection if target is not reachable from source. */ Iterable<Deque<V>> getShortestPaths(V sourceNode, V targetNode); /** * Returns the collection of paths from the source node to the target node (if such exists). If there is no path * between them, an empty collection is returned. * * @param sourceNode the source node of the path * @param targetNode the target node of the path * @return the collection of paths from the source to the target, or empty collection if target is not reachable from source. */ Iterable<Deque<V>> getAllPaths(V sourceNode, V targetNode); /** * Returns the collection of paths from the source node to any of the target nodes (if such exists). If there is no path * between them, an empty collection is returned. * * @param sourceNode the source node of the path * @param targetNodes the set of target nodes of the paths * @return the collection of paths from the source to any of the targets, or empty collection if neither target is reachable from source. */ Iterable<Deque<V>> getAllPathsToTargets(V sourceNode, Set<V> targetNodes); }
apache-2.0
jjhaggar/ludum30_a_hole_new_world
core/src/com/blogspot/ludumdaresforfun/Enemy.java
2894
package com.blogspot.ludumdaresforfun; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; public class Enemy extends Image{ final float VELOCITY = 50f; final float ATTACK_VELOCITY = 130f; enum State { Walking, Running, Hurting, BeingInvoked } Vector2 desiredPosition = new Vector2(); final Vector2 velocity = new Vector2(); State state = State.Walking; boolean facesRight = false; public boolean updateVelocity; public boolean setToDie = false; public boolean running = false; public float attackHereX = 0; public boolean attackRight = false; public enum Direction { Left, Right } public Direction dir = Direction.Left; public Rectangle rect = new Rectangle(); public int diffInitialPos = 0; public final int RANGE = 100; public final int ATTACK_DISTANCE = 100; protected Animation animation = null; float stateTime = 0; float offSetX; public boolean dying = false; public boolean canMove = false; public AtlasRegion actualFrame; public boolean beingInvoked = false; public Enemy(Animation animation) { super(animation.getKeyFrame(0)); this.animation = animation; this.actualFrame = ((AtlasRegion)animation.getKeyFrame(0)); } public Rectangle getRect() { this.rect.set(this.getX(), this.getY(),this.actualFrame.packedWidth, this.actualFrame.packedHeight); return this.rect; } public void die(){ // sound and set to die Assets.playSound("enemyDead"); this.state = State.Hurting; this.stateTime = 0; this.dying = true; this.velocity.x = 0; } public void run() { if (this.state != Enemy.State.Running) { Assets.playSound("enemyAttack"); if (this.dir == Direction.Left) { this.diffInitialPos -= 2; this.velocity.x = -this.ATTACK_VELOCITY; } else { this.diffInitialPos += 2; this.velocity.x = this.ATTACK_VELOCITY; } this.state = Enemy.State.Running; this.stateTime = 0; this.running = true; } } public void walk() { if (this.dir == Direction.Left) { this.diffInitialPos -= 1; this.velocity.x = -this.VELOCITY; } else { this.diffInitialPos += 1; this.velocity.x = this.VELOCITY; } this.state = Enemy.State.Walking; } @Override public void act(float delta) { ((TextureRegionDrawable)this.getDrawable()).setRegion(this.animation.getKeyFrame(this.stateTime+=delta, true)); super.act(delta); } }
apache-2.0
TomeOkin/LsPush-Server
src/main/java/app/receiver/CollectionReceiver.java
1028
/* * Copyright 2016 TomeOkin * * 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 app.receiver; import app.data.model.Collection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //@Component public class CollectionReceiver { private static final Logger logger = LoggerFactory.getLogger(CollectionReceiver.class); public void receiveMessage(Object message) { Collection collection = (Collection) message; logger.info("receive message: {}", collection.toString()); } }
apache-2.0
ashnl007/jeesms
src/main/java/com/jeesms/entity/system/LoginLog.java
1947
package com.jeesms.entity.system; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.jeesms.common.Constants; import com.jeesms.entity.base.IdEntity; import javax.persistence.*; import java.util.Date; /** * 登录日志Entity * * @author ASHNL * @time 2014-08-22 15:42:51 */ @Entity @Table(name = "T_S_LOGIN_LOG") @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler"}) public class LoginLog extends IdEntity { /** * 登录用户 */ private User user; /** * 登录时间 */ private Date loginTime; /** * 登录IP */ private String loginIp; /** * 描述 */ private String remark; public LoginLog() { } public LoginLog(String id) { this(); this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") @JsonIgnore public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } @Column(name = "LOGIN_TIME") @JsonFormat(pattern = Constants.yyyyMMddHHmmss, locale = Constants.LOCALE_ZH, timezone = Constants.TIMEZONE) public Date getLoginTime() { return this.loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } @Column(name = "LOGIN_IP", length = 255) public String getLoginIp() { return this.loginIp; } public void setLoginIp(String loginIp) { this.loginIp = loginIp; } @Column(name = "REMARK", length = 255) public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Transient public String getLoginName() { return user == null ? null : user.getName(); } }
apache-2.0
nano-projects/nano-framework
nano-orm/nano-orm-jdbc/src/main/java/org/nanoframework/orm/jdbc/config/DruidJdbcConfig.java
5059
/* * Copyright 2015-2016 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.nanoframework.orm.jdbc.config; import java.util.Properties; import org.nanoframework.commons.util.Assert; /** * @author yanghe * @since 1.2 */ public class DruidJdbcConfig extends JdbcConfig { private static final long serialVersionUID = -565746278164485851L; @Property("druid.initialSize") private Integer initialSize; @Property("druid.maxActive") private Integer maxActive; @Property("druid.maxIdle") private Integer maxIdle; @Property("druid.minIdle") private Integer minIdle; @Property("druid.maxWait") private Long maxWait; @Property("druid.removeAbandoned") private Boolean removeAbandoned; @Property("druid.removeAbandonedTimeout") private Integer removeAbandonedTimeout; @Property("druid.timeBetweenEvictionRunsMillis") private Long timeBetweenEvictionRunsMillis; @Property("druid.minEvictableIdleTimeMillis") private Long minEvictableIdleTimeMillis; @Property("druid.validationQuery") private String validationQuery; @Property("druid.testWhileIdle") private Boolean testWhileIdle; @Property("druid.testOnBorrow") private Boolean testOnBorrow; @Property("druid.testOnReturn") private Boolean testOnReturn; @Property("druid.poolPreparedStatements") private Boolean poolPreparedStatements; @Property("druid.maxPoolPreparedStatementPerConnectionSize") private Integer maxPoolPreparedStatementPerConnectionSize; @Property("druid.filters") private String filters; public DruidJdbcConfig() { } public DruidJdbcConfig(Properties properties) { Assert.notNull(properties); this.setProperties(properties); } public Integer getInitialSize() { return initialSize; } public void setInitialSize(Integer initialSize) { this.initialSize = initialSize; } public Integer getMaxActive() { return maxActive; } public void setMaxActive(Integer maxActive) { this.maxActive = maxActive; } public Integer getMaxIdle() { return maxIdle; } public void setMaxIdle(Integer maxIdle) { this.maxIdle = maxIdle; } public Integer getMinIdle() { return minIdle; } public void setMinIdle(Integer minIdle) { this.minIdle = minIdle; } public Long getMaxWait() { return maxWait; } public void setMaxWait(Long maxWait) { this.maxWait = maxWait; } public Boolean getRemoveAbandoned() { return removeAbandoned; } public void setRemoveAbandoned(Boolean removeAbandoned) { this.removeAbandoned = removeAbandoned; } public Integer getRemoveAbandonedTimeout() { return removeAbandonedTimeout; } public void setRemoveAbandonedTimeout(Integer removeAbandonedTimeout) { this.removeAbandonedTimeout = removeAbandonedTimeout; } public Long getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public Long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public Boolean getTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(Boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } public Boolean getTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(Boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public Boolean getTestOnReturn() { return testOnReturn; } public void setTestOnReturn(Boolean testOnReturn) { this.testOnReturn = testOnReturn; } public Boolean getPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(Boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public Integer getMaxPoolPreparedStatementPerConnectionSize() { return maxPoolPreparedStatementPerConnectionSize; } public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) { this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters; } }
apache-2.0
JeremyJacquemont/SchoolProjects
IUT/Android-Projects/Loupe/Sources/app/src/main/java/com/lpiem/apps/loupelec/utilities/customUiElement/CustomListPreference.java
707
package com.lpiem.apps.loupelec.utilities.customUiElement; import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; /** * CustomListPreference Class */ public class CustomListPreference extends ListPreference { /** * Constructors */ public CustomListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public CustomListPreference(Context context) { super(context); } /** * getSummary Method (Override) * @return CharSequence */ @Override public CharSequence getSummary() { return this.getEntry() != null ? this.getEntry().toString() : ""; } }
apache-2.0
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFlatMapSingle.java
11229
/* * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * 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.reactivex.rxjava3.internal.operators.flowable; import java.util.Objects; import java.util.concurrent.atomic.*; import org.reactivestreams.*; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.disposables.*; import io.reactivex.rxjava3.exceptions.Exceptions; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.internal.disposables.DisposableHelper; import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper; import io.reactivex.rxjava3.internal.util.*; import io.reactivex.rxjava3.operators.SpscLinkedArrayQueue; /** * Maps upstream values into SingleSources and merges their signals into one sequence. * @param <T> the source value type * @param <R> the result value type */ public final class FlowableFlatMapSingle<T, R> extends AbstractFlowableWithUpstream<T, R> { final Function<? super T, ? extends SingleSource<? extends R>> mapper; final boolean delayErrors; final int maxConcurrency; public FlowableFlatMapSingle(Flowable<T> source, Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayError, int maxConcurrency) { super(source); this.mapper = mapper; this.delayErrors = delayError; this.maxConcurrency = maxConcurrency; } @Override protected void subscribeActual(Subscriber<? super R> s) { source.subscribe(new FlatMapSingleSubscriber<>(s, mapper, delayErrors, maxConcurrency)); } static final class FlatMapSingleSubscriber<T, R> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { private static final long serialVersionUID = 8600231336733376951L; final Subscriber<? super R> downstream; final boolean delayErrors; final int maxConcurrency; final AtomicLong requested; final CompositeDisposable set; final AtomicInteger active; final AtomicThrowable errors; final Function<? super T, ? extends SingleSource<? extends R>> mapper; final AtomicReference<SpscLinkedArrayQueue<R>> queue; Subscription upstream; volatile boolean cancelled; FlatMapSingleSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayErrors, int maxConcurrency) { this.downstream = actual; this.mapper = mapper; this.delayErrors = delayErrors; this.maxConcurrency = maxConcurrency; this.requested = new AtomicLong(); this.set = new CompositeDisposable(); this.errors = new AtomicThrowable(); this.active = new AtomicInteger(1); this.queue = new AtomicReference<>(); } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { this.upstream = s; downstream.onSubscribe(this); int m = maxConcurrency; if (m == Integer.MAX_VALUE) { s.request(Long.MAX_VALUE); } else { s.request(maxConcurrency); } } } @Override public void onNext(T t) { SingleSource<? extends R> ms; try { ms = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.cancel(); onError(ex); return; } active.getAndIncrement(); InnerObserver inner = new InnerObserver(); if (!cancelled && set.add(inner)) { ms.subscribe(inner); } } @Override public void onError(Throwable t) { active.decrementAndGet(); if (errors.tryAddThrowableOrReport(t)) { if (!delayErrors) { set.dispose(); } drain(); } } @Override public void onComplete() { active.decrementAndGet(); drain(); } @Override public void cancel() { cancelled = true; upstream.cancel(); set.dispose(); errors.tryTerminateAndReport(); } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { BackpressureHelper.add(requested, n); drain(); } } void innerSuccess(InnerObserver inner, R value) { set.delete(inner); if (get() == 0 && compareAndSet(0, 1)) { boolean d = active.decrementAndGet() == 0; if (requested.get() != 0) { downstream.onNext(value); SpscLinkedArrayQueue<R> q = queue.get(); if (d && (q == null || q.isEmpty())) { errors.tryTerminateConsumer(downstream); return; } BackpressureHelper.produced(requested, 1); if (maxConcurrency != Integer.MAX_VALUE) { upstream.request(1); } } else { SpscLinkedArrayQueue<R> q = getOrCreateQueue(); synchronized (q) { q.offer(value); } } if (decrementAndGet() == 0) { return; } } else { SpscLinkedArrayQueue<R> q = getOrCreateQueue(); synchronized (q) { q.offer(value); } active.decrementAndGet(); if (getAndIncrement() != 0) { return; } } drainLoop(); } SpscLinkedArrayQueue<R> getOrCreateQueue() { SpscLinkedArrayQueue<R> current = queue.get(); if (current != null) { return current; } current = new SpscLinkedArrayQueue<>(Flowable.bufferSize()); if (queue.compareAndSet(null, current)) { return current; } return queue.get(); } void innerError(InnerObserver inner, Throwable e) { set.delete(inner); if (errors.tryAddThrowableOrReport(e)) { if (!delayErrors) { upstream.cancel(); set.dispose(); } else { if (maxConcurrency != Integer.MAX_VALUE) { upstream.request(1); } } active.decrementAndGet(); drain(); } } void drain() { if (getAndIncrement() == 0) { drainLoop(); } } void clear() { SpscLinkedArrayQueue<R> q = queue.get(); if (q != null) { q.clear(); } } void drainLoop() { int missed = 1; Subscriber<? super R> a = downstream; AtomicInteger n = active; AtomicReference<SpscLinkedArrayQueue<R>> qr = queue; for (;;) { long r = requested.get(); long e = 0L; while (e != r) { if (cancelled) { clear(); return; } if (!delayErrors) { Throwable ex = errors.get(); if (ex != null) { clear(); errors.tryTerminateConsumer(downstream); return; } } boolean d = n.get() == 0; SpscLinkedArrayQueue<R> q = qr.get(); R v = q != null ? q.poll() : null; boolean empty = v == null; if (d && empty) { errors.tryTerminateConsumer(a); return; } if (empty) { break; } a.onNext(v); e++; } if (e == r) { if (cancelled) { clear(); return; } if (!delayErrors) { Throwable ex = errors.get(); if (ex != null) { clear(); errors.tryTerminateConsumer(a); return; } } boolean d = n.get() == 0; SpscLinkedArrayQueue<R> q = qr.get(); boolean empty = q == null || q.isEmpty(); if (d && empty) { errors.tryTerminateConsumer(a); return; } } if (e != 0L) { BackpressureHelper.produced(requested, e); if (maxConcurrency != Integer.MAX_VALUE) { upstream.request(e); } } missed = addAndGet(-missed); if (missed == 0) { break; } } } final class InnerObserver extends AtomicReference<Disposable> implements SingleObserver<R>, Disposable { private static final long serialVersionUID = -502562646270949838L; @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this, d); } @Override public void onSuccess(R value) { innerSuccess(this, value); } @Override public void onError(Throwable e) { innerError(this, e); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } @Override public void dispose() { DisposableHelper.dispose(this); } } } }
apache-2.0
keepsl/keepsmis
ksxtmanager/src/main/java/com/keeps/ksxtmanager/system/service/DictService.java
1385
package com.keeps.ksxtmanager.system.service; import java.util.List; import com.keeps.core.service.SoftService; import com.keeps.model.TDict; import com.keeps.model.TDictType; import com.keeps.tools.utils.page.Page; import com.keeps.utils.TreeNode; /** * <p>Title: DictService.java</p> * <p>Description: 字典SERVICE接口 </p> * <p>Copyright: Copyright (c) KEEPS</p> * @author keeps * @version v 1.00 * @date 创建日期:2017年1月19日 * 修改日期: * 修改人: * 复审人: */ public interface DictService extends SoftService{ public Page queryDictList(TDict dict); public List<TreeNode> getDictTree(String code); public List<TDict> getDictList(TDict dict); public List<TDictType> getDictTypeList(TDictType tDictType); public TDict getDictById(Integer id); public TDictType geTDictTypeById(Integer id); public String deleteDictById(String ids); public String deleteDictTypeById(Integer id); public List<TreeNode> getDictTypeTree(); public List<TreeNode> getDicttypeTreeByCode(String code); public List<TreeNode> getDictTypeSelectByCode(String code); public String saveOrUpdateDict(TDict dict); public String saveOrUpdateDictType(TDictType dictType); public List<TDictType> getDictTypeByCode(String code); public List<TDict> getDictByCode(String code); }
apache-2.0
leopardoooo/cambodia
boss-job/src/main/java/com/yaochen/boss/dao/ProdIncludeDao.java
826
package com.yaochen.boss.dao; import java.util.List; import org.springframework.stereotype.Component; import com.ycsoft.beans.core.cust.CCust; import com.ycsoft.beans.core.prod.CProdInclude; import com.ycsoft.daos.abstracts.BaseEntityDao; import com.ycsoft.daos.core.JDBCException; @Component public class ProdIncludeDao extends BaseEntityDao<CCust> { public ProdIncludeDao(){} //设置产品之间的关系 public void saveProdInclude(String userId,List<CProdInclude> includeList) throws Exception{ for (CProdInclude include :includeList){ String sql = "insert into c_prod_include_lxr (cust_id,user_id,prod_sn,include_prod_sn) " + " values (?,?,?,?)"; executeUpdate(sql,include.getCust_id(),include.getUser_id(),include.getProd_sn(),include.getInclude_prod_sn()); } } }
apache-2.0
consulo/consulo
modules/base/core-impl/src/main/java/com/intellij/psi/impl/PsiDocumentManagerBase.java
42122
// Copyright 2000-2019 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.psi.impl; import com.google.common.annotations.VisibleForTesting; import com.intellij.injected.editor.DocumentWindow; import com.intellij.lang.ASTNode; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.application.*; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.DocumentRunnable; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.PrioritizedInternalDocumentListener; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.impl.EditorDocumentPriorities; import com.intellij.openapi.editor.impl.FrozenDocument; import com.intellij.openapi.editor.impl.event.RetargetRangeMarkers; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.util.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.file.impl.FileManager; import com.intellij.psi.impl.file.impl.FileManagerImpl; import com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.FileElement; import com.intellij.psi.text.BlockSupport; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.*; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import consulo.application.TransactionGuardEx; import consulo.disposer.Disposable; import consulo.disposer.Disposer; import consulo.logging.Logger; import consulo.util.dataholder.Key; import consulo.util.lang.DeprecatedMethodException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.TestOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.ConcurrentMap; public abstract class PsiDocumentManagerBase extends PsiDocumentManager implements DocumentListener, Disposable { static final Logger LOG = Logger.getInstance(PsiDocumentManagerBase.class); private static final Key<Document> HARD_REF_TO_DOCUMENT = Key.create("HARD_REFERENCE_TO_DOCUMENT"); private static final Key<List<Runnable>> ACTION_AFTER_COMMIT = Key.create("ACTION_AFTER_COMMIT"); protected final Project myProject; private final PsiManager myPsiManager; protected final DocumentCommitProcessor myDocumentCommitProcessor; final Set<Document> myUncommittedDocuments = ContainerUtil.newConcurrentSet(); private final Map<Document, UncommittedInfo> myUncommittedInfos = ContainerUtil.newConcurrentMap(); boolean myStopTrackingDocuments; private boolean myPerformBackgroundCommit = true; private volatile boolean myIsCommitInProgress; private static volatile boolean ourIsFullReparseInProgress; private final PsiToDocumentSynchronizer mySynchronizer; private final List<Listener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); protected PsiDocumentManagerBase(@Nonnull Project project, DocumentCommitProcessor documentCommitProcessor) { myProject = project; myPsiManager = PsiManager.getInstance(project); myDocumentCommitProcessor = documentCommitProcessor; mySynchronizer = new PsiToDocumentSynchronizer(this, project.getMessageBus()); myPsiManager.addPsiTreeChangeListener(mySynchronizer); project.getMessageBus().connect(this).subscribe(PsiDocumentTransactionListener.TOPIC, (document, file) -> { myUncommittedDocuments.remove(document); }); } @Override @Nullable public PsiFile getPsiFile(@Nonnull Document document) { if (document instanceof DocumentWindow && !((DocumentWindow)document).isValid()) { return null; } PsiFile psiFile = getCachedPsiFile(document); if (psiFile != null) { return ensureValidFile(psiFile, "Cached PSI"); } final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null || !virtualFile.isValid()) return null; psiFile = getPsiFile(virtualFile); if (psiFile == null) return null; fireFileCreated(document, psiFile); return psiFile; } @Nonnull private static PsiFile ensureValidFile(@Nonnull PsiFile psiFile, @Nonnull String debugInfo) { if (!psiFile.isValid()) throw new PsiInvalidElementAccessException(psiFile, debugInfo); return psiFile; } @Deprecated //@ApiStatus.ScheduledForRemoval(inVersion = "2017") // todo remove when plugins come to their senses and stopped using it // todo to be removed in idea 17 public static void cachePsi(@Nonnull Document document, @Nullable PsiFile file) { DeprecatedMethodException.report("Unsupported method"); } public void associatePsi(@Nonnull Document document, @Nullable PsiFile file) { throw new UnsupportedOperationException(); } @Override public PsiFile getCachedPsiFile(@Nonnull Document document) { final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null || !virtualFile.isValid()) return null; return getCachedPsiFile(virtualFile); } @Nullable FileViewProvider getCachedViewProvider(@Nonnull Document document) { final VirtualFile virtualFile = getVirtualFile(document); if (virtualFile == null) return null; return getFileManager().findCachedViewProvider(virtualFile); } @Nullable private static VirtualFile getVirtualFile(@Nonnull Document document) { final VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null || !virtualFile.isValid()) return null; return virtualFile; } @Nullable PsiFile getCachedPsiFile(@Nonnull VirtualFile virtualFile) { return getFileManager().getCachedPsiFile(virtualFile); } @Nullable private PsiFile getPsiFile(@Nonnull VirtualFile virtualFile) { return getFileManager().findFile(virtualFile); } @Nonnull private FileManager getFileManager() { return ((PsiManagerEx)myPsiManager).getFileManager(); } @Override public Document getDocument(@Nonnull PsiFile file) { Document document = getCachedDocument(file); if (document != null) { if (!file.getViewProvider().isPhysical()) { PsiUtilCore.ensureValid(file); associatePsi(document, file); } return document; } FileViewProvider viewProvider = file.getViewProvider(); if (!viewProvider.isEventSystemEnabled()) return null; document = FileDocumentManager.getInstance().getDocument(viewProvider.getVirtualFile()); if (document != null) { if (document.getTextLength() != file.getTextLength()) { String message = "Document/PSI mismatch: " + file + " (" + file.getClass() + "); physical=" + viewProvider.isPhysical(); if (document.getTextLength() + file.getTextLength() < 8096) { message += "\n=== document ===\n" + document.getText() + "\n=== PSI ===\n" + file.getText(); } throw new AssertionError(message); } if (!viewProvider.isPhysical()) { PsiUtilCore.ensureValid(file); associatePsi(document, file); file.putUserData(HARD_REF_TO_DOCUMENT, document); } } return document; } @Override public Document getCachedDocument(@Nonnull PsiFile file) { if (!file.isPhysical()) return null; VirtualFile vFile = file.getViewProvider().getVirtualFile(); return FileDocumentManager.getInstance().getCachedDocument(vFile); } @Override public void commitAllDocuments() { ApplicationManager.getApplication().assertIsWriteThread(); ((TransactionGuardEx)TransactionGuard.getInstance()).assertWriteActionAllowed(); if (myUncommittedDocuments.isEmpty()) return; final Document[] documents = getUncommittedDocuments(); for (Document document : documents) { if (isCommitted(document)) { boolean success = doCommitWithoutReparse(document); LOG.error("Committed document in uncommitted set: " + document + ", force-committed=" + success); } else if (!doCommit(document)) { LOG.error("Couldn't commit " + document); } } assertEverythingCommitted(); } @Override public boolean commitAllDocumentsUnderProgress() { Application application = ApplicationManager.getApplication(); //backward compatibility with unit tests if (application.isUnitTestMode()) { commitAllDocuments(); return true; } assert !application.isWriteAccessAllowed() : "Do not call commitAllDocumentsUnderProgress inside write-action"; final int semaphoreTimeoutInMs = 50; final Runnable commitAllDocumentsRunnable = () -> { Semaphore semaphore = new Semaphore(1); application.invokeLater(() -> { PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(() -> { semaphore.up(); }); }); while (!semaphore.waitFor(semaphoreTimeoutInMs)) { ProgressManager.checkCanceled(); } }; return ProgressManager.getInstance().runProcessWithProgressSynchronously(commitAllDocumentsRunnable, "Processing Documents", true, myProject); } private void assertEverythingCommitted() { LOG.assertTrue(!hasUncommitedDocuments(), myUncommittedDocuments); } @VisibleForTesting public boolean doCommitWithoutReparse(@Nonnull Document document) { return finishCommitInWriteAction(document, Collections.emptyList(), Collections.emptyList(), true, true); } @Override public void performForCommittedDocument(@Nonnull final Document doc, @Nonnull final Runnable action) { Document document = getTopLevelDocument(doc); if (isCommitted(document)) { action.run(); } else { addRunOnCommit(document, action); } } private final Map<Object, Runnable> actionsWhenAllDocumentsAreCommitted = new LinkedHashMap<>(); //accessed from EDT only private static final Object PERFORM_ALWAYS_KEY = ObjectUtil.sentinel("PERFORM_ALWAYS"); /** * Cancel previously registered action and schedules (new) action to be executed when all documents are committed. * * @param key the (unique) id of the action. * @param action The action to be executed after automatic commit. * This action will overwrite any action which was registered under this key earlier. * The action will be executed in EDT. * @return true if action has been run immediately, or false if action was scheduled for execution later. */ public boolean cancelAndRunWhenAllCommitted(@NonNls @Nonnull Object key, @Nonnull final Runnable action) { ApplicationManager.getApplication().assertIsDispatchThread(); if (myProject.isDisposed()) { action.run(); return true; } if (myUncommittedDocuments.isEmpty()) { if (!isCommitInProgress()) { // in case of fireWriteActionFinished() we didn't execute 'actionsWhenAllDocumentsAreCommitted' yet assert actionsWhenAllDocumentsAreCommitted.isEmpty() : actionsWhenAllDocumentsAreCommitted; } action.run(); return true; } checkWeAreOutsideAfterCommitHandler(); actionsWhenAllDocumentsAreCommitted.put(key, action); return false; } public static void addRunOnCommit(@Nonnull Document document, @Nonnull Runnable action) { synchronized (ACTION_AFTER_COMMIT) { List<Runnable> list = document.getUserData(ACTION_AFTER_COMMIT); if (list == null) { document.putUserData(ACTION_AFTER_COMMIT, list = new SmartList<>()); } list.add(action); } } private static List<Runnable> getAndClearActionsAfterCommit(@Nonnull Document document) { List<Runnable> list; synchronized (ACTION_AFTER_COMMIT) { list = document.getUserData(ACTION_AFTER_COMMIT); if (list != null) { list = new ArrayList<>(list); document.putUserData(ACTION_AFTER_COMMIT, null); } } return list; } @Override public void commitDocument(@Nonnull final Document doc) { final Document document = getTopLevelDocument(doc); if (isEventSystemEnabled(document)) { ((TransactionGuardEx)TransactionGuard.getInstance()).assertWriteActionAllowed(); } if (!isCommitted(document)) { doCommit(document); } } private boolean isEventSystemEnabled(Document document) { FileViewProvider viewProvider = getCachedViewProvider(document); return viewProvider != null && viewProvider.isEventSystemEnabled() && !AbstractFileViewProvider.isFreeThreaded(viewProvider); } boolean finishCommit(@Nonnull final Document document, @Nonnull List<? extends BooleanRunnable> finishProcessors, @Nonnull List<? extends BooleanRunnable> reparseInjectedProcessors, final boolean synchronously, @Nonnull final Object reason) { assert !myProject.isDisposed() : "Already disposed"; ApplicationManager.getApplication().assertIsDispatchThread(); final boolean[] ok = {true}; Runnable runnable = new DocumentRunnable(document, myProject) { @Override public void run() { ok[0] = finishCommitInWriteAction(document, finishProcessors, reparseInjectedProcessors, synchronously, false); } }; if (synchronously) { runnable.run(); } else { ApplicationManager.getApplication().runWriteAction(runnable); } if (ok[0]) { // run after commit actions outside write action runAfterCommitActions(document); if (DebugUtil.DO_EXPENSIVE_CHECKS && !ApplicationInfoImpl.isInPerformanceTest()) { checkAllElementsValid(document, reason); } } return ok[0]; } protected boolean finishCommitInWriteAction(@Nonnull final Document document, @Nonnull List<? extends BooleanRunnable> finishProcessors, @Nonnull List<? extends BooleanRunnable> reparseInjectedProcessors, final boolean synchronously, boolean forceNoPsiCommit) { ApplicationManager.getApplication().assertIsDispatchThread(); if (myProject.isDisposed()) return false; assert !(document instanceof DocumentWindow); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile != null) { getSmartPointerManager().fastenBelts(virtualFile); } FileViewProvider viewProvider = forceNoPsiCommit ? null : getCachedViewProvider(document); myIsCommitInProgress = true; Ref<Boolean> success = new Ref<>(true); try { ProgressManager.getInstance().executeNonCancelableSection(() -> { if (viewProvider == null) { handleCommitWithoutPsi(document); } else { success.set(commitToExistingPsi(document, finishProcessors, reparseInjectedProcessors, synchronously, virtualFile)); } }); } catch (Throwable e) { try { forceReload(virtualFile, viewProvider); } finally { LOG.error(e); } } finally { if (success.get()) { myUncommittedDocuments.remove(document); } myIsCommitInProgress = false; } return success.get(); } private boolean commitToExistingPsi(@Nonnull Document document, @Nonnull List<? extends BooleanRunnable> finishProcessors, @Nonnull List<? extends BooleanRunnable> reparseInjectedProcessors, boolean synchronously, @Nullable VirtualFile virtualFile) { for (BooleanRunnable finishRunnable : finishProcessors) { boolean success = finishRunnable.run(); if (synchronously) { assert success : finishRunnable + " in " + finishProcessors; } if (!success) { return false; } } clearUncommittedInfo(document); if (virtualFile != null) { getSmartPointerManager().updatePointerTargetsAfterReparse(virtualFile); } FileViewProvider viewProvider = getCachedViewProvider(document); if (viewProvider != null) { viewProvider.contentsSynchronized(); } for (BooleanRunnable runnable : reparseInjectedProcessors) { if (!runnable.run()) return false; } return true; } void forceReload(VirtualFile virtualFile, @Nullable FileViewProvider viewProvider) { if (viewProvider != null) { ((AbstractFileViewProvider)viewProvider).markInvalidated(); } if (virtualFile != null) { ((FileManagerImpl)getFileManager()).forceReload(virtualFile); } } private void checkAllElementsValid(@Nonnull Document document, @Nonnull final Object reason) { final PsiFile psiFile = getCachedPsiFile(document); if (psiFile != null) { psiFile.accept(new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { if (!element.isValid()) { throw new AssertionError("Commit to '" + psiFile.getVirtualFile() + "' has led to invalid element: " + element + "; Reason: '" + reason + "'"); } } }); } } private boolean doCommit(@Nonnull final Document document) { assert !myIsCommitInProgress : "Do not call commitDocument() from inside PSI change listener"; // otherwise there are many clients calling commitAllDocs() on PSI childrenChanged() if (getSynchronizer().isDocumentAffectedByTransactions(document)) return false; final PsiFile psiFile = getPsiFile(document); if (psiFile == null) { myUncommittedDocuments.remove(document); runAfterCommitActions(document); return true; // the project must be closing or file deleted } Runnable runnable = () -> { myIsCommitInProgress = true; try { myDocumentCommitProcessor.commitSynchronously(document, myProject, psiFile); } finally { myIsCommitInProgress = false; } assert !isInUncommittedSet(document) : "Document :" + document; }; ApplicationManager.getApplication().runWriteAction(runnable); return true; } // true if the PSI is being modified and events being sent public boolean isCommitInProgress() { return myIsCommitInProgress || isFullReparseInProgress(); } public static boolean isFullReparseInProgress() { return ourIsFullReparseInProgress; } @Override public <T> T commitAndRunReadAction(@Nonnull final Computable<T> computation) { final Ref<T> ref = Ref.create(null); commitAndRunReadAction(() -> ref.set(computation.compute())); return ref.get(); } @Override public void reparseFiles(@Nonnull Collection<? extends VirtualFile> files, boolean includeOpenFiles) { FileContentUtilCore.reparseFiles(files); } @Override public void commitAndRunReadAction(@Nonnull final Runnable runnable) { final Application application = ApplicationManager.getApplication(); if (application.isDispatchThread()) { commitAllDocuments(); runnable.run(); return; } if (application.isReadAccessAllowed()) { LOG.error("Don't call commitAndRunReadAction inside ReadAction, it will cause a deadlock. " + Thread.currentThread()); } while (true) { boolean executed = ReadAction.compute(() -> { if (myUncommittedDocuments.isEmpty()) { runnable.run(); return true; } return false; }); if (executed) break; TransactionId contextTransaction = TransactionGuard.getInstance().getContextTransaction(); Semaphore semaphore = new Semaphore(1); application.invokeLater(() -> { if (myProject.isDisposed()) { // committedness doesn't matter anymore; give clients a chance to do checkCanceled semaphore.up(); return; } performWhenAllCommitted(() -> semaphore.up(), contextTransaction); }, ModalityState.any()); while (!semaphore.waitFor(10)) { ProgressManager.checkCanceled(); } } } /** * Schedules action to be executed when all documents are committed. * * @return true if action has been run immediately, or false if action was scheduled for execution later. */ @Override public boolean performWhenAllCommitted(@Nonnull final Runnable action) { return performWhenAllCommitted(action, TransactionGuard.getInstance().getContextTransaction()); } private boolean performWhenAllCommitted(@Nonnull Runnable action, @Nullable TransactionId context) { ApplicationManager.getApplication().assertIsDispatchThread(); checkWeAreOutsideAfterCommitHandler(); assert !myProject.isDisposed() : "Already disposed: " + myProject; if (myUncommittedDocuments.isEmpty()) { action.run(); return true; } CompositeRunnable actions = (CompositeRunnable)actionsWhenAllDocumentsAreCommitted.get(PERFORM_ALWAYS_KEY); if (actions == null) { actions = new CompositeRunnable(); actionsWhenAllDocumentsAreCommitted.put(PERFORM_ALWAYS_KEY, actions); } actions.add(action); if (context != null) { // re-add all uncommitted documents into the queue with this new modality // because this client obviously expects them to commit even inside modal dialog for (Document document : myUncommittedDocuments) { myDocumentCommitProcessor.commitAsynchronously(myProject, document, "re-added with context " + context + " because performWhenAllCommitted(" + context + ") was called", context); } } return false; } @Override public void performLaterWhenAllCommitted(@Nonnull final Runnable runnable) { performLaterWhenAllCommitted(runnable, ModalityState.defaultModalityState()); } @Override public void performLaterWhenAllCommitted(@Nonnull final Runnable runnable, final ModalityState modalityState) { final Runnable whenAllCommitted = () -> ApplicationManager.getApplication().invokeLater(() -> { if (hasUncommitedDocuments()) { // no luck, will try later performLaterWhenAllCommitted(runnable); } else { runnable.run(); } }, modalityState, myProject.getDisposed()); if (ApplicationManager.getApplication().isDispatchThread() && isInsideCommitHandler()) { whenAllCommitted.run(); } else { UIUtil.invokeLaterIfNeeded(() -> { if (!myProject.isDisposed()) performWhenAllCommitted(whenAllCommitted); }); } } private static class CompositeRunnable extends ArrayList<Runnable> implements Runnable { @Override public void run() { for (Runnable runnable : this) { runnable.run(); } } } private void runAfterCommitActions(@Nonnull Document document) { if (!ApplicationManager.getApplication().isDispatchThread()) { // have to run in EDT to guarantee data structure safe access and "execute in EDT" callbacks contract ApplicationManager.getApplication().invokeLater(() -> { if (!myProject.isDisposed() && isCommitted(document)) runAfterCommitActions(document); }); return; } ApplicationManager.getApplication().assertIsDispatchThread(); List<Runnable> list = getAndClearActionsAfterCommit(document); if (list != null) { for (final Runnable runnable : list) { runnable.run(); } } if (!hasUncommitedDocuments() && !actionsWhenAllDocumentsAreCommitted.isEmpty()) { List<Runnable> actions = new ArrayList<>(actionsWhenAllDocumentsAreCommitted.values()); beforeCommitHandler(); List<Pair<Runnable, Throwable>> exceptions = new ArrayList<>(); try { for (Runnable action : actions) { try { action.run(); } catch (ProcessCanceledException e) { // some actions are crazy enough to use PCE for their own control flow. // swallow and ignore to not disrupt completely unrelated control flow. } catch (Throwable e) { exceptions.add(Pair.create(action, e)); } } } finally { // unblock adding listeners actionsWhenAllDocumentsAreCommitted.clear(); } for (Pair<Runnable, Throwable> pair : exceptions) { Runnable action = pair.getFirst(); Throwable e = pair.getSecond(); LOG.error("During running " + action, e); } } } private void beforeCommitHandler() { actionsWhenAllDocumentsAreCommitted.put(PERFORM_ALWAYS_KEY, EmptyRunnable.getInstance()); // to prevent listeners from registering new actions during firing } private void checkWeAreOutsideAfterCommitHandler() { if (isInsideCommitHandler()) { throw new IncorrectOperationException("You must not call performWhenAllCommitted()/cancelAndRunWhenCommitted() from within after-commit handler"); } } private boolean isInsideCommitHandler() { return actionsWhenAllDocumentsAreCommitted.get(PERFORM_ALWAYS_KEY) == EmptyRunnable.getInstance(); } @Override public void addListener(@Nonnull Listener listener) { myListeners.add(listener); } @Override public void removeListener(@Nonnull Listener listener) { myListeners.remove(listener); } @Override public boolean isDocumentBlockedByPsi(@Nonnull Document doc) { return false; } @Override public void doPostponedOperationsAndUnblockDocument(@Nonnull Document doc) { } void fireDocumentCreated(@Nonnull Document document, PsiFile file) { myProject.getMessageBus().syncPublisher(PsiDocumentListener.TOPIC).documentCreated(document, file, myProject); for (Listener listener : myListeners) { listener.documentCreated(document, file); } } private void fireFileCreated(@Nonnull Document document, @Nonnull PsiFile file) { myProject.getMessageBus().syncPublisher(PsiDocumentListener.TOPIC).fileCreated(file, document); for (Listener listener : myListeners) { listener.fileCreated(file, document); } } @Override @Nonnull public CharSequence getLastCommittedText(@Nonnull Document document) { return getLastCommittedDocument(document).getImmutableCharSequence(); } @Override public long getLastCommittedStamp(@Nonnull Document document) { return getLastCommittedDocument(getTopLevelDocument(document)).getModificationStamp(); } @Override @Nullable public Document getLastCommittedDocument(@Nonnull PsiFile file) { Document document = getDocument(file); return document == null ? null : getLastCommittedDocument(document); } @Nonnull public DocumentEx getLastCommittedDocument(@Nonnull Document document) { if (document instanceof FrozenDocument) return (DocumentEx)document; if (document instanceof DocumentWindow) { DocumentWindow window = (DocumentWindow)document; Document delegate = window.getDelegate(); if (delegate instanceof FrozenDocument) return (DocumentEx)window; if (!window.isValid()) { throw new AssertionError("host committed: " + isCommitted(delegate) + ", window=" + window); } UncommittedInfo info = myUncommittedInfos.get(delegate); DocumentWindow answer = info == null ? null : info.myFrozenWindows.get(document); if (answer == null) answer = freezeWindow(window); if (info != null) answer = ConcurrencyUtil.cacheOrGet(info.myFrozenWindows, window, answer); return (DocumentEx)answer; } assert document instanceof DocumentImpl; UncommittedInfo info = myUncommittedInfos.get(document); return info != null ? info.myFrozen : ((DocumentImpl)document).freeze(); } @Nonnull protected DocumentWindow freezeWindow(@Nonnull DocumentWindow document) { throw new UnsupportedOperationException(); } @Nonnull public List<DocumentEvent> getEventsSinceCommit(@Nonnull Document document) { assert document instanceof DocumentImpl : document; UncommittedInfo info = myUncommittedInfos.get(document); if (info != null) { //noinspection unchecked return (List<DocumentEvent>)info.myEvents.clone(); } return Collections.emptyList(); } @Override @Nonnull public Document[] getUncommittedDocuments() { ApplicationManager.getApplication().assertReadAccessAllowed(); //noinspection UnnecessaryLocalVariable Document[] documents = myUncommittedDocuments.toArray(Document.EMPTY_ARRAY); return documents; // java.util.ConcurrentHashMap.keySet().toArray() guaranteed to return array with no nulls } boolean isInUncommittedSet(@Nonnull Document document) { return myUncommittedDocuments.contains(getTopLevelDocument(document)); } @Override public boolean isUncommited(@Nonnull Document document) { return !isCommitted(document); } @Override public boolean isCommitted(@Nonnull Document document) { document = getTopLevelDocument(document); if (getSynchronizer().isInSynchronization(document)) return true; return (!(document instanceof DocumentEx) || !((DocumentEx)document).isInEventsHandling()) && !isInUncommittedSet(document); } @Nonnull private static Document getTopLevelDocument(@Nonnull Document document) { return document instanceof DocumentWindow ? ((DocumentWindow)document).getDelegate() : document; } @Override public boolean hasUncommitedDocuments() { return !myIsCommitInProgress && !myUncommittedDocuments.isEmpty(); } @Override public void beforeDocumentChange(@Nonnull DocumentEvent event) { if (myStopTrackingDocuments || myProject.isDisposed()) return; final Document document = event.getDocument(); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); boolean isRelevant = virtualFile != null && isRelevant(virtualFile); if (document instanceof DocumentImpl && !myUncommittedInfos.containsKey(document)) { myUncommittedInfos.put(document, new UncommittedInfo((DocumentImpl)document)); } final FileViewProvider viewProvider = getCachedViewProvider(document); boolean inMyProject = viewProvider != null && viewProvider.getManager() == myPsiManager; if (!isRelevant || !inMyProject) { return; } final List<PsiFile> files = viewProvider.getAllFiles(); PsiFile psiCause = null; for (PsiFile file : files) { if (file == null) { throw new AssertionError("View provider " + viewProvider + " (" + viewProvider.getClass() + ") returned null in its files array: " + files + " for file " + viewProvider.getVirtualFile()); } if (PsiToDocumentSynchronizer.isInsideAtomicChange(file)) { psiCause = file; } } if (psiCause == null) { beforeDocumentChangeOnUnlockedDocument(viewProvider); } } protected void beforeDocumentChangeOnUnlockedDocument(@Nonnull final FileViewProvider viewProvider) { } @Override public void documentChanged(@Nonnull DocumentEvent event) { if (myStopTrackingDocuments || myProject.isDisposed()) return; final Document document = event.getDocument(); VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); boolean isRelevant = virtualFile != null && isRelevant(virtualFile); final FileViewProvider viewProvider = getCachedViewProvider(document); if (viewProvider == null) { handleCommitWithoutPsi(document); return; } boolean inMyProject = viewProvider.getManager() == myPsiManager; if (!isRelevant || !inMyProject) { clearUncommittedInfo(document); return; } List<PsiFile> files = viewProvider.getAllFiles(); if (files.isEmpty()) { handleCommitWithoutPsi(document); return; } boolean commitNecessary = files.stream().noneMatch(file -> PsiToDocumentSynchronizer.isInsideAtomicChange(file) || !(file instanceof PsiFileImpl)); boolean forceCommit = ApplicationManager.getApplication().hasWriteAction(ExternalChangeAction.class) && (SystemProperties.getBooleanProperty("idea.force.commit.on.external.change", false) || ApplicationManager.getApplication().isHeadlessEnvironment() && !ApplicationManager.getApplication().isUnitTestMode()); // Consider that it's worth to perform complete re-parse instead of merge if the whole document text is replaced and // current document lines number is roughly above 5000. This makes sense in situations when external change is performed // for the huge file (that causes the whole document to be reloaded and 'merge' way takes a while to complete). if (event.isWholeTextReplaced() && document.getTextLength() > 100000) { document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE); } if (commitNecessary) { assert !(document instanceof DocumentWindow); myUncommittedDocuments.add(document); if (forceCommit) { commitDocument(document); } else if (!document.isInBulkUpdate() && myPerformBackgroundCommit) { myDocumentCommitProcessor.commitAsynchronously(myProject, document, event, TransactionGuard.getInstance().getContextTransaction()); } } else { clearUncommittedInfo(document); } } @Override public void bulkUpdateStarting(@Nonnull Document document) { document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE); } @Override public void bulkUpdateFinished(@Nonnull Document document) { myDocumentCommitProcessor.commitAsynchronously(myProject, document, "Bulk update finished", TransactionGuard.getInstance().getContextTransaction()); } class PriorityEventCollector implements PrioritizedInternalDocumentListener { @Override public int getPriority() { return EditorDocumentPriorities.RANGE_MARKER; } @Override public void moveTextHappened(@Nonnull Document document, int start, int end, int base) { UncommittedInfo info = myUncommittedInfos.get(document); if (info != null) { info.myEvents.add(new RetargetRangeMarkers(document, start, end, base)); } } @Override public void documentChanged(@Nonnull DocumentEvent event) { UncommittedInfo info = myUncommittedInfos.get(event.getDocument()); if (info != null) { info.myEvents.add(event); } } } void handleCommitWithoutPsi(@Nonnull Document document) { final UncommittedInfo prevInfo = clearUncommittedInfo(document); if (prevInfo == null) { return; } myUncommittedDocuments.remove(document); if (!myProject.isInitialized() || myProject.isDisposed() || myProject.isDefault()) { return; } VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile != null) { FileManager fileManager = getFileManager(); FileViewProvider viewProvider = fileManager.findCachedViewProvider(virtualFile); if (viewProvider != null) { // we can end up outside write action here if the document has forUseInNonAWTThread=true ApplicationManager.getApplication().runWriteAction((ExternalChangeAction)() -> ((AbstractFileViewProvider)viewProvider).onContentReload()); } else if (FileIndexFacade.getInstance(myProject).isInContent(virtualFile)) { ApplicationManager.getApplication().runWriteAction((ExternalChangeAction)() -> ((FileManagerImpl)fileManager).firePropertyChangedForUnloadedPsi()); } } runAfterCommitActions(document); } @Nullable private UncommittedInfo clearUncommittedInfo(@Nonnull Document document) { UncommittedInfo info = myUncommittedInfos.remove(document); if (info != null) { getSmartPointerManager().updatePointers(document, info.myFrozen, info.myEvents); } return info; } private SmartPointerManagerImpl getSmartPointerManager() { return (SmartPointerManagerImpl)SmartPointerManager.getInstance(myProject); } private boolean isRelevant(@Nonnull VirtualFile virtualFile) { return !myProject.isDisposed() && !virtualFile.getFileType().isBinary(); } public static boolean checkConsistency(@Nonnull PsiFile psiFile, @Nonnull Document document) { //todo hack if (psiFile.getVirtualFile() == null) return true; CharSequence editorText = document.getCharsSequence(); int documentLength = document.getTextLength(); if (psiFile.textMatches(editorText)) { LOG.assertTrue(psiFile.getTextLength() == documentLength); return true; } char[] fileText = psiFile.textToCharArray(); @SuppressWarnings("NonConstantStringShouldBeStringBuffer") @NonNls String error = "File '" + psiFile.getName() + "' text mismatch after reparse. " + "File length=" + fileText.length + "; Doc length=" + documentLength + "\n"; int i = 0; for (; i < documentLength; i++) { if (i >= fileText.length) { error += "editorText.length > psiText.length i=" + i + "\n"; break; } if (i >= editorText.length()) { error += "editorText.length > psiText.length i=" + i + "\n"; break; } if (editorText.charAt(i) != fileText[i]) { error += "first unequal char i=" + i + "\n"; break; } } //error += "*********************************************" + "\n"; //if (i <= 500){ // error += "Equal part:" + editorText.subSequence(0, i) + "\n"; //} //else{ // error += "Equal part start:\n" + editorText.subSequence(0, 200) + "\n"; // error += "................................................" + "\n"; // error += "................................................" + "\n"; // error += "................................................" + "\n"; // error += "Equal part end:\n" + editorText.subSequence(i - 200, i) + "\n"; //} error += "*********************************************" + "\n"; error += "Editor Text tail:(" + (documentLength - i) + ")\n";// + editorText.subSequence(i, Math.min(i + 300, documentLength)) + "\n"; error += "*********************************************" + "\n"; error += "Psi Text tail:(" + (fileText.length - i) + ")\n"; error += "*********************************************" + "\n"; if (document instanceof DocumentWindow) { error += "doc: '" + document.getText() + "'\n"; error += "psi: '" + psiFile.getText() + "'\n"; error += "ast: '" + psiFile.getNode().getText() + "'\n"; error += psiFile.getLanguage() + "\n"; PsiElement context = InjectedLanguageManager.getInstance(psiFile.getProject()).getInjectionHost(psiFile); if (context != null) { error += "context: " + context + "; text: '" + context.getText() + "'\n"; error += "context file: " + context.getContainingFile() + "\n"; } error += "document window ranges: " + Arrays.asList(((DocumentWindow)document).getHostRanges()) + "\n"; } LOG.error(error); //document.replaceString(0, documentLength, psiFile.getText()); return false; } @VisibleForTesting @TestOnly public void clearUncommittedDocuments() { myUncommittedInfos.clear(); myUncommittedDocuments.clear(); mySynchronizer.cleanupForNextTest(); } @TestOnly public void disableBackgroundCommit(@Nonnull Disposable parentDisposable) { assert myPerformBackgroundCommit; myPerformBackgroundCommit = false; Disposer.register(parentDisposable, () -> myPerformBackgroundCommit = true); } @Override public void dispose() { clearUncommittedDocuments(); } @Nonnull public PsiToDocumentSynchronizer getSynchronizer() { return mySynchronizer; } @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod") public void reparseFileFromText(@Nonnull PsiFileImpl file) { ApplicationManager.getApplication().assertIsDispatchThread(); if (isCommitInProgress()) throw new IllegalStateException("Re-entrant commit is not allowed"); FileElement node = file.calcTreeElement(); CharSequence text = node.getChars(); ourIsFullReparseInProgress = true; try { WriteAction.run(() -> { ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator(); if (indicator == null) indicator = new EmptyProgressIndicator(); DiffLog log = BlockSupportImpl.makeFullParse(file, node, text, indicator, text).log; log.doActualPsiChange(file); file.getViewProvider().contentsSynchronized(); }); } finally { ourIsFullReparseInProgress = false; } } private static class UncommittedInfo { private final FrozenDocument myFrozen; private final ArrayList<DocumentEvent> myEvents = new ArrayList<>(); private final ConcurrentMap<DocumentWindow, DocumentWindow> myFrozenWindows = ContainerUtil.newConcurrentMap(); private UncommittedInfo(@Nonnull DocumentImpl original) { myFrozen = original.freeze(); } } @Nonnull List<BooleanRunnable> reparseChangedInjectedFragments(@Nonnull Document hostDocument, @Nonnull PsiFile hostPsiFile, @Nonnull TextRange range, @Nonnull ProgressIndicator indicator, @Nonnull ASTNode oldRoot, @Nonnull ASTNode newRoot) { return Collections.emptyList(); } @TestOnly public boolean isDefaultProject() { return myProject.isDefault(); } }
apache-2.0
czyzby/gdx-lml
uedi/src/test/java/com/github/czyzby/uedi/test/ambiguous/AmbiguousInjector.java
445
package com.github.czyzby.uedi.test.ambiguous; import com.github.czyzby.uedi.stereotype.Singleton; public class AmbiguousInjector implements Singleton { private Ambiguous ambiguousA; private Ambiguous ambiguousB; private Ambiguous named; public Ambiguous getA() { return ambiguousA; } public Ambiguous getB() { return ambiguousB; } public Ambiguous getNamed() { return named; } }
apache-2.0
mikessh/mageri
src/main/java/com/antigenomics/mageri/core/variant/model/ErrorRateEstimate.java
1639
/* * Copyright 2014-2016 Mikhail Shugay * * 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.antigenomics.mageri.core.variant.model; import java.io.Serializable; import java.util.Arrays; public class ErrorRateEstimate implements Serializable { public static ErrorRateEstimate createDummy(int statisticCount) { double[] statistics = new double[statisticCount]; Arrays.fill(statistics, Double.NaN); return new ErrorRateEstimate(0.0, statistics); } private final double[] statistics; private final double errorRate; public ErrorRateEstimate(double errorRate, double... statistics) { this.errorRate = errorRate; this.statistics = statistics; } public double[] getStatistics() { return statistics; } public double getErrorRate() { return errorRate; } public String getErrorRateEstimateRowPart() { String res = ""; if (statistics.length > 0) { for (double statistic : statistics) { res += "\t" + (float) statistic; } } return res; } }
apache-2.0
consulo/consulo-properties
src/main/java/com/intellij/lang/properties/PropertiesHighlightingLexer.java
1637
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.lang.properties; import com.intellij.lang.properties.parsing.PropertiesTokenTypes; import com.intellij.lang.properties.parsing._PropertiesLexer; import com.intellij.lexer.LayeredLexer; import com.intellij.lexer.StringLiteralLexer; import com.intellij.psi.tree.IElementType; /** * @author cdr */ public class PropertiesHighlightingLexer extends LayeredLexer{ public PropertiesHighlightingLexer() { super(new _PropertiesLexer()); registerSelfStoppingLayer(new StringLiteralLexer(StringLiteralLexer.NO_QUOTE_CHAR, PropertiesTokenTypes.VALUE_CHARACTERS, true, "#!=:"), new IElementType[]{PropertiesTokenTypes.VALUE_CHARACTERS}, IElementType.EMPTY_ARRAY); registerSelfStoppingLayer(new StringLiteralLexer(StringLiteralLexer.NO_QUOTE_CHAR, PropertiesTokenTypes.KEY_CHARACTERS, true, "#!=: "), new IElementType[]{PropertiesTokenTypes.KEY_CHARACTERS}, IElementType.EMPTY_ARRAY); } }
apache-2.0
OgaworldEX/ORS
src/http/HttpMessage.java
703
package http; import java.io.Serializable; public class HttpMessage implements Serializable{ private static final long serialVersionUID = -1114764212343485987L; private HttpRequest httpRequest; private HttpResponse httpResponse; public HttpMessage(HttpRequest request){ this.httpRequest = request; } public HttpRequest getHttpRequest() { return httpRequest; } public void setHttpRequest(HttpRequest httpRequest) { this.httpRequest = httpRequest; } public HttpResponse getHttpResponse() { return httpResponse; } public void setHttpResponse(HttpResponse httpResponse) { this.httpResponse = httpResponse; } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-people/v1/1.31.0/com/google/api/services/people/v1/model/DeleteContactPhotoResponse.java
2351
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.people.v1.model; /** * The response for deleting a contact's photo. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the People API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class DeleteContactPhotoResponse extends com.google.api.client.json.GenericJson { /** * The updated person, if person_fields is set in the DeleteContactPhotoRequest; otherwise this * will be unset. * The value may be {@code null}. */ @com.google.api.client.util.Key private Person person; /** * The updated person, if person_fields is set in the DeleteContactPhotoRequest; otherwise this * will be unset. * @return value or {@code null} for none */ public Person getPerson() { return person; } /** * The updated person, if person_fields is set in the DeleteContactPhotoRequest; otherwise this * will be unset. * @param person person or {@code null} for none */ public DeleteContactPhotoResponse setPerson(Person person) { this.person = person; return this; } @Override public DeleteContactPhotoResponse set(String fieldName, Object value) { return (DeleteContactPhotoResponse) super.set(fieldName, value); } @Override public DeleteContactPhotoResponse clone() { return (DeleteContactPhotoResponse) super.clone(); } }
apache-2.0
apache/incubator-asterixdb
asterixdb/asterix-common/src/main/java/org/apache/asterix/common/utils/StorageConstants.java
3098
/* * 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.asterix.common.utils; import java.util.LinkedHashMap; import java.util.Map; import org.apache.hyracks.storage.am.common.api.ITreeIndexFrame; import org.apache.hyracks.storage.am.lsm.common.impls.AbstractLSMIndexFileManager; import org.apache.hyracks.storage.am.lsm.common.impls.ConcurrentMergePolicyFactory; /** * A static class that stores storage constants */ public class StorageConstants { public static final String STORAGE_ROOT_DIR_NAME = "storage"; public static final String PARTITION_DIR_PREFIX = "partition_"; /** * Any file that shares the same directory as the LSM index files must * begin with ".". Otherwise {@link AbstractLSMIndexFileManager} will try to * use them as index files. */ public static final String INDEX_CHECKPOINT_FILE_PREFIX = ".idx_checkpoint_"; public static final String METADATA_FILE_NAME = ".metadata"; public static final String MASK_FILE_PREFIX = ".mask_"; public static final String COMPONENT_MASK_FILE_PREFIX = MASK_FILE_PREFIX + "C_"; public static final float DEFAULT_TREE_FILL_FACTOR = 1.00f; public static final String DEFAULT_COMPACTION_POLICY_NAME = ConcurrentMergePolicyFactory.NAME; public static final String DEFAULT_FILTERED_DATASET_COMPACTION_POLICY_NAME = "correlated-prefix"; public static final Map<String, String> DEFAULT_COMPACTION_POLICY_PROPERTIES; /** * The storage version of AsterixDB related artifacts (e.g. log files, checkpoint files, etc..). */ private static final int LOCAL_STORAGE_VERSION = 5; /** * The storage version of AsterixDB stack. */ public static final int VERSION = LOCAL_STORAGE_VERSION + ITreeIndexFrame.Constants.VERSION; static { DEFAULT_COMPACTION_POLICY_PROPERTIES = new LinkedHashMap<>(); DEFAULT_COMPACTION_POLICY_PROPERTIES.put(ConcurrentMergePolicyFactory.MAX_COMPONENT_COUNT, "30"); DEFAULT_COMPACTION_POLICY_PROPERTIES.put(ConcurrentMergePolicyFactory.MIN_MERGE_COMPONENT_COUNT, "3"); DEFAULT_COMPACTION_POLICY_PROPERTIES.put(ConcurrentMergePolicyFactory.MAX_MERGE_COMPONENT_COUNT, "10"); DEFAULT_COMPACTION_POLICY_PROPERTIES.put(ConcurrentMergePolicyFactory.SIZE_RATIO, "1.2"); } private StorageConstants() { } }
apache-2.0
gemxd/gemfirexd-oss
gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/persistence/soplog/ByteComparator.java
1907
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. 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. See accompanying * LICENSE file. */ package com.gemstone.gemfire.internal.cache.persistence.soplog; import org.apache.hadoop.hbase.util.Bytes; import com.gemstone.gemfire.internal.cache.persistence.soplog.SortedReader.SerializedComparator; /** * Compares objects byte-by-byte. This is fast and sufficient for cases when * lexicographic ordering is not important or the serialization is order- * preserving. * * @author bakera */ public class ByteComparator implements SerializedComparator { @Override public int compare(byte[] rhs, byte[] lhs) { return compare(rhs, 0, rhs.length, lhs, 0, lhs.length); } @Override public int compare(byte[] r, int rOff, int rLen, byte[] l, int lOff, int lLen) { return compareBytes(r, rOff, rLen, l, lOff, lLen); } /** * Compares two byte arrays element-by-element. * * @param r the right array * @param rOff the offset of r * @param rLen the length of r to compare * @param l the left array * @param lOff the offset of l * @param lLen the length of l to compare * @return -1 if r < l; 0 if r == l; 1 if r > 1 */ public static int compareBytes(byte[] r, int rOff, int rLen, byte[] l, int lOff, int lLen) { return Bytes.compareTo(r, rOff, rLen, l, lOff, lLen); } }
apache-2.0
sergio11/struts2-hibernate
ejercicio4-web/src/main/java/listeners/GuiceListener.java
1267
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package listeners; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Singleton; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; import com.google.inject.struts2.Struts2GuicePluginModule; import guice.EJBModule; import org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter; /** * * @author sergio */ public class GuiceListener extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector(new Struts2GuicePluginModule(), new ServletModule() { @Override protected void configureServlets() { // Struts 2 setup bind(StrutsPrepareAndExecuteFilter.class).in(Singleton.class); filter("/*").through(StrutsPrepareAndExecuteFilter.class); } }, new EJBModule() ); } }
apache-2.0
yhhyes/coolweather
src/com/coolweather/app/db/CoolWeatherDB.java
3550
package com.coolweather.app.db; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.coolweather.app.model.City; import com.coolweather.app.model.County; import com.coolweather.app.model.Province; public class CoolWeatherDB { /* * Êý¾Ý¿âÃû */ public static final String DB_NAME = "cool_weather"; /* * Êý¾Ý¿â°æ±¾ */ public static final int VERSION = 1; private static CoolWeatherDB coolWeatherDB; private SQLiteDatabase db; /* * ½«¹¹Ôì·½·¨Ë½Óл¯ */ private CoolWeatherDB(Context context){ CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context,DB_NAME,null,VERSION); db = dbHelper.getWritableDatabase(); } /* * »ñÈ¡CoolWeatherDBʵÀý * */ public synchronized static CoolWeatherDB getInstance(Context context){ if(coolWeatherDB == null){ coolWeatherDB = new CoolWeatherDB(context); } return coolWeatherDB; } /* * ½«ProvinceʵÀý´æ´¢µ½Êý¾Ý¿â¡£ * */ public void saveProvince(Province province){ if (province !=null){ ContentValues values = new ContentValues(); values.put("province_name", province.getProvinceName()); db.insert("Province", null, values); } } /* * ´ÓÊý¾Ý¿â¶Áȡȫ¹úËùÓÐÊ¡·ÝµÄÐÅÏ¢¡£ * */ public List<Province> loadProvinces(){ List<Province>list = new ArrayList<Province>(); Cursor cursor = db.query("Province", null, null,null, null, null, null); if(cursor.moveToFirst()){ do{ Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); list.add(province); }while(cursor.moveToNext()); } return list; } /* * ½«CityÊý¾Ý´æ´¢µ½Êý¾Ý¿âÖÐ */ public void saveCity(City city) { if(city !=null){ ContentValues values = new ContentValues(); values.put("city_name", city.getCityName()); values.put("province_id", city.getProvinceId()); db.insert("City", null, values); } } /* * ´ÓÊý¾Ý¿â¶ÁȡijʡÏÂËùÓеijÇÊÐÐÅÏ¢ * */ public List<City> loadCities(int provinceId){ List<City>list = new ArrayList<City>(); Cursor cursor = db.query("City", null, "province_id = ?",new String[] {String.valueOf(provinceId) },null,null,null); if(cursor.moveToFirst()){ do { City city = new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setProvinceId(provinceId); list.add(city); }while(cursor.moveToNext()); } return list; } /* * ½«CountyʵÀý´æ´¢µ½Êý¾Ý¿â¡£ */ public void saveCounty(County county){ if(county !=null){ ContentValues values = new ContentValues(); values.put("county_name", county.getCountyName()); values.put("city_id", county.getCityId()); db.insert("County", null, values); } } /* * ´ÓÊý¾Ý¿â¶Áȡij³ÇÊÐÏÂËùÓеÄÏØÐÅÏ¢¡£ */ public List<County> loadCounty(int cityId){ List<County> list = new ArrayList<County>(); Cursor cursor = db.query("County", null, "city_id = ?", new String [] {String.valueOf(cityId)}, null, null,null); if (cursor.moveToFirst()){ do{ County county = new County(); county.setCityId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); county.setCityId(cityId); list.add(county); }while(cursor.moveToNext()); } return list; } }
apache-2.0
googleapis/java-dlp
proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/ColorOrBuilder.java
1515
/* * 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/privacy/dlp/v2/dlp.proto package com.google.privacy.dlp.v2; public interface ColorOrBuilder extends // @@protoc_insertion_point(interface_extends:google.privacy.dlp.v2.Color) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The amount of red in the color as a value in the interval [0, 1]. * </pre> * * <code>float red = 1;</code> * * @return The red. */ float getRed(); /** * * * <pre> * The amount of green in the color as a value in the interval [0, 1]. * </pre> * * <code>float green = 2;</code> * * @return The green. */ float getGreen(); /** * * * <pre> * The amount of blue in the color as a value in the interval [0, 1]. * </pre> * * <code>float blue = 3;</code> * * @return The blue. */ float getBlue(); }
apache-2.0
OSEHRA/ISAAC
core/mojo/src/main/java/sh/isaac/mojo/Shutdown.java
2748
/* * 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. * * Contributions from 2013-2017 where performed either by US government * employees, or under US Veterans Health Administration contracts. * * US Veterans Health Administration contributions by government employees * are work of the U.S. Government and are not subject to copyright * protection in the United States. Portions contributed by government * employees are USGovWork (17USC §105). Not subject to copyright. * * Contribution by contractors to the US Veterans Health Administration * during this period are contractually contributed under the * Apache License, Version 2.0. * * See: https://www.usa.gov/government-works * * Contributions prior to 2013: * * Copyright (C) International Health Terminology Standards Development Organisation. * Licensed under the Apache License, Version 2.0. * */ package sh.isaac.mojo; //~--- non-JDK imports -------------------------------------------------------- import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import sh.isaac.api.LookupService; //~--- classes ---------------------------------------------------------------- /** * Goal which shuts down an open data store. */ @Mojo( defaultPhase = LifecyclePhase.PROCESS_RESOURCES, name = "shutdown-isaac" ) public class Shutdown extends AbstractMojo { /** * Execute. * * @throws MojoExecutionException the mojo execution exception */ @Override public void execute() throws MojoExecutionException { Headless.setHeadless(); try { long start = System.currentTimeMillis(); getLog().info("Shutdown terminology store"); // ASSUMES setup has run already getLog().info(" Shutting Down"); LookupService.shutdownSystem(); getLog().info("Done shutting down terminology store in " + (System.currentTimeMillis() - start) + " ms"); } catch (final Exception e) { throw new MojoExecutionException("Database shutdown failure", e); } } }
apache-2.0
OSUCartography/JMapProjLib
src/com/jhlabs/map/proj/McBrydeThomasFlatPolarSinusoidalProjection.java
2052
/* Copyright 2014 Bojan Savric 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.jhlabs.map.proj; import com.jhlabs.map.MapMath; import java.awt.geom.*; public class McBrydeThomasFlatPolarSinusoidalProjection extends PseudoCylindricalProjection { private static final double m = 0.5; private static final double n = 1 + 0.25 * Math.PI; private static final double C_y = Math.sqrt((m + 1) / n); private static final double C_x = C_y / (m + 1); private static final int MAX_ITER = 8; private static final double LOOP_TOL = 1e-7; public Point2D.Double project(double lam, double phi, Point2D.Double xy) { int i; double k, V; k = n * Math.sin(phi); for (i = MAX_ITER; i > 0;) { phi -= V = (m * phi + Math.sin(phi) - k) / (m + Math.cos(phi)); if (Math.abs(V) < LOOP_TOL) { break; } --i; } if (i == 0) { throw new ProjectionException("F_ERROR"); } xy.x = C_x * lam * (m + Math.cos(phi)); xy.y = C_y * phi; return xy; } public Point2D.Double projectInverse(double x, double y, Point2D.Double lp) { y /= C_y; lp.y = MapMath.asin((m * y + Math.sin(y)) / n); lp.x = x / (C_x * (m + Math.cos(y))); return lp; } public boolean hasInverse() { return true; } public boolean isEqualArea() { return true; } public String toString() { return "McBryde-Thomas Flat Polar Sinusoidal"; } }
apache-2.0
gstevey/gradle
subprojects/language-java/src/main/java/org/gradle/api/internal/tasks/compile/incremental/cache/CompileCaches.java
1295
/* * Copyright 2014 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.gradle.api.internal.tasks.compile.incremental.cache; import org.gradle.api.internal.tasks.compile.incremental.analyzer.ClassAnalysisCache; import org.gradle.api.internal.tasks.compile.incremental.deps.LocalClassSetAnalysisStore; import org.gradle.api.internal.tasks.compile.incremental.jar.JarSnapshotCache; import org.gradle.api.internal.tasks.compile.incremental.jar.LocalJarClasspathSnapshotStore; public interface CompileCaches { ClassAnalysisCache getClassAnalysisCache(); JarSnapshotCache getJarSnapshotCache(); LocalJarClasspathSnapshotStore getLocalJarClasspathSnapshotStore(); LocalClassSetAnalysisStore getLocalClassSetAnalysisStore(); }
apache-2.0
gawkermedia/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201509/rm/AccessReason.java
2989
/** * AccessReason.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201509.rm; public class AccessReason implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected AccessReason(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _OWNED = "OWNED"; public static final java.lang.String _SHARED = "SHARED"; public static final java.lang.String _LICENSED = "LICENSED"; public static final java.lang.String _SUBSCRIBED = "SUBSCRIBED"; public static final AccessReason OWNED = new AccessReason(_OWNED); public static final AccessReason SHARED = new AccessReason(_SHARED); public static final AccessReason LICENSED = new AccessReason(_LICENSED); public static final AccessReason SUBSCRIBED = new AccessReason(_SUBSCRIBED); public java.lang.String getValue() { return _value_;} public static AccessReason fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { AccessReason enumeration = (AccessReason) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static AccessReason fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(AccessReason.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/rm/v201509", "AccessReason")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
apache-2.0
amzn/exoplayer-amazon-port
library/common/src/main/java/com/google/android/exoplayer2/text/Cue.java
24639
/* * Copyright (C) 2016 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; import android.graphics.Bitmap; import android.graphics.Color; import android.text.Layout; import android.text.Layout.Alignment; import androidx.annotation.ColorInt; import androidx.annotation.IntDef; import androidx.annotation.Nullable; import com.google.android.exoplayer2.util.Assertions; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** Contains information about a specific cue, including textual content and formatting data. */ // This class shouldn't be sub-classed. If a subtitle format needs additional fields, either they // should be generic enough to be added here, or the format-specific decoder should pass the // information around in a sidecar object. public final class Cue { /** The empty cue. */ public static final Cue EMPTY = new Cue.Builder().setText("").build(); /** An unset position, width or size. */ // Note: We deliberately don't use Float.MIN_VALUE because it's positive & very close to zero. public static final float DIMEN_UNSET = -Float.MAX_VALUE; /** * The type of anchor, which may be unset. One of {@link #TYPE_UNSET}, {@link #ANCHOR_TYPE_START}, * {@link #ANCHOR_TYPE_MIDDLE} or {@link #ANCHOR_TYPE_END}. */ @Documented @Retention(RetentionPolicy.SOURCE) @IntDef({TYPE_UNSET, ANCHOR_TYPE_START, ANCHOR_TYPE_MIDDLE, ANCHOR_TYPE_END}) public @interface AnchorType {} /** An unset anchor, line, text size or vertical type value. */ public static final int TYPE_UNSET = Integer.MIN_VALUE; /** * Anchors the left (for horizontal positions) or top (for vertical positions) edge of the cue * box. */ public static final int ANCHOR_TYPE_START = 0; /** * Anchors the middle of the cue box. */ public static final int ANCHOR_TYPE_MIDDLE = 1; /** * Anchors the right (for horizontal positions) or bottom (for vertical positions) edge of the cue * box. */ public static final int ANCHOR_TYPE_END = 2; /** * The type of line, which may be unset. One of {@link #TYPE_UNSET}, {@link #LINE_TYPE_FRACTION} * or {@link #LINE_TYPE_NUMBER}. */ @Documented @Retention(RetentionPolicy.SOURCE) @IntDef({TYPE_UNSET, LINE_TYPE_FRACTION, LINE_TYPE_NUMBER}) public @interface LineType {} /** * Value for {@link #lineType} when {@link #line} is a fractional position. */ public static final int LINE_TYPE_FRACTION = 0; /** * Value for {@link #lineType} when {@link #line} is a line number. */ public static final int LINE_TYPE_NUMBER = 1; /** * The type of default text size for this cue, which may be unset. One of {@link #TYPE_UNSET}, * {@link #TEXT_SIZE_TYPE_FRACTIONAL}, {@link #TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING} or {@link * #TEXT_SIZE_TYPE_ABSOLUTE}. */ @Documented @Retention(RetentionPolicy.SOURCE) @IntDef({ TYPE_UNSET, TEXT_SIZE_TYPE_FRACTIONAL, TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING, TEXT_SIZE_TYPE_ABSOLUTE }) public @interface TextSizeType {} /** Text size is measured as a fraction of the viewport size minus the view padding. */ public static final int TEXT_SIZE_TYPE_FRACTIONAL = 0; /** Text size is measured as a fraction of the viewport size, ignoring the view padding */ public static final int TEXT_SIZE_TYPE_FRACTIONAL_IGNORE_PADDING = 1; /** Text size is measured in number of pixels. */ public static final int TEXT_SIZE_TYPE_ABSOLUTE = 2; /** * The type of vertical layout for this cue, which may be unset (i.e. horizontal). One of {@link * #TYPE_UNSET}, {@link #VERTICAL_TYPE_RL} or {@link #VERTICAL_TYPE_LR}. */ @Documented @Retention(RetentionPolicy.SOURCE) @IntDef({ TYPE_UNSET, VERTICAL_TYPE_RL, VERTICAL_TYPE_LR, }) public @interface VerticalType {} /** Vertical right-to-left (e.g. for Japanese). */ public static final int VERTICAL_TYPE_RL = 1; /** Vertical left-to-right (e.g. for Mongolian). */ public static final int VERTICAL_TYPE_LR = 2; /** * The cue text, or null if this is an image cue. Note the {@link CharSequence} may be decorated * with styling spans. */ @Nullable public final CharSequence text; /** The alignment of the cue text within the cue box, or null if the alignment is undefined. */ @Nullable public final Alignment textAlignment; /** The cue image, or null if this is a text cue. */ @Nullable public final Bitmap bitmap; /** * The position of the cue box within the viewport in the direction orthogonal to the writing * direction (determined by {@link #verticalType}), or {@link #DIMEN_UNSET}. When set, the * interpretation of the value depends on the value of {@link #lineType}. * * <p>The measurement direction depends on {@link #verticalType}: * * <ul> * <li>For {@link #TYPE_UNSET} (i.e. horizontal), this is the vertical position relative to the * top of the viewport. * <li>For {@link #VERTICAL_TYPE_LR} this is the horizontal position relative to the left of the * viewport. * <li>For {@link #VERTICAL_TYPE_RL} this is the horizontal position relative to the right of * the viewport. * </ul> */ public final float line; /** * The type of the {@link #line} value. * * <ul> * <li>{@link #LINE_TYPE_FRACTION} indicates that {@link #line} is a fractional position within * the viewport (measured to the part of the cue box determined by {@link #lineAnchor}). * <li>{@link #LINE_TYPE_NUMBER} indicates that {@link #line} is a viewport line number. The * viewport is divided into lines (each equal in size to the first line of the cue box). The * cue box is positioned to align with the viewport lines as follows: * <ul> * <li>{@link #lineAnchor}) is ignored. * <li>When {@code line} is greater than or equal to 0 the first line in the cue box is * aligned with a viewport line, with 0 meaning the first line of the viewport. * <li>When {@code line} is negative the last line in the cue box is aligned with a * viewport line, with -1 meaning the last line of the viewport. * <li>For horizontal text the start and end of the viewport are the top and bottom * respectively. * </ul> * </ul> */ public final @LineType int lineType; /** * The cue box anchor positioned by {@link #line} when {@link #lineType} is {@link * #LINE_TYPE_FRACTION}. * * <p>One of: * * <ul> * <li>{@link #ANCHOR_TYPE_START} * <li>{@link #ANCHOR_TYPE_MIDDLE} * <li>{@link #ANCHOR_TYPE_END} * <li>{@link #TYPE_UNSET} * </ul> * * <p>For the normal case of horizontal text, {@link #ANCHOR_TYPE_START}, {@link * #ANCHOR_TYPE_MIDDLE} and {@link #ANCHOR_TYPE_END} correspond to the top, middle and bottom of * the cue box respectively. */ public final @AnchorType int lineAnchor; /** * The fractional position of the {@link #positionAnchor} of the cue box within the viewport in * the direction orthogonal to {@link #line}, or {@link #DIMEN_UNSET}. * * <p>The measurement direction depends on {@link #verticalType}. * * <ul> * <li>For {@link #TYPE_UNSET} (i.e. horizontal), this is the horizontal position relative to * the left of the viewport. Note that positioning is relative to the left of the viewport * even in the case of right-to-left text. * <li>For {@link #VERTICAL_TYPE_LR} and {@link #VERTICAL_TYPE_RL} (i.e. vertical), this is the * vertical position relative to the top of the viewport. * </ul> */ public final float position; /** * The cue box anchor positioned by {@link #position}. One of {@link #ANCHOR_TYPE_START}, {@link * #ANCHOR_TYPE_MIDDLE}, {@link #ANCHOR_TYPE_END} and {@link #TYPE_UNSET}. * * <p>For the normal case of horizontal text, {@link #ANCHOR_TYPE_START}, {@link * #ANCHOR_TYPE_MIDDLE} and {@link #ANCHOR_TYPE_END} correspond to the left, middle and right of * the cue box respectively. */ public final @AnchorType int positionAnchor; /** * The size of the cue box in the writing direction specified as a fraction of the viewport size * in that direction, or {@link #DIMEN_UNSET}. */ public final float size; /** * The bitmap height as a fraction of the of the viewport size, or {@link #DIMEN_UNSET} if the * bitmap should be displayed at its natural height given the bitmap dimensions and the specified * {@link #size}. */ public final float bitmapHeight; /** * Specifies whether or not the {@link #windowColor} property is set. */ public final boolean windowColorSet; /** * The fill color of the window. */ public final int windowColor; /** * The default text size type for this cue's text, or {@link #TYPE_UNSET} if this cue has no * default text size. */ public final @TextSizeType int textSizeType; /** * The default text size for this cue's text, or {@link #DIMEN_UNSET} if this cue has no default * text size. */ public final float textSize; /** * The vertical formatting of this Cue, or {@link #TYPE_UNSET} if the cue has no vertical setting * (and so should be horizontal). */ public final @VerticalType int verticalType; /** * The shear angle in degrees to be applied to this Cue, expressed in graphics coordinates. This * results in a skew transform for the block along the inline progression axis. */ public final float shearDegrees; /** * Creates a text cue whose {@link #textAlignment} is null, whose type parameters are set to * {@link #TYPE_UNSET} and whose dimension parameters are set to {@link #DIMEN_UNSET}. * * @param text See {@link #text}. * @deprecated Use {@link Builder}. */ @SuppressWarnings("deprecation") @Deprecated public Cue(CharSequence text) { this( text, /* textAlignment= */ null, /* line= */ DIMEN_UNSET, /* lineType= */ TYPE_UNSET, /* lineAnchor= */ TYPE_UNSET, /* position= */ DIMEN_UNSET, /* positionAnchor= */ TYPE_UNSET, /* size= */ DIMEN_UNSET); } /** * Creates a text cue. * * @param text See {@link #text}. * @param textAlignment See {@link #textAlignment}. * @param line See {@link #line}. * @param lineType See {@link #lineType}. * @param lineAnchor See {@link #lineAnchor}. * @param position See {@link #position}. * @param positionAnchor See {@link #positionAnchor}. * @param size See {@link #size}. * @deprecated Use {@link Builder}. */ @SuppressWarnings("deprecation") @Deprecated public Cue( CharSequence text, @Nullable Alignment textAlignment, float line, @LineType int lineType, @AnchorType int lineAnchor, float position, @AnchorType int positionAnchor, float size) { this( text, textAlignment, line, lineType, lineAnchor, position, positionAnchor, size, /* windowColorSet= */ false, /* windowColor= */ Color.BLACK); } /** * Creates a text cue. * * @param text See {@link #text}. * @param textAlignment See {@link #textAlignment}. * @param line See {@link #line}. * @param lineType See {@link #lineType}. * @param lineAnchor See {@link #lineAnchor}. * @param position See {@link #position}. * @param positionAnchor See {@link #positionAnchor}. * @param size See {@link #size}. * @param textSizeType See {@link #textSizeType}. * @param textSize See {@link #textSize}. * @deprecated Use {@link Builder}. */ @SuppressWarnings("deprecation") @Deprecated public Cue( CharSequence text, @Nullable Alignment textAlignment, float line, @LineType int lineType, @AnchorType int lineAnchor, float position, @AnchorType int positionAnchor, float size, @TextSizeType int textSizeType, float textSize) { this( text, textAlignment, /* bitmap= */ null, line, lineType, lineAnchor, position, positionAnchor, textSizeType, textSize, size, /* bitmapHeight= */ DIMEN_UNSET, /* windowColorSet= */ false, /* windowColor= */ Color.BLACK, /* verticalType= */ TYPE_UNSET, /* shearDegrees= */ 0f); } /** * Creates a text cue. * * @param text See {@link #text}. * @param textAlignment See {@link #textAlignment}. * @param line See {@link #line}. * @param lineType See {@link #lineType}. * @param lineAnchor See {@link #lineAnchor}. * @param position See {@link #position}. * @param positionAnchor See {@link #positionAnchor}. * @param size See {@link #size}. * @param windowColorSet See {@link #windowColorSet}. * @param windowColor See {@link #windowColor}. * @deprecated Use {@link Builder}. */ @Deprecated public Cue( CharSequence text, @Nullable Alignment textAlignment, float line, @LineType int lineType, @AnchorType int lineAnchor, float position, @AnchorType int positionAnchor, float size, boolean windowColorSet, int windowColor) { this( text, textAlignment, /* bitmap= */ null, line, lineType, lineAnchor, position, positionAnchor, /* textSizeType= */ TYPE_UNSET, /* textSize= */ DIMEN_UNSET, size, /* bitmapHeight= */ DIMEN_UNSET, windowColorSet, windowColor, /* verticalType= */ TYPE_UNSET, /* shearDegrees= */ 0f); } private Cue( @Nullable CharSequence text, @Nullable Alignment textAlignment, @Nullable Bitmap bitmap, float line, @LineType int lineType, @AnchorType int lineAnchor, float position, @AnchorType int positionAnchor, @TextSizeType int textSizeType, float textSize, float size, float bitmapHeight, boolean windowColorSet, int windowColor, @VerticalType int verticalType, float shearDegrees) { // Exactly one of text or bitmap should be set. if (text == null) { Assertions.checkNotNull(bitmap); } else { Assertions.checkArgument(bitmap == null); } this.text = text; this.textAlignment = textAlignment; this.bitmap = bitmap; this.line = line; this.lineType = lineType; this.lineAnchor = lineAnchor; this.position = position; this.positionAnchor = positionAnchor; this.size = size; this.bitmapHeight = bitmapHeight; this.windowColorSet = windowColorSet; this.windowColor = windowColor; this.textSizeType = textSizeType; this.textSize = textSize; this.verticalType = verticalType; this.shearDegrees = shearDegrees; } /** Returns a new {@link Cue.Builder} initialized with the same values as this Cue. */ public Builder buildUpon() { return new Cue.Builder(this); } /** A builder for {@link Cue} objects. */ public static final class Builder { @Nullable private CharSequence text; @Nullable private Bitmap bitmap; @Nullable private Alignment textAlignment; private float line; @LineType private int lineType; @AnchorType private int lineAnchor; private float position; @AnchorType private int positionAnchor; @TextSizeType private int textSizeType; private float textSize; private float size; private float bitmapHeight; private boolean windowColorSet; @ColorInt private int windowColor; @VerticalType private int verticalType; private float shearDegrees; public Builder() { text = null; bitmap = null; textAlignment = null; line = DIMEN_UNSET; lineType = TYPE_UNSET; lineAnchor = TYPE_UNSET; position = DIMEN_UNSET; positionAnchor = TYPE_UNSET; textSizeType = TYPE_UNSET; textSize = DIMEN_UNSET; size = DIMEN_UNSET; bitmapHeight = DIMEN_UNSET; windowColorSet = false; windowColor = Color.BLACK; verticalType = TYPE_UNSET; } private Builder(Cue cue) { text = cue.text; bitmap = cue.bitmap; textAlignment = cue.textAlignment; line = cue.line; lineType = cue.lineType; lineAnchor = cue.lineAnchor; position = cue.position; positionAnchor = cue.positionAnchor; textSizeType = cue.textSizeType; textSize = cue.textSize; size = cue.size; bitmapHeight = cue.bitmapHeight; windowColorSet = cue.windowColorSet; windowColor = cue.windowColor; verticalType = cue.verticalType; shearDegrees = cue.shearDegrees; } /** * Sets the cue text. * * <p>Note that {@code text} may be decorated with styling spans. * * @see Cue#text */ public Builder setText(CharSequence text) { this.text = text; return this; } /** * Gets the cue text. * * @see Cue#text */ @Nullable public CharSequence getText() { return text; } /** * Sets the cue image. * * @see Cue#bitmap */ public Builder setBitmap(Bitmap bitmap) { this.bitmap = bitmap; return this; } /** * Gets the cue image. * * @see Cue#bitmap */ @Nullable public Bitmap getBitmap() { return bitmap; } /** * Sets the alignment of the cue text within the cue box. * * <p>Passing null means the alignment is undefined. * * @see Cue#textAlignment */ public Builder setTextAlignment(@Nullable Layout.Alignment textAlignment) { this.textAlignment = textAlignment; return this; } /** * Gets the alignment of the cue text within the cue box, or null if the alignment is undefined. * * @see Cue#textAlignment */ @Nullable public Alignment getTextAlignment() { return textAlignment; } /** * Sets the position of the cue box within the viewport in the direction orthogonal to the * writing direction. * * @see Cue#line * @see Cue#lineType */ public Builder setLine(float line, @LineType int lineType) { this.line = line; this.lineType = lineType; return this; } /** * Gets the position of the {@code lineAnchor} of the cue box within the viewport in the * direction orthogonal to the writing direction. * * @see Cue#line */ public float getLine() { return line; } /** * Gets the type of the value of {@link #getLine()}. * * @see Cue#lineType */ @LineType public int getLineType() { return lineType; } /** * Sets the cue box anchor positioned by {@link #setLine(float, int) line}. * * @see Cue#lineAnchor */ public Builder setLineAnchor(@AnchorType int lineAnchor) { this.lineAnchor = lineAnchor; return this; } /** * Gets the cue box anchor positioned by {@link #setLine(float, int) line}. * * @see Cue#lineAnchor */ @AnchorType public int getLineAnchor() { return lineAnchor; } /** * Sets the fractional position of the {@link #setPositionAnchor(int) positionAnchor} of the cue * box within the viewport in the direction orthogonal to {@link #setLine(float, int) line}. * * @see Cue#position */ public Builder setPosition(float position) { this.position = position; return this; } /** * Gets the fractional position of the {@link #setPositionAnchor(int) positionAnchor} of the cue * box within the viewport in the direction orthogonal to {@link #setLine(float, int) line}. * * @see Cue#position */ public float getPosition() { return position; } /** * Sets the cue box anchor positioned by {@link #setPosition(float) position}. * * @see Cue#positionAnchor */ public Builder setPositionAnchor(@AnchorType int positionAnchor) { this.positionAnchor = positionAnchor; return this; } /** * Gets the cue box anchor positioned by {@link #setPosition(float) position}. * * @see Cue#positionAnchor */ @AnchorType public int getPositionAnchor() { return positionAnchor; } /** * Sets the default text size and type for this cue's text. * * @see Cue#textSize * @see Cue#textSizeType */ public Builder setTextSize(float textSize, @TextSizeType int textSizeType) { this.textSize = textSize; this.textSizeType = textSizeType; return this; } /** * Gets the default text size type for this cue's text. * * @see Cue#textSizeType */ @TextSizeType public int getTextSizeType() { return textSizeType; } /** * Gets the default text size for this cue's text. * * @see Cue#textSize */ public float getTextSize() { return textSize; } /** * Sets the size of the cue box in the writing direction specified as a fraction of the viewport * size in that direction. * * @see Cue#size */ public Builder setSize(float size) { this.size = size; return this; } /** * Gets the size of the cue box in the writing direction specified as a fraction of the viewport * size in that direction. * * @see Cue#size */ public float getSize() { return size; } /** * Sets the bitmap height as a fraction of the viewport size. * * @see Cue#bitmapHeight */ public Builder setBitmapHeight(float bitmapHeight) { this.bitmapHeight = bitmapHeight; return this; } /** * Gets the bitmap height as a fraction of the viewport size. * * @see Cue#bitmapHeight */ public float getBitmapHeight() { return bitmapHeight; } /** * Sets the fill color of the window. * * <p>Also sets {@link Cue#windowColorSet} to true. * * @see Cue#windowColor * @see Cue#windowColorSet */ public Builder setWindowColor(@ColorInt int windowColor) { this.windowColor = windowColor; this.windowColorSet = true; return this; } /** Sets {@link Cue#windowColorSet} to false. */ public Builder clearWindowColor() { this.windowColorSet = false; return this; } /** * Returns true if the fill color of the window is set. * * @see Cue#windowColorSet */ public boolean isWindowColorSet() { return windowColorSet; } /** * Gets the fill color of the window. * * @see Cue#windowColor */ @ColorInt public int getWindowColor() { return windowColor; } /** * Sets the vertical formatting for this Cue. * * @see Cue#verticalType */ public Builder setVerticalType(@VerticalType int verticalType) { this.verticalType = verticalType; return this; } /** Sets the shear angle for this Cue. */ public Builder setShearDegrees(float shearDegrees) { this.shearDegrees = shearDegrees; return this; } /** * Gets the vertical formatting for this Cue. * * @see Cue#verticalType */ @VerticalType public int getVerticalType() { return verticalType; } /** Build the cue. */ public Cue build() { return new Cue( text, textAlignment, bitmap, line, lineType, lineAnchor, position, positionAnchor, textSizeType, textSize, size, bitmapHeight, windowColorSet, windowColor, verticalType, shearDegrees); } } }
apache-2.0
cloudera/hcatalog
core/src/test/java/org/apache/hcatalog/mapreduce/HCatMapReduceTest.java
13101
/** * 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.hcatalog.mapreduce; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.MetaStoreUtils; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.SerDeInfo; import org.apache.hadoop.hive.metastore.api.StorageDescriptor; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.ql.io.RCFileInputFormat; import org.apache.hadoop.hive.ql.io.RCFileOutputFormat; import org.apache.hadoop.hive.serde.serdeConstants; import org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hcatalog.HcatTestUtils; import org.apache.hcatalog.common.HCatConstants; import org.apache.hcatalog.common.HCatUtil; import org.apache.hcatalog.data.DefaultHCatRecord; import org.apache.hcatalog.data.HCatRecord; import org.apache.hcatalog.data.schema.HCatFieldSchema; import org.apache.hcatalog.data.schema.HCatSchema; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertTrue; /** * Test for HCatOutputFormat. Writes a partition using HCatOutputFormat and reads * it back using HCatInputFormat, checks the column values and counts. */ public abstract class HCatMapReduceTest extends HCatBaseTest { private static final Logger LOG = LoggerFactory.getLogger(HCatMapReduceTest.class); protected static String dbName = MetaStoreUtils.DEFAULT_DATABASE_NAME; protected static String tableName = "testHCatMapReduceTable"; protected String inputFormat = RCFileInputFormat.class.getName(); protected String outputFormat = RCFileOutputFormat.class.getName(); protected String serdeClass = ColumnarSerDe.class.getName(); private static List<HCatRecord> writeRecords = new ArrayList<HCatRecord>(); private static List<HCatRecord> readRecords = new ArrayList<HCatRecord>(); protected abstract List<FieldSchema> getPartitionKeys(); protected abstract List<FieldSchema> getTableColumns(); private static FileSystem fs; @BeforeClass public static void setUpOneTime() throws Exception { fs = new LocalFileSystem(); fs.initialize(fs.getWorkingDirectory().toUri(), new Configuration()); HiveConf hiveConf = new HiveConf(); hiveConf.setInt(HCatConstants.HCAT_HIVE_CLIENT_EXPIRY_TIME, 0); // Hack to initialize cache with 0 expiry time causing it to return a new hive client every time // Otherwise the cache doesn't play well with the second test method with the client gets closed() in the // tearDown() of the previous test HCatUtil.getHiveClient(hiveConf); MapCreate.writeCount = 0; MapRead.readCount = 0; } @After public void deleteTable() throws Exception { try { String databaseName = (dbName == null) ? MetaStoreUtils.DEFAULT_DATABASE_NAME : dbName; client.dropTable(databaseName, tableName); } catch (Exception e) { e.printStackTrace(); throw e; } } @Before public void createTable() throws Exception { String databaseName = (dbName == null) ? MetaStoreUtils.DEFAULT_DATABASE_NAME : dbName; try { client.dropTable(databaseName, tableName); } catch (Exception e) { } //can fail with NoSuchObjectException Table tbl = new Table(); tbl.setDbName(databaseName); tbl.setTableName(tableName); tbl.setTableType("MANAGED_TABLE"); StorageDescriptor sd = new StorageDescriptor(); sd.setCols(getTableColumns()); tbl.setPartitionKeys(getPartitionKeys()); tbl.setSd(sd); sd.setBucketCols(new ArrayList<String>(2)); sd.setSerdeInfo(new SerDeInfo()); sd.getSerdeInfo().setName(tbl.getTableName()); sd.getSerdeInfo().setParameters(new HashMap<String, String>()); sd.getSerdeInfo().getParameters().put(serdeConstants.SERIALIZATION_FORMAT, "1"); sd.getSerdeInfo().setSerializationLib(serdeClass); sd.setInputFormat(inputFormat); sd.setOutputFormat(outputFormat); Map<String, String> tableParams = new HashMap<String, String>(); tbl.setParameters(tableParams); client.createTable(tbl); } //Create test input file with specified number of rows private void createInputFile(Path path, int rowCount) throws IOException { if (fs.exists(path)) { fs.delete(path, true); } FSDataOutputStream os = fs.create(path); for (int i = 0; i < rowCount; i++) { os.writeChars(i + "\n"); } os.close(); } public static class MapCreate extends Mapper<LongWritable, Text, BytesWritable, HCatRecord> { static int writeCount = 0; //test will be in local mode @Override public void map(LongWritable key, Text value, Context context ) throws IOException, InterruptedException { { try { HCatRecord rec = writeRecords.get(writeCount); context.write(null, rec); writeCount++; } catch (Exception e) { e.printStackTrace(System.err); //print since otherwise exception is lost throw new IOException(e); } } } } public static class MapRead extends Mapper<WritableComparable, HCatRecord, BytesWritable, Text> { static int readCount = 0; //test will be in local mode @Override public void map(WritableComparable key, HCatRecord value, Context context ) throws IOException, InterruptedException { { try { readRecords.add(value); readCount++; } catch (Exception e) { e.printStackTrace(); //print since otherwise exception is lost throw new IOException(e); } } } } Job runMRCreate(Map<String, String> partitionValues, List<HCatFieldSchema> partitionColumns, List<HCatRecord> records, int writeCount, boolean assertWrite) throws Exception { return runMRCreate(partitionValues, partitionColumns, records, writeCount, assertWrite, true); } /** * Run a local map reduce job to load data from in memory records to an HCatalog Table * @param partitionValues * @param partitionColumns * @param records data to be written to HCatalog table * @param writeCount * @param assertWrite * @param asSingleMapTask * @return * @throws Exception */ Job runMRCreate(Map<String, String> partitionValues, List<HCatFieldSchema> partitionColumns, List<HCatRecord> records, int writeCount, boolean assertWrite, boolean asSingleMapTask) throws Exception { writeRecords = records; MapCreate.writeCount = 0; Configuration conf = new Configuration(); Job job = new Job(conf, "hcat mapreduce write test"); job.setJarByClass(this.getClass()); job.setMapperClass(HCatMapReduceTest.MapCreate.class); // input/output settings job.setInputFormatClass(TextInputFormat.class); if (asSingleMapTask) { // One input path would mean only one map task Path path = new Path(fs.getWorkingDirectory(), "mapred/testHCatMapReduceInput"); createInputFile(path, writeCount); TextInputFormat.setInputPaths(job, path); } else { // Create two input paths so that two map tasks get triggered. There could be other ways // to trigger two map tasks. Path path = new Path(fs.getWorkingDirectory(), "mapred/testHCatMapReduceInput"); createInputFile(path, writeCount / 2); Path path2 = new Path(fs.getWorkingDirectory(), "mapred/testHCatMapReduceInput2"); createInputFile(path2, (writeCount - writeCount / 2)); TextInputFormat.setInputPaths(job, path, path2); } job.setOutputFormatClass(HCatOutputFormat.class); OutputJobInfo outputJobInfo = OutputJobInfo.create(dbName, tableName, partitionValues); HCatOutputFormat.setOutput(job, outputJobInfo); job.setMapOutputKeyClass(BytesWritable.class); job.setMapOutputValueClass(DefaultHCatRecord.class); job.setNumReduceTasks(0); HCatOutputFormat.setSchema(job, new HCatSchema(partitionColumns)); boolean success = job.waitForCompletion(true); // Ensure counters are set when data has actually been read. if (partitionValues != null) { assertTrue(job.getCounters().getGroup("FileSystemCounters") .findCounter("FILE_BYTES_READ").getValue() > 0); } if (!HcatTestUtils.isHadoop23() && !HcatTestUtils.isHadoop2_0()) { // Local mode outputcommitter hook is not invoked in Hadoop 1.x if (success) { new FileOutputCommitterContainer(job, null).commitJob(job); } else { new FileOutputCommitterContainer(job, null).abortJob(job, JobStatus.State.FAILED); } } if (assertWrite) { // we assert only if we expected to assert with this call. Assert.assertEquals(writeCount, MapCreate.writeCount); } return job; } List<HCatRecord> runMRRead(int readCount) throws Exception { return runMRRead(readCount, null); } /** * Run a local map reduce job to read records from HCatalog table and verify if the count is as expected * @param readCount * @param filter * @return * @throws Exception */ List<HCatRecord> runMRRead(int readCount, String filter) throws Exception { MapRead.readCount = 0; readRecords.clear(); Configuration conf = new Configuration(); Job job = new Job(conf, "hcat mapreduce read test"); job.setJarByClass(this.getClass()); job.setMapperClass(HCatMapReduceTest.MapRead.class); // input/output settings job.setInputFormatClass(HCatInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); HCatInputFormat.setInput(job, dbName, tableName).setFilter(filter); job.setMapOutputKeyClass(BytesWritable.class); job.setMapOutputValueClass(Text.class); job.setNumReduceTasks(0); Path path = new Path(fs.getWorkingDirectory(), "mapred/testHCatMapReduceOutput"); if (fs.exists(path)) { fs.delete(path, true); } TextOutputFormat.setOutputPath(job, path); job.waitForCompletion(true); Assert.assertEquals(readCount, MapRead.readCount); return readRecords; } protected HCatSchema getTableSchema() throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "hcat mapreduce read schema test"); job.setJarByClass(this.getClass()); // input/output settings job.setInputFormatClass(HCatInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); HCatInputFormat.setInput(job, dbName, tableName); return HCatInputFormat.getTableSchema(job); } }
apache-2.0
Eminenz/itunesJacobExample
src/com/pew/itunes/IITVisual.java
979
/** * JacobGen generated file --- do not edit * * (http://www.sourceforge.net/projects/jacob-project */ package com.pew.itunes; import com.jacob.com.*; public class IITVisual extends Dispatch { public static final String componentName = "iTunesLib.IITVisual"; public IITVisual() { super(componentName); } /** * This constructor is used instead of a case operation to * turn a Dispatch object into a wider object - it must exist * in every wrapper class whose instances may be returned from * method calls wrapped in VT_DISPATCH Variants. */ public IITVisual(Dispatch d) { // take over the IDispatch pointer m_pDispatch = d.m_pDispatch; // null out the input's pointer d.m_pDispatch = 0; } public IITVisual(String compName) { super(compName); } /** * Wrapper for calling the ActiveX-Method with input-parameter(s). * @return the result is of type String */ public String getName() { return Dispatch.get(this, "Name").toString(); } }
apache-2.0
petezybrick/iote2e
iote2e-ws/src/main/java/com/pzybrick/iote2e/ws/nrt/ServerSideSocketNearRealTime.java
11460
/** * Copyright 2016, 2017 Peter Zybrick and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Pete Zybrick * @version 1.0.0, 2017-09 * */ package com.pzybrick.iote2e.ws.nrt; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.cache.CacheException; import javax.websocket.ClientEndpoint; import javax.websocket.CloseReason; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.apache.avro.util.Utf8; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.pzybrick.iote2e.common.ignite.IgniteGridConnection; import com.pzybrick.iote2e.common.ignite.ThreadIgniteSubscribe; import com.pzybrick.iote2e.common.utils.Iote2eConstants; import com.pzybrick.iote2e.common.utils.Iote2eUtils; import com.pzybrick.iote2e.schema.avro.Iote2eResult; import com.pzybrick.iote2e.schema.avro.OPERATION; import com.pzybrick.iote2e.schema.util.Iote2eResultReuseItem; import com.pzybrick.iote2e.schema.util.Iote2eSchemaConstants; /** * The Class ServerSideSocketNearRealTime. */ @ClientEndpoint @ServerEndpoint(value = "/nrt/") public class ServerSideSocketNearRealTime { /** The Constant logger. */ private static final Logger logger = LogManager.getLogger(ServerSideSocketNearRealTime.class); /** The session. */ private Session session; /** The thread ignite subscribe temperature. */ private ThreadIgniteSubscribe threadIgniteSubscribeTemperature; /** The thread ignite subscribe omh. */ private ThreadIgniteSubscribe threadIgniteSubscribeOmh; /** The thread ignite subscribe bdbb. */ private ThreadIgniteSubscribe threadIgniteSubscribeBdbb; /** * Gets the session. * * @return the session */ public Session getSession() { return session; } /** * Sets the session. * * @param session the new session */ public void setSession(Session session) { this.session = session; } /** * Instantiates a new server side socket near real time. */ public ServerSideSocketNearRealTime() { } /** * On web socket connect. * * @param session the session * @throws Exception the exception */ @OnOpen public void onWebSocketConnect(Session session) throws Exception { this.session = session; ThreadEntryPointNearRealTime.serverSideSocketNearRealTimes.put(Iote2eConstants.SOCKET_KEY_NRT, this); threadIgniteSubscribeTemperature = ThreadIgniteSubscribe.startThreadSubscribe( ThreadEntryPointNearRealTime.masterConfig, Iote2eConstants.IGNITE_KEY_NRT_TEMPERATURE, ThreadEntryPointNearRealTime.toClientIote2eResults, (Thread)null ); threadIgniteSubscribeOmh = ThreadIgniteSubscribe.startThreadSubscribe( ThreadEntryPointNearRealTime.masterConfig, Iote2eConstants.IGNITE_KEY_NRT_OMH, ThreadEntryPointNearRealTime.toClientIote2eResults, (Thread)null ); threadIgniteSubscribeBdbb = ThreadIgniteSubscribe.startThreadSubscribe( ThreadEntryPointNearRealTime.masterConfig, Iote2eConstants.IGNITE_KEY_NRT_BDBB, ThreadEntryPointNearRealTime.toClientIote2eResults, (Thread)null ); //new ThreadPumpTestData().start(); logger.info("Socket Connected: " + session.getId()); } /** * On web socket text. * * @param message the message */ @OnMessage public void onWebSocketText(String message) { logger.debug("onWebSocketText " + message); } /** * On web socket byte. * * @param bytes the bytes */ @OnMessage public void onWebSocketByte(byte[] bytes) { logger.debug("onWebSocketByte len=" + bytes.length); } /** * On web socket close. * * @param reason the reason */ @OnClose public void onWebSocketClose(CloseReason reason) { boolean isRemove = ThreadEntryPointNearRealTime.serverSideSocketNearRealTimes.remove(Iote2eConstants.SOCKET_KEY_NRT, this); logger.info("Socket Closed: " + reason + ", isRemove=" + isRemove); shutdownThreadIgniteSubscribe(); } /** * On web socket error. * * @param cause the cause */ @OnError public void onWebSocketError(Throwable cause) { boolean isRemove = ThreadEntryPointNearRealTime.serverSideSocketNearRealTimes.remove(Iote2eConstants.SOCKET_KEY_NRT, this); logger.info("Socket Error: " + cause.getMessage() + ", isRemove=" + isRemove); shutdownThreadIgniteSubscribe(); } /** * Shutdown thread ignite subscribe. */ private void shutdownThreadIgniteSubscribe() { logger.debug("Shutting down threadIgniteSubscribe"); try { threadIgniteSubscribeTemperature.shutdown(); threadIgniteSubscribeOmh.shutdown(); threadIgniteSubscribeBdbb.shutdown(); threadIgniteSubscribeTemperature.join(5000); threadIgniteSubscribeOmh.join(5000); threadIgniteSubscribeBdbb.join(5000); } catch( InterruptedException e ) { } catch( Exception e ) { logger.error(e.getMessage()); } } /** * The Class ThreadPumpTestData. */ public class ThreadPumpTestData extends Thread { /** The shutdown. */ private boolean shutdown; /** * Shutdown. */ public void shutdown() { logger.info("Shutdown"); shutdown = true; interrupt(); } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { logger.info("ThreadPumpTestData Run"); final List<String> rpis = Arrays.asList("rpi-001","rpi-002","rpi-003"); final float tempMin = 30.0f; final float tempMax = 50.0f; final float tempIncr = 4.0f; try { IgniteGridConnection igniteGridConnection = new IgniteGridConnection().connect(ThreadEntryPointNearRealTime.masterConfig); Iote2eResultReuseItem iote2eResultReuseItem = new Iote2eResultReuseItem(); List<PumpTemperatureItem> pumpTemperatureItems = new ArrayList<PumpTemperatureItem>(); pumpTemperatureItems.add( new PumpTemperatureItem("rpi-001", tempMin )); pumpTemperatureItems.add( new PumpTemperatureItem("rpi-002", tempMin + tempIncr )); pumpTemperatureItems.add( new PumpTemperatureItem("rpi-003", tempMin + (2*tempIncr) )); TemperatureSensorItem temperatureSensorItem = new TemperatureSensorItem(); while( true ) { for( PumpTemperatureItem pumpTemperatureItem : pumpTemperatureItems ) { Map<CharSequence,CharSequence> pairs = new HashMap<CharSequence,CharSequence>(); pairs.put( new Utf8(Iote2eSchemaConstants.PAIRNAME_SENSOR_NAME), new Utf8("temp1")); pairs.put( new Utf8(Iote2eSchemaConstants.PAIRNAME_SENSOR_VALUE), new Utf8(String.valueOf(pumpTemperatureItem.getDegreesC()) )); Iote2eResult iote2eResult = Iote2eResult.newBuilder() .setPairs(pairs) //.setMetadata(ruleEvalResult.getMetadata()) .setLoginName("$nrt$") .setSourceName(new Utf8(pumpTemperatureItem.getSourceName())) .setSourceType("temp") .setRequestUuid(new Utf8(UUID.randomUUID().toString())) .setRequestTimestamp(new Utf8(Iote2eUtils.getDateNowUtc8601())) .setOperation(OPERATION.SENSORS_VALUES) .setResultCode(0) .setResultTimestamp( new Utf8(Iote2eUtils.getDateNowUtc8601())) .setResultUuid( new Utf8(UUID.randomUUID().toString())) .build(); // EntryPointNearRealTime.toClientIote2eResults.add( iote2eResult ); boolean isSuccess = false; Exception lastException = null; long timeoutAt = System.currentTimeMillis() + (15*1000L); while( System.currentTimeMillis() < timeoutAt ) { try { igniteGridConnection.getCache().put(Iote2eConstants.IGNITE_KEY_NRT_TEMPERATURE, iote2eResultReuseItem.toByteArray(iote2eResult)); isSuccess = true; logger.debug("cache.put successful, cache name={}, pk={}, iote2eResult={}", igniteGridConnection.getCache().getName(), Iote2eConstants.IGNITE_KEY_NRT_TEMPERATURE, iote2eResult.toString() ); break; } catch( CacheException cacheException ) { lastException = cacheException; logger.warn("cache.put failed with CacheException, will retry, cntRetry={}" ); try { Thread.sleep(1000L); } catch(Exception e ) {} } catch( Exception e ) { logger.error(e.getMessage(),e); throw e; } } if( !isSuccess ) { logger.error("Ignite cache write failure, pk={}, iote2eResult={}, lastException: {}", Iote2eConstants.IGNITE_KEY_NRT_TEMPERATURE, iote2eResult.toString(), lastException.getLocalizedMessage(), lastException); throw new Exception( lastException); } if( pumpTemperatureItem.isIncreasing ) pumpTemperatureItem.setDegreesC(pumpTemperatureItem.getDegreesC() + tempIncr ); else pumpTemperatureItem.setDegreesC(pumpTemperatureItem.getDegreesC() - tempIncr); if( pumpTemperatureItem.getDegreesC() > tempMax ) pumpTemperatureItem.setIncreasing(false); else if( pumpTemperatureItem.getDegreesC() < tempMin ) pumpTemperatureItem.setIncreasing(true); } try { sleep(1000L); } catch (InterruptedException e) {} if (shutdown) return; } } catch (Exception e) { logger.error("Exception processing target text message", e); } logger.info("Exit"); } } /** * The Class PumpTemperatureItem. */ private class PumpTemperatureItem { /** The source name. */ private String sourceName; /** The degrees C. */ private float degreesC; /** The is increasing. */ private boolean isIncreasing = true; /** * Instantiates a new pump temperature item. * * @param rpiName the rpi name * @param temperature the temperature */ public PumpTemperatureItem(String rpiName, float temperature) { super(); this.sourceName = rpiName; this.degreesC = temperature; } /** * Gets the source name. * * @return the source name */ public String getSourceName() { return sourceName; } /** * Sets the source name. * * @param sourceName the source name * @return the pump temperature item */ public PumpTemperatureItem setSourceName(String sourceName) { this.sourceName = sourceName; return this; } /** * Gets the degrees C. * * @return the degrees C */ public float getDegreesC() { return degreesC; } /** * Checks if is increasing. * * @return true, if is increasing */ public boolean isIncreasing() { return isIncreasing; } /** * Sets the degrees C. * * @param degreesC the degrees C * @return the pump temperature item */ public PumpTemperatureItem setDegreesC(float degreesC) { this.degreesC = degreesC; return this; } /** * Sets the increasing. * * @param isIncreasing the is increasing * @return the pump temperature item */ public PumpTemperatureItem setIncreasing(boolean isIncreasing) { this.isIncreasing = isIncreasing; return this; } } }
apache-2.0
murat8505/REST_client_retrofit
retrofit/src/test/java/retrofit/converter/GsonConverterTest.java
2382
// Copyright 2015 Square, Inc. package retrofit.converter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.ResponseBody; import java.io.IOException; import java.lang.reflect.Type; import okio.Buffer; import org.assertj.core.api.AbstractCharSequenceAssert; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; public final class GsonConverterTest { private Converter converter; interface Example { String getName(); } class Impl implements Example { private final String theName; Impl(String name) { theName = name; } @Override public String getName() { return theName; } } @Before public void setUp() { Gson gson = new GsonBuilder() .registerTypeAdapter(Example.class, new JsonSerializer<Example>() { @Override public JsonElement serialize(Example example, Type type, JsonSerializationContext json) { JsonObject object = new JsonObject(); object.addProperty("name", example.getName()); return object; } }) .create(); converter = new GsonConverter(gson); } @Test public void serialization() throws IOException { RequestBody body = converter.toBody(new Impl("value"), Impl.class); assertBody(body).isEqualTo("{\"theName\":\"value\"}"); } @Test public void serializationTypeUsed() throws IOException { RequestBody body = converter.toBody(new Impl("value"), Example.class); assertBody(body).isEqualTo("{\"name\":\"value\"}"); } @Test public void deserialization() throws IOException { ResponseBody body = ResponseBody.create(MediaType.parse("text/plain"), "{\"theName\":\"value\"}"); Impl impl = (Impl) converter.fromBody(body, Impl.class); assertEquals("value", impl.getName()); } private static AbstractCharSequenceAssert<?, String> assertBody(RequestBody body) throws IOException { Buffer buffer = new Buffer(); body.writeTo(buffer); return assertThat(buffer.readUtf8()); } }
apache-2.0
zuzanamullerova/unitime
JavaSource/org/unitime/timetable/gwt/client/rooms/RoomHint.java
7518
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.gwt.client.rooms; import java.util.ArrayList; import java.util.List; import org.unitime.timetable.gwt.client.GwtHint; import org.unitime.timetable.gwt.client.widgets.SimpleForm; import org.unitime.timetable.gwt.command.client.GwtRpcService; import org.unitime.timetable.gwt.command.client.GwtRpcServiceAsync; import org.unitime.timetable.gwt.resources.GwtMessages; import org.unitime.timetable.gwt.shared.RoomInterface; import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureInterface; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; /** * @author Tomas Muller */ public class RoomHint { private static long sLastLocationId = -1; private static GwtRpcServiceAsync RPC = GWT.create(GwtRpcService.class); private static final GwtMessages MESSAGES = GWT.create(GwtMessages.class); private static boolean sShowHint = false; private static Timer sLastSwapper = null; public static Widget content(RoomInterface.RoomHintResponse room, String prefix, String distance) { if (sLastSwapper != null) { sLastSwapper.cancel(); sLastSwapper = null; } SimpleForm form = new SimpleForm(); form.removeStyleName("unitime-NotPrintableBottomLine"); if (prefix != null && prefix.contains("{0}")) { String label = prefix.replace("{0}", room.getLabel()); if (prefix.contains("{1}")) label = label.replace("{1}", room.hasDisplayName() ? room.getDisplayName() : room.hasRoomTypeLabel() ? room.getRoomTypeLabel() : ""); form.addRow(new Label(label, false)); } else { form.addRow(new Label((prefix == null || prefix.isEmpty() ? "" : prefix + " ") + (room.hasDisplayName() || room.hasRoomTypeLabel() ? MESSAGES.label(room.getLabel(), room.hasDisplayName() ? room.getDisplayName() : room.getRoomTypeLabel()) : room.getLabel()), false)); } List<String> urls = new ArrayList<String>(); if (room.hasMiniMapUrl()) { urls.add(room.getMiniMapUrl()); } if (room.hasPictures()) { for (RoomPictureInterface picture: room.getPictures()) urls.add(GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId()); } if (!urls.isEmpty()) { Image image = new Image(urls.get(0)); image.setStyleName("minimap"); form.addRow(image); if (urls.size() > 1) { sLastSwapper = new ImageSwapper(image, urls); sLastSwapper.scheduleRepeating(3000); } } if (room.hasCapacity()) { if (room.hasExamCapacity()) { if (room.hasExamType()) { form.addRow(MESSAGES.propRoomCapacity(), new Label(MESSAGES.capacityWithExamType(room.getCapacity().toString(), room.getExamCapacity().toString(), room.getExamType()), false)); } else { form.addRow(MESSAGES.propRoomCapacity(), new Label(MESSAGES.capacityWithExam(room.getCapacity().toString(), room.getExamCapacity().toString()), false)); } } else { form.addRow(MESSAGES.propRoomCapacity(), new Label(MESSAGES.capacity(room.getCapacity().toString()), false)); } } if (room.hasArea()) form.addRow(MESSAGES.propRoomArea(), new HTML(room.getArea(), false)); if (room.hasFeatures()) for (String name: room.getFeatureNames()) form.addRow(name + ":", new Label(room.getFeatures(name))); if (room.hasGroups()) form.addRow(MESSAGES.propRoomGroups(), new Label(room.getGroups())); if (room.hasEventStatus()) form.addRow(MESSAGES.propRoomEventStatus(), new Label(room.getEventStatus())); if (room.hasEventDepartment()) form.addRow(MESSAGES.propRoomEventDepartment(), new Label(room.getEventDepartment())); if (room.hasBreakTime()) form.addRow(MESSAGES.propRoomBreakTime(), new Label(MESSAGES.breakTime(room.getBreakTime().toString()))); if (room.hasNote()) form.addRow(new HTML(room.getNote())); if (room.isIgnoreRoomCheck()) form.addRow(new HTML(MESSAGES.ignoreRoomCheck())); if (distance != null && !distance.isEmpty() && !"0".equals(distance)) form.addRow(MESSAGES.propRoomDistance(), new Label(MESSAGES.roomDistance(distance), false)); SimplePanel panel = new SimplePanel(form); panel.setStyleName("unitime-RoomHint"); return panel; } /** Never use from GWT code */ public static void _showRoomHint(JavaScriptObject source, String locationId, String prefix, String distance, String note) { showHint((Element) source.cast(), Long.valueOf(locationId), prefix, distance, note, true); } public static void showHint(final Element relativeObject, final long locationId, final String prefix, final String distance, final boolean showRelativeToTheObject) { showHint(relativeObject, locationId, prefix, distance, null, showRelativeToTheObject); } public static void showHint(final Element relativeObject, final long locationId, final String prefix, final String distance, final String note, final boolean showRelativeToTheObject) { sLastLocationId = locationId; sShowHint = true; RPC.execute(RoomInterface.RoomHintRequest.load(locationId), new AsyncCallback<RoomInterface.RoomHintResponse>() { @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(RoomInterface.RoomHintResponse result) { if (result != null && locationId == sLastLocationId && sShowHint) { if (note != null) result.setNote(note); GwtHint.showHint(relativeObject, content(result, prefix, distance), showRelativeToTheObject); } } }); } public static void hideHint() { sShowHint = false; if (sLastSwapper != null) { sLastSwapper.cancel(); sLastSwapper = null; } GwtHint.hideHint(); } public static native void createTriggers()/*-{ $wnd.showGwtRoomHint = function(source, content, prefix, distance, note) { @org.unitime.timetable.gwt.client.rooms.RoomHint::_showRoomHint(Lcom/google/gwt/core/client/JavaScriptObject;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)(source, content, prefix, distance, note); }; $wnd.hideGwtRoomHint = function() { @org.unitime.timetable.gwt.client.rooms.RoomHint::hideHint()(); }; }-*/; private static class ImageSwapper extends Timer { Image iImage; List<String> iUrls; int iIndex; ImageSwapper(Image image, List<String> urls) { iImage = image; iUrls = urls; iIndex = 0; } @Override public void run() { iIndex ++; iImage.setUrl(iUrls.get(iIndex % iUrls.size())); if (!iImage.isAttached()) cancel(); } } }
apache-2.0
Har-insa/front-end
app/src/main/java/com/hardis/connect/fragment/FeedsFragment.java
2144
package com.hardis.connect.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hardis.connect.R; import com.hardis.connect.adapter.FeedsFragmentAdapter; import com.github.florent37.materialviewpager.MaterialViewPagerHelper; import com.github.florent37.materialviewpager.adapter.RecyclerViewMaterialAdapter; import java.util.ArrayList; import java.util.List; public class FeedsFragment extends Fragment { private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; public static FeedsFragment newInstance() { return new FeedsFragment(); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_recyclerview, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); //permet un affichage sous forme liste verticale RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setHasFixedSize(true); //100 faux contenu List<Object> mContentItems = new ArrayList<>(); for (int i = 0; i < 100; ++i) mContentItems.add(new Object()); //penser à passer notre Adapter (ici : FeedsFragmentAdapter) à un RecyclerViewMaterialAdapter mAdapter = new RecyclerViewMaterialAdapter(new FeedsFragmentAdapter(mContentItems)); mRecyclerView.setAdapter(mAdapter); //notifier le MaterialViewPager qu'on va utiliser une RecyclerView MaterialViewPagerHelper.registerRecyclerView(getActivity(), mRecyclerView, null); } }
apache-2.0
nanchengking/Drawing
src/table/WelcomeWindow.java
1380
package table; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class WelcomeWindow implements Runnable { private JFrame frame; private String fileName="image.png"; public void run() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int a=screenSize.width/2-250; int b=screenSize.height/2-250; frame = new JFrame("»¶Ó­Ê¹ÓÃÁõÊöÇåÏÈÉú±àдµÄÈí¼þ"); frame.setBounds(a-80, b, 500, 500); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL base = this.getClass().getResource(fileName); //Properties property= System.getProperties(); //String classPath=property.get("java.class.path").toString(); //String path=base.toString().substring(6).replace("Drawing/bin/table/", "").replace("le:/","").replace("drawing.jar!/table/","")+"Image/image.gif"; String path=base.getPath(); System.out.println(path); //System.out.println("classPath is:"+classPath); JLabel lable=new JLabel(new ImageIcon(base)); lable.setSize(500, 500); lable.setVisible(true); frame.add(lable, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); //JOptionPane.showMessageDialog(frame, path+"\n"); } }
apache-2.0
ThorbenLindhauer/activiti-engine-ppi
modules/activiti-engine/src/main/java/org/activiti/engine/impl/pvm/runtime/ExecutionImpl.java
25877
/* Copyright 2010-2012 Alfresco Software, Ltd. * Copyright 2012 Thorben Lindhauer * * Licensed under the Apache License, ersion 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.activiti.engine.impl.pvm.runtime; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.activiti.engine.impl.pvm.PvmActivity; import org.activiti.engine.impl.pvm.PvmException; import org.activiti.engine.impl.pvm.PvmExecution; import org.activiti.engine.impl.pvm.PvmProcessDefinition; import org.activiti.engine.impl.pvm.PvmProcessElement; import org.activiti.engine.impl.pvm.PvmProcessInstance; import org.activiti.engine.impl.pvm.PvmTransition; import org.activiti.engine.impl.pvm.delegate.ActivityExecution; import org.activiti.engine.impl.pvm.delegate.ExecutionListenerExecution; import org.activiti.engine.impl.pvm.delegate.SignallableActivityBehavior; import org.activiti.engine.impl.pvm.process.ActivityImpl; import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl; import org.activiti.engine.impl.pvm.process.TransitionImpl; /** * @author Tom Baeyens * @author Joram Barrez */ public class ExecutionImpl implements Serializable, ActivityExecution, ExecutionListenerExecution, PvmExecution, InterpretableExecution { private static final long serialVersionUID = 1L; private static Logger log = Logger.getLogger(ExecutionImpl.class.getName()); // current position // ///////////////////////////////////////////////////////// protected ProcessDefinitionImpl processDefinition; /** current activity */ protected ActivityImpl activity; /** current transition. is null when there is no transition being taken. */ protected TransitionImpl transition = null; /** * the process instance. this is the root of the execution tree. the * processInstance of a process instance is a self reference. */ protected ExecutionImpl processInstance; /** the parent execution */ protected ExecutionImpl parent; /** nested executions representing scopes or concurrent paths */ protected List<ExecutionImpl> executions; /** super execution, not-null if this execution is part of a subprocess */ protected ExecutionImpl superExecution; /** * reference to a subprocessinstance, not-null if currently subprocess is * started from this execution */ protected ExecutionImpl subProcessInstance; /** only available until the process instance is started */ protected StartingExecution startingExecution; // state/type of execution // ////////////////////////////////////////////////// /** * indicates if this execution represents an active path of execution. * Executions are made inactive in the following situations: * <ul> * <li>an execution enters a nested scope</li> * <li>an execution is split up into multiple concurrent executions, then * the parent is made inactive.</li> * <li>an execution has arrived in a parallel gateway or join and that join * has not yet activated/fired.</li> * <li>an execution is ended.</li> * </ul> */ protected boolean isActive = true; protected boolean isScope = true; protected boolean isConcurrent = false; protected boolean isEnded = false; protected boolean isEventScope = false; protected Map<String, Object> variables = null; // events // /////////////////////////////////////////////////////////////////// protected String eventName; protected PvmProcessElement eventSource; protected int executionListenerIndex = 0; // cascade deletion //////////////////////////////////////////////////////// protected boolean deleteRoot; protected String deleteReason; // replaced by // ////////////////////////////////////////////////////////////// /** * when execution structure is pruned during a takeAll, then the original * execution has to be resolved to the replaced execution. * * @see {@link #takeAll(List, List)} {@link OutgoingExecution} */ protected ExecutionImpl replacedBy; // atomic operations // //////////////////////////////////////////////////////// /** * next operation. process execution is in fact runtime interpretation of * the process model. each operation is a logical unit of interpretation of * the process. so sequentially processing the operations drives the * interpretation or execution of a process. * * @see AtomicOperation * @see #performOperation(AtomicOperation) */ protected AtomicOperation nextOperation; protected boolean isOperating = false; /* Default constructor for ibatis/jpa/etc. */ public ExecutionImpl() { } public ExecutionImpl(ActivityImpl initial) { startingExecution = new StartingExecution(initial); } // lifecycle methods // //////////////////////////////////////////////////////// /** * creates a new execution. properties processDefinition, processInstance * and activity will be initialized. */ public ExecutionImpl createExecution() { // create the new child execution ExecutionImpl createdExecution = newExecution(); // manage the bidirectional parent-child relation ensureExecutionsInitialized(); executions.add(createdExecution); createdExecution.setParent(this); // initialize the new execution createdExecution.setProcessDefinition(getProcessDefinition()); createdExecution.setProcessInstance(getProcessInstance()); createdExecution.setActivity(getActivity()); return createdExecution; } /** instantiates a new execution. can be overridden by subclasses */ protected ExecutionImpl newExecution() { return new ExecutionImpl(); } public PvmProcessInstance createSubProcessInstance( PvmProcessDefinition processDefinition) { ExecutionImpl subProcessInstance = newExecution(); // manage bidirectional super-subprocess relation subProcessInstance.setSuperExecution(this); this.setSubProcessInstance(subProcessInstance); // Initialize the new execution subProcessInstance .setProcessDefinition((ProcessDefinitionImpl) processDefinition); subProcessInstance.setProcessInstance(subProcessInstance); return subProcessInstance; } public void initialize() { } public void destroy() { setScope(false); } public void remove() { ensureParentInitialized(); if (parent != null) { parent.ensureExecutionsInitialized(); parent.executions.remove(this); } // remove event scopes: List<InterpretableExecution> childExecutions = new ArrayList<InterpretableExecution>( getExecutions()); for (InterpretableExecution childExecution : childExecutions) { if (childExecution.isEventScope()) { log.fine("removing eventScope " + childExecution); childExecution.destroy(); childExecution.remove(); } } } // parent // /////////////////////////////////////////////////////////////////// /** ensures initialization and returns the parent */ public ExecutionImpl getParent() { ensureParentInitialized(); return parent; } /** * all updates need to go through this setter as subclasses can override * this method */ public void setParent(InterpretableExecution parent) { this.parent = (ExecutionImpl) parent; } /** * must be called before memberfield parent is used. can be used by * subclasses to provide parent member field initialization. */ protected void ensureParentInitialized() { } // executions // /////////////////////////////////////////////////////////////// /** ensures initialization and returns the non-null executions list */ public List<ExecutionImpl> getExecutions() { ensureExecutionsInitialized(); return executions; } public ExecutionImpl getSuperExecution() { ensureSuperExecutionInitialized(); return superExecution; } public void setSuperExecution(ExecutionImpl superExecution) { this.superExecution = superExecution; if (superExecution != null) { superExecution.setSubProcessInstance(null); } } // Meant to be overridden by persistent subclasseses protected void ensureSuperExecutionInitialized() { } public ExecutionImpl getSubProcessInstance() { ensureSubProcessInstanceInitialized(); return subProcessInstance; } public void setSubProcessInstance(InterpretableExecution subProcessInstance) { this.subProcessInstance = (ExecutionImpl) subProcessInstance; } // Meant to be overridden by persistent subclasses protected void ensureSubProcessInstanceInitialized() { } public void deleteCascade(String deleteReason) { this.deleteReason = deleteReason; this.deleteRoot = true; performOperation(AtomicOperation.DELETE_CASCADE); } /** * removes an execution. if there are nested executions, those will be ended * recursively. if there is a parent, this method removes the bidirectional * relation between parent and this execution. */ public void end() { isActive = false; isEnded = true; performOperation(AtomicOperation.ACTIVITY_END); } /** searches for an execution positioned in the given activity */ public ExecutionImpl findExecution(String activityId) { if ((getActivity() != null) && (getActivity().getId().equals(activityId))) { return this; } for (ExecutionImpl nestedExecution : getExecutions()) { ExecutionImpl result = nestedExecution.findExecution(activityId); if (result != null) { return result; } } return null; } public List<String> findActiveActivityIds() { List<String> activeActivityIds = new ArrayList<String>(); collectActiveActivityIds(activeActivityIds); return activeActivityIds; } protected void collectActiveActivityIds(List<String> activeActivityIds) { ensureActivityInitialized(); if (isActive && activity != null) { activeActivityIds.add(activity.getId()); } ensureExecutionsInitialized(); for (ExecutionImpl execution : executions) { execution.collectActiveActivityIds(activeActivityIds); } } /** * must be called before memberfield executions is used. can be used by * subclasses to provide executions member field initialization. */ protected void ensureExecutionsInitialized() { if (executions == null) { executions = new ArrayList<ExecutionImpl>(); } } // process definition // /////////////////////////////////////////////////////// /** ensures initialization and returns the process definition. */ public ProcessDefinitionImpl getProcessDefinition() { ensureProcessDefinitionInitialized(); return processDefinition; } public String getProcessDefinitionId() { return getProcessDefinition().getId(); } /** * for setting the process definition, this setter must be used as * subclasses can override */ /** * must be called before memberfield processDefinition is used. can be used * by subclasses to provide processDefinition member field initialization. */ protected void ensureProcessDefinitionInitialized() { } // process instance // ///////////////////////////////////////////////////////// /** ensures initialization and returns the process instance. */ public ExecutionImpl getProcessInstance() { ensureProcessInstanceInitialized(); return processInstance; } public String getProcessInstanceId() { return getProcessInstance().getId(); } public String getBusinessKey() { return getProcessInstance().getBusinessKey(); } public String getProcessBusinessKey() { return getProcessInstance().getBusinessKey(); } /** * for setting the process instance, this setter must be used as subclasses * can override */ public void setProcessInstance(InterpretableExecution processInstance) { this.processInstance = (ExecutionImpl) processInstance; } /** * must be called before memberfield processInstance is used. can be used by * subclasses to provide processInstance member field initialization. */ protected void ensureProcessInstanceInitialized() { } // activity // ///////////////////////////////////////////////////////////////// /** ensures initialization and returns the activity */ public ActivityImpl getActivity() { ensureActivityInitialized(); return activity; } /** * sets the current activity. can be overridden by subclasses. doesn't * require initialization. */ public void setActivity(ActivityImpl activity) { this.activity = activity; } /** * must be called before the activity member field or getActivity() is * called */ protected void ensureActivityInitialized() { } // scopes // /////////////////////////////////////////////////////////////////// protected void ensureScopeInitialized() { } public boolean isScope() { return isScope; } public void setScope(boolean isScope) { this.isScope = isScope; } // process instance start implementation // //////////////////////////////////// public void start() { if (startingExecution == null && isProcessInstance()) { startingExecution = new StartingExecution( processDefinition.getInitial()); } performOperation(AtomicOperation.PROCESS_START); } // methods that translate to operations // ///////////////////////////////////// public void signal(String signalName, Object signalData) { ensureActivityInitialized(); SignallableActivityBehavior activityBehavior = (SignallableActivityBehavior) activity .getActivityBehavior(); try { activityBehavior.signal(this, signalName, signalData); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new PvmException("couldn't process signal '" + signalName + "' on activity '" + activity.getId() + "': " + e.getMessage(), e); } } public void take(PvmTransition transition) { if (this.transition != null) { throw new PvmException("already taking a transition"); } if (transition == null) { throw new PvmException("transition is null"); } setTransition((TransitionImpl) transition); performOperation(AtomicOperation.TRANSITION_NOTIFY_LISTENER_END); } public void executeActivity(PvmActivity activity) { setActivity((ActivityImpl) activity); performOperation(AtomicOperation.ACTIVITY_START); } public List<ActivityExecution> findInactiveConcurrentExecutions( PvmActivity activity) { List<ActivityExecution> inactiveConcurrentExecutionsInActivity = new ArrayList<ActivityExecution>(); List<ActivityExecution> otherConcurrentExecutions = new ArrayList<ActivityExecution>(); if (isConcurrent()) { List<? extends ActivityExecution> concurrentExecutions = getParent() .getExecutions(); for (ActivityExecution concurrentExecution : concurrentExecutions) { if (concurrentExecution.getActivity() == activity) { if (concurrentExecution.isActive()) { throw new PvmException( "didn't expect active execution in " + activity + ". bug?"); } inactiveConcurrentExecutionsInActivity .add(concurrentExecution); } else { otherConcurrentExecutions.add(concurrentExecution); } } } else { if (!isActive()) { inactiveConcurrentExecutionsInActivity.add(this); } else { otherConcurrentExecutions.add(this); } } if (log.isLoggable(Level.FINE)) { log.fine("inactive concurrent executions in '" + activity + "': " + inactiveConcurrentExecutionsInActivity); log.fine("other concurrent executions: " + otherConcurrentExecutions); } return inactiveConcurrentExecutionsInActivity; } @SuppressWarnings("unchecked") public void takeAll(List<PvmTransition> transitions, List<ActivityExecution> recyclableExecutions) { transitions = new ArrayList<PvmTransition>(transitions); recyclableExecutions = (recyclableExecutions != null ? new ArrayList<ActivityExecution>( recyclableExecutions) : new ArrayList<ActivityExecution>()); if (recyclableExecutions.size() > 1) { for (ActivityExecution recyclableExecution : recyclableExecutions) { if (((ExecutionImpl) recyclableExecution).isScope()) { throw new PvmException( "joining scope executions is not allowed"); } } } ExecutionImpl concurrentRoot = ((isConcurrent && !isScope) ? getParent() : this); List<ExecutionImpl> concurrentActiveExecutions = new ArrayList<ExecutionImpl>(); for (ExecutionImpl execution : concurrentRoot.getExecutions()) { if (execution.isActive()) { concurrentActiveExecutions.add(execution); } } if (log.isLoggable(Level.FINE)) { log.fine("transitions to take concurrent: " + transitions); log.fine("active concurrent executions: " + concurrentActiveExecutions); } if ((transitions.size() == 1) && (concurrentActiveExecutions.isEmpty())) { List<ExecutionImpl> recyclableExecutionImpls = (List) recyclableExecutions; for (ExecutionImpl prunedExecution : recyclableExecutionImpls) { // End the pruned executions if necessary. // Some recyclable executions are inactivated (joined // executions) // Others are already ended (end activities) if (!prunedExecution.isEnded()) { log.fine("pruning execution " + prunedExecution); prunedExecution.remove(); } } log.fine("activating the concurrent root " + concurrentRoot + " as the single path of execution going forward"); concurrentRoot.setActive(true); concurrentRoot.setActivity(activity); concurrentRoot.setConcurrent(false); concurrentRoot.take(transitions.get(0)); } else { List<OutgoingExecution> outgoingExecutions = new ArrayList<OutgoingExecution>(); recyclableExecutions.remove(concurrentRoot); log.fine("recyclable executions for reused: " + recyclableExecutions); // first create the concurrent executions while (!transitions.isEmpty()) { PvmTransition outgoingTransition = transitions.remove(0); ExecutionImpl outgoingExecution = null; if (recyclableExecutions.isEmpty()) { outgoingExecution = concurrentRoot.createExecution(); log.fine("new " + outgoingExecution + " created to take transition " + outgoingTransition); } else { outgoingExecution = (ExecutionImpl) recyclableExecutions .remove(0); log.fine("recycled " + outgoingExecution + " to take transition " + outgoingTransition); } outgoingExecution.setActive(true); outgoingExecution.setScope(false); outgoingExecution.setConcurrent(true); outgoingExecutions.add(new OutgoingExecution(outgoingExecution, outgoingTransition, true)); } // prune the executions that are not recycled for (ActivityExecution prunedExecution : recyclableExecutions) { log.fine("pruning execution " + prunedExecution); prunedExecution.end(); } // then launch all the concurrent executions for (OutgoingExecution outgoingExecution : outgoingExecutions) { outgoingExecution.take(); } } } public void performOperation(AtomicOperation executionOperation) { this.nextOperation = executionOperation; if (!isOperating) { isOperating = true; while (nextOperation != null) { AtomicOperation currentOperation = this.nextOperation; this.nextOperation = null; if (log.isLoggable(Level.FINEST)) { log.finest("AtomicOperation: " + currentOperation + " on " + this); } currentOperation.execute(this); } isOperating = false; } } public boolean isActive(String activityId) { return findExecution(activityId) != null; } // variables // //////////////////////////////////////////////////////////////// public Object getVariable(String variableName) { ensureVariablesInitialized(); // If value is found in this scope, return it if (variables.containsKey(variableName)) { return variables.get(variableName); } // If value not found in this scope, check the parent scope ensureParentInitialized(); if (parent != null) { return parent.getVariable(variableName); } // Variable is nowhere to be found return null; } public Map<String, Object> getVariables() { Map<String, Object> collectedVariables = new HashMap<String, Object>(); collectVariables(collectedVariables); return collectedVariables; } protected void collectVariables(Map<String, Object> collectedVariables) { ensureParentInitialized(); if (parent != null) { parent.collectVariables(collectedVariables); } ensureVariablesInitialized(); for (String variableName : variables.keySet()) { collectedVariables.put(variableName, variables.get(variableName)); } } public void setVariables(Map<String, ? extends Object> variables) { ensureVariablesInitialized(); if (variables != null) { for (String variableName : variables.keySet()) { setVariable(variableName, variables.get(variableName)); } } } public void setVariable(String variableName, Object value) { ensureVariablesInitialized(); if (variables.containsKey(variableName)) { setVariableLocally(variableName, value); } else { ensureParentInitialized(); if (parent != null) { parent.setVariable(variableName, value); } else { setVariableLocally(variableName, value); } } } public void setVariableLocally(String variableName, Object value) { log.fine("setting variable '" + variableName + "' to value '" + value + "' on " + this); variables.put(variableName, value); } public boolean hasVariable(String variableName) { ensureVariablesInitialized(); if (variables.containsKey(variableName)) { return true; } ensureParentInitialized(); if (parent != null) { return parent.hasVariable(variableName); } return false; } protected void ensureVariablesInitialized() { if (variables == null) { variables = new HashMap<String, Object>(); } } // toString // ///////////////////////////////////////////////////////////////// public String toString() { if (isProcessInstance()) { return "ProcessInstance[" + getToStringIdentity() + "]"; } else { return (isEventScope ? "EventScope" : "") + (isConcurrent ? "Concurrent" : "") + (isScope() ? "Scope" : "") + "Execution[" + getToStringIdentity() + "]"; } } protected String getToStringIdentity() { return Integer.toString(System.identityHashCode(this)); } // customized getters and setters // /////////////////////////////////////////// public boolean isProcessInstance() { ensureParentInitialized(); return parent == null; } public void inactivate() { this.isActive = false; } // allow for subclasses to expose a real id // ///////////////////////////////// public String getId() { return null; } // getters and setters // ////////////////////////////////////////////////////// public TransitionImpl getTransition() { return transition; } public void setTransition(TransitionImpl transition) { this.transition = transition; } public Integer getExecutionListenerIndex() { return executionListenerIndex; } public void setExecutionListenerIndex(Integer executionListenerIndex) { this.executionListenerIndex = executionListenerIndex; } public boolean isConcurrent() { return isConcurrent; } public void setConcurrent(boolean isConcurrent) { this.isConcurrent = isConcurrent; } public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } public boolean isEnded() { return isEnded; } public void setProcessDefinition(ProcessDefinitionImpl processDefinition) { this.processDefinition = processDefinition; } public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public PvmProcessElement getEventSource() { return eventSource; } public void setEventSource(PvmProcessElement eventSource) { this.eventSource = eventSource; } public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } public ExecutionImpl getReplacedBy() { return replacedBy; } public void setReplacedBy(InterpretableExecution replacedBy) { this.replacedBy = (ExecutionImpl) replacedBy; } public void setExecutions(List<ExecutionImpl> executions) { this.executions = executions; } public boolean isDeleteRoot() { return deleteRoot; } public void createVariableLocal(String variableName, Object value) { } public void createVariablesLocal(Map<String, ? extends Object> variables) { } public Object getVariableLocal(Object variableName) { return null; } public Set<String> getVariableNames() { return null; } public Set<String> getVariableNamesLocal() { return null; } public Map<String, Object> getVariablesLocal() { return null; } public boolean hasVariableLocal(String variableName) { return false; } public boolean hasVariables() { return false; } public boolean hasVariablesLocal() { return false; } public void removeVariable(String variableName) { } public void removeVariableLocal(String variableName) { } public void removeVariables() { } public void removeVariablesLocal() { } public Object setVariableLocal(String variableName, Object value) { return null; } public void setVariablesLocal(Map<String, ? extends Object> variables) { } public boolean isEventScope() { return isEventScope; } public void setEventScope(boolean isEventScope) { this.isEventScope = isEventScope; } public StartingExecution getStartingExecution() { return startingExecution; } public void disposeStartingExecution() { startingExecution = null; } }
apache-2.0
marsbits/restfbmessenger
samples/restfbmessenger-echo-spring-boot/src/main/java/com/github/marsbits/restfbmessenger/sample/EchoCallbackHandler.java
3553
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marsbits.restfbmessenger.sample; import static java.lang.String.format; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import org.springframework.stereotype.Component; import com.github.marsbits.restfbmessenger.Messenger; import com.github.marsbits.restfbmessenger.webhook.AbstractCallbackHandler; import com.restfb.types.send.IdMessageRecipient; import com.restfb.types.send.MediaAttachment; import com.restfb.types.webhook.messaging.CoordinatesItem; import com.restfb.types.webhook.messaging.MessageItem; import com.restfb.types.webhook.messaging.MessagingAttachment; import com.restfb.types.webhook.messaging.MessagingItem; /** * The Echo {@code CallbackHandler}. * * @author Marcel Overdijk */ @Component public class EchoCallbackHandler extends AbstractCallbackHandler { private static final Logger logger = Logger.getLogger(EchoCallbackHandler.class.getName()); @Override public void onMessage(Messenger messenger, MessagingItem messaging) { String senderId = messaging.getSender().getId(); MessageItem message = messaging.getMessage(); logger.fine(format("Message received from %s: %s", senderId, message.getText())); IdMessageRecipient recipient = new IdMessageRecipient(senderId); messenger.send().markSeen(recipient); messenger.send().typingOn(recipient); sleep(TimeUnit.SECONDS, 1); if (message.getText() != null) { // Echo the received text message messenger.send().textMessage(recipient, format("Echo: %s", message.getText())); } else { if (message.getAttachments() != null) { for (MessagingAttachment attachment : message.getAttachments()) { String type = attachment.getType(); if ("location".equals(type)) { // Echo the received location as text message(s) CoordinatesItem coordinates = attachment.getPayload().getCoordinates(); Double lat = coordinates.getLat(); Double longVal = coordinates.getLongVal(); messenger.send().textMessage(recipient, format("Lat: %s", lat)); messenger.send().textMessage(recipient, format("Long: %s", longVal)); } else { // Echo the attachment String url = attachment.getPayload().getUrl(); messenger.send().attachment(recipient, MediaAttachment.Type.valueOf(type.toUpperCase()), url); } } } } messenger.send().typingOff(recipient); } private void sleep(TimeUnit timeUnit, long duration) { try { timeUnit.sleep(duration); } catch (InterruptedException ignore) { } } }
apache-2.0
yangjae/android-beacon-library
src/main/java/org/altbeacon/bluetooth/BluetoothCrashResolver.java
19332
package org.altbeacon.bluetooth; import android.annotation.TargetApi; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.util.Log; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * * This class provides relief for Android Bug 67272. This bug in the Bluedroid stack causes crashes * in Android's BluetoothService when scanning for BLE devices encounters a large number of unique * devices. It is rare for most users but can be problematic for those with apps scanning for * Bluetooth LE devices in the background (e.g. beacon-enabled apps), especially when these users * are around Bluetooth LE devices that randomize their mac address like Gimbal beacons. * * This class can both recover from crashes and prevent crashes from happening in the first place * * More details on the bug can be found at the following URLs: * * https://code.google.com/p/android/issues/detail?id=67272 * https://github.com/RadiusNetworks/android-ibeacon-service/issues/16 * * Version 1.0 * * Created by dyoung on 3/24/14. */ @TargetApi(5) public class BluetoothCrashResolver { private static final String TAG = "BluetoothCrashResolver"; private static final boolean PREEMPTIVE_ACTION_ENABLED = true; private boolean debugEnabled = false; /** * This is not the same file that bluedroid uses. This is just to maintain state of this module */ private static final String DISTINCT_BLUETOOTH_ADDRESSES_FILE = "BluetoothCrashResolverState.txt"; private boolean recoveryInProgress = false; private boolean discoveryStartConfirmed = false; private long lastBluetoothOffTime = 0l; private long lastBluetoothTurningOnTime = 0l; private long lastBluetoothCrashDetectionTime = 0l; private int detectedCrashCount = 0; private int recoveryAttemptCount = 0; private boolean lastRecoverySucceeded = false; private long lastStateSaveTime = 0l; private static final long MIN_TIME_BETWEEN_STATE_SAVES_MILLIS = 60000l; private Context context = null; private UpdateNotifier updateNotifier; private Set<String> distinctBluetoothAddresses = new HashSet<String>(); private DiscoveryCanceller discoveryCanceller = new DiscoveryCanceller(); /** // It is very likely a crash if Bluetooth turns off and comes // back on in an extremely short interval. Testing on a Nexus 4 shows // that when the BluetoothService crashes, the time between the STATE_OFF // and the STATE_TURNING_ON ranges from 0ms-684ms // Out of 3614 samples: // 99.4% (3593) < 600 ms // 84.7% (3060) < 500 ms // So we will assume any power off sequence of < 600ms to be a crash // // While it is possible to manually turn bluetooth off then back on in // about 600ms, but it is pretty hard to do. // */ private static final long SUSPICIOUSLY_SHORT_BLUETOOTH_OFF_INTERVAL_MILLIS = 600l; /** * The Bluedroid stack can only track only 1990 unique Bluetooth mac addresses without crashing */ private static final int BLUEDROID_MAX_BLUETOOTH_MAC_COUNT = 1990; /** * The discovery process will pare back the mac address list to 256, but more may * be found in the time we let the discovery process run, depending hon how many BLE * devices are around. */ private static final int BLUEDROID_POST_DISCOVERY_ESTIMATED_BLUETOOTH_MAC_COUNT = 400; /** * It takes a little over 2 seconds after discovery is started before the pared-down mac file * is written to persistent storage. We let discovery run for a few more seconds just to be * sure. */ private static final int TIME_TO_LET_DISCOVERY_RUN_MILLIS = 5000; /* if 0, it means forever */ /** * Constructor should be called only once per long-running process that does Bluetooth LE * scanning. Must call start() to make it do anything. * * @param context the Activity or Service that is doing the Bluetooth scanning */ public BluetoothCrashResolver(Context context) { this.context = context.getApplicationContext(); if (isDebugEnabled()) Log.d(TAG, "constructed"); loadState(); } /** * Starts looking for crashes of the Bluetooth LE system and taking proactive steps to stop * crashes from happening. Proactive steps require calls to notifyScannedDevice(Device device) * so that crashes can be predicted ahead of time. */ public void start() { IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); context.registerReceiver(receiver, filter); if (isDebugEnabled()) Log.d(TAG, "started listening for BluetoothAdapter events"); } /** * Stops looking for crashes. Does not need to be called in normal operations, but may be * useful for testing. */ public void stop() { context.unregisterReceiver(receiver); if (isDebugEnabled()) Log.d(TAG, "stopped listening for BluetoothAdapter events"); saveState(); } /** * Enable debug logging. By default no debug lines are logged. */ public void enableDebug() { debugEnabled = true; } /** * Disable debug logging */ public void disableDebug() { debugEnabled = false; } /** * Call this method from your BluetoothAdapter.LeScanCallback method. * Doing so is optional, but if you do, this class will be able to count the number of * disctinct bluetooth devices scanned, and prevent crashes before they happen. * * This works very well if the app containing this class is the only one running bluetooth * LE scans on the device, or it is constantly doing scans (e.g. is in the foreground for * extended periods of time.) * * This will not work well if the application using this class is only scanning periodically * (e.g. when in the background to save battery) and another application is also scanning on * the same device, because this class will only get the counts from this application. * * Future augmentation of this class may improve this by somehow centralizing the list of * unique scanned devices. * * @param device */ @TargetApi(18) public void notifyScannedDevice(BluetoothDevice device, BluetoothAdapter.LeScanCallback scanner) { int oldSize = 0, newSize = 0; if (isDebugEnabled()) oldSize = distinctBluetoothAddresses.size(); synchronized(distinctBluetoothAddresses) { distinctBluetoothAddresses.add(device.getAddress()); } if (isDebugEnabled()) { newSize = distinctBluetoothAddresses.size(); if (oldSize != newSize && newSize % 100 == 0) { if (isDebugEnabled()) Log.d(TAG, "Distinct bluetooth devices seen: "+distinctBluetoothAddresses.size()); } } if (distinctBluetoothAddresses.size() > getCrashRiskDeviceCount()) { if (PREEMPTIVE_ACTION_ENABLED && !recoveryInProgress) { Log.w(TAG, "Large number of bluetooth devices detected: "+distinctBluetoothAddresses.size()+" Proactively attempting to clear out address list to prevent a crash"); Log.w(TAG, "Stopping LE Scan"); BluetoothAdapter.getDefaultAdapter().stopLeScan(scanner); startRecovery(); processStateChange(); } } } public void crashDetected() { if (android.os.Build.VERSION.SDK_INT < 18) { if (isDebugEnabled()) Log.d(TAG, "Ignoring crashes before SDK 18, because BLE is unsupported."); return; } Log.w(TAG, "BluetoothService crash detected"); if (distinctBluetoothAddresses.size() > 0) { if (isDebugEnabled()) Log.d(TAG, "Distinct bluetooth devices seen at crash: "+distinctBluetoothAddresses.size()); } long nowTimestamp = new Date().getTime(); lastBluetoothCrashDetectionTime = nowTimestamp; detectedCrashCount++; if (recoveryInProgress) { if (isDebugEnabled()) Log.d(TAG, "Ignoring bluetooth crash because recovery is already in progress."); } else { startRecovery(); } processStateChange(); } public long getLastBluetoothCrashDetectionTime() { return lastBluetoothCrashDetectionTime; } public int getDetectedCrashCount() { return detectedCrashCount; } public int getRecoveryAttemptCount() { return recoveryAttemptCount; } public boolean isLastRecoverySucceeded() { return lastRecoverySucceeded; } public boolean isRecoveryInProgress() { return recoveryInProgress; } public interface UpdateNotifier { public void dataUpdated(); } public void setUpdateNotifier(UpdateNotifier updateNotifier) { this.updateNotifier = updateNotifier; } /** Used to force a recovery operation */ public void forceFlush() { startRecovery(); processStateChange(); } private boolean isDebugEnabled() { return debugEnabled; } private int getCrashRiskDeviceCount() { // 1990 distinct devices tracked by Bluedroid will cause a crash. But we don't know how many // devices bluedroid is tracking, we only know how many we have seen, which will be smaller // than the number tracked by bluedroid because the number we track does not include its // initial state. We therefore assume that there are some devices being tracked by bluedroid // after a recovery operation or on startup return BLUEDROID_MAX_BLUETOOTH_MAC_COUNT-BLUEDROID_POST_DISCOVERY_ESTIMATED_BLUETOOTH_MAC_COUNT; } private void processStateChange() { if (updateNotifier != null) { updateNotifier.dataUpdated(); } if (new Date().getTime() - lastStateSaveTime > MIN_TIME_BETWEEN_STATE_SAVES_MILLIS) { saveState(); } } @TargetApi(17) private void startRecovery() { // The discovery operation will start by clearing out the bluetooth mac list to only the 256 // most recently seen BLE mac addresses. recoveryAttemptCount++; BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (isDebugEnabled()) Log.d(TAG, "about to check if discovery is active"); if (!adapter.isDiscovering()) { Log.w(TAG, "Recovery attempt started"); recoveryInProgress = true; discoveryStartConfirmed = false; if (isDebugEnabled()) Log.d(TAG, "about to command discovery"); if (!adapter.startDiscovery()) { Log.w(TAG, "Can't start discovery. Is bluetooth turned on?"); } if (isDebugEnabled()) Log.d(TAG, "startDiscovery commanded. isDiscovering()="+adapter.isDiscovering()); // We don't actually need to do a discovery -- we just need to kick one off so the // mac list will be pared back to 256. Because discovery is an expensive operation in // terms of battery, we will cancel it. if (TIME_TO_LET_DISCOVERY_RUN_MILLIS > 0 ) { if (isDebugEnabled()) Log.d(TAG, "We will be cancelling this discovery in "+TIME_TO_LET_DISCOVERY_RUN_MILLIS+" milliseconds."); discoveryCanceller.doInBackground(); } else { Log.d(TAG, "We will let this discovery run its course."); } } else { Log.w(TAG, "Already discovering. Recovery attempt abandoned."); } } private void finishRecovery() { Log.w(TAG, "Recovery attempt finished"); synchronized(distinctBluetoothAddresses) { distinctBluetoothAddresses.clear(); } recoveryInProgress = false; } private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { if (recoveryInProgress) { if (isDebugEnabled()) Log.d(TAG, "Bluetooth discovery finished"); finishRecovery(); } else { if (isDebugEnabled()) Log.d(TAG, "Bluetooth discovery finished (external)"); } } if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) { if (recoveryInProgress) { discoveryStartConfirmed = true; if (isDebugEnabled()) Log.d(TAG, "Bluetooth discovery started"); } else { if (isDebugEnabled()) Log.d(TAG, "Bluetooth discovery started (external)"); } } if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) { case BluetoothAdapter.ERROR: if (isDebugEnabled()) Log.d(TAG, "Bluetooth state is ERROR"); break; case BluetoothAdapter.STATE_OFF: if (isDebugEnabled()) Log.d(TAG, "Bluetooth state is OFF"); lastBluetoothOffTime = new Date().getTime(); break; case BluetoothAdapter.STATE_TURNING_OFF: break; case BluetoothAdapter.STATE_ON: if (isDebugEnabled()) Log.d(TAG, "Bluetooth state is ON"); if (isDebugEnabled()) Log.d(TAG, "Bluetooth was turned off for "+(lastBluetoothTurningOnTime - lastBluetoothOffTime)+" milliseconds"); if (lastBluetoothTurningOnTime - lastBluetoothOffTime < SUSPICIOUSLY_SHORT_BLUETOOTH_OFF_INTERVAL_MILLIS) { crashDetected(); } break; case BluetoothAdapter.STATE_TURNING_ON: lastBluetoothTurningOnTime = new Date().getTime(); if (isDebugEnabled()) Log.d(TAG, "Bluetooth state is TURNING_ON"); break; } } } }; private void saveState() { FileOutputStream outputStream = null; OutputStreamWriter writer = null; lastStateSaveTime = new Date().getTime(); try { outputStream = context.openFileOutput(DISTINCT_BLUETOOTH_ADDRESSES_FILE, Context.MODE_PRIVATE); writer = new OutputStreamWriter(outputStream); writer.write(lastBluetoothCrashDetectionTime+"\n"); writer.write(detectedCrashCount+"\n"); writer.write(recoveryAttemptCount+"\n"); writer.write(lastRecoverySucceeded ? "1\n" : "0\n"); synchronized (distinctBluetoothAddresses) { for (String mac : distinctBluetoothAddresses) { writer.write(mac); writer.write("\n"); } } } catch (IOException e) { Log.w(TAG, "Can't write macs to "+DISTINCT_BLUETOOTH_ADDRESSES_FILE); } finally { if (writer != null) { try { writer.close(); } catch (IOException e1) { } } } if (isDebugEnabled()) Log.d(TAG, "Wrote "+distinctBluetoothAddresses.size()+" bluetooth addresses"); } private void loadState() { FileInputStream inputStream = null; BufferedReader reader = null; try { inputStream = context.openFileInput(DISTINCT_BLUETOOTH_ADDRESSES_FILE); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; line = reader.readLine(); if (line != null) { lastBluetoothCrashDetectionTime = Long.parseLong(line); } line = reader.readLine(); if (line != null) { detectedCrashCount = Integer.parseInt(line); } line = reader.readLine(); if (line != null) { recoveryAttemptCount = Integer.parseInt(line); } line = reader.readLine(); if (line != null) { lastRecoverySucceeded = false; if (line.equals("1")) { lastRecoverySucceeded = true; } } String mac; while ((mac = reader.readLine()) != null) { distinctBluetoothAddresses.add(mac); } } catch (IOException e) { Log.w(TAG, "Can't read macs from "+DISTINCT_BLUETOOTH_ADDRESSES_FILE); } catch (NumberFormatException e) { Log.w(TAG, "Can't parse file "+DISTINCT_BLUETOOTH_ADDRESSES_FILE); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } if (isDebugEnabled()) Log.d(TAG, "Read "+distinctBluetoothAddresses.size()+" bluetooth addresses"); } private class DiscoveryCanceller extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { try { Thread.sleep(TIME_TO_LET_DISCOVERY_RUN_MILLIS); if (!discoveryStartConfirmed) { Log.w(TAG, "BluetoothAdapter.ACTION_DISCOVERY_STARTED never received. Recovery may fail."); } final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter.isDiscovering()) { if (isDebugEnabled()) Log.d(TAG, "Cancelling discovery"); adapter.cancelDiscovery(); } else { if (isDebugEnabled()) Log.d(TAG, "Discovery not running. Won't cancel it"); } } catch (InterruptedException e) { if (isDebugEnabled()) Log.d(TAG, "DiscoveryCanceller sleep interrupted."); } return null; } @Override protected void onPostExecute(Void result) { } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } } }
apache-2.0
terrancesnyder/solr-analytics
lucene/spatial/src/java/org/apache/lucene/spatial/query/SpatialArgs.java
4992
package org.apache.lucene.spatial.query; /* * 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 com.spatial4j.core.context.SpatialContext; import com.spatial4j.core.shape.Point; import com.spatial4j.core.shape.Rectangle; import com.spatial4j.core.shape.Shape; /** * Principally holds the query {@link Shape} and the {@link SpatialOperation}. * It's used as an argument to some methods on {@link org.apache.lucene.spatial.SpatialStrategy}. * * @lucene.experimental */ public class SpatialArgs { public static final double DEFAULT_DISTERRPCT = 0.025d; private SpatialOperation operation; private Shape shape; private Double distErrPct; private Double distErr; public SpatialArgs(SpatialOperation operation, Shape shape) { if (operation == null || shape == null) throw new NullPointerException("operation and shape are required"); this.operation = operation; this.shape = shape; } /** * Computes the distance given a shape and the {@code distErrPct}. The * algorithm is the fraction of the distance from the center of the query * shape to its furthest bounding box corner. * * @param shape Mandatory. * @param distErrPct 0 to 0.5 * @param ctx Mandatory * @return A distance (in degrees). */ public static double calcDistanceFromErrPct(Shape shape, double distErrPct, SpatialContext ctx) { if (distErrPct < 0 || distErrPct > 0.5) { throw new IllegalArgumentException("distErrPct " + distErrPct + " must be between [0 to 0.5]"); } if (distErrPct == 0 || shape instanceof Point) { return 0; } Rectangle bbox = shape.getBoundingBox(); //The diagonal distance should be the same computed from any opposite corner, // and this is the longest distance that might be occurring within the shape. double diagonalDist = ctx.getDistCalc().distance( ctx.makePoint(bbox.getMinX(), bbox.getMinY()), bbox.getMaxX(), bbox.getMaxY()); return diagonalDist * 0.5 * distErrPct; } /** * Gets the error distance that specifies how precise the query shape is. This * looks at {@link #getDistErr()}, {@link #getDistErrPct()}, and {@code * defaultDistErrPct}. * @param defaultDistErrPct 0 to 0.5 * @return >= 0 */ public double resolveDistErr(SpatialContext ctx, double defaultDistErrPct) { if (distErr != null) return distErr; double distErrPct = (this.distErrPct != null ? this.distErrPct : defaultDistErrPct); return calcDistanceFromErrPct(shape, distErrPct, ctx); } /** Check if the arguments make sense -- throw an exception if not */ public void validate() throws IllegalArgumentException { if (operation.isTargetNeedsArea() && !shape.hasArea()) { throw new IllegalArgumentException(operation + " only supports geometry with area"); } if (distErr != null && distErrPct != null) throw new IllegalArgumentException("Only distErr or distErrPct can be specified."); } @Override public String toString() { return SpatialArgsParser.writeSpatialArgs(this); } //------------------------------------------------ // Getters & Setters //------------------------------------------------ public SpatialOperation getOperation() { return operation; } public void setOperation(SpatialOperation operation) { this.operation = operation; } public Shape getShape() { return shape; } public void setShape(Shape shape) { this.shape = shape; } /** * A measure of acceptable error of the shape as a fraction. This effectively * inflates the size of the shape but should not shrink it. * * @return 0 to 0.5 * @see #calcDistanceFromErrPct(com.spatial4j.core.shape.Shape, double, * com.spatial4j.core.context.SpatialContext) */ public Double getDistErrPct() { return distErrPct; } public void setDistErrPct(Double distErrPct) { if (distErrPct != null) this.distErrPct = distErrPct; } /** * The acceptable error of the shape. This effectively inflates the * size of the shape but should not shrink it. * * @return >= 0 */ public Double getDistErr() { return distErr; } public void setDistErr(Double distErr) { this.distErr = distErr; } }
apache-2.0
prestodb/presto
presto-main/src/main/java/com/facebook/presto/operator/scalar/JsonToRowCast.java
6466
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.scalar; import com.facebook.presto.annotation.UsedByGeneratedCode; import com.facebook.presto.common.block.Block; import com.facebook.presto.common.block.BlockBuilder; import com.facebook.presto.common.block.SingleRowBlockWriter; import com.facebook.presto.common.function.OperatorType; import com.facebook.presto.common.function.SqlFunctionProperties; import com.facebook.presto.common.type.RowType; import com.facebook.presto.common.type.RowType.Field; import com.facebook.presto.common.type.StandardTypes; import com.facebook.presto.metadata.BoundVariables; import com.facebook.presto.metadata.FunctionAndTypeManager; import com.facebook.presto.metadata.SqlOperator; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.util.JsonCastException; import com.facebook.presto.util.JsonUtil.BlockBuilderAppender; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.google.common.collect.ImmutableList; import io.airlift.slice.Slice; import java.lang.invoke.MethodHandle; import java.util.List; import java.util.Map; import java.util.Optional; import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.ArgumentProperty.valueTypeArgumentProperty; import static com.facebook.presto.operator.scalar.ScalarFunctionImplementationChoice.NullConvention.RETURN_NULL_ON_NULL; import static com.facebook.presto.spi.StandardErrorCode.INVALID_CAST_ARGUMENT; import static com.facebook.presto.spi.function.Signature.withVariadicBound; import static com.facebook.presto.util.Failures.checkCondition; import static com.facebook.presto.util.JsonUtil.BlockBuilderAppender.createBlockBuilderAppender; import static com.facebook.presto.util.JsonUtil.JSON_FACTORY; import static com.facebook.presto.util.JsonUtil.canCastFromJson; import static com.facebook.presto.util.JsonUtil.createJsonParser; import static com.facebook.presto.util.JsonUtil.getFieldNameToIndex; import static com.facebook.presto.util.JsonUtil.parseJsonToSingleRowBlock; import static com.facebook.presto.util.JsonUtil.truncateIfNecessaryForErrorMessage; import static com.facebook.presto.util.Reflection.methodHandle; import static com.fasterxml.jackson.core.JsonToken.START_ARRAY; import static com.fasterxml.jackson.core.JsonToken.START_OBJECT; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; public class JsonToRowCast extends SqlOperator { public static final JsonToRowCast JSON_TO_ROW = new JsonToRowCast(); private static final MethodHandle METHOD_HANDLE = methodHandle(JsonToRowCast.class, "toRow", RowType.class, BlockBuilderAppender[].class, Optional.class, SqlFunctionProperties.class, Slice.class); private JsonToRowCast() { super(OperatorType.CAST, ImmutableList.of(withVariadicBound("T", "row")), ImmutableList.of(), parseTypeSignature("T"), ImmutableList.of(parseTypeSignature(StandardTypes.JSON))); } @Override public BuiltInScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, FunctionAndTypeManager functionAndTypeManager) { checkArgument(arity == 1, "Expected arity to be 1"); RowType rowType = (RowType) boundVariables.getTypeVariable("T"); checkCondition(canCastFromJson(rowType), INVALID_CAST_ARGUMENT, "Cannot cast JSON to %s", rowType); List<Field> rowFields = rowType.getFields(); BlockBuilderAppender[] fieldAppenders = rowFields.stream() .map(rowField -> createBlockBuilderAppender(rowField.getType())) .toArray(BlockBuilderAppender[]::new); MethodHandle methodHandle = METHOD_HANDLE.bindTo(rowType).bindTo(fieldAppenders).bindTo(getFieldNameToIndex(rowFields)); return new BuiltInScalarFunctionImplementation( true, ImmutableList.of(valueTypeArgumentProperty(RETURN_NULL_ON_NULL)), methodHandle); } @UsedByGeneratedCode public static Block toRow( RowType rowType, BlockBuilderAppender[] fieldAppenders, Optional<Map<String, Integer>> fieldNameToIndex, SqlFunctionProperties properties, Slice json) { try (JsonParser jsonParser = createJsonParser(JSON_FACTORY, json)) { jsonParser.nextToken(); if (jsonParser.getCurrentToken() == JsonToken.VALUE_NULL) { return null; } if (jsonParser.getCurrentToken() != START_ARRAY && jsonParser.getCurrentToken() != START_OBJECT) { throw new JsonCastException(format("Expected a json array or object, but got %s", jsonParser.getText())); } BlockBuilder rowBlockBuilder = rowType.createBlockBuilder(null, 1); parseJsonToSingleRowBlock( jsonParser, (SingleRowBlockWriter) rowBlockBuilder.beginBlockEntry(), fieldAppenders, fieldNameToIndex); rowBlockBuilder.closeEntry(); if (jsonParser.nextToken() != null) { throw new JsonCastException(format("Unexpected trailing token: %s", jsonParser.getText())); } return rowType.getObject(rowBlockBuilder, 0); } catch (PrestoException | JsonCastException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast to %s. %s\n%s", rowType, e.getMessage(), truncateIfNecessaryForErrorMessage(json)), e); } catch (Exception e) { throw new PrestoException(INVALID_CAST_ARGUMENT, format("Cannot cast to %s.\n%s", rowType, truncateIfNecessaryForErrorMessage(json)), e); } } }
apache-2.0
lgoldstein/communitychest
chest/gui/swing/src/main/java/net/community/chest/swing/text/MutableAttributeSetXmlProxy.java
3524
/* * */ package net.community.chest.swing.text; import java.lang.reflect.Method; import java.util.Map; import javax.swing.Icon; import javax.swing.text.MutableAttributeSet; import javax.swing.text.SimpleAttributeSet; import net.community.chest.awt.dom.UIReflectiveAttributesProxy; import net.community.chest.reflect.AttributeAccessor; /** * <P>Copyright 2009 as per GPLv2</P> * * @param <V> Type of {@link MutableAttributeSet} being proxy-ed * @author Lyor G. * @since Jul 30, 2009 9:20:48 AM */ public class MutableAttributeSetXmlProxy<V extends MutableAttributeSet> extends UIReflectiveAttributesProxy<V> { protected MutableAttributeSetXmlProxy (Class<V> objClass, boolean registerAsDefault) throws IllegalArgumentException, IllegalStateException { super(objClass, registerAsDefault); } public MutableAttributeSetXmlProxy (Class<V> vc) { this(vc, false); } /* * @see net.community.chest.dom.proxy.ReflectiveAttributesProxy#updateObjectResourceAttribute(java.lang.Object, java.lang.String, java.lang.String, java.lang.Class, java.lang.reflect.Method) */ @Override protected V updateObjectResourceAttribute (final V src, final String aName, final String aValue, final Class<?> t, final Method setter) throws Exception { final Object o=loadObjectResourceAttribute(src, aName, aValue, t); setter.invoke(null, src, o); return src; } public V updateStyleAttribute (final V src, final String aName, final String aValue, final Class<?> aType, final Method setter) throws Exception { if ((aType != null) && Icon.class.isAssignableFrom(aType)) return updateObjectResourceAttribute(src, aName, aValue, Icon.class, setter); final Object objValue=getObjectAttributeValue(src, aName, aValue, aType); setter.invoke(null, src, objValue); return src; } public V updateStyleAttribute (final V src, final String aName, final String aValue, final Map<String,? extends Method> accsMap) throws Exception { final Map<String,? extends AttributeAccessor> aMap= ((null == aName) || (aName.length() <= 0)) ? null : StyleConstantsUtils.getDefaultStyleConstantsSetters(); final AttributeAccessor aa= ((null == aMap) || (aMap.size() <= 0)) ? null : aMap.get(aName); final Class<?> aType= (null == aa) ? null : aa.getType(); final Method setter= (null == aa) ? null : aa.getSetter(); if ((null == aType) || (null == setter)) return super.handleUnknownAttribute(src, aName, aValue, accsMap); return updateStyleAttribute(src, aName, aValue, aType, setter); } /* * @see net.community.chest.dom.proxy.ReflectiveAttributesProxy#handleUnknownAttribute(java.lang.Object, java.lang.String, java.lang.String, java.util.Map) */ @Override protected V handleUnknownAttribute (V src, String name, String value, Map<String,? extends Method> accsMap) throws Exception { if (NAME_ATTR.equalsIgnoreCase(name)) return src; return updateStyleAttribute(src, name, value, accsMap); } public static final MutableAttributeSetXmlProxy<SimpleAttributeSet> SIMPLESET= new MutableAttributeSetXmlProxy<SimpleAttributeSet>(SimpleAttributeSet.class, true); }
apache-2.0
liuhailin/zookeeper-console
src/main/java/com/lhl/zk/interceptor/AuthInterceptor.java
1148
package com.lhl.zk.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.lhl.zk.util.AuthUtils; public class AuthInterceptor extends HandlerInterceptorAdapter { private static final Logger log =LoggerFactory.getLogger(AuthInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // if (!AuthUtils.isLogin()) { // throw new RuntimeException("没有登录"); // // } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { modelAndView.addObject("host", request.getContextPath()); modelAndView.addObject("isLogin", AuthUtils.isLogin()); log.info("=========contextPath:{}",request.getContextPath()); super.postHandle(request, response, handler, modelAndView); } }
apache-2.0
thomasgalvin/Utils
src/main/java/galvin/Selectable.java
131
package galvin; public interface Selectable { public boolean isSelected(); public void setSelected( boolean selected ); }
apache-2.0
slolars/yql-plus
yqlplus_engine/src/main/java/com/yahoo/yqlplus/engine/guice/MultibinderPlannerNamespace.java
2406
/* * Copyright (c) 2016 Yahoo Inc. * Licensed under the terms of the Apache version 2.0 license. * See LICENSE file for terms. */ package com.yahoo.yqlplus.engine.guice; import com.google.common.base.Joiner; import com.google.inject.Inject; import com.google.inject.Provider; import com.yahoo.yqlplus.api.Exports; import com.yahoo.yqlplus.api.Source; import com.yahoo.yqlplus.engine.api.DependencyNotFoundException; import com.yahoo.yqlplus.engine.internal.plan.*; import com.yahoo.yqlplus.engine.internal.source.ExportUnitGenerator; import com.yahoo.yqlplus.engine.internal.source.SourceUnitGenerator; import com.yahoo.yqlplus.language.parser.Location; import com.yahoo.yqlplus.language.parser.ProgramCompileException; import java.util.List; import java.util.Map; /** * Implement the Namespace binding with a Guice MapBinder. */ public class MultibinderPlannerNamespace implements SourceNamespace, ModuleNamespace { private final Map<String, Provider<Source>> sourceBindings; private final Map<String, Provider<Exports>> exportsBindings; private String keyFor(List<String> path) { return Joiner.on('.').join(path); } @Inject MultibinderPlannerNamespace(Map<String, Provider<Exports>> exportsBindings, Map<String, Provider<Source>> sourceBindings) { this.exportsBindings = exportsBindings; this.sourceBindings = sourceBindings; } @Override public ModuleType findModule(Location location, ContextPlanner planner, List<String> modulePath) { Provider<Exports> moduleProvider = exportsBindings.get(keyFor(modulePath)); if (moduleProvider == null) { throw new ProgramCompileException(location, "No source '%s' found", keyFor(modulePath)); } ExportUnitGenerator adapter = new ExportUnitGenerator(planner.getGambitScope()); return adapter.apply(modulePath, moduleProvider); } @Override public SourceType findSource(Location location, ContextPlanner planner, List<String> sourcePath) { Provider<Source> sourceProvider = sourceBindings.get(keyFor(sourcePath)); if (sourceProvider == null) { throw new DependencyNotFoundException(location, "No source '%s' found", keyFor(sourcePath)); } SourceUnitGenerator adapter = new SourceUnitGenerator(planner.getGambitScope()); return adapter.apply(sourcePath, sourceProvider); } }
apache-2.0
marklogic/data-hub-in-a-box
web/src/main/java/com/marklogic/hub/web/model/StatusMessage.java
901
/* * Copyright 2012-2019 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.marklogic.hub.web.model; public class StatusMessage { public int percentComplete; public String message; public StatusMessage(int percentComplete, String message) { this.percentComplete = percentComplete; this.message = message; } }
apache-2.0
jjaquinta/EchoSim
jo.alexa.sim/src/jo/alexa/sim/logic/UtteranceLogic.java
5919
package jo.alexa.sim.logic; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.List; import jo.alexa.sim.data.ApplicationBean; import jo.alexa.sim.data.IntentBean; import jo.alexa.sim.data.PhraseSegmentBean; import jo.alexa.sim.data.SlotBean; import jo.alexa.sim.data.SlotSegmentBean; import jo.alexa.sim.data.TextSegmentBean; import jo.alexa.sim.data.UtteranceBean; public class UtteranceLogic { private static final String[] BUILT_IN_UTTERANCES = { "AMAZON.CancelIntent\tcancel", "AMAZON.CancelIntent\tnever mind", "AMAZON.CancelIntent\tforget it", "AMAZON.HelpIntent\thelp", "AMAZON.HelpIntent\thelp me", "AMAZON.HelpIntent\tcan you help me", "AMAZON.NoIntent\tno", "AMAZON.NoIntent\tno thanks", "AMAZON.RepeatIntent\trepeat", "AMAZON.RepeatIntent\tsay that again", "AMAZON.RepeatIntent\trepeat that", "AMAZON.StartOverIntent\tstart over", "AMAZON.StartOverIntent\trestart", "AMAZON.StartOverIntent\tstart again", "AMAZON.StopIntent\tstop", "AMAZON.StopIntent\toff", "AMAZON.StopIntent\tshut up", "AMAZON.YesIntent\tyes", "AMAZON.YesIntent\tyes please", "AMAZON.YesIntent\tsure", }; public static void read(ApplicationBean app, Reader r) throws IOException { app.getUtterances().clear(); for (IntentBean intent : app.getIntentIndex().values()) for (SlotBean slot : intent.getSlots()) slot.getValues().clear(); BufferedReader rdr = new BufferedReader(r); for (;;) { String inbuf = rdr.readLine(); if (inbuf == null) break; inbuf = inbuf.trim(); if (inbuf.length() > 0) parseUtterance(app, inbuf, true); } rdr.close(); // simulate built in utterances for (String inbuf : BUILT_IN_UTTERANCES) parseUtterance(app, inbuf, false); } private static void parseUtterance(ApplicationBean app, String inbuf, boolean strict) { int o = inbuf.indexOf('\t'); if (o < 0) { o = inbuf.indexOf(' '); if (o < 0) throw new IllegalArgumentException("Badly formed utterance line '"+inbuf+"'"); } UtteranceBean utterance = new UtteranceBean(); utterance.setIntent(app.getIntentIndex().get(inbuf.substring(0, o))); if ((utterance.getIntent() == null) && strict) throw new IllegalArgumentException("Unknown intent '"+inbuf.substring(0, o)+"'"); inbuf = inbuf.substring(o + 1).trim(); while (inbuf.length() > 0) if (inbuf.charAt(0) == '{') { int end = inbuf.indexOf('}'); if (end < 0) throw new IllegalArgumentException("Can't find end of slot '"+inbuf+"'"); String slotPhrase = inbuf.substring(1, end); inbuf = inbuf.substring(end + 1).trim(); SlotSegmentBean slotSeg = new SlotSegmentBean(); int mid = slotPhrase.indexOf('|'); if (mid < 0) { slotSeg.setText(null); slotSeg.setSlot(app.getSlotIndex().get(slotPhrase)); } else { slotSeg.setText(slotPhrase.substring(0, mid).toLowerCase()); slotSeg.setSlot(app.getSlotIndex().get(slotPhrase.substring(mid + 1))); } if (slotSeg.getSlot() == null) throw new IllegalArgumentException("Unknown slot '"+slotPhrase.substring(mid + 1)+"'"); utterance.getPhrase().add(slotSeg); if (slotSeg.getText() != null) slotSeg.getSlot().getValues().add(slotSeg.getText()); } else { int end = inbuf.indexOf('{'); if (end < 0) end = inbuf.length(); TextSegmentBean textSeg = new TextSegmentBean(); textSeg.setText(inbuf.substring(0, end).trim().toLowerCase()); inbuf = inbuf.substring(end).trim(); utterance.getPhrase().add(textSeg); } app.getUtterances().add(utterance); } public static String renderAsHTML(List<UtteranceBean> utterances) { StringBuffer html = new StringBuffer(); for (UtteranceBean u : utterances) { if (html.length() > 0) html.append("<br/>"); html.append(renderAsHTML(u)); } return html.toString(); } public static String renderAsHTML(UtteranceBean utterance) { StringBuffer html = new StringBuffer(); html.append("<b>"); html.append(utterance.getIntent().getIntent()); html.append("</b>"); html.append(" "); for (PhraseSegmentBean p : utterance.getPhrase()) if (p instanceof TextSegmentBean) { html.append(((TextSegmentBean)p).getText()); html.append(" "); } else if (p instanceof SlotSegmentBean) { html.append("<span title=\""+((SlotSegmentBean)p).getSlot().getName()+" ("+((SlotSegmentBean)p).getSlot().getName()+")\">"); html.append(((SlotSegmentBean)p).getText()); html.append("</span>"); html.append(" "); } else throw new IllegalArgumentException("Unknown PhraseSegment: "+p.getClass().getName()); return html.toString(); } }
apache-2.0
chmyga/component-runtime
component-runtime-manager/src/test/java/org/talend/sdk/component/runtime/manager/reflect/IconFinderTest.java
3250
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.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 org.talend.sdk.component.runtime.manager.reflect; import org.junit.jupiter.api.Test; import org.talend.sdk.component.api.component.Icon; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Locale; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; class IconFinderTest { private final IconFinder finder = new IconFinder(); @Test void findDirectIcon() { assertFalse(finder.findDirectIcon(None.class).isPresent()); assertEquals("foo", finder.findDirectIcon(Direct.class).get()); } @Test void findInDirectIcon() { assertFalse(finder.findDirectIcon(Indirect.class).isPresent()); assertEquals("yes", finder.findIndirectIcon(Indirect.class).get()); } @Test void findMetaIcon() { assertFalse(finder.findDirectIcon(Indirect.class).isPresent()); assertEquals("complex_", finder.findIndirectIcon(Meta.class).get()); } @Test void findIcon() { assertEquals("foo", finder.findIcon(Direct.class)); assertEquals("yes", finder.findIcon(Indirect.class)); assertEquals("default", finder.findIcon(None.class)); } @Test void helperMethod() { { final boolean isCustom = finder.isCustom(finder.extractIcon(Direct.class)); final String name = finder.findIcon(Direct.class); assertEquals("foo/true", name + '/' + isCustom); } { final boolean isCustom = finder.isCustom(finder.extractIcon(Meta.class)); final String name = finder.findIcon(Meta.class); assertEquals("complex_/false", name + '/' + isCustom); } } public static class None { } @Icon(custom = "foo") public static class Direct { } @MyIcon public static class Indirect { } @MetaIcon(MetaIcon.MetaIconValue.COMPLEX) public static class Meta { } @Icon @Target(TYPE) @Retention(RUNTIME) public @interface MetaIcon { MetaIconValue value(); // optional but normally not needed EnumOrString type() default "custom"; enum MetaIconValue { SIMPLE, COMPLEX; public String getKey() { return name().toLowerCase(Locale.ROOT) + '_'; } } } @Target(TYPE) @Retention(RUNTIME) public @interface MyIcon { String value() default "yes"; } }
apache-2.0
albertonavarro/nifty-flow
examples/ex1/src/main/java/indep_screen3/Controller3.java
1048
package indep_screen3; import com.navid.nifty.flow.ScreenFlowManager; import com.navid.nifty.flow.ScreenFlowManagerImpl; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; /** * Created by alberto on 08/07/15. */ public class Controller3 implements ScreenController { private final ScreenFlowManager screenFlowManager; private Nifty nifty; public Controller3(ScreenFlowManager screenFlowManager) { this.screenFlowManager = screenFlowManager; } @Override public void bind(Nifty nifty, Screen screen) { this.nifty = nifty; } @Override public void onStartScreen() { } @Override public void onEndScreen() { } public void back() { screenFlowManager.setNextScreenHint(ScreenFlowManagerImpl.PREV); nifty.gotoScreen("redirector"); } public void next() { screenFlowManager.setNextScreenHint(ScreenFlowManagerImpl.NEXT); nifty.gotoScreen("redirector"); } }
apache-2.0
CatalystIT/sonar-score-plugin
src/test/java/com/catalyst/sonar/score/api/CriterionTest.java
2683
/** * */ package com.catalyst.sonar.score.api; import static org.junit.Assert.*; import static com.catalyst.sonar.score.api.ApiTestConstants.*; import org.junit.Before; import org.junit.Test; /** * Test Class for {@link Criterion}. * * @author JDunn */ public class CriterionTest { private Criterion testCriterion; private Criterion twinCriterion; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { testCriterion = new Criterion(METRIC_1, AMOUNT_1, DAYS_1); twinCriterion = new Criterion(METRIC_1, AMOUNT_1, DAYS_1); } /** * Test method for {@link Criterion#hashCode()} . */ @Test public void testHashCode() { assertEquals(testCriterion.hashCode(), twinCriterion.hashCode()); testCriterion.setMetric(NULL_METRIC); twinCriterion.setMetric(NULL_METRIC); assertEquals(testCriterion.hashCode(), twinCriterion.hashCode()); } /** * Test method for {@link Criterion#Criterion()}. */ @Test public void testCriterion() { Criterion defaultCriterion = new Criterion(); assertEquals(0, defaultCriterion.getAmount(), 0); assertNull(defaultCriterion.getMetric()); assertEquals(0, defaultCriterion.getDays()); } /** * Test method for * {@link Criterion#Criterion(org.sonar.api.measures.Metric, double, int)} . */ @Test public void testCriterionMetricDoubleInt() { assertEquals(METRIC_1, testCriterion.getMetric()); assertEquals(AMOUNT_1, testCriterion.getAmount(), 0); assertEquals(DAYS_1, testCriterion.getDays()); } /** * Test method for {@link Criterion#getMetric()}. */ @Test public void testGetMetric() { assertEquals(METRIC_1, testCriterion.getMetric()); } /** * Test method for {@link Criterion#setMetric(Metric)} . */ @Test public void testSetMetric() { testCriterion.setMetric(METRIC_2); assertEquals(METRIC_2, testCriterion.getMetric()); } /** * Test method for {@link Criterion#getAmount()}. */ @Test public void testGetAmount() { assertEquals(AMOUNT_1, testCriterion.getAmount(), 0); } /** * Test method for {@link Criterion#setAmount(double)}. */ @Test public void testSetAmount() { testCriterion.setAmount(AMOUNT_2); assertEquals(AMOUNT_2, testCriterion.getAmount(), 0); } /** * Test method for {@link Criterion#getDays()}. */ @Test public void testGetDays() { assertEquals(DAYS_1, testCriterion.getDays()); } /** * Test method for {@link Criterion#setDays(int)}. */ @Test public void testSetDays() { testCriterion.setDays(DAYS_2); assertEquals(DAYS_2, testCriterion.getDays()); } }
apache-2.0
FoxconnPeter/IMOCC
imooc_business/vuandroidadsdk/src/main/java/com/youdu/core/display/DisplayAdContext.java
1271
package com.youdu.core.display; import android.view.ViewGroup; /** * Created by qndroid on 16/10/27. * * @function 用来与外界通信的类, 接收参数, 发送请求 */ public class DisplayAdContext implements DisplayAdSlot.DisplayConextListener { /** * Data */ private DisplayAdSlot mDisplayAdSlot; //图片类型广告 private DisplayAdAppListener mAdAppListener; public DisplayAdContext(ViewGroup parentView) { mDisplayAdSlot = new DisplayAdSlot(parentView); mDisplayAdSlot.setContextListener(this); } public void setAdAppListener(DisplayAdAppListener listener) { mAdAppListener = listener; } @Override public void onLoadingComplete() { if (mAdAppListener != null) { mAdAppListener.onLoadingComplete(); } } //真正的加载图片失败 @Override public void onLoadingFailed() { if (mAdAppListener != null) { mAdAppListener.onLoadingFailed(); } } public void onDispose() { if (mDisplayAdSlot != null) { mDisplayAdSlot.onDispose(); } } public interface DisplayAdAppListener { void onLoadingComplete(); void onLoadingFailed(); } }
apache-2.0
tangjf420/ttweb
ttweb/src/main/java/com/tangjf/tally/dao/TallyTypeMapper.java
187
package com.tangjf.tally.dao; import com.tangjf.framework.dao.BaseMapper; import com.tangjf.tally.dto.TallyType; public interface TallyTypeMapper extends BaseMapper<TallyType> { }
apache-2.0
connecto/connecto-java
src/main/java/io/connecto/connectoapi/SegmentResponse.java
1428
package io.connecto.connectoapi; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.List; /** * A model class which wraps around a list of segment objects. * * An instance of this class is returned by the getSegments api. * @see ConnectoAPI#getSegments(String, String) * */ public class SegmentResponse { /** * Formats a generic identify message. * @param segmentList a payload of the operation. Will be converted to JSON, and should be of types * Boolean, Double, Integer, Long, String, JSONArray, JSONObject, the JSONObject.NULL object, or null. * NaN and negative/positive infinity will throw an IllegalArgumentException * @throws JSONException if the JSON object is not convertible to a segment array * * @see ConnectoAPI#getSegments(String, String) */ public SegmentResponse(JSONArray segmentList) throws JSONException { if (segmentList.length() != 0) { mSegments = new ArrayList<Segment>(); for (int i = 0; i < segmentList.length(); i++) { Segment segmentObj = null; segmentObj = new Segment(segmentList.getJSONObject(i)); mSegments.add(segmentObj); } } } /* package */ public List<Segment> getSegments() { return mSegments; } private List<Segment> mSegments; }
apache-2.0
fenik17/netty
codec/src/main/java/io/netty/handler/codec/base64/Base64Decoder.java
2347
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.codec.base64; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import io.netty.handler.codec.MessageToMessageDecoder; import io.netty.util.internal.ObjectUtil; import java.util.List; /** * Decodes a Base64-encoded {@link ByteBuf} or US-ASCII {@link String} * into a {@link ByteBuf}. Please note that this decoder must be used * with a proper {@link ByteToMessageDecoder} such as {@link DelimiterBasedFrameDecoder} * if you are using a stream-based transport such as TCP/IP. A typical decoder * setup for TCP/IP would be: * <pre> * {@link ChannelPipeline} pipeline = ...; * * // Decoders * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()})); * pipeline.addLast("base64Decoder", new {@link Base64Decoder}()); * * // Encoder * pipeline.addLast("base64Encoder", new {@link Base64Encoder}()); * </pre> */ @Sharable public class Base64Decoder extends MessageToMessageDecoder<ByteBuf> { private final Base64Dialect dialect; public Base64Decoder() { this(Base64Dialect.STANDARD); } public Base64Decoder(Base64Dialect dialect) { this.dialect = ObjectUtil.checkNotNull(dialect, "dialect"); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { out.add(Base64.decode(msg, msg.readerIndex(), msg.readableBytes(), dialect)); } }
apache-2.0
googleapis/java-common-protos
grpc-google-common-protos/src/main/java/com/google/longrunning/OperationsGrpc.java
42722
/* * 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. */ package com.google.longrunning; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * * * <pre> * Manages long-running operations with an API service. * When an API method normally takes long time to complete, it can be designed * to return [Operation][google.longrunning.Operation] to the client, and the client can use this * interface to receive the real response asynchronously by polling the * operation resource, or pass the operation resource to another API (such as * Google Cloud Pub/Sub API) to receive the response. Any API service that * returns long-running operations should implement the `Operations` interface * so developers can have a consistent client experience. * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/longrunning/operations.proto") @io.grpc.stub.annotations.GrpcGenerated public final class OperationsGrpc { private OperationsGrpc() {} public static final String SERVICE_NAME = "google.longrunning.Operations"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor< com.google.longrunning.ListOperationsRequest, com.google.longrunning.ListOperationsResponse> getListOperationsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "ListOperations", requestType = com.google.longrunning.ListOperationsRequest.class, responseType = com.google.longrunning.ListOperationsResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.longrunning.ListOperationsRequest, com.google.longrunning.ListOperationsResponse> getListOperationsMethod() { io.grpc.MethodDescriptor< com.google.longrunning.ListOperationsRequest, com.google.longrunning.ListOperationsResponse> getListOperationsMethod; if ((getListOperationsMethod = OperationsGrpc.getListOperationsMethod) == null) { synchronized (OperationsGrpc.class) { if ((getListOperationsMethod = OperationsGrpc.getListOperationsMethod) == null) { OperationsGrpc.getListOperationsMethod = getListOperationsMethod = io.grpc.MethodDescriptor .<com.google.longrunning.ListOperationsRequest, com.google.longrunning.ListOperationsResponse> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListOperations")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.ListOperationsRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.ListOperationsResponse.getDefaultInstance())) .setSchemaDescriptor(new OperationsMethodDescriptorSupplier("ListOperations")) .build(); } } } return getListOperationsMethod; } private static volatile io.grpc.MethodDescriptor< com.google.longrunning.GetOperationRequest, com.google.longrunning.Operation> getGetOperationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetOperation", requestType = com.google.longrunning.GetOperationRequest.class, responseType = com.google.longrunning.Operation.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.longrunning.GetOperationRequest, com.google.longrunning.Operation> getGetOperationMethod() { io.grpc.MethodDescriptor< com.google.longrunning.GetOperationRequest, com.google.longrunning.Operation> getGetOperationMethod; if ((getGetOperationMethod = OperationsGrpc.getGetOperationMethod) == null) { synchronized (OperationsGrpc.class) { if ((getGetOperationMethod = OperationsGrpc.getGetOperationMethod) == null) { OperationsGrpc.getGetOperationMethod = getGetOperationMethod = io.grpc.MethodDescriptor .<com.google.longrunning.GetOperationRequest, com.google.longrunning.Operation> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetOperation")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.GetOperationRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.Operation.getDefaultInstance())) .setSchemaDescriptor(new OperationsMethodDescriptorSupplier("GetOperation")) .build(); } } } return getGetOperationMethod; } private static volatile io.grpc.MethodDescriptor< com.google.longrunning.DeleteOperationRequest, com.google.protobuf.Empty> getDeleteOperationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "DeleteOperation", requestType = com.google.longrunning.DeleteOperationRequest.class, responseType = com.google.protobuf.Empty.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.longrunning.DeleteOperationRequest, com.google.protobuf.Empty> getDeleteOperationMethod() { io.grpc.MethodDescriptor< com.google.longrunning.DeleteOperationRequest, com.google.protobuf.Empty> getDeleteOperationMethod; if ((getDeleteOperationMethod = OperationsGrpc.getDeleteOperationMethod) == null) { synchronized (OperationsGrpc.class) { if ((getDeleteOperationMethod = OperationsGrpc.getDeleteOperationMethod) == null) { OperationsGrpc.getDeleteOperationMethod = getDeleteOperationMethod = io.grpc.MethodDescriptor .<com.google.longrunning.DeleteOperationRequest, com.google.protobuf.Empty> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeleteOperation")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.DeleteOperationRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.protobuf.Empty.getDefaultInstance())) .setSchemaDescriptor( new OperationsMethodDescriptorSupplier("DeleteOperation")) .build(); } } } return getDeleteOperationMethod; } private static volatile io.grpc.MethodDescriptor< com.google.longrunning.CancelOperationRequest, com.google.protobuf.Empty> getCancelOperationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CancelOperation", requestType = com.google.longrunning.CancelOperationRequest.class, responseType = com.google.protobuf.Empty.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.longrunning.CancelOperationRequest, com.google.protobuf.Empty> getCancelOperationMethod() { io.grpc.MethodDescriptor< com.google.longrunning.CancelOperationRequest, com.google.protobuf.Empty> getCancelOperationMethod; if ((getCancelOperationMethod = OperationsGrpc.getCancelOperationMethod) == null) { synchronized (OperationsGrpc.class) { if ((getCancelOperationMethod = OperationsGrpc.getCancelOperationMethod) == null) { OperationsGrpc.getCancelOperationMethod = getCancelOperationMethod = io.grpc.MethodDescriptor .<com.google.longrunning.CancelOperationRequest, com.google.protobuf.Empty> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CancelOperation")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.CancelOperationRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.protobuf.Empty.getDefaultInstance())) .setSchemaDescriptor( new OperationsMethodDescriptorSupplier("CancelOperation")) .build(); } } } return getCancelOperationMethod; } private static volatile io.grpc.MethodDescriptor< com.google.longrunning.WaitOperationRequest, com.google.longrunning.Operation> getWaitOperationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "WaitOperation", requestType = com.google.longrunning.WaitOperationRequest.class, responseType = com.google.longrunning.Operation.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.longrunning.WaitOperationRequest, com.google.longrunning.Operation> getWaitOperationMethod() { io.grpc.MethodDescriptor< com.google.longrunning.WaitOperationRequest, com.google.longrunning.Operation> getWaitOperationMethod; if ((getWaitOperationMethod = OperationsGrpc.getWaitOperationMethod) == null) { synchronized (OperationsGrpc.class) { if ((getWaitOperationMethod = OperationsGrpc.getWaitOperationMethod) == null) { OperationsGrpc.getWaitOperationMethod = getWaitOperationMethod = io.grpc.MethodDescriptor .<com.google.longrunning.WaitOperationRequest, com.google.longrunning.Operation> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "WaitOperation")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.WaitOperationRequest.getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.longrunning.Operation.getDefaultInstance())) .setSchemaDescriptor(new OperationsMethodDescriptorSupplier("WaitOperation")) .build(); } } } return getWaitOperationMethod; } /** Creates a new async stub that supports all call types for the service */ public static OperationsStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<OperationsStub> factory = new io.grpc.stub.AbstractStub.StubFactory<OperationsStub>() { @java.lang.Override public OperationsStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OperationsStub(channel, callOptions); } }; return OperationsStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static OperationsBlockingStub newBlockingStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<OperationsBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<OperationsBlockingStub>() { @java.lang.Override public OperationsBlockingStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OperationsBlockingStub(channel, callOptions); } }; return OperationsBlockingStub.newStub(factory, channel); } /** Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static OperationsFutureStub newFutureStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<OperationsFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<OperationsFutureStub>() { @java.lang.Override public OperationsFutureStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OperationsFutureStub(channel, callOptions); } }; return OperationsFutureStub.newStub(factory, channel); } /** * * * <pre> * Manages long-running operations with an API service. * When an API method normally takes long time to complete, it can be designed * to return [Operation][google.longrunning.Operation] to the client, and the client can use this * interface to receive the real response asynchronously by polling the * operation resource, or pass the operation resource to another API (such as * Google Cloud Pub/Sub API) to receive the response. Any API service that * returns long-running operations should implement the `Operations` interface * so developers can have a consistent client experience. * </pre> */ public abstract static class OperationsImplBase implements io.grpc.BindableService { /** * * * <pre> * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/&#42;&#47;operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/&#42;}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. * </pre> */ public void listOperations( com.google.longrunning.ListOperationsRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.ListOperationsResponse> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getListOperationsMethod(), responseObserver); } /** * * * <pre> * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * </pre> */ public void getOperation( com.google.longrunning.GetOperationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getGetOperationMethod(), responseObserver); } /** * * * <pre> * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * </pre> */ public void deleteOperation( com.google.longrunning.DeleteOperationRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getDeleteOperationMethod(), responseObserver); } /** * * * <pre> * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * [Operations.GetOperation][google.longrunning.Operations.GetOperation] or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, * corresponding to `Code.CANCELLED`. * </pre> */ public void cancelOperation( com.google.longrunning.CancelOperationRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getCancelOperationMethod(), responseObserver); } /** * * * <pre> * Waits until the specified long-running operation is done or reaches at most * a specified timeout, returning the latest state. If the operation is * already done, the latest state is immediately returned. If the timeout * specified is greater than the default HTTP/RPC timeout, the HTTP/RPC * timeout is used. If the server does not support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * Note that this method is on a best-effort basis. It may return the latest * state before the specified timeout (including immediately), meaning even an * immediate response is no guarantee that the operation is done. * </pre> */ public void waitOperation( com.google.longrunning.WaitOperationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getWaitOperationMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getListOperationsMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.longrunning.ListOperationsRequest, com.google.longrunning.ListOperationsResponse>( this, METHODID_LIST_OPERATIONS))) .addMethod( getGetOperationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.longrunning.GetOperationRequest, com.google.longrunning.Operation>( this, METHODID_GET_OPERATION))) .addMethod( getDeleteOperationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.longrunning.DeleteOperationRequest, com.google.protobuf.Empty>( this, METHODID_DELETE_OPERATION))) .addMethod( getCancelOperationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.longrunning.CancelOperationRequest, com.google.protobuf.Empty>( this, METHODID_CANCEL_OPERATION))) .addMethod( getWaitOperationMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.longrunning.WaitOperationRequest, com.google.longrunning.Operation>(this, METHODID_WAIT_OPERATION))) .build(); } } /** * * * <pre> * Manages long-running operations with an API service. * When an API method normally takes long time to complete, it can be designed * to return [Operation][google.longrunning.Operation] to the client, and the client can use this * interface to receive the real response asynchronously by polling the * operation resource, or pass the operation resource to another API (such as * Google Cloud Pub/Sub API) to receive the response. Any API service that * returns long-running operations should implement the `Operations` interface * so developers can have a consistent client experience. * </pre> */ public static final class OperationsStub extends io.grpc.stub.AbstractAsyncStub<OperationsStub> { private OperationsStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected OperationsStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OperationsStub(channel, callOptions); } /** * * * <pre> * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/&#42;&#47;operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/&#42;}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. * </pre> */ public void listOperations( com.google.longrunning.ListOperationsRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.ListOperationsResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getListOperationsMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * </pre> */ public void getOperation( com.google.longrunning.GetOperationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getGetOperationMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * </pre> */ public void deleteOperation( com.google.longrunning.DeleteOperationRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getDeleteOperationMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * [Operations.GetOperation][google.longrunning.Operations.GetOperation] or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, * corresponding to `Code.CANCELLED`. * </pre> */ public void cancelOperation( com.google.longrunning.CancelOperationRequest request, io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCancelOperationMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * Waits until the specified long-running operation is done or reaches at most * a specified timeout, returning the latest state. If the operation is * already done, the latest state is immediately returned. If the timeout * specified is greater than the default HTTP/RPC timeout, the HTTP/RPC * timeout is used. If the server does not support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * Note that this method is on a best-effort basis. It may return the latest * state before the specified timeout (including immediately), meaning even an * immediate response is no guarantee that the operation is done. * </pre> */ public void waitOperation( com.google.longrunning.WaitOperationRequest request, io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getWaitOperationMethod(), getCallOptions()), request, responseObserver); } } /** * * * <pre> * Manages long-running operations with an API service. * When an API method normally takes long time to complete, it can be designed * to return [Operation][google.longrunning.Operation] to the client, and the client can use this * interface to receive the real response asynchronously by polling the * operation resource, or pass the operation resource to another API (such as * Google Cloud Pub/Sub API) to receive the response. Any API service that * returns long-running operations should implement the `Operations` interface * so developers can have a consistent client experience. * </pre> */ public static final class OperationsBlockingStub extends io.grpc.stub.AbstractBlockingStub<OperationsBlockingStub> { private OperationsBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected OperationsBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OperationsBlockingStub(channel, callOptions); } /** * * * <pre> * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/&#42;&#47;operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/&#42;}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. * </pre> */ public com.google.longrunning.ListOperationsResponse listOperations( com.google.longrunning.ListOperationsRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getListOperationsMethod(), getCallOptions(), request); } /** * * * <pre> * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * </pre> */ public com.google.longrunning.Operation getOperation( com.google.longrunning.GetOperationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getGetOperationMethod(), getCallOptions(), request); } /** * * * <pre> * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * </pre> */ public com.google.protobuf.Empty deleteOperation( com.google.longrunning.DeleteOperationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getDeleteOperationMethod(), getCallOptions(), request); } /** * * * <pre> * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * [Operations.GetOperation][google.longrunning.Operations.GetOperation] or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, * corresponding to `Code.CANCELLED`. * </pre> */ public com.google.protobuf.Empty cancelOperation( com.google.longrunning.CancelOperationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCancelOperationMethod(), getCallOptions(), request); } /** * * * <pre> * Waits until the specified long-running operation is done or reaches at most * a specified timeout, returning the latest state. If the operation is * already done, the latest state is immediately returned. If the timeout * specified is greater than the default HTTP/RPC timeout, the HTTP/RPC * timeout is used. If the server does not support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * Note that this method is on a best-effort basis. It may return the latest * state before the specified timeout (including immediately), meaning even an * immediate response is no guarantee that the operation is done. * </pre> */ public com.google.longrunning.Operation waitOperation( com.google.longrunning.WaitOperationRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getWaitOperationMethod(), getCallOptions(), request); } } /** * * * <pre> * Manages long-running operations with an API service. * When an API method normally takes long time to complete, it can be designed * to return [Operation][google.longrunning.Operation] to the client, and the client can use this * interface to receive the real response asynchronously by polling the * operation resource, or pass the operation resource to another API (such as * Google Cloud Pub/Sub API) to receive the response. Any API service that * returns long-running operations should implement the `Operations` interface * so developers can have a consistent client experience. * </pre> */ public static final class OperationsFutureStub extends io.grpc.stub.AbstractFutureStub<OperationsFutureStub> { private OperationsFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected OperationsFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OperationsFutureStub(channel, callOptions); } /** * * * <pre> * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/&#42;&#47;operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/&#42;}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.longrunning.ListOperationsResponse> listOperations(com.google.longrunning.ListOperationsRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getListOperationsMethod(), getCallOptions()), request); } /** * * * <pre> * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation> getOperation(com.google.longrunning.GetOperationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getGetOperationMethod(), getCallOptions()), request); } /** * * * <pre> * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty> deleteOperation(com.google.longrunning.DeleteOperationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getDeleteOperationMethod(), getCallOptions()), request); } /** * * * <pre> * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * [Operations.GetOperation][google.longrunning.Operations.GetOperation] or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, * corresponding to `Code.CANCELLED`. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty> cancelOperation(com.google.longrunning.CancelOperationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCancelOperationMethod(), getCallOptions()), request); } /** * * * <pre> * Waits until the specified long-running operation is done or reaches at most * a specified timeout, returning the latest state. If the operation is * already done, the latest state is immediately returned. If the timeout * specified is greater than the default HTTP/RPC timeout, the HTTP/RPC * timeout is used. If the server does not support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. * Note that this method is on a best-effort basis. It may return the latest * state before the specified timeout (including immediately), meaning even an * immediate response is no guarantee that the operation is done. * </pre> */ public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation> waitOperation(com.google.longrunning.WaitOperationRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getWaitOperationMethod(), getCallOptions()), request); } } private static final int METHODID_LIST_OPERATIONS = 0; private static final int METHODID_GET_OPERATION = 1; private static final int METHODID_DELETE_OPERATION = 2; private static final int METHODID_CANCEL_OPERATION = 3; private static final int METHODID_WAIT_OPERATION = 4; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final OperationsImplBase serviceImpl; private final int methodId; MethodHandlers(OperationsImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_LIST_OPERATIONS: serviceImpl.listOperations( (com.google.longrunning.ListOperationsRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.ListOperationsResponse>) responseObserver); break; case METHODID_GET_OPERATION: serviceImpl.getOperation( (com.google.longrunning.GetOperationRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver); break; case METHODID_DELETE_OPERATION: serviceImpl.deleteOperation( (com.google.longrunning.DeleteOperationRequest) request, (io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver); break; case METHODID_CANCEL_OPERATION: serviceImpl.cancelOperation( (com.google.longrunning.CancelOperationRequest) request, (io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver); break; case METHODID_WAIT_OPERATION: serviceImpl.waitOperation( (com.google.longrunning.WaitOperationRequest) request, (io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private abstract static class OperationsBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { OperationsBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.longrunning.OperationsProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("Operations"); } } private static final class OperationsFileDescriptorSupplier extends OperationsBaseDescriptorSupplier { OperationsFileDescriptorSupplier() {} } private static final class OperationsMethodDescriptorSupplier extends OperationsBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; OperationsMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (OperationsGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new OperationsFileDescriptorSupplier()) .addMethod(getListOperationsMethod()) .addMethod(getGetOperationMethod()) .addMethod(getDeleteOperationMethod()) .addMethod(getCancelOperationMethod()) .addMethod(getWaitOperationMethod()) .build(); } } } return result; } }
apache-2.0
alexander071/cf-java-client
cloudfoundry-operations/src/test/java/org/cloudfoundry/operations/useradmin/ListOrganizationUsersRequestTest.java
1079
/* * Copyright 2013-2019 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.cloudfoundry.operations.useradmin; import org.junit.Test; public final class ListOrganizationUsersRequestTest { @Test(expected = IllegalStateException.class) public void noOrganizationName() { ListOrganizationUsersRequest.builder() .build(); } @Test public void valid() { ListOrganizationUsersRequest.builder() .organizationName("test-organization") .build(); } }
apache-2.0
lmjacksoniii/hazelcast
hazelcast/src/main/java/com/hazelcast/config/JobTrackerConfigReadOnly.java
2164
/* * Copyright (c) 2008-2016, Hazelcast, Inc. 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.hazelcast.config; import com.hazelcast.mapreduce.TopologyChangedStrategy; /** * Contains the configuration for an {@link com.hazelcast.mapreduce.JobTracker}. * * @deprecated this class will be removed in 3.8; it is meant for internal usage only. */ public class JobTrackerConfigReadOnly extends JobTrackerConfig { JobTrackerConfigReadOnly(JobTrackerConfig jobTrackerConfig) { super(jobTrackerConfig); } @Override public JobTrackerConfigReadOnly setName(String name) { throw new UnsupportedOperationException("This config is read-only"); } @Override public void setMaxThreadSize(int maxThreadSize) { throw new UnsupportedOperationException("This config is read-only"); } @Override public void setRetryCount(int retryCount) { throw new UnsupportedOperationException("This config is read-only"); } @Override public void setChunkSize(int chunkSize) { throw new UnsupportedOperationException("This config is read-only"); } @Override public void setQueueSize(int queueSize) { throw new UnsupportedOperationException("This config is read-only"); } @Override public void setCommunicateStats(boolean communicateStats) { throw new UnsupportedOperationException("This config is read-only"); } @Override public void setTopologyChangedStrategy(TopologyChangedStrategy topologyChangedStrategy) { throw new UnsupportedOperationException("This config is read-only"); } }
apache-2.0
jamesyong/o3erp
java/specialpurpose/camel/src/org/ofbiz/camel/services/CamelServices.java
1242
package org.ofbiz.camel.services; import org.apache.camel.CamelExecutionException; import org.ofbiz.base.util.Debug; import org.ofbiz.camel.loader.CamelContainer; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.ServiceUtil; import java.util.Collections; import java.util.Map; public class CamelServices { private static String module = CamelServices.class.getName(); public static Map<String, Object> sendCamelMessage(DispatchContext ctx, Map<String, Object> context) { Object body = context.get("body"); String endpoint = (String) context.get("endpoint"); Map<String, Object> headers = getHeaders(context); try { CamelContainer.getProducerTemplate().sendBodyAndHeaders(endpoint, body, headers); } catch (CamelExecutionException cee) { Debug.logError(cee, module); return ServiceUtil.returnError(cee.getMessage()); } return ServiceUtil.returnSuccess(); } private static Map<String, Object> getHeaders(Map<String, Object> context) { Map<String, Object> headers = (Map<String, Object>) context.get("headers"); return headers != null ? headers : Collections.<String, Object>emptyMap(); } }
apache-2.0
statisticsnorway/java-vtl
java-vtl-script/src/test/java/no/ssb/vtl/script/operations/join/NewInnerJoinOperationTest.java
9205
package no.ssb.vtl.script.operations.join; /*- * ========================LICENSE_START================================= * Java VTL * %% * Copyright (C) 2016 - 2018 Hadrien Kohl * %% * 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. * =========================LICENSE_END================================== */ import com.carrotsearch.randomizedtesting.RandomizedTest; import com.carrotsearch.randomizedtesting.annotations.Repeat; import com.carrotsearch.randomizedtesting.annotations.Seed; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import no.ssb.vtl.model.Component; import no.ssb.vtl.model.DataPoint; import no.ssb.vtl.model.DataStructure; import no.ssb.vtl.model.Dataset; import no.ssb.vtl.model.StaticDataset; import no.ssb.vtl.script.operations.drop.KeepOperation; import no.ssb.vtl.test.RandomizedDataset; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import java.util.stream.IntStream; import java.util.stream.Stream; import static no.ssb.vtl.model.Component.Role.ATTRIBUTE; import static no.ssb.vtl.model.Component.Role.IDENTIFIER; import static no.ssb.vtl.model.Component.Role.MEASURE; public class NewInnerJoinOperationTest extends RandomizedTest { private DataStructure structureTemplate; @Before public void setUp() { structureTemplate = DataStructure.builder() .put("stringId", IDENTIFIER, String.class) .put("longId", IDENTIFIER, Long.class) .put("doubleId", IDENTIFIER, Double.class) .put("booleanId", IDENTIFIER, Boolean.class) .put("instantId", IDENTIFIER, Instant.class) .put("stringMeasure", MEASURE, String.class) .put("longMeasure", MEASURE, Long.class) .put("doubleMeasure", MEASURE, Double.class) .put("booleanMeasure", MEASURE, Boolean.class) .put("instantMeasure", MEASURE, Instant.class) .put("stringAttribute", ATTRIBUTE, String.class) .put("longAttribute", ATTRIBUTE, Long.class) .put("doubleAttribute", ATTRIBUTE, Double.class) .put("booleanAttribute", ATTRIBUTE, Boolean.class) .put("instantAttribute", ATTRIBUTE, Instant.class) .build(); } private Object randomObjectOrNullOfType(Class clazz) { if (rarely()) return null; return randomObjectOfType(clazz); } private Object randomObjectOfType(Class clazz) { if (Boolean.class.equals(clazz)) return randomBoolean(); if (String.class.equals(clazz)) return randomAsciiOfLengthBetween(10, 20); if (Long.class.equals(clazz)) return randomLong(); if (Double.class.equals(clazz)) return randomDouble(); if (Instant.class.equals(clazz)) return Instant.ofEpochMilli(randomLong()); throw new IllegalArgumentException( "Could not generate random value of type " + clazz.getSimpleName() ); } private List<DataPoint> randomData(DataStructure structure, int numRow) { ArrayList<DataPoint> data = Lists.newArrayList(); ArrayList<Object> values = Lists.newArrayList(); for (int i = 0; i < numRow; i++) { for (Component component : structure.values()) { values.add(randomObjectOrNullOfType(component.getType())); } data.add(DataPoint.create(values.toArray())); values.clear(); } return data; } StaticDataset randomDatasetFromValues(DataStructure structure, List<DataPoint> data) { StaticDataset.ValueBuilder builder = StaticDataset.create(structure); ArrayList<DataPoint> copy = Lists.newArrayList(data); Collections.shuffle(copy, getRandom()); int max = randomInt(data.size()); for (int i = 0; i < max; i++) { builder.addPoints(data.get(i)); } return builder.build(); } List<Component> randomComponents(DataStructure structure, Predicate<Component> predicate, int min) { List<Component> collect = structure.values().stream() .filter(predicate) .collect(ImmutableList.toImmutableList()); int max = randomIntBetween(min, collect.size()); ImmutableList.Builder<Component> components = ImmutableList.builder(); for (int i = 0; i < max; i++) { Component component = randomFrom(collect); components.add(component); } return components.build(); } List<String> randomComponentsName(DataStructure structure, Predicate<Component> predicate, int min) { return randomComponents(structure, predicate, min).stream() .map(structure::getName) .collect(ImmutableList.toImmutableList()); } List<String> randomIdentifiersName(DataStructure structure, int min) { return randomComponentsName(structure, Component::isIdentifier, min); } List<Component> randomIdentifiers(DataStructure structure, int min) { return randomComponents(structure, Component::isIdentifier, min); } List<String> randomMeasuresName(DataStructure structure, int min) { return randomComponentsName(structure, Component::isMeasure, min); } List<Component> randomMeasures(DataStructure structure, int min) { return randomComponents(structure, Component::isMeasure, min); } List<String> randomAttributesName(DataStructure structure, int min) { return randomComponentsName(structure, Component::isAttribute, min); } List<Component> randomAttributes(DataStructure structure, int min) { return randomComponents(structure, Component::isAttribute, min); } @Test @Repeat(iterations = 1, useConstantSeed = true) @Seed("D1F262C1DA20FE15") public void regressionTest() { testInnerJoin(); } @Test @Repeat(iterations = 10) public void testInnerJoin() { // A couple of important things to test: // * variable amount of datasets // * variable amount of null value in identifiers // * random structure order // * random data order List<DataPoint> dataPoints = randomData(structureTemplate, scaledRandomIntBetween(10, 100)); // Keep a list of identifiers that will be common. List<String> commonIdentifiers = randomIdentifiersName(structureTemplate, 1); System.out.println("Common identifier" + commonIdentifiers); Map<String, Dataset> datasetMap = IntStream.range(1, randomIntBetween(2, 3)) .mapToObj(value -> "ds" + Integer.toString(value)) .collect(ImmutableMap.toImmutableMap( o -> o, o -> { // Rarely return empty dataset. StaticDataset staticDataset = randomDatasetFromValues( structureTemplate, rarely() ? Collections.emptyList() : dataPoints ); Dataset randomizedDataset = RandomizedDataset.create(getRandom(), staticDataset).shuffleStructure(); Set<Component> components = Stream.of( commonIdentifiers.stream(), randomMeasuresName(randomizedDataset.getDataStructure(), 1).stream(), randomAttributesName(randomizedDataset.getDataStructure(), 1).stream() ).flatMap(s -> s) .map(randomizedDataset.getDataStructure()::get) .collect(ImmutableSet.toImmutableSet()); return new KeepOperation(randomizedDataset, components); } )); InnerJoinOperation innerJoinOperation = new InnerJoinOperation(datasetMap); // Uncomment to debug. // VTLPrintStream printStream = new VTLPrintStream(System.out); // datasetMap.forEach((name, dataset) -> { // printStream.println("Dataset " + name); // printStream.println(dataset); // }); // printStream.println(innerJoinOperation); } }
apache-2.0
samtingleff/dgrid
java/src/api/com/dgrid/errors/MailException.java
278
package com.dgrid.errors; public class MailException extends DGridException { /** * */ private static final long serialVersionUID = 1107025858152537437L; public MailException(String msg) { super(msg); } public MailException(Throwable root) { super(root); } }
apache-2.0
doordeck/simplegpio
simplegpio-core/src/main/java/com/doordeck/simplegpio/gpio/PinBlockedException.java
1446
package com.doordeck.simplegpio.gpio; /* * (C) Copyright 2014 libbulldog (http://libbulldog.org/) and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * The Class PinBlockedException. */ public class PinBlockedException extends RuntimeException { /** * The Constant serialVersionUID. */ private static final long serialVersionUID = 6737984685844582750L; /** * The blocker. */ private PinFeature blocker; /** * Instantiates a new pin blocked exception. * * @param blocker * the blocker */ public PinBlockedException(PinFeature blocker) { super(String.format("Pin %s is currently blocked by %s", blocker.getPin().getName(), blocker.getName())); this.blocker = blocker; } /** * Gets the blocker. * * @return the blocker */ public PinFeature getBlocker() { return blocker; } }
apache-2.0
TheLimeGlass/Skellett
src/main/java/com/gmail/thelimeglass/Scoreboards/ExprTeamFriendlyInvisibles.java
1691
package com.gmail.thelimeglass.Scoreboards; import org.bukkit.event.Event; import org.bukkit.scoreboard.Team; import org.eclipse.jdt.annotation.Nullable; import ch.njol.skript.classes.Changer; import ch.njol.skript.classes.Changer.ChangeMode; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; public class ExprTeamFriendlyInvisibles extends SimpleExpression<Boolean>{ //(score[ ][board]|[skellett[ ]]board) [friendly] invisible[s] [state] [(for|of)] [team] %team% private Expression<Team> team; @Override public Class<? extends Boolean> getReturnType() { return Boolean.class; } @Override public boolean isSingle() { return true; } @SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] e, int matchedPattern, Kleenean isDelayed, ParseResult parser) { team = (Expression<Team>) e[0]; return true; } @Override public String toString(@Nullable Event e, boolean arg1) { return "(score[ ][board]|[skellett[ ]]board) [friendly] invisible[s] [state] [(for|of)] [team] %team%"; } @Override @Nullable protected Boolean[] get(Event e) { return new Boolean[]{team.getSingle(e).canSeeFriendlyInvisibles()}; } @Override public void change(Event e, Object[] delta, Changer.ChangeMode mode){ if (mode == ChangeMode.SET) { team.getSingle(e).setCanSeeFriendlyInvisibles((Boolean)delta[0]); } } @Override public Class<?>[] acceptChange(final Changer.ChangeMode mode) { if (mode == ChangeMode.SET) { return CollectionUtils.array(Boolean.class); } return null; } }
apache-2.0
dmwu/sparrow
src/main/java/edu/berkeley/sparrow/daemon/nodemonitor/TaskScheduler.java
6672
/* * Copyright 2013 The Regents of The University California * * 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 edu.berkeley.sparrow.daemon.nodemonitor; import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import edu.berkeley.sparrow.daemon.util.Logging; import edu.berkeley.sparrow.daemon.util.Network; import edu.berkeley.sparrow.thrift.TEnqueueTaskReservationsRequest; import edu.berkeley.sparrow.thrift.TFullTaskId; import edu.berkeley.sparrow.thrift.TTaskLaunchSpec; import edu.berkeley.sparrow.thrift.TUserGroupInfo; /** * A TaskScheduler is a buffer that holds task reservations until an application backend is * available to run the task. When a backend is ready, the TaskScheduler requests the task * from the {@link Scheduler} that submitted the reservation. * * Each scheduler will implement a different policy determining when to launch tasks. * * Schedulers are required to be thread safe, as they will be accessed concurrently from * multiple threads. */ public abstract class TaskScheduler { protected class TaskSpec { public String appId; public TUserGroupInfo user; public String requestId; public InetSocketAddress schedulerAddress; public InetSocketAddress appBackendAddress; /** * ID of the task that previously ran in the slot this task is using. Used * to track how long it takes to fill an empty slot on a slave. Empty if this task was launched * immediately, because there were empty slots available on the slave. Filled in when * the task is launched. */ public String previousRequestId; public String previousTaskId; /** Filled in after the getTask() RPC completes. */ public TTaskLaunchSpec taskSpec; public TaskSpec(TEnqueueTaskReservationsRequest request, InetSocketAddress appBackendAddress) { appId = request.getAppId(); user = request.getUser(); requestId = request.getRequestId(); schedulerAddress = new InetSocketAddress(request.getSchedulerAddress().getHost(), request.getSchedulerAddress().getPort()); this.appBackendAddress = appBackendAddress; previousRequestId = ""; previousTaskId = ""; } } private final static Logger LOG = Logger.getLogger(TaskScheduler.class); private final static Logger AUDIT_LOG = Logging.getAuditLogger(TaskScheduler.class); private String ipAddress; protected Configuration conf; private final BlockingQueue<TaskSpec> runnableTaskQueue = new LinkedBlockingQueue<TaskSpec>(); /** Initialize the task scheduler, passing it the current available resources * on the machine. */ void initialize(Configuration conf, int nodeMonitorPort) { this.conf = conf; this.ipAddress = Network.getIPAddress(conf); } /** * Get the next task available for launching. This will block until a task is available. */ TaskSpec getNextTask() { TaskSpec task = null; try { task = runnableTaskQueue.take(); } catch (InterruptedException e) { LOG.fatal(e); } return task; } /** * Returns the current number of runnable tasks (for testing). */ int runnableTasks() { return runnableTaskQueue.size(); } void tasksFinished(List<TFullTaskId> finishedTasks) { for (TFullTaskId t : finishedTasks) { AUDIT_LOG.info(Logging.auditEventString("task_completed", t.getRequestId(), t.getTaskId())); handleTaskFinished(t.getRequestId(), t.getTaskId()); } } void noTaskForReservation(TaskSpec taskReservation) { AUDIT_LOG.info(Logging.auditEventString("node_monitor_get_task_no_task", taskReservation.requestId, taskReservation.previousRequestId, taskReservation.previousTaskId)); handleNoTaskForReservation(taskReservation); } protected void makeTaskRunnable(TaskSpec task) { try { LOG.debug("Putting reservation for request " + task.requestId + " in runnable queue"); runnableTaskQueue.put(task); } catch (InterruptedException e) { LOG.fatal("Unable to add task to runnable queue: " + e.getMessage()); } } public synchronized void submitTaskReservations(TEnqueueTaskReservationsRequest request, InetSocketAddress appBackendAddress) { for (int i = 0; i < request.getNumTasks(); ++i) { LOG.debug("Creating reservation " + i + " for request " + request.getRequestId()); TaskSpec reservation = new TaskSpec(request, appBackendAddress); int queuedReservations = handleSubmitTaskReservation(reservation); AUDIT_LOG.info(Logging.auditEventString("reservation_enqueued [WDM] on NM", ipAddress, request.requestId, queuedReservations)); } } // TASK SCHEDULERS MUST IMPLEMENT THE FOLLOWING. /** * Handles a task reservation. Returns the number of queued reservations. */ abstract int handleSubmitTaskReservation(TaskSpec taskReservation); /** * Cancels all task reservations with the given request id. Returns the number of task * reservations cancelled. */ abstract int cancelTaskReservations(String requestId); /** * Handles the completion of a task that has finished executing. */ protected abstract void handleTaskFinished(String requestId, String taskId); /** * Handles the case when the node monitor tried to launch a task for a reservation, but * the corresponding scheduler didn't return a task (typically because all of the corresponding * job's tasks have been launched). */ protected abstract void handleNoTaskForReservation(TaskSpec taskSpec); /** * Returns the maximum number of active tasks allowed (the number of slots). * * -1 signals that the scheduler does not enforce a maximum number of active tasks. */ abstract int getMaxActiveTasks(); }
apache-2.0
rgfernandes/dex2jar
dex-translator/src/main/java/com/googlecode/d2j/dex/LambadaNameSafeClassAdapter.java
576
package com.googlecode.d2j.dex; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.commons.Remapper; import org.objectweb.asm.commons.RemappingClassAdapter; public class LambadaNameSafeClassAdapter extends RemappingClassAdapter { public String getClassName() { return remapper.mapType(className); } public LambadaNameSafeClassAdapter(ClassVisitor cv) { super(cv, new Remapper() { @Override public String mapType(String type) { return type.replace('-', '_'); } }); } }
apache-2.0
citlab/vs.msc.ws14
flink-0-7-custom/flink-java/src/main/java/org/apache/flink/api/java/operators/SingleInputOperator.java
2357
/* * 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.flink.api.java.operators; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.DataSet; /** * Base class for operations that operates on a single input data set. * * @param <IN> The data type of the input data set. * @param <OUT> The data type of the returned data set. */ public abstract class SingleInputOperator<IN, OUT, O extends SingleInputOperator<IN, OUT, O>> extends Operator<OUT, O> { private final DataSet<IN> input; protected SingleInputOperator(DataSet<IN> input, TypeInformation<OUT> resultType) { super(input.getExecutionEnvironment(), resultType); this.input = input; } /** * Gets the data set that this operation uses as its input. * * @return The data set that this operation uses as its input. */ public DataSet<IN> getInput() { return this.input; } /** * Gets the type information of the data type of the input data set. * This method returns equivalent information as {@code getInput().getType()}. * * @return The input data type. */ public TypeInformation<IN> getInputType() { return this.input.getType(); } /** * Translates this operation to a data flow operator of the common data flow API. * * @param input The data flow operator that produces this operation's input data. * @return The translated data flow operator. */ protected abstract org.apache.flink.api.common.operators.SingleInputOperator<?, OUT, ?> translateToDataFlow( org.apache.flink.api.common.operators.Operator<IN> input); }
apache-2.0
hejzgithub/CworldEarnGold
src/com/cworld/earngold/sys/action/UserAction.java
3106
package com.cworld.earngold.sys.action; import org.springframework.stereotype.Controller; import com.core.code.action.BaseAction; import com.cworld.earngold.mobile.inf.InterfaceLogin; import com.cworld.earngold.mobile.inf.InterfaceUser; import com.cworld.earngold.mobile.inf.impl.InterfaceLoginImpl; import com.cworld.earngold.sys.beans.User; @SuppressWarnings("serial") @Controller public class UserAction extends BaseAction { private String phone; private String pwd; private String checkPwd; private String checkCode; private String messageCode; private InterfaceUser infUser = null; private InterfaceLogin infLogin = null; private boolean isLogin() { if (this.httpSession.getAttribute("User") != null) { return true; } else { return false; } } public String login() { infLogin = new InterfaceLoginImpl(); // User user = infLogin.login(phone, pwd); // Use to Test Start Integer count = (Integer) this.httpSession .getAttribute("PasswordFault"); String checkCode = (String)this.httpSession.getAttribute("checkCode"); System.out.println(count+"--------"+checkCode); if (null != count && count >= 3) { if(null == checkCode || checkCode.equalsIgnoreCase((String)this.httpSession.getAttribute("CheckCode"))){ // Set Error Message return "loginPage"; } } if ("admin".equalsIgnoreCase(phone) && "admin".equalsIgnoreCase(pwd)) { User user = new User(); user.setUserId(1); user.setPhone("123456789"); user.setType("admin"); user.setAccountHead("123456789.png"); // End if (user != null) { this.httpSession.setAttribute("user", user); if ("admin".equalsIgnoreCase(user.getType())) { System.out.println("adminPage"); return "adminPage"; } else { System.out.println("mainPage"); return "mainPage"; } } else { System.out.println("loginPage"); passwordFaultFunc(); return "loginPage"; } } else { System.out.println("loginPage"); passwordFaultFunc(); return "loginPage"; } } public String register(){ return ""; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } private void passwordFaultFunc() { Integer count = (Integer) this.httpSession .getAttribute("PasswordFault"); if (null == count) { this.httpSession.setAttribute("PasswordFault", 1); } else { this.httpSession.setAttribute("PasswordFault", count++); } } public String getCheckCode() { return checkCode; } public void setCheckCode(String checkCode) { this.checkCode = checkCode; } public String getCheckPwd() { return checkPwd; } public void setCheckPwd(String checkPwd) { this.checkPwd = checkPwd; } public String getMessageCode() { return messageCode; } public void setMessageCode(String messageCode) { this.messageCode = messageCode; } }
apache-2.0