text
stringlengths
7
1.01M
package de.qaware.esh.netatmo.handler; import de.qaware.esh.netatmo.NetatmoBindingConstants; import de.qaware.esh.netatmo.NetatmoWebservice; import de.qaware.esh.netatmo.model.DashboardData; import de.qaware.esh.netatmo.model.Device; import de.qaware.esh.netatmo.model.StationData; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; import org.eclipse.smarthome.core.types.Command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * The {@link NetatmoHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Moritz Kammerer - Initial contribution */ public class NetatmoHandler extends BaseThingHandler { private Logger logger = LoggerFactory.getLogger(NetatmoHandler.class); private static final long DELAY_IN_MINUTES = 10; private ScheduledFuture<?> scheduledFuture; public NetatmoHandler(Thing thing) { super(thing); } @Override public void handleCommand(ChannelUID channelUID, Command command) { } @Override public void initialize() { updateStatus(ThingStatus.ONLINE); scheduledFuture = scheduler.scheduleWithFixedDelay(new Runnable() { @Override public void run() { refresh(); } }, 0, DELAY_IN_MINUTES, TimeUnit.MINUTES); } @Override public void dispose() { scheduledFuture.cancel(false); super.dispose(); } private void refresh() { String id = getThing().getProperties().get("id"); logger.debug("Refreshing data for weatherstation {}", id); StationData data; try { data = NetatmoWebservice.INSTANCE.fetchStationData(); } catch (IOException e) { logger.error("Exception while fetching data from webservice", e); updateStatus(ThingStatus.OFFLINE); return; } for (Device device : data.getBody().getDevices()) { if (device.getId().equals(id)) { DashboardData dashboard = device.getDashboardData(); updateState(NetatmoBindingConstants.CHANNEL_TEMPERATURE, new DecimalType(dashboard.getTemperature())); updateState(NetatmoBindingConstants.CHANNEL_HUMIDITY, new DecimalType(dashboard.getHumidity())); updateState(NetatmoBindingConstants.CHANNEL_CO2, new DecimalType(dashboard.getCo2())); updateStatus(ThingStatus.ONLINE); return; } } // Weather station not found, switch to offline updateStatus(ThingStatus.OFFLINE); } }
/* * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.sleuth.instrument.web; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Sleuth HTTP settings * * @since 2.0.0 */ @ConfigurationProperties("spring.sleuth.http") public class SleuthHttpProperties { private boolean enabled = true; private Legacy legacy = new Legacy(); public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Legacy getLegacy() { return this.legacy; } public void setLegacy(Legacy legacy) { this.legacy = legacy; } /** * Legacy Sleuth support. Related to the way headers are parsed and tags are set */ public static class Legacy { private boolean enabled = false; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
/* * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * * @summary converted from VM Testbase runtime/jbe/subcommon/subcommon03. * VM Testbase keywords: [quick, runtime] * * @library /vmTestbase * /test/lib * @run main/othervm vm.compiler.jbe.subcommon.subcommon03.subcommon03 */ package vm.compiler.jbe.subcommon.subcommon03; /* Tests the Local Common Sub-expression Elimination optimization, including duplicate calls to math function. */ public class subcommon03 { int k, m, n; float a, b, c, d, x; float arr[] = new float[100]; float arr_opt[] = new float[100]; float arr1[][] = new float[10][10]; float arr1_opt[][] = new float[10][10]; public static void main(String args[]) { subcommon03 sce = new subcommon03(); sce.init(); sce.un_optimized(); sce.hand_optimized(); sce.mat(); if (sce.eCheck()) { System.out.println("Test subcommon03 Passed."); } else { throw new Error("Test subcommon03 Failed."); } } void init() { for(int i = 0; i < 10; i++) { arr[i] = (float)1E-2; arr_opt[i] = (float)1E-2; } for(m = 0; m < 10; m++) { arr1[0][m] = arr[m]; arr1_opt[0][m] = arr_opt[m]; } } void mat() { for(k = 1; k < 10; k++) { n = k*10; for(m = 0; m < 10; m++) { arr[n+m] = (float)Math.exp((double)arr[m]); arr1[k][m] = (float)(arr[m] * 1/Math.PI); arr_opt[n+m] = (float)Math.exp((double)arr_opt[m]); arr1_opt[k][m] = (float)(arr_opt[m] * 1/Math.PI); } } } void un_optimized() { c = (float)1.123456789; d = (float)1.010101012; // example 1 a = (float)((c * Math.sqrt(d * 2.0)) / (2.0 * d)); b = (float)((c / Math.sqrt(d * 2.0)) / (2.0 * d)); System.out.print("a="+a+"; b="+b); // example 2 c = arr[0] / (arr[0] * arr[0] + arr[1] * arr[1]); d = arr[1] * (arr[0] * arr[0] + arr[1] * arr[1]); System.out.println("; c="+c+"; d="+d); // example 3 k = 0; float t1 = arr[k]; float t2 = arr[k] * 2; arr[2] = a; arr[3] = b; arr[4] = c; arr[5] = d; arr[8] = b / c; arr[9] = c - a; // Example -4 c = t2 / t1 * b / a; x = (float)(d * 2.0); d = t2 / t1 * b / a; arr[6] = c; arr[7] = d; } void hand_optimized() { c = (float)1.123456789; d = (float)1.010101012; // example 1 x = d * (float)2.0; double t1 = Math.sqrt((double)x); double t2 = 1.0 / (double)x; a = (float)(c * t1 * t2); b = (float)(c / t1 * t2); System.out.print("a_opt="+a+"; b_opt="+b); // example 2 t1 = (double)arr_opt[0]; t2 = (double)arr_opt[1]; double t3 = 1.0 / (t1*t1 + t2*t2); c = (float)t1 * (float)t3; d = (float)t2 / (float)t3; System.out.println("; c_opt="+c+"; d_opt="+d); // example 3 t2 = t1 * 2; arr_opt[2] = a; arr_opt[3] = b; arr_opt[4] = c; arr_opt[5] = d; arr_opt[8] = b / c; arr_opt[9] = c - a; // example 4 c = (float)t2 / (float)t1 * b / a; d = c; arr_opt[6] = c; arr_opt[7] = d; } boolean eCheck() { boolean st = true; for (int i = 0; i < arr.length; i++) { if (arr[i] != arr_opt[i]) { System.out.println(">>Bad output: arr["+i+"]="+arr[i]+"; arr_opt["+i+"]="+arr_opt[i]); st = false; } } for (int i = 0; i < arr1.length; i++) for (int j = 0; j < arr1[i].length; j++) { if (arr1[i][j] != arr1_opt[i][j]) { System.out.println(">>Bad output: arr["+i+"]["+j+"]="+arr1[i][j]+"; arr_opt["+i+"]["+j+"]="+arr1_opt[i][j]); st = false; } } return st; } }
/** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ package com.raytheon.uf.viz.monitor.data; import java.util.Date; import java.util.SortedMap; import java.util.TreeMap; import com.raytheon.uf.common.monitor.data.CommonConfig; import com.raytheon.uf.common.monitor.data.CommonConfig.AppName; import com.raytheon.uf.common.monitor.data.MonitorConfigConstants; import com.raytheon.uf.common.monitor.data.ObConst; import com.raytheon.uf.common.monitor.data.ObConst.DataUsageKey; import com.raytheon.uf.common.monitor.data.ObConst.ProductName; import com.raytheon.uf.common.monitor.data.ObConst.VarName; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.viz.monitor.thresholds.AbstractThresholdMgr; import com.raytheon.uf.viz.monitor.thresholds.AbstractThresholdMgr.ThresholdKey; /** * This class models data for a SNOW/FOG/SAFESEAS trending plot. * * <pre> * * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Dec.23, 2009 3424 zhao Initial creation. * Dec 26, 2015 5114 skorolev Replaced MonitorConfigConstants import. * * </pre> * * @author zhao * @version 1.0 */ public class ObTrendDataSet { private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(ObTrendDataSet.class); /** * application name (snow, fog, safeseas, etc) */ private final CommonConfig.AppName appName; /** * the zone ID */ private final String zone; /** * the enumerated type representation of the trending variable */ private final ObConst.VarName varName; /** * the enumerated type representation of product name for a trending * variable */ private final ObConst.ProductName productName; /** * the red threshold */ private float redThreshold = Float.NaN; /** * the second value in the case of dual-valued thresholds */ private float redThreshold_2 = Float.NaN; /** * the yellow threshold */ private float yellowThreshold = Float.NaN; /** * the second value in the case of dual-valued thresholds */ private float yellowThreshold_2 = Float.NaN; /** * the lowest value of the variable in the trending plot */ private float minValue = ObConst.MISSING; /** * the highest value of the variable in the trending plot */ private float maxValue = ObConst.MISSING; /** * the trending data set key is observation time; value is Float object of * the variable's observation value */ private final SortedMap<Date, Float> dataset; private final AbstractThresholdMgr thresholdMgr; /** * 'CLR' if ceiling value = 88888.88f */ public String ceilingCond = ""; /** * Constructor * * @param zone * zone ID * @param station * station ID * @param varName * variable name of enumerated-type * @param appName * application name (snow, fog, safeseas) of enumerated-type */ public ObTrendDataSet(String zone, ObConst.VarName varName, ObConst.ProductName productName, CommonConfig.AppName appName, AbstractThresholdMgr thresholdMgr) { this.zone = zone; this.varName = varName; this.productName = productName; this.appName = appName; this.thresholdMgr = thresholdMgr; dataset = new TreeMap<Date, Float>(); setThresholds(); } private void setThresholds() { if (appName == AppName.FOG) { if (varName == VarName.VISIBILITY) { redThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_VIS .getXmlKey()) / 16; yellowThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_VIS .getXmlKey()) / 16; } else if (varName == VarName.CEILING) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_CEILING .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_CEILING .getXmlKey()); } else if (varName == VarName.WIND_DIR) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_DIR_FROM .getXmlKey()); redThreshold_2 = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_DIR_TO .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_DIR_FROM .getXmlKey()); yellowThreshold_2 = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_DIR_TO .getXmlKey()); } else if (varName == VarName.WIND_SPEED) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_WIND_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_WIND_SPEED .getXmlKey()); } else if (varName == VarName.MAX_WIND_SPEED) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_PEAK_WIND .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_PEAK_WIND .getXmlKey()); } else if (varName == VarName.GUST_SPEED) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_GUST_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_GUST_SPEED .getXmlKey()); } else if (varName == VarName.TEMPERATURE) { redThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_TEMP .getXmlKey()); yellowThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_TEMP .getXmlKey()); } else if (varName == VarName.DEWPOINT) { redThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_DEWPT .getXmlKey()); yellowThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_DEWPT .getXmlKey()); } else if (varName == VarName.DEWPOINT_DEPR) { redThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_T_TD .getXmlKey()); yellowThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_T_TD .getXmlKey()); } else if (varName == VarName.RELATIVE_HUMIDITY) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_REL_HUMIDITY .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_REL_HUMIDITY .getXmlKey()); } else { statusHandler.warn("Unknow variable name = " + varName + " for FOG trend plot"); } } else if (appName == AppName.SNOW) { if (varName == VarName.WIND_DIR) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_DIR_FROM .getXmlKey()); redThreshold_2 = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_DIR_TO .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_DIR_FROM .getXmlKey()); yellowThreshold_2 = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_DIR_TO .getXmlKey()); } else if (varName == VarName.WIND_SPEED) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_WIND_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_WIND_SPEED .getXmlKey()); } else if (varName == VarName.MAX_WIND_SPEED) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_PEAK_WIND .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_PEAK_WIND .getXmlKey()); } else if (varName == VarName.GUST_SPEED) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_GUST_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_WIND_GUST_SPEED .getXmlKey()); } else if (varName == VarName.TEMPERATURE) { redThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_TEMP .getXmlKey()); yellowThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_TEMP .getXmlKey()); } else if (varName == VarName.DEWPOINT) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_DEWPT .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_DEWPT .getXmlKey()); } else if (varName == VarName.VISIBILITY) { redThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_VIS .getXmlKey()) / 16; yellowThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_VIS .getXmlKey()) / 16; } else if (varName == VarName.SEA_LEVEL_PRESS) { redThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_SLP .getXmlKey()); yellowThreshold = (float) thresholdMgr.getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_SLP .getXmlKey()); } else if (varName == VarName.WIND_CHILL) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_WIND_CHILL .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_WIND_CHILL .getXmlKey()); } else if (varName == VarName.FROSTBITE_TIME) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_FROSTBITE .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_FROSTBITE .getXmlKey()); } else if (varName == VarName.HOURLY_PRECIP) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_HOURLY_PRECIP .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_HOURLY_PRECIP .getXmlKey()); } else if (varName == VarName.SNOW_DEPTH) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_SNOW_DEPTH .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_SNOW_DEPTH .getXmlKey()); } else if (varName == VarName.SNINCR_HOURLY) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_SNINCR_HOURLY .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_SNINCR_HOURLY .getXmlKey()); } else if (varName == VarName.SNINCR_TOTAL) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_SNINCR_TOTAL .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SnowDisplay.SNOW_DISP_METEO_SNINCR_TOTAL .getXmlKey()); } else { statusHandler.warn("Unknow variable name = " + varName + " for SNOW trend plot"); } } else if (appName == AppName.SAFESEAS) { if (varName == VarName.WIND_DIR) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_DIR_FROM .getXmlKey()); redThreshold_2 = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_DIR_TO .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_DIR_FROM .getXmlKey()); yellowThreshold_2 = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_DIR_TO .getXmlKey()); } else if (varName == VarName.WIND_SPEED) { if (productName == ProductName.SCA) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_SCA_WIND_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_SCA_WIND_SPEED .getXmlKey()); } else if (productName == ProductName.GALE_WARNING) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_GALE_WIND_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_GALE_WIND_SPEED .getXmlKey()); } else if (productName == ProductName.STORM_WARNING) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_STORM_WIND_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_STORM_WIND_SPEED .getXmlKey()); } else if (productName == ProductName.HFWW) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_HFWW_WIND_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_HFWW_WIND_SPEED .getXmlKey()); } else { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_WIND_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_WIND_SPEED .getXmlKey()); } } else if (varName == VarName.MAX_WIND_SPEED) { if (productName == ProductName.SCA) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_SCA_PEAK_WIND .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_SCA_PEAK_WIND .getXmlKey()); } else if (productName == ProductName.GALE_WARNING) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_GALE_PEAK_WIND .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_GALE_PEAK_WIND .getXmlKey()); } else if (productName == ProductName.STORM_WARNING) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_STORM_PEAK_WIND .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_STORM_PEAK_WIND .getXmlKey()); } else if (productName == ProductName.HFWW) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_HFWW_PEAK_WIND .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_HFWW_PEAK_WIND .getXmlKey()); } else { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_PEAK_WIND .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_PEAK_WIND .getXmlKey()); } } else if (varName == VarName.GUST_SPEED) { if (productName == ProductName.SCA) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_SCA_GUST_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_SCA_GUST_SPEED .getXmlKey()); } else if (productName == ProductName.GALE_WARNING) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_GALE_GUST_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_GALE_GUST_SPEED .getXmlKey()); } else if (productName == ProductName.STORM_WARNING) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_STORM_GUST_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_STORM_GUST_SPEED .getXmlKey()); } else if (productName == ProductName.HFWW) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_HFWW_GUST_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_HFWW_GUST_SPEED .getXmlKey()); } else { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_GUST_SPEED .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_WIND_GUST_SPEED .getXmlKey()); } } else if (varName == VarName.VISIBILITY) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_VIS .getXmlKey()) / 16; yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_VIS .getXmlKey()) / 16; } else if (varName == VarName.TEMPERATURE) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_TEMP .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_TEMP .getXmlKey()); } else if (varName == VarName.DEWPOINT) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_DEWPT .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_DEWPT .getXmlKey()); } else if (varName == VarName.SEA_LEVEL_PRESS) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_SLP .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_SLP .getXmlKey()); } else if (varName == VarName.SEA_SURFACE_TEMPERATURE) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_SST .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_SST .getXmlKey()); } else if (varName == VarName.WAVE_HEIGHT) { if (productName == ProductName.SCA) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_SCA_WAVE_HT .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_PROD_SCA_WAVE_HT .getXmlKey()); } else { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_WAVE_HT .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_WAVE_HT .getXmlKey()); } } else if (varName == VarName.WAVE_STEEPNESS) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_WAVE_STEEP .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_METEO_WAVE_STEEP .getXmlKey()); } else if (varName == VarName.PRIM_SWELL_HT) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_HT .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_HT .getXmlKey()); } else if (varName == VarName.PRIM_SWELL_PD) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_PD .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_PD .getXmlKey()); } else if (varName == VarName.PRIM_SWELL_DIR) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_DIR_FROM .getXmlKey()); redThreshold_2 = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_DIR_TO .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_DIR_FROM .getXmlKey()); yellowThreshold_2 = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_DIR_TO .getXmlKey()); } else if (varName == VarName.SEC_SWELL_HT) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_PRIM_HT .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_SEC_HT .getXmlKey()); } else if (varName == VarName.SEC_SWELL_PD) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_SEC_PD .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_SEC_PD .getXmlKey()); } else if (varName == VarName.SEC_SWELL_DIR) { redThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_SEC_DIR_FROM .getXmlKey()); redThreshold_2 = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.RED, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_SEC_DIR_TO .getXmlKey()); yellowThreshold = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_SEC_DIR_FROM .getXmlKey()); yellowThreshold_2 = (float) thresholdMgr .getThresholdValue( DataUsageKey.DISPLAY, ThresholdKey.YELLOW, zone, MonitorConfigConstants.SafeSeasDisplay.SS_DISP_SWELL_SEC_DIR_TO .getXmlKey()); } else { statusHandler.warn("Unknow variable name = " + varName + " for SAFESEAS trend plot"); } } } /** * add a data point (a pair of observation time and observation value of the * trend variable) * * @param obsTime * observation time * @param varValue * observation value of the variable */ public void addDataPoint(Date obsTime, Float varValue) { if (varName == VarName.VISIBILITY && appName == AppName.SAFESEAS) { if (varValue != ObConst.MISSING) { varValue = varValue / TableUtil.milesPerNauticalMile; } else { varValue = ObConst.MISSING; } } // miss CLR and SKC in the Trend plot. if (varName == VarName.CEILING) { if (varValue == ObConst.CLR_SKY_FLOAT) { varValue = ObConst.MISSING; ceilingCond = this.setCeilingCond(ObConst.CLR_SKY_STRING); } else if (varValue == ObConst.SKC_SKY_FLOAT) { varValue = ObConst.MISSING; ceilingCond = this.setCeilingCond(ObConst.SKC_SKY_STRING); } } dataset.put(obsTime, varValue); updateMinMaxValues(varValue.floatValue()); } private void updateMinMaxValues(float newValue) { if (varName == VarName.WIND_DIR || varName == VarName.PRIM_SWELL_DIR || varName == VarName.SEC_SWELL_DIR) { // nothing to do return; } if (newValue != ObConst.MISSING) { minValue = minValue == ObConst.MISSING ? newValue : Math.min( minValue, newValue); maxValue = maxValue == ObConst.MISSING ? newValue : Math.max( maxValue, newValue); } } /** * determine range of the y-axis of the trend plot based on min and max * values and that at least two threat levels must be shown on a trend plot * * @return the lower and upper range limits of the y-axis of the trend plot; * return null if no data available [0] = lower limit; [1] = upper * limit [obsolete: use getYAxisMinMaxIncrement() Jan 8, 2010, zhao] */ public float[] getRange() { float[] range = new float[2]; if (varName == ObConst.VarName.WIND_DIR || varName == VarName.PRIM_SWELL_DIR || varName == VarName.SEC_SWELL_DIR) { // this module has nothing to do with wind direction return null; } if (minValue == ObConst.MISSING || maxValue == ObConst.MISSING || dataset.isEmpty()) { // no data yet return null; } // in case thresholds are not set (due to incompleteness of or bugs in // the code) if (Float.isNaN(redThreshold) || Float.isNaN(yellowThreshold)) { return new float[] { minValue - 0.2f * Math.abs(minValue), maxValue + 0.2f * Math.abs(maxValue) }; } // data is available, and minValue and maxValue have been set // (the thresholds have been set) float upperThreshold = Math.max(redThreshold, yellowThreshold); float lowerThreshold = Math.min(redThreshold, yellowThreshold); if (minValue < lowerThreshold && lowerThreshold < maxValue || minValue < upperThreshold && upperThreshold < maxValue || minValue < lowerThreshold && upperThreshold < maxValue) { // ( minValue < lowerThreshold < maxValue ) || ( minValue < // upperThreshold < maxValue) || // ( minValue < the two thresholds < maxValue ) // i.e., this is the case that there is at least one threshold // between the min and max values range[0] = minValue - 0.2f * Math.abs(minValue); range[1] = maxValue + 0.2f * Math.abs(maxValue); } else if (upperThreshold < minValue) { // both thresholds are below min value range[0] = upperThreshold - 0.2f * Math.abs(upperThreshold); range[1] = maxValue + 0.2f * Math.abs(maxValue); } else if (maxValue < lowerThreshold) { // max value is below both threshold range[0] = minValue - 0.2f * Math.abs(minValue); range[1] = lowerThreshold + 0.2f * Math.abs(lowerThreshold); } else if (lowerThreshold < minValue && upperThreshold < maxValue) { // min and max values are between the two threshold range[0] = lowerThreshold - 0.2f * Math.abs(lowerThreshold); range[1] = upperThreshold + 0.2f * Math.abs(upperThreshold); } else { // any other case? no! } return range; } /** * Determine the min and max values and the increment of the y-axis of the * trend plot based on (1) the min and max values of the observation data * and (2) at least two threat levels are shown on a trend plot * * @return the min and max values and the increment of the y-axis of the * trend plot; return null if no data available [0] = min; [1] = * max; [2] = increment */ public float[] getYAxisMinMaxIncrement() { if (varName == ObConst.VarName.WIND_DIR || varName == VarName.PRIM_SWELL_DIR || varName == VarName.SEC_SWELL_DIR) { // this module has nothing to do with wind direction return null; } if (minValue == ObConst.MISSING || maxValue == ObConst.MISSING || dataset.isEmpty()) { // no data yet return null; } float lowerThreshold; float upperThreshold; if (Float.isNaN(redThreshold) || Float.isNaN(yellowThreshold)) { // thresholds are not set (due to incompleteness of or bugs in the // code) lowerThreshold = minValue - 0.2f * Math.abs(minValue); upperThreshold = maxValue + 0.2f * Math.abs(maxValue); } else { // the thresholds have been set upperThreshold = Math.max(redThreshold, yellowThreshold); lowerThreshold = Math.min(redThreshold, yellowThreshold); } // Here, "lowerlimit", "upperLimit", and "increment" are the min, max // and increment that we want to calculate // "min" and "max" are temporary guesses for "lowerLimit" and // "upperLimit" // "minValue" and "maxValue" are the min and max values of the // observation data float lowerLimit = minValue, upperLimit = maxValue; float increment = (maxValue - minValue) / 5; float min = minValue; float max = maxValue; // Adjust the min/max value, so it will at least cover two colors // (red/yellow/green) // there are six different cases: 1 above + 5 below if (maxValue <= lowerThreshold) // values are below the lower threshold max = lowerThreshold * 1.1f; else if (minValue >= upperThreshold) // values are above upper threshold min = upperThreshold * .9f; else if (maxValue < upperThreshold) { max = upperThreshold; // values covers across the lower threshold if (minValue >= lowerThreshold) min = lowerThreshold * .9f; // values are within the thresholds } else if (minValue > lowerThreshold) min = lowerThreshold; // values cover across the upper threshold float range = max - min; if (range > 5) { if (range > 1000) { increment = 200; } else if (range > 500) { increment = 100; } else if (range > 200) { increment = 50; } else if (range > 100) { increment = 20; } else if (range > 50) { increment = 10; } else if (range > 10) { increment = 5; } else { increment = 2; } lowerLimit = (int) min; upperLimit = (int) max; if (lowerLimit > min) { lowerLimit -= increment; } if (upperLimit < max) { upperLimit += increment; } } else { if (varName == ObConst.VarName.VISIBILITY) { if (range < 2) { if (range < 0.5) { increment = 0.125f; } else { increment = 0.25f; } } else if (range <= 3) { increment = 0.5f; } else { increment = 1; } increment = 1000 * increment; lowerLimit = Float.valueOf(min * 1000) / increment * increment * 0.001f; upperLimit = Float.valueOf(max * 1000) / increment * increment * 0.001f; increment = increment / 1000; if (lowerLimit > min) { lowerLimit -= increment; } if (upperLimit < max) { upperLimit += increment; } } else { if (varName == ObConst.VarName.WAVE_HEIGHT) { increment = 0.5f; } else { increment = 1; } increment = 10 * increment; lowerLimit = Float.valueOf(min * 10) / increment * increment * 0.1f; upperLimit = Float.valueOf(max * 10) / increment * increment * 0.1f; increment = increment / 10; if (lowerLimit > min) { lowerLimit -= increment; } if (upperLimit < max) { upperLimit += increment; } } } // allow lowerLimit go below zero for temperature-type variables; // perform eror check otherwise if (varName != ObConst.VarName.TEMPERATURE && varName != ObConst.VarName.WIND_CHILL && varName != ObConst.VarName.DEWPOINT) { if (lowerLimit < 0) { lowerLimit = 0; } } // (SK) SLP limits (20% too much for SLP range) if (varName == ObConst.VarName.SEA_LEVEL_PRESS) { increment = (float) 1.0; lowerLimit = minValue - increment; upperLimit = maxValue; } // (SK) Rel. Humidity limits if (varName == ObConst.VarName.RELATIVE_HUMIDITY) { if (maxValue >= 100.0) { upperLimit = (float) 100.0; } } return new float[] { lowerLimit, upperLimit, increment }; } /** * * @return the min and max values of the trend variable [0] = min; [1] = max */ public float[] getMinMaxValues() { return new float[] { minValue, maxValue }; } /** * * @return thresholds ([0]=red, [1]=yellow) */ public float[] getSingleValuedThresholds() { return new float[] { redThreshold, yellowThreshold }; } /** * * @return thresholds ([0]=red, [1]=red_2, [2]=yellow, [3]=yellow_2) */ public float[] getDualValuedThresholds() { return new float[] { redThreshold, redThreshold_2, yellowThreshold, yellowThreshold_2 }; } /** * * @return the trend data set in the form of a SortedMap<Date,Float> object */ public SortedMap<Date, Float> getDataSet() { return dataset; } /** * * @return true if no data availe */ public boolean isEmpty() { return dataset.isEmpty(); } /** * * @return number of data points (obsTime-value mappings) contained in * dataset */ public int numberOfDataPoints() { return dataset.size(); } /** * @return ceilingCond: "" or "CLR" */ public String getCeilingCond() { return ceilingCond; } /** * @param ceilingCond * @return */ public String setCeilingCond(String ceilingCond) { return this.ceilingCond = ceilingCond; } }
package com.lyz.textinputlayoutdemo.widget; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.EditText; import com.lyz.textinputlayoutdemo.R; /** * author: bwl on 2016-06-01. * email: bxl049@163.com */ public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher { //EditText右侧的删除图标 private Drawable mClearDrawable; //EditText是否聚焦 private boolean hasFocus; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mClearDrawable = getCompoundDrawables()[2]; if (null == mClearDrawable) { mClearDrawable = getResources().getDrawable(R.mipmap.clear); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); setClearIconVisible(false); setOnFocusChangeListener(this); addTextChangedListener(this); } /** * 设置清除图标是否可见 * @param visible */ private void setClearIconVisible(boolean visible) { Drawable right = (visible ? mClearDrawable : null); setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } @Override public void onFocusChange(View v, boolean hasFocus) { this.hasFocus = hasFocus; if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (hasFocus) { setClearIconVisible(s.length() > 0); } } @Override public boolean onTouchEvent(MotionEvent event) { if (MotionEvent.ACTION_UP == event.getAction()) { if (null != getCompoundDrawables()[2]) { int x = (int) event.getX(); int y = (int) event.getY(); Rect rect = getCompoundDrawables()[2].getBounds(); int height = rect.height();//清除图标高 int distance = (getHeight() - height) / 2;//清除图标顶部到控件顶部的距离 boolean w = (x < getWidth() - getPaddingRight()) && (x > getWidth() - getTotalPaddingRight()); boolean h = (y > distance) && (y < distance + height); if (w && h) { setText(""); } } } return super.onTouchEvent(event); } }
package com.cds.iot.data.entity; /** * Created by Administrator Chengzj * * @date 2018/10/11 12:26 */ public class CarPosition { /** * place_memo : * device_id : 22 * latitude : * speed : * longitude : * device_time : */ private String place_memo; private String device_id; private String latitude; private String speed; private String longitude; private String device_time; public String getPlace_memo() { return place_memo; } public void setPlace_memo(String place_memo) { this.place_memo = place_memo; } public String getDevice_id() { return device_id; } public void setDevice_id(String device_id) { this.device_id = device_id; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getSpeed() { return speed; } public void setSpeed(String speed) { this.speed = speed; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getDevice_time() { return device_time; } public void setDevice_time(String device_time) { this.device_time = device_time; } }
package com.longbow.security.core.core.otherway; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; import org.springframework.security.access.intercept.InterceptorStatusToken; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import javax.annotation.Resource; import javax.servlet.*; import java.io.IOException; /** * 该类的目的是拦截的入口,首先启动的时候会注入注入里面的属性,然后当用户访问你配置过的URL的时候, * 就会被拦截进入到doFilter方法中,在调用infoke()方法进入到CustomAccessDecisionManagerImpl.decide() * 方法中将访问的url与配置的url的权限做比较 * * 该过滤器的主要作用就是通过spring著名的IoC生成securityMetadataSource。 * securityMetadataSource相当于本包中自定义的CostomInvocationSecurityMetadataSourceService。 * 该CostomInvocationSecurityMetadataSourceService的作用提从数据库提取权限和资源,装配到HashMap中, * 供Spring Security使用,用于权限校验。 * * Created by zhangbin on 2017/8/1. */ //@Service("customFilterSecurityInterceptor") public class CustomFilterSecurityInterceptorImpl extends AbstractSecurityInterceptor implements CustomFilterSecurityInterceptor { @Resource @Qualifier("customInvocationSecurityMetadataSource") private FilterInvocationSecurityMetadataSource securityMetadataSource; @Resource @Qualifier("customAccessDecisionManager") @Override public void setAccessDecisionManager(AccessDecisionManager accessDecisionManager) { // TODO Auto-generated method stub super.setAccessDecisionManager(accessDecisionManager); } @Resource // @Qualifier("authenticationManager") @Override public void setAuthenticationManager(AuthenticationManager authenticationManager) { super.setAuthenticationManager(authenticationManager); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(request, response, chain); infoke(fi); } private void infoke(FilterInvocation fi) throws IOException, ServletException { InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } @Override public Class<?> getSecureObjectClass() { // TODO Auto-generated method stub return FilterInvocation.class; } @Override public SecurityMetadataSource obtainSecurityMetadataSource() { // TODO Auto-generated method stub return this.securityMetadataSource; } @Override public void destroy() { // TODO Auto-generated method stub } public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return securityMetadataSource; } public void setSecurityMetadataSource( FilterInvocationSecurityMetadataSource securityMetadataSource) { this.securityMetadataSource = securityMetadataSource; } }
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.ssp.service.impl; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.hibernate.exception.ConstraintViolationException; import org.jasig.ssp.dao.DirectoryPersonSearchDao; import org.jasig.ssp.dao.ObjectExistsException; import org.jasig.ssp.dao.WatchStudentDao; import org.jasig.ssp.factory.PersonSearchRequestTOFactory; import org.jasig.ssp.factory.WatchStudentTOFactory; import org.jasig.ssp.model.ObjectStatus; import org.jasig.ssp.model.Person; import org.jasig.ssp.model.PersonSearchRequest; import org.jasig.ssp.model.PersonSearchResult2; import org.jasig.ssp.model.WatchStudent; import org.jasig.ssp.model.reference.ProgramStatus; import org.jasig.ssp.service.AbstractPersonAssocAuditableService; import org.jasig.ssp.service.ObjectNotFoundException; import org.jasig.ssp.service.PersonSearchService; import org.jasig.ssp.service.PersonService; import org.jasig.ssp.service.SecurityService; import org.jasig.ssp.service.WatchStudentService; import org.jasig.ssp.service.jobqueue.AbstractJobExecutor; import org.jasig.ssp.service.jobqueue.AbstractPersonSearchBasedJobExecutor; import org.jasig.ssp.service.jobqueue.AbstractPersonSearchBasedJobQueuer; import org.jasig.ssp.service.jobqueue.BasePersonSearchBasedJobExecutionState; import org.jasig.ssp.service.jobqueue.JobExecutionResult; import org.jasig.ssp.service.jobqueue.JobService; import org.jasig.ssp.service.reference.ConfigService; import org.jasig.ssp.transferobject.ImmutablePersonIdentifiersTO; import org.jasig.ssp.transferobject.WatchStudentTO; import org.jasig.ssp.transferobject.form.BulkWatchChangeJobSpec; import org.jasig.ssp.transferobject.form.BulkWatchChangeRequestForm; import org.jasig.ssp.transferobject.form.BulkWatchChangeTO; import org.jasig.ssp.transferobject.jobqueue.JobTO; import org.jasig.ssp.util.csvwriter.CaseloadCsvWriterHelper; import org.jasig.ssp.util.sort.PagingWrapper; import org.jasig.ssp.util.sort.SortingAndPaging; import org.jasig.ssp.web.api.validation.ValidationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.io.PrintWriter; import java.util.*; /** * WatchStudent service implementation */ @Service public class WatchStudentServiceImpl extends AbstractPersonAssocAuditableService<WatchStudent> implements WatchStudentService, InitializingBean { private static final Logger OUTER_CLASS_LOGGER = LoggerFactory .getLogger(PersonProgramStatusServiceImpl.class); private static final ThreadLocal<Logger> CURRENT_LOGGER = new ThreadLocal<Logger>(); public static final String BULK_WATCH_CHANGE_JOB_EXECUTOR_NAME = "bulk-watch-executor"; private static final String BULK_WATCH_CHANGE_BATCH_SIZE_CONFIG_NAME = "watch_bulk_change_batch_size"; private static final String BULK_WATCH_CHANGE_MAX_DLQ_SIZE_CONFIG_NAME = "watch_bulk_change_max_dlq_size"; private static final String BULK_WATCH_CHANGE_FAIL_ON_DLQ_OVERFLOW_CONFIG_NAME = "watch_bulk_change_fail_on_dlq_overflow"; // could be created or deleted watch IDs private static final String WATCH_ID_FIELD_NAME = "watchId"; @Autowired private transient WatchStudentDao dao; @Autowired protected transient WatchStudentTOFactory watchStudentTOFactory; @Autowired private transient DirectoryPersonSearchDao directoryPersonDao; @Autowired private transient PersonService personService; @Autowired private transient SecurityService securityService; @Autowired private transient PersonSearchRequestTOFactory personSearchRequestFactory; @Autowired private transient PersonSearchService personSearchService; @Autowired private transient JobService jobService; @Autowired private transient ConfigService configService; @Autowired private transient PlatformTransactionManager transactionManager; private static class BulkWatchChangeJobExecutionState extends BasePersonSearchBasedJobExecutionState { public int personsSkippedCount; // b/c they're external or already have the requested status } private AbstractJobExecutor<BulkWatchChangeJobSpec, BulkWatchChangeJobExecutionState> bulkJobExecutor; private AbstractPersonSearchBasedJobQueuer<BulkWatchChangeRequestForm, BulkWatchChangeJobSpec> bulkJobQueuer; @Override protected WatchStudentDao getDao() { return dao; } @Override public void afterPropertiesSet() throws Exception { initBulkWatchChangeJobExecutor(); initBulkWatchChangeJobQueuer(); } @Override public WatchStudent get(UUID watcherId, UUID studentId) { return dao.getStudentWatcherRelationShip(watcherId,studentId); } @Override public PagingWrapper<PersonSearchResult2> watchListFor(ProgramStatus programStatus, Person person, SortingAndPaging sAndP) { PersonSearchRequest form = new PersonSearchRequest(); form.setWatcher(person); form.setProgramStatus(programStatus); form.setSortAndPage(sAndP); return directoryPersonDao.search(form); } @Override public WatchStudent create(final WatchStudent obj) throws ObjectNotFoundException, ValidationException, ObjectExistsException { try { return super.create(obj); } catch (final ConstraintViolationException e) { if ( e.getConstraintName().equalsIgnoreCase("watch_student_watcher_id_student_id_key") ) { final LinkedHashMap<String, UUID> lookupKeys = Maps.newLinkedHashMap(); lookupKeys.put("watcherId", obj.getPerson().getId()); lookupKeys.put("studentId", obj.getStudent().getId()); throw new ObjectExistsException(WatchStudent.class.getName(), lookupKeys, e); } throw new ObjectExistsException("Constraint violation trying to store a WatchStudent record", e); } } @Override public void delete(final UUID id) throws ObjectNotFoundException { final WatchStudent current = getDao().get(id); dao.delete(current); } @Override // Would really rather make this non-transactional, but @Transactional is being set // well above us in the inheritance hierarchy so the best we can do is readOnly @Transactional(readOnly = true) public void exportWatchListFor(PrintWriter writer, ProgramStatus programStatus, Person person, SortingAndPaging buildSortAndPage) throws IOException { PersonSearchRequest form = new PersonSearchRequest(); form.setWatcher(person); form.setProgramStatus(programStatus); form.setSortAndPage(buildSortAndPage); directoryPersonDao.exportableSearch(new CaseloadCsvWriterHelper(writer), form); } @Override public Long watchListCountFor(ProgramStatus programStatus, Person person, SortingAndPaging buildSortAndPage) { PersonSearchRequest form = new PersonSearchRequest(); form.setWatcher(person); form.setProgramStatus(programStatus); form.setSortAndPage(buildSortAndPage); return directoryPersonDao.getCaseloadCountFor(form, buildSortAndPage); } @Override public PagingWrapper<Person> getWatchersForStudent(UUID studentId) { final PagingWrapper<WatchStudent> results = dao.getWatchersForStudent(studentId); final Collection<Person> peopleWatching = Lists.newArrayList(); for (WatchStudent watcher : results) { peopleWatching.add(watcher.getPerson()); //convert to person model } return new PagingWrapper<Person>(peopleWatching.size(), peopleWatching); } @Override @Transactional(rollbackFor = {ObjectNotFoundException.class, IOException.class, ValidationException.class}) public JobTO changeInBulk(BulkWatchChangeRequestForm form) throws IOException, ObjectNotFoundException, ValidationException { return bulkJobQueuer.enqueueJob(form); } /** * Intentionally private b/c we do not want this to participate in this service's "transactional-by-default" * public interface. Its transaction is managed by the {@code JobExecutor} assumed to be invoking it. * */ private Map<String, ?> changeSingleFromBulkRequest(ImmutablePersonIdentifiersTO personIds, BulkWatchChangeRequestForm coreSpec) throws ValidationException, ObjectNotFoundException { final Map<String,UUID> rslt = Maps.newLinkedHashMap(); final UUID targetPersonId = personIds.getId(); final UUID watcherId = coreSpec.getWatchSpec().getWatcherId(); final BulkWatchChangeTO.BulkWatchOperation operation = coreSpec.getWatchSpec().getOperation(); if ( targetPersonId == null ) { getCurrentLogger().debug("Skipping Watch change [{}] for target person [{}] and watcher [{}] " + "because that person has no operational record.", new Object[] { operation, personIds, watcherId }); return rslt; } WatchStudent watch = this.get(watcherId, targetPersonId); if ( watch == null || watch.getObjectStatus() != ObjectStatus.ACTIVE ) { if ( operation == BulkWatchChangeTO.BulkWatchOperation.UNWATCH ) { getCurrentLogger().debug("Skipping UNWATCH operation for target person [{}] and watcher [{}] " + "because the change would be redudant.", personIds, watcherId ); watch = null; } else { if ( watch != null ) { watch.setObjectStatus(ObjectStatus.ACTIVE); // Was hard to know whether to implement as a pure skip or just freshen the date b/c we don't // actually do anything with the date. Decided to go ahead and freshen so its a little bit easier // to correlate watch records with watch requests watch.setWatchDate(new Date()); watch = save(watch); } else { final WatchStudentTO watchTO = new WatchStudentTO(); watchTO.setStudentId(targetPersonId); watchTO.setWatcherId(watcherId); watchTO.setWatchDate(new Date()); // will raise ObjectNotFoundException if either target or watcher not found watch = watchStudentTOFactory.from(watchTO); watch = this.create(watch); } } } else { if ( operation == BulkWatchChangeTO.BulkWatchOperation.UNWATCH ) { this.delete(watch.getId()); } else { // Was hard to know whether to implement as a pure skip or just freshen the date b/c we don't actually // do anything with the date. Decided to go ahead and freshen so its a little bit easier to correlate // watch records with watch requests. (Same as above) watch.setWatchDate(new Date()); watch = save(watch); } } rslt.put(WATCH_ID_FIELD_NAME, watch == null ? null : watch.getId()); return rslt; } private void initBulkWatchChangeJobExecutor() { this.bulkJobExecutor = new AbstractPersonSearchBasedJobExecutor<BulkWatchChangeJobSpec, BulkWatchChangeJobExecutionState>( BULK_WATCH_CHANGE_JOB_EXECUTOR_NAME, jobService, transactionManager, null, personSearchService, personSearchRequestFactory, configService ) { private final Logger logger = LoggerFactory.getLogger(WatchStudentServiceImpl.this.getClass().getName() + ".BulkWatchChangeJobExecutor"); /** * The actual 'important' override... all the rest of the overrides are mostly boilerplate. */ @Override protected Map<String, ?> executeForSinglePerson(ImmutablePersonIdentifiersTO personIds, BulkWatchChangeJobSpec executionSpec, BulkWatchChangeJobExecutionState executionState, UUID jobId) throws ValidationException, ObjectNotFoundException { return changeSingleFromBulkRequest(personIds, executionSpec.getCoreSpec()); } @Override protected JobExecutionResult<BulkWatchChangeJobExecutionState> executeJobDeserialized(BulkWatchChangeJobSpec executionSpec, BulkWatchChangeJobExecutionState executionState, UUID jobId) { // TODO this copy pasted all over in these executor subclasses... abstract somehow try { WatchStudentServiceImpl.this.setCurrentLogger(logger); return super.executeJobDeserialized(executionSpec, executionState, jobId); } finally { WatchStudentServiceImpl.this.setCurrentLogger(null); } } @Override protected void recordSuccessful(ImmutablePersonIdentifiersTO personIds, Map<String, ?> results, BulkWatchChangeJobSpec executionSpec, BulkWatchChangeJobExecutionState executionState, UUID jobId) { super.recordSuccessful(personIds, results, executionSpec, executionState, jobId); if ( results.get(WATCH_ID_FIELD_NAME) == null ) { executionState.personsSkippedCount++; } } @Override protected BulkWatchChangeJobSpec deserializeJobSpecWithCheckedExceptions(String jobSpecStr) throws Exception { return getObjectMapper().readValue(jobSpecStr, BulkWatchChangeJobSpec.class); } @Override protected BulkWatchChangeJobExecutionState deserializeJobStateWithCheckedExceptions(String jobStateStr) throws Exception { return getObjectMapper().readValue(jobStateStr, BulkWatchChangeJobExecutionState.class); } @Override protected String decorateProcessingCompleteLogMessage(String baseMsg, BulkWatchChangeJobExecutionState executionState) { return new StringBuilder(baseMsg).append(" Persons skipped : [").append(executionState.personsSkippedCount) .append("].").toString(); } @Override protected BulkWatchChangeJobExecutionState newJobExecutionState() { return new BulkWatchChangeJobExecutionState(); } @Override protected Logger getCurrentLogger() { return WatchStudentServiceImpl.this.getCurrentLogger(); } @Override protected String getPageSizeConfigName() { return BULK_WATCH_CHANGE_BATCH_SIZE_CONFIG_NAME; } @Override protected String getDlqSizeConfigName() { return BULK_WATCH_CHANGE_MAX_DLQ_SIZE_CONFIG_NAME; } @Override protected String getFailOnSlqOverflowConfigName() { return BULK_WATCH_CHANGE_FAIL_ON_DLQ_OVERFLOW_CONFIG_NAME; } }; this.jobService.registerJobExecutor(this.bulkJobExecutor); } private void initBulkWatchChangeJobQueuer() { if ( this.bulkJobExecutor == null ) { // programmer error throw new IllegalStateException("Bulk Watch changing JobExecutor not yet initialized"); } this.bulkJobQueuer = new AbstractPersonSearchBasedJobQueuer<BulkWatchChangeRequestForm, BulkWatchChangeJobSpec> (this.bulkJobExecutor, securityService, personSearchRequestFactory, personSearchService) { @Override protected BulkWatchChangeRequestForm validateJobRequest(BulkWatchChangeRequestForm jobRequest) throws ValidationException { validateBulkWatchChangeRequest(jobRequest); return jobRequest; } @Override protected BulkWatchChangeJobSpec newJobSpec(BulkWatchChangeRequestForm jobRequest, Person currentSspPerson, PersonSearchRequest searchRequest, long searchResultCount) { return new BulkWatchChangeJobSpec(jobRequest); } }; } private void validateBulkWatchChangeRequest(BulkWatchChangeRequestForm jobRequest) throws ValidationException { final BulkWatchChangeTO watchSpec = jobRequest.getWatchSpec(); if ( watchSpec == null ) { throw new ValidationException("Must specify a target watch state"); } final BulkWatchChangeTO.BulkWatchOperation operation = watchSpec.getOperation(); if ( operation == null ) { throw new ValidationException("Must specify a watch change operation"); } if ( watchSpec.getWatcherId() == null ) { throw new ValidationException("Must specify a watcher ID"); } Person watcher = null; try { watcher = personService.get(watchSpec.getWatcherId()); } catch ( ObjectNotFoundException e ) { // nothing to do } if ( watcher == null ) { throw new ValidationException("Watcher ID [" + watchSpec.getWatcherId() + "] not on file"); } } private Logger getCurrentLogger() { return CURRENT_LOGGER.get() == null ? OUTER_CLASS_LOGGER : CURRENT_LOGGER.get(); } private void setCurrentLogger(Logger logger) { CURRENT_LOGGER.set(logger); } private static enum EmailVolume { SINGLE,BULK } }
package mb.jsglr.pie; import mb.common.result.Result; import mb.jsglr.common.JSGLRTokens; import mb.jsglr.common.JsglrParseException; import mb.jsglr.common.JsglrParseOutput; class TokensFunction extends MapperFunction<Result<JsglrParseOutput, JsglrParseException>, Result<JSGLRTokens, JsglrParseException>> { public static final TokensFunction instance = new TokensFunction(); @Override public Result<JSGLRTokens, JsglrParseException> apply(Result<JsglrParseOutput, JsglrParseException> result) { return result.flatMap(r -> { if(r.recovered) { return Result.ofErr(JsglrParseException.recoveryDisallowedFail(r.messages, r.startSymbol, r.fileHint, r.rootDirectoryHint)); } else { return Result.ofOk(r.tokens); } }); } private TokensFunction() {} private Object readResolve() { return instance; } }
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-util nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.util.collect; import java.util.Comparator; import java.util.Iterator; import com.google.common.annotations.Beta; import com.google.common.collect.Ordering; /** * A generic implementation of lexicographical comparison using iterators. * This is similar to Guava's {@link Ordering#lexicographical()}, but that method requires {@link Iterable}s, * which prevents its (proper) use with iterators. * * Given two iterators over ranges a1, a2, ..., an and b1, b2, ..., bm, * defines * <pre> * lex(a1..an, b1..bm) = -1 if (n = 0 and m &gt; 0) or a1 &lt; b1 * = 1 if (m = 0 and n &gt; 0) or b1 &gt; a1 * = lex(a2..an, b2..bm) if n = m = 0 or a1 == b1 * </pre> * * The operator &lt; can be provided as a comparator, or the given base type default comparison is used. * * This class does not extend {@link Comparator} because it has the side effect of exhausting the iterators. * * @author braz */ @Beta public class LexicographicComparison<T extends Comparable> { private Comparator<T> baseComparator; public LexicographicComparison() { this.baseComparator = Ordering.natural(); } public LexicographicComparison(Comparator<T> baseComparator) { this.baseComparator = baseComparator; } public int compare(Iterator<T> a, Iterator<T> b) { int result; if ( !a.hasNext()) { if ( !b.hasNext()) { result = 0; // two empty iterators } else { result = -1; // a is empty, b is not, so a is less than b. } } else if ( !b.hasNext()) { result = +1; // a is not empty, b is empty, so a is more than b. } else { // both are not empty, so both have a first element T aFirst = a.next(); T bFirst = b.next(); int bc = baseComparator.compare(aFirst, bFirst); if (bc == 0) { // first elements are equal, so defer decision to remaining elements result = compare(a,b); } else { result = bc; // first elements are not equal, so they determine entire comparison } } return result; } }
package com.example.skinet.core.entity; import lombok.Data; import javax.persistence.*; @Entity @Data @Table(name = "product_types") public class ProductType { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; }
package org.cloudburstmc.protocol.bedrock.packet; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.longs.LongList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.cloudburstmc.protocol.bedrock.data.MapDecoration; import org.cloudburstmc.protocol.bedrock.data.MapTrackedObject; import org.cloudburstmc.protocol.common.PacketSignal; import java.util.List; @Data @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class ClientboundMapItemDataPacket implements BedrockPacket { private final LongList trackedEntityIds = new LongArrayList(); private final List<MapTrackedObject> trackedObjects = new ObjectArrayList<>(); private final List<MapDecoration> decorations = new ObjectArrayList<>(); private long uniqueMapId; private int dimensionId; private boolean locked; private int scale; private int height; private int width; private int xOffset; private int yOffset; private int[] colors; @Override public final PacketSignal handle(BedrockPacketHandler handler) { return handler.handle(this); } public BedrockPacketType getPacketType() { return BedrockPacketType.CLIENTBOUND_MAP_ITEM_DATA; } }
/******************************************************************************* * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.internal.ole.win32; public class VARDESC { public int memid; /** @field cast=(OLECHAR FAR *) */ public long /*int*/ lpstrSchema; public int oInst; // ELEMDESC elemdescVar // TYPEDESC elemdescVar.tdesc /** @field accessor=elemdescVar.tdesc.lptdesc,cast=(struct FARSTRUCT tagTYPEDESC FAR *) */ public long /*int*/ elemdescVar_tdesc_union; /** @field accessor=elemdescVar.tdesc.vt */ public short elemdescVar_tdesc_vt; // PARAMDESC elemdescFunc.paramdesc /** @field accessor=elemdescVar.paramdesc.pparamdescex,cast=(LPPARAMDESCEX) */ public long /*int*/ elemdescVar_paramdesc_pparamdescex; /** @field accessor=elemdescVar.paramdesc.wParamFlags */ public short elemdescVar_paramdesc_wParamFlags; public short wVarFlags; public int varkind; public static final int sizeof = COM.VARDESC_sizeof (); }
package alien4cloud.it.setup; import java.io.IOException; import java.nio.file.Path; import java.util.Map; import lombok.extern.slf4j.Slf4j; import alien4cloud.git.RepositoryManager; import alien4cloud.utils.FileUtil; /** * Simple class that package the test archives as zip. */ @Slf4j public class PrepareTestData { private final static RepositoryManager repositoryManager = new RepositoryManager(); public static void main(String[] args) { System.setProperty("basedir", args[0]); try { FileUtil.delete(TestDataRegistry.IT_ARTIFACTS_DIR); } catch (IOException e) { log.error("Failed to delete zipped archives repository.", e); } try { FileUtil.delete(TestDataRegistry.GIT_ARTIFACTS_DIR); } catch (IOException e) { log.error("Failed to delete zipped archives repository.", e); } repositoryManager.cloneOrCheckout(TestDataRegistry.GIT_ARTIFACTS_DIR, "https://github.com/alien4cloud/tosca-normative-types.git", "master", "tosca-normative-types"); repositoryManager.cloneOrCheckout(TestDataRegistry.GIT_ARTIFACTS_DIR, "https://github.com/alien4cloud/alien4cloud-extended-types.git", "master", "alien4cloud-extended-types"); repositoryManager.cloneOrCheckout(TestDataRegistry.GIT_ARTIFACTS_DIR, "https://github.com/alien4cloud/samples.git", "master", "samples"); for (Map.Entry<Path, Path> entry : TestDataRegistry.SOURCE_TO_TARGET_ARTIFACT_MAPPING.entrySet()) { try { Path from = entry.getKey(); Path to = entry.getValue(); log.info("Zip from [{}] to [{}]", from, to); FileUtil.zip(from, to); } catch (IOException e) { throw new RuntimeException("Failed to zip archive for tests.", e); } } } }
package com.fasterxml.jackson.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Locale; import java.util.TimeZone; /** * General-purpose annotation used for configuring details of how * values of properties are to be serialized. * Unlike most other Jackson annotations, annotation does not * have specific universal interpretation: instead, effect depends on datatype * of property being annotated (or more specifically, deserializer * and serializer being used). *<p> * Common uses include choosing between alternate representations -- for example, * whether {@link java.util.Date} is to be serialized as number (Java timestamp) * or String (such as ISO-8601 compatible time value) -- as well as configuring * exact details with {@link #pattern} property. *<p> * As of Jackson 2.1, known special handling include: *<ul> * <li>{@link java.util.Date}: Shape can be {@link Shape#STRING} or {@link Shape#NUMBER}; * pattern may contain {@link java.text.SimpleDateFormat}-compatible pattern definition. * </li> *</ul> * Jackson 2.1 added following new features: *<ul> * <li>Can now be used on Classes (types) as well, for modified default behavior, possibly * overridden by per-property annotation * </li> * <li>{@link java.lang.Enum}s: Shapes {@link Shape#STRING} and {@link Shape#NUMBER} can be * used to change between numeric (index) and textual (name or <code>toString()</code>); * but it is also possible to use {@link Shape#OBJECT} to serialize (but not deserialize) * {@link java.lang.Enum}s as JSON Objects (as if they were POJOs). NOTE: serialization * as JSON Object only works with class annotation; * will not work as per-property annotation. * </li> * <li>{@link java.util.Collection}s can be serialized as (and deserialized from) JSON Objects, * if {@link Shape#OBJECT} is used. NOTE: can ONLY be used as class annotation; * will not work as per-property annotation. * </li> *</ul> * In Jackson 2.4: * <ul> * <li>{@link java.lang.Number} subclasses can be serialized as full objects if * {@link Shape#OBJECT} is used. Otherwise the default behavior of serializing to a * scalar number value will be preferred. NOTE: can ONLY be used as class annotation; * will not work as per-property annotation. * </li> *</ul> * * @since 2.0 */ @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation public @interface JsonFormat { /** * Value that indicates that default {@link java.util.Locale} * (from deserialization or serialization context) should be used: * annotation does not define value to use. */ public final static String DEFAULT_LOCALE = "##default"; /** * Value that indicates that default {@link java.util.TimeZone} * (from deserialization or serialization context) should be used: * annotation does not define value to use. */ public final static String DEFAULT_TIMEZONE = "##default"; /** * Datatype-specific additional piece of configuration that may be used * to further refine formatting aspects. This may, for example, determine * low-level format String used for {@link java.util.Date} serialization; * however, exact use is determined by specific <code>JsonSerializer</code> */ public String pattern() default ""; /** * Structure to use for serialization: definition of mapping depends on datatype, * but usually has straight-forward counterpart in data format (JSON). * Note that commonly only a subset of shapes is available; and if 'invalid' value * is chosen, defaults are usually used. */ public Shape shape() default Shape.ANY; /** * {@link java.util.Locale} to use for serialization (if needed). * Special value of {@link #DEFAULT_LOCALE} * can be used to mean "just use the default", where default is specified * by the serialization context, which in turn defaults to system * defaults ({@link java.util.Locale#getDefault()}) unless explicitly * set to another locale. */ public String locale() default DEFAULT_LOCALE; /** * {@link java.util.TimeZone} to use for serialization (if needed). * Special value of {@link #DEFAULT_TIMEZONE} * can be used to mean "just use the default", where default is specified * by the serialization context, which in turn defaults to system * defaults ({@link java.util.TimeZone#getDefault()}) unless explicitly * set to another locale. */ public String timezone() default DEFAULT_TIMEZONE; /* /********************************************************** /* Value enumeration(s), value class(es) /********************************************************** */ /** * Value enumeration used for indicating preferred Shape; translates * loosely to JSON types, with some extra values to indicate less precise * choices (i.e. allowing one of multiple actual shapes) */ public enum Shape { /** * Marker enum value that indicates "default" (or "whatever") choice; needed * since Annotations can not have null values for enums. */ ANY, /** * Value that indicates shape should not be structural (that is, not * {@link #ARRAY} or {@link #OBJECT}, but can be any other shape. */ SCALAR, /** * Value that indicates that (JSON) Array type should be used. */ ARRAY, /** * Value that indicates that (JSON) Object type should be used. */ OBJECT, /** * Value that indicates that a numeric (JSON) type should be used * (but does not specify whether integer or floating-point representation * should be used) */ NUMBER, /** * Value that indicates that floating-point numeric type should be used */ NUMBER_FLOAT, /** * Value that indicates that integer number type should be used * (and not {@link #NUMBER_FLOAT}). */ NUMBER_INT, /** * Value that indicates that (JSON) String type should be used. */ STRING, /** * Value that indicates that (JSON) boolean type * (true, false) should be used. */ BOOLEAN ; public boolean isNumeric() { return (this == NUMBER) || (this == NUMBER_INT) || (this == NUMBER_FLOAT); } public boolean isStructured() { return (this == OBJECT) || (this == ARRAY); } } /** * Helper class used to contain information from a single {@link JsonFormat} * annotation. */ public static class Value { private final String pattern; private final Shape shape; private final Locale locale; private final String timezoneStr; // lazily constructed when created from annotations private TimeZone _timezone; public Value() { this("", Shape.ANY, "", ""); } public Value(JsonFormat ann) { this(ann.pattern(), ann.shape(), ann.locale(), ann.timezone()); } public Value(String p, Shape sh, String localeStr, String tzStr) { this(p, sh, (localeStr == null || localeStr.length() == 0 || DEFAULT_LOCALE.equals(localeStr)) ? null : new Locale(localeStr), (tzStr == null || tzStr.length() == 0 || DEFAULT_TIMEZONE.equals(tzStr)) ? null : tzStr, null ); } /** * @since 2.1 */ public Value(String p, Shape sh, Locale l, TimeZone tz) { pattern = p; shape = (sh == null) ? Shape.ANY : sh; locale = l; _timezone = tz; timezoneStr = null; } /** * @since 2.4 */ public Value(String p, Shape sh, Locale l, String tzStr, TimeZone tz) { pattern = p; shape = (sh == null) ? Shape.ANY : sh; locale = l; _timezone = tz; timezoneStr = tzStr; } /** * @since 2.1 */ public Value withPattern(String p) { return new Value(p, shape, locale, timezoneStr, _timezone); } /** * @since 2.1 */ public Value withShape(Shape s) { return new Value(pattern, s, locale, timezoneStr, _timezone); } /** * @since 2.1 */ public Value withLocale(Locale l) { return new Value(pattern, shape, l, timezoneStr, _timezone); } /** * @since 2.1 */ public Value withTimeZone(TimeZone tz) { return new Value(pattern, shape, locale, null, tz); } public String getPattern() { return pattern; } public Shape getShape() { return shape; } public Locale getLocale() { return locale; } /** * Alternate access (compared to {@link #getTimeZone()}) which is useful * when caller just wants time zone id to convert, but not as JDK * provided {@link TimeZone} * * @since 2.4 */ public String timeZoneAsString() { if (_timezone != null) { return _timezone.getID(); } return timezoneStr; } public TimeZone getTimeZone() { TimeZone tz = _timezone; if (tz == null) { if (timezoneStr == null) { return null; } tz = TimeZone.getTimeZone(timezoneStr); _timezone = tz; } return tz; } /** * @since 2.4 */ public boolean hasShape() { return shape != Shape.ANY; } /** * @since 2.4 */ public boolean hasPattern() { return (pattern != null) && (pattern.length() > 0); } /** * @since 2.4 */ public boolean hasLocale() { return locale != null; } /** * @since 2.4 */ public boolean hasTimeZone() { return (_timezone != null) || (timezoneStr != null && !timezoneStr.isEmpty()); } } }
package com.test.es.service.impl; import com.alibaba.fastjson.JSON; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import com.test.es.model.EsPage; import com.test.es.model.MappingFieldInfo; import com.test.es.service.IEsService; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequestBuilder; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.action.admin.indices.get.GetIndexResponse; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.*; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.sort.SortOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; import java.util.*; @Service public class EsServiceImpl implements IEsService { private final Logger logger = LoggerFactory.getLogger(EsServiceImpl.class); @Resource private TransportClient client; private final String dateFormat = "yyyy-MM-dd HH:mm:ss.SSS || date_time || strict_date_time"; private final IndicesOptions IGNORE = IndicesOptions.fromOptions(true, true, true, false); @Override public boolean existIndex(String index) { IndicesExistsResponse indicesExistsResponse = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet(); return indicesExistsResponse.isExists(); } @Override public boolean deleteIndex(String index) { DeleteIndexRequestBuilder deleteIndexRequestBuilder = client.admin().indices().prepareDelete(index); AcknowledgedResponse acknowledgedResponse = deleteIndexRequestBuilder.execute().actionGet(); return acknowledgedResponse.isAcknowledged(); } @Override public boolean createIndexWithCommonMapping(String index, String type) throws IOException { CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(index); XContentBuilder properties = XContentFactory.jsonBuilder().startObject().startObject("properties"); properties.startObject("createTime").field("type", "date") .field("format",dateFormat).endObject().endObject().endObject(); createIndexRequestBuilder.addMapping(type, properties); CreateIndexResponse createIndexResponse = createIndexRequestBuilder.execute().actionGet(); return createIndexResponse.isAcknowledged(); } @Override public boolean createIndexWithCustomMapping(String index, String type, List<MappingFieldInfo> list) throws IOException { CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(index); XContentBuilder properties = XContentFactory.jsonBuilder().startObject().startObject("properties"); for (MappingFieldInfo info : list) { properties.startObject(info.getName()).field("type", info.getType()); if (!StringUtils.isEmpty(info.getFormatType())) { properties.field("format",info.getFormatType()); } properties.endObject(); } properties.endObject().endObject(); createIndexRequestBuilder.addMapping(type, properties); CreateIndexResponse createIndexResponse = createIndexRequestBuilder.execute().actionGet(); return createIndexResponse.isAcknowledged(); } @Override public boolean insertRecord(Map<String, Object> record, String index) { return insertRecord(record, index, "doc"); } @Override public boolean insertRecord(Map<String, Object> record, String index, String type) { IndexResponse indexResponse = client.prepareIndex(index, type).setSource(record).get(); RestStatus status = indexResponse.status(); return "ok".equalsIgnoreCase(status.name()); } @Override public boolean insertRecordBulk(List<Map<String, Object>> records, String index) { return insertRecordBulk(records, index, "doc"); } @Override public boolean insertRecordBulk(List<Map<String, Object>> records, String index, String type) { BulkRequestBuilder bulkRequestBuilder = client.prepareBulk(); records.stream().forEach(record -> bulkRequestBuilder.add(client.prepareIndex(index, type).setSource(record))); BulkResponse response = bulkRequestBuilder.execute().actionGet(); RestStatus status = response.status(); return "ok".equalsIgnoreCase(status.name()); } @Override public boolean deleteRecordById(String index, String type, String id) { DeleteResponse deleteResponse = client.prepareDelete(index, type, id).get(); RestStatus status = deleteResponse.status(); return "ok".equalsIgnoreCase(status.name()); } @Override public List<Map<String, Object>> query(List<String> index, String type, Map<String, Object> condition) { BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); if (condition == null) { boolQueryBuilder.must(new MatchAllQueryBuilder()); } else { for (Map.Entry<String, Object> entry : condition.entrySet()) { boolQueryBuilder.must(new WildcardQueryBuilder(entry.getKey(), "*" + entry.getValue() + "*")); } } SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index.toArray(new String[]{})).setTypes(type) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(boolQueryBuilder) .setIndicesOptions(IGNORE) // .setFrom(0) pageSize * (pageNum - 1) // .setSize(10) pageSize .addSort("createTime", SortOrder.DESC); logger.info("search condition:{}", searchRequestBuilder); SearchResponse searchResponse = searchRequestBuilder.execute().actionGet(); SearchHits hits = searchResponse.getHits(); long totalHits = hits.getTotalHits(); SearchHit[] searchHits = hits.getHits(); List<Map<String, Object>> list = new ArrayList<>(); for (SearchHit hit : searchHits) { String id = hit.getId(); Map<String, Object> sourceAsMap = hit.getSourceAsMap(); sourceAsMap.put("_id", id); list.add(sourceAsMap); } return list; } @Override public Object getIndexMappings() { String[] indices = ((GetIndexResponse)client.admin().indices().prepareGetIndex().execute().actionGet()).getIndices(); List<Map<String, Object>> list = new ArrayList(); int var5 = indices.length; byte var6 = 0; if (var6 < var5) { String index = indices[var6]; Map<String, Object> mappingInfo = new HashMap<>(); list.add(mappingInfo); mappingInfo.put("indexName", index); ImmutableOpenMap<String, MappingMetaData> mappings = ((IndexMetaData)((ClusterStateResponse)client.admin().cluster().prepareState().execute().actionGet()).getState().getMetaData().getIndices().get(index)).getMappings(); Iterator iterator = mappings.iterator(); while(iterator.hasNext()) { ObjectObjectCursor<String, MappingMetaData> cursor = (ObjectObjectCursor)iterator.next(); if (((String)cursor.key).equals("doc")) { String source = (cursor.value).source().toString(); Map map = JSON.parseObject(source, Map.class); Map<String, Object> doc = (Map)map.get("doc"); Map<String, Object> properties = (Map)doc.get("properties"); List<Map<String, String>> fields = new ArrayList(); Iterator propertiesIterator = properties.entrySet().iterator(); while(propertiesIterator.hasNext()) { Map.Entry<String, Object> entry = (Map.Entry)propertiesIterator.next(); String key = (String)entry.getKey(); Map<String, Object> value = (Map)entry.getValue(); String type = value.get("type").toString(); Map<String, String> field = new HashMap(); field.put("name", key); field.put("type", type); fields.add(field); } mappingInfo.put("fields", fields); break; } } } return list; } /** * 使用分词查询,并分页 * * @param index 索引名称 * @param type 类型名称,可传入多个type逗号分隔 * @param startPage 当前页 * @param pageSize 每页显示条数 * @param query 查询条件 * @param fields 需要显示的字段,逗号分隔(缺省为全部字段) * @param sortField 排序字段 * @param highlightField 高亮字段 * @return */ private EsPage searchDataPage(String index, String type, int startPage, int pageSize, QueryBuilder query, String fields, String sortField, String highlightField) { SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index); if (StringUtils.isNotEmpty(type)) { searchRequestBuilder.setTypes(type.split(",")); } searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH); // 需要显示的字段,逗号分隔(缺省为全部字段) if (StringUtils.isNotEmpty(fields)) { searchRequestBuilder.setFetchSource(fields.split(","), null); } //排序字段 if (StringUtils.isNotEmpty(sortField)) { searchRequestBuilder.addSort(sortField, SortOrder.DESC); } // 高亮(xxx=111,aaa=222) if (StringUtils.isNotEmpty(highlightField)) { HighlightBuilder highlightBuilder = new HighlightBuilder(); //highlightBuilder.preTags("<span style='color:red' >");//设置前缀 //highlightBuilder.postTags("</span>");//设置后缀 // 设置高亮字段 highlightBuilder.field(highlightField); searchRequestBuilder.highlighter(highlightBuilder); } // searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); searchRequestBuilder.setQuery(query); // 分页应用 searchRequestBuilder.setFrom(startPage).setSize(pageSize); // searchRequestBuilder.setSize(pageSize); // 设置是否按查询匹配度排序 searchRequestBuilder.setExplain(true); // 打印的内容 可以在 Elasticsearch head 和 Kibana 上执行查询 logger.info("query condition:\n{}", searchRequestBuilder); // 执行搜索,返回搜索响应信息 SearchResponse searchResponse = searchRequestBuilder.execute().actionGet(); long totalHits = searchResponse.getHits().totalHits; long length = searchResponse.getHits().getHits().length; logger.info("共查询到[{}]条数据,处理数据条数[{}]", totalHits, length); if (searchResponse.status().getStatus() == HttpStatus.SC_OK) { // 解析对象 List<Map<String, Object>> sourceList = setSearchResponse(searchResponse, highlightField); return new EsPage(startPage, pageSize, (int) totalHits, sourceList); } return null; } /** * 高亮结果集 特殊处理 * * @param searchResponse * @param highlightField */ private List<Map<String, Object>> setSearchResponse(SearchResponse searchResponse, String highlightField) { List<Map<String, Object>> sourceList = new ArrayList<Map<String, Object>>(); StringBuffer stringBuffer = new StringBuffer(); for (SearchHit searchHit : searchResponse.getHits().getHits()) { searchHit.getSourceAsMap().put("id", searchHit.getId()); if (StringUtils.isNotEmpty(highlightField)) { System.out.println("遍历 高亮结果集,覆盖 正常结果集" + searchHit.getSourceAsMap()); Text[] text = searchHit.getHighlightFields().get(highlightField).getFragments(); if (text != null) { for (Text str : text) { stringBuffer.append(str.string()); } //遍历 高亮结果集,覆盖 正常结果集 searchHit.getSourceAsMap().put(highlightField, stringBuffer.toString()); } } sourceList.add(searchHit.getSourceAsMap()); } return sourceList; } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.compute.v2019_11_01; import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; /** * Specifies information about the gallery Application Definition that you want * to update. */ @JsonFlatten public class GalleryApplicationUpdate extends UpdateResource { /** * The description of this gallery Application Definition resource. This * property is updatable. */ @JsonProperty(value = "properties.description") private String description; /** * The Eula agreement for the gallery Application Definition. */ @JsonProperty(value = "properties.eula") private String eula; /** * The privacy statement uri. */ @JsonProperty(value = "properties.privacyStatementUri") private String privacyStatementUri; /** * The release note uri. */ @JsonProperty(value = "properties.releaseNoteUri") private String releaseNoteUri; /** * The end of life date of the gallery Application Definition. This * property can be used for decommissioning purposes. This property is * updatable. */ @JsonProperty(value = "properties.endOfLifeDate") private DateTime endOfLifeDate; /** * This property allows you to specify the supported type of the OS that * application is built for. &lt;br&gt;&lt;br&gt; Possible values are: * &lt;br&gt;&lt;br&gt; **Windows** &lt;br&gt;&lt;br&gt; **Linux**. * Possible values include: 'Windows', 'Linux'. */ @JsonProperty(value = "properties.supportedOSType", required = true) private OperatingSystemTypes supportedOSType; /** * Get the description of this gallery Application Definition resource. This property is updatable. * * @return the description value */ public String description() { return this.description; } /** * Set the description of this gallery Application Definition resource. This property is updatable. * * @param description the description value to set * @return the GalleryApplicationUpdate object itself. */ public GalleryApplicationUpdate withDescription(String description) { this.description = description; return this; } /** * Get the Eula agreement for the gallery Application Definition. * * @return the eula value */ public String eula() { return this.eula; } /** * Set the Eula agreement for the gallery Application Definition. * * @param eula the eula value to set * @return the GalleryApplicationUpdate object itself. */ public GalleryApplicationUpdate withEula(String eula) { this.eula = eula; return this; } /** * Get the privacy statement uri. * * @return the privacyStatementUri value */ public String privacyStatementUri() { return this.privacyStatementUri; } /** * Set the privacy statement uri. * * @param privacyStatementUri the privacyStatementUri value to set * @return the GalleryApplicationUpdate object itself. */ public GalleryApplicationUpdate withPrivacyStatementUri(String privacyStatementUri) { this.privacyStatementUri = privacyStatementUri; return this; } /** * Get the release note uri. * * @return the releaseNoteUri value */ public String releaseNoteUri() { return this.releaseNoteUri; } /** * Set the release note uri. * * @param releaseNoteUri the releaseNoteUri value to set * @return the GalleryApplicationUpdate object itself. */ public GalleryApplicationUpdate withReleaseNoteUri(String releaseNoteUri) { this.releaseNoteUri = releaseNoteUri; return this; } /** * Get the end of life date of the gallery Application Definition. This property can be used for decommissioning purposes. This property is updatable. * * @return the endOfLifeDate value */ public DateTime endOfLifeDate() { return this.endOfLifeDate; } /** * Set the end of life date of the gallery Application Definition. This property can be used for decommissioning purposes. This property is updatable. * * @param endOfLifeDate the endOfLifeDate value to set * @return the GalleryApplicationUpdate object itself. */ public GalleryApplicationUpdate withEndOfLifeDate(DateTime endOfLifeDate) { this.endOfLifeDate = endOfLifeDate; return this; } /** * Get this property allows you to specify the supported type of the OS that application is built for. &lt;br&gt;&lt;br&gt; Possible values are: &lt;br&gt;&lt;br&gt; **Windows** &lt;br&gt;&lt;br&gt; **Linux**. Possible values include: 'Windows', 'Linux'. * * @return the supportedOSType value */ public OperatingSystemTypes supportedOSType() { return this.supportedOSType; } /** * Set this property allows you to specify the supported type of the OS that application is built for. &lt;br&gt;&lt;br&gt; Possible values are: &lt;br&gt;&lt;br&gt; **Windows** &lt;br&gt;&lt;br&gt; **Linux**. Possible values include: 'Windows', 'Linux'. * * @param supportedOSType the supportedOSType value to set * @return the GalleryApplicationUpdate object itself. */ public GalleryApplicationUpdate withSupportedOSType(OperatingSystemTypes supportedOSType) { this.supportedOSType = supportedOSType; return this; } }
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.presentation.pipelinehistory; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.materials.MaterialConfigs; import com.thoughtworks.go.config.materials.mercurial.HgMaterial; import com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig; import com.thoughtworks.go.config.materials.svn.SvnMaterial; import com.thoughtworks.go.domain.JobResult; import com.thoughtworks.go.domain.JobState; import com.thoughtworks.go.domain.MaterialRevision; import com.thoughtworks.go.domain.MaterialRevisions; import com.thoughtworks.go.domain.StageIdentifier; import com.thoughtworks.go.domain.buildcause.BuildCause; import com.thoughtworks.go.domain.materials.Material; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.helper.MaterialConfigsMother; import com.thoughtworks.go.helper.MaterialsMother; import com.thoughtworks.go.helper.ModificationsMother; import com.thoughtworks.go.helper.PipelineHistoryMother; import org.joda.time.DateTime; import org.junit.Test; import static com.thoughtworks.go.domain.buildcause.BuildCause.createWithEmptyModifications; import static com.thoughtworks.go.helper.MaterialsMother.hgMaterial; import static com.thoughtworks.go.helper.MaterialsMother.svnMaterial; import static com.thoughtworks.go.helper.PipelineHistoryMother.job; import static com.thoughtworks.go.helper.PipelineHistoryMother.stagePerJob; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; public class PipelineInstanceModelTest { private static final Modification HG_MATERIAL_MODIFICATION = new Modification("user", "Comment", "email", new Date(), "a087402bd2a7828a130c1bdf43f2d9ef8f48fd46"); @Test public void shouldUnderstandActiveStage() { StageInstanceModels stages = new StageInstanceModels(); stages.addStage("unit1", JobHistory.withJob("test", JobState.Completed, JobResult.Passed, new Date())); JobHistory history = new JobHistory(); history.add(new JobHistoryItem("test-1", JobState.Completed, JobResult.Failed, new Date())); history.add(new JobHistoryItem("test-2", JobState.Building, JobResult.Unknown, new Date())); StageInstanceModel activeStage = new StageInstanceModel("unit2", "1", history); stages.add(activeStage); stages.addFutureStage("unit3", false); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createManualForced(), stages); assertThat(model.activeStage(), is(activeStage)); } @Test public void shouldReturnNullWhenNoActiveStage() { StageInstanceModels stages = new StageInstanceModels(); stages.addStage("unit1", JobHistory.withJob("test", JobState.Completed, JobResult.Passed, new Date())); JobHistory history = new JobHistory(); history.add(new JobHistoryItem("test-1", JobState.Completed, JobResult.Failed, new Date())); history.add(new JobHistoryItem("test-2", JobState.Completed, JobResult.Passed, new Date())); stages.add(new StageInstanceModel("unit2", "1", history)); stages.addFutureStage("unit3", false); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createManualForced(), stages); assertThat(model.activeStage(), is(nullValue())); } @Test public void shouldUnderstandPipelineStatusMessage() throws Exception { MaterialRevisions revisions = ModificationsMother.modifyOneFile(MaterialsMother.hgMaterials("url"), "revision"); StageInstanceModels stages = new StageInstanceModels(); stages.addStage("unit1", JobHistory.withJob("test", JobState.Completed, JobResult.Passed, new Date())); stages.addFutureStage("unit2", false); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createWithModifications(revisions, ""), stages); assertThat(model.getPipelineStatusMessage(), is("Passed: unit1")); } @Test public void shouldGetCurrentRevisionForMaterial() { MaterialRevisions revisions = new MaterialRevisions(); HgMaterial material = MaterialsMother.hgMaterial(); revisions.addRevision(material, HG_MATERIAL_MODIFICATION); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createWithModifications(revisions, ""), new StageInstanceModels()); assertThat(model.getCurrentRevision(material.config()).getRevision(), is("a087402bd2a7828a130c1bdf43f2d9ef8f48fd46")); } @Test public void shouldGetCurrentMaterialRevisionForMaterial() { MaterialRevisions revisions = new MaterialRevisions(); HgMaterial material = MaterialsMother.hgMaterial(); revisions.addRevision(material, HG_MATERIAL_MODIFICATION); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createWithModifications(revisions, ""), new StageInstanceModels()); assertThat(model.findCurrentMaterialRevisionForUI(material.config()), is(revisions.getMaterialRevision(0))); } @Test public void shouldFallbackToPipelineFingerpringWhenGettingCurrentMaterialRevisionForMaterialIsNull() { MaterialRevisions revisions = new MaterialRevisions(); HgMaterial material = MaterialsMother.hgMaterial(); HgMaterial materialWithDifferentDest = MaterialsMother.hgMaterial(); materialWithDifferentDest.setFolder("otherFolder"); revisions.addRevision(material, HG_MATERIAL_MODIFICATION); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createWithModifications(revisions, ""), new StageInstanceModels()); assertThat(model.findCurrentMaterialRevisionForUI(materialWithDifferentDest.config()), is(revisions.getMaterialRevision(0))); } @Test public void shouldGetCurrentRevisionForMaterialByName() { MaterialRevisions revisions = new MaterialRevisions(); HgMaterial material = MaterialsMother.hgMaterial(); SvnMaterial svnMaterial = MaterialsMother.svnMaterial(); material.setName(new CaseInsensitiveString("hg_material")); revisions.addRevision(svnMaterial, new Modification(new Date(), "1024", "MOCK_LABEL-12", null)); revisions.addRevision(material, HG_MATERIAL_MODIFICATION); BuildCause buildCause = BuildCause.createWithModifications(revisions, ""); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", buildCause, new StageInstanceModels()); assertThat(model.getCurrentRevision("hg_material").getRevision(), is("a087402bd2a7828a130c1bdf43f2d9ef8f48fd46")); } @Test public void shouldGetLatestMaterialRevisionForMaterial() { HgMaterial material = MaterialsMother.hgMaterial(); assertThat(setUpModificationForHgMaterial().getLatestMaterialRevision(material.config()), is(new MaterialRevision(material, HG_MATERIAL_MODIFICATION))); } @Test public void shouldGetLatestRevisionForMaterial() { HgMaterialConfig hgMaterialConfig = MaterialConfigsMother.hgMaterialConfig(); assertThat(setUpModificationForHgMaterial().getLatestRevision(hgMaterialConfig).getRevision(), is("a087402bd2a7828a130c1bdf43f2d9ef8f48fd46")); } @Test public void shouldGetLatestRevisionForMaterialWithNoModifications() { assertThat(hgMaterialWithNoModifications().getLatestRevision(MaterialConfigsMother.hgMaterialConfig()).getRevision(), is("No historical data")); } @Test public void shouldGetCurrentRevisionForMaterialName() { HgMaterial material = MaterialsMother.hgMaterial(); material.setName(new CaseInsensitiveString("foo")); assertThat(setUpModificationFor(material).getCurrentRevision(CaseInsensitiveString.str(material.getName())).getRevision(), is("a087402bd2a7828a130c1bdf43f2d9ef8f48fd46")); } @Test public void shouldThrowExceptionWhenCurrentRevisionForUnknownMaterialNameRequested() { HgMaterial material = MaterialsMother.hgMaterial(); material.setName(new CaseInsensitiveString("foo")); try { assertThat(setUpModificationFor(material).getCurrentRevision("blah").getRevision(), is("a087402bd2a7828a130c1bdf43f2d9ef8f48fd46")); fail("should have raised an exeption for unknown material name"); } catch (Exception ignored) { } } private PipelineInstanceModel setUpModificationForHgMaterial() { MaterialRevisions revisions = new MaterialRevisions(); revisions.addRevision(MaterialsMother.hgMaterial(), HG_MATERIAL_MODIFICATION); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", null, new StageInstanceModels()); model.setLatestRevisions(revisions); return model; } private PipelineInstanceModel hgMaterialWithNoModifications() { MaterialRevisions revisions = new MaterialRevisions(); revisions.addRevision(MaterialsMother.hgMaterial(), new ArrayList<Modification>()); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", null, new StageInstanceModels()); model.setLatestRevisions(revisions); return model; } private PipelineInstanceModel setUpModificationFor(HgMaterial material) { MaterialRevisions revisions = new MaterialRevisions(); revisions.addRevision(material, HG_MATERIAL_MODIFICATION); return PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createWithModifications(revisions, ""), new StageInstanceModels()); } @Test public void shouldKnowIfLatestRevisionIsReal() throws Exception { assertThat(setUpModificationForHgMaterial().hasModificationsFor(MaterialConfigsMother.hgMaterialConfig()), is(true)); } @Test public void shouldKnowApproverAsApproverForTheFirstStage() { MaterialRevisions revisions = new MaterialRevisions(); StageInstanceModels models = new StageInstanceModels(); StageInstanceModel firstStage = new StageInstanceModel("dev", "1", new JobHistory()); firstStage.setApprovedBy("some_user"); models.add(firstStage); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createWithModifications(revisions, ""), models); assertThat(model.getApprovedBy(), is("some_user")); assertThat(model.getApprovedByForDisplay(), is("Triggered by some_user")); } @Test public void shouldUnderstandIfReal() { assertThat(PipelineInstanceModel.createEmptyModel().hasHistoricalData(), is(true)); assertThat(PipelineInstanceModel.createEmptyPipelineInstanceModel("pipeline", createWithEmptyModifications(), new StageInstanceModels()).hasHistoricalData(), is(false)); } //Pipeline: Red -> Green -> Has_Not_Run_Yet @Test public void shouldBeSucessfulOnAForceContinuedPass_Red_AND_Green_AND_Has_Not_Run_Yet() { Date occuredFirst = new Date(2008, 12, 13); Date occuredSecond = new Date(2008, 12, 14); StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Failed, occuredFirst), job(JobResult.Passed, occuredSecond)); stageInstanceModels.add(new NullStageHistoryItem("stage-3", false)); PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels); assertThat(instanceModel.isLatestStageUnsuccessful(), is(false)); assertThat(instanceModel.isLatestStageSuccessful(), is(true)); assertThat(instanceModel.isRunning(), is(true)); } //Pipeline: Red(Rerun after second stage passed i.e. latest stage) -> Green -> Has_Not_Run_Yet @Test public void shouldReturnStatusOfAfailedRerunAndIncompleteStage() { Date occuredFirst = new Date(2008, 12, 13); Date occuredSecond = new Date(2008, 12, 14); StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Failed, occuredSecond), job(JobResult.Passed, occuredFirst)); stageInstanceModels.add(new NullStageHistoryItem("stage-3", false)); PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels); assertThat(instanceModel.isLatestStageUnsuccessful(), is(true)); assertThat(instanceModel.isLatestStageSuccessful(), is(false)); assertThat(instanceModel.isRunning(), is(true)); } @Test public void shouldReturnStatusOfAFailedRerun() { Date occuredFirst = new Date(2008, 12, 13); Date occuredSecond = new Date(2008, 12, 14); StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Failed, occuredSecond), job(JobResult.Passed, occuredFirst)); PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels); assertThat(instanceModel.isLatestStageUnsuccessful(), is(true)); assertThat(instanceModel.isLatestStageSuccessful(), is(false)); assertThat(instanceModel.isRunning(), is(false)); } @Test public void shouldReturnStatusOfAPassedForceThrough() { Date occuredFirst = new Date(2008, 12, 13); Date occuredSecond = new Date(2008, 12, 14); StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Failed, occuredFirst), job(JobResult.Passed, occuredSecond)); PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels); assertThat(instanceModel.isLatestStageUnsuccessful(), is(false)); assertThat(instanceModel.isLatestStageSuccessful(), is(true)); assertThat(instanceModel.isRunning(), is(false)); } @Test public void shouldReturnPipelineStatusAsPassedWhenAllTheStagesPass() { Date occuredFirst = new Date(2008, 12, 13); Date occuredSecond = new Date(2008, 12, 14); StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Passed, occuredSecond), job(JobResult.Passed, occuredFirst)); PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels); assertThat(instanceModel.isLatestStageUnsuccessful(), is(false)); assertThat(instanceModel.isLatestStageSuccessful(), is(true)); assertThat(instanceModel.isRunning(), is(false)); } @Test public void shouldReturnTheLatestStageEvenWhenThereIsANullStage() { Date occuredFirst = new DateTime().minusDays(1).toDate(); Date occuredSecond = new DateTime().toDate(); StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Passed, occuredSecond), job(JobResult.Passed, occuredFirst)); NullStageHistoryItem stageHistoryItem = new NullStageHistoryItem("not_yet_run", false); stageInstanceModels.add(stageHistoryItem); PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels); StageInstanceModel value = stageInstanceModels.get(0); assertThat(instanceModel.latestStage(), is(value)); } @Test public void shouldReturnIfAStageIsLatest() { Date occuredFirst = new DateTime().minusDays(1).toDate(); Date occuredSecond = new DateTime().toDate(); StageInstanceModels stageInstanceModels = stagePerJob("stage", job(JobResult.Passed, occuredSecond), job(JobResult.Passed, occuredFirst)); NullStageHistoryItem stageHistoryItem = new NullStageHistoryItem("not_yet_run", false); stageInstanceModels.add(stageHistoryItem); PipelineInstanceModel instanceModel = PipelineInstanceModel.createPipeline("pipeline", -1, "label", createWithEmptyModifications(), stageInstanceModels); assertThat(instanceModel.isLatestStage(stageInstanceModels.get(0)), is(true)); assertThat(instanceModel.isLatestStage(stageInstanceModels.get(1)), is(false)); } @Test public void shouldReturnIfAnyMaterialHasModifications() { final SvnMaterial svnMaterial = svnMaterial("http://svnurl"); final HgMaterial hgMaterial = hgMaterial("http://hgurl", "hgdir"); MaterialRevisions currentRevisions = ModificationsMother.getMaterialRevisions(new HashMap<Material, String>() {{ put(svnMaterial, "1"); put(hgMaterial, "a"); }}); MaterialRevisions latestRevisions = ModificationsMother.getMaterialRevisions(new HashMap<Material, String>() {{ put(svnMaterial, "1"); put(hgMaterial, "b"); }}); MaterialConfigs materialConfigs = new MaterialConfigs(); materialConfigs.add(svnMaterial.config()); materialConfigs.add(hgMaterial.config()); StageInstanceModels stages = new StageInstanceModels(); stages.addStage("unit1", JobHistory.withJob("test", JobState.Completed, JobResult.Passed, new Date())); stages.addFutureStage("unit2", false); PipelineInstanceModel model = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createWithModifications(currentRevisions, ""), stages); model.setLatestRevisions(latestRevisions); model.setMaterialConfigs(materialConfigs); assertThat("svnMaterial hasNewRevisions", model.hasNewRevisions(svnMaterial.config()), is(false)); assertThat("hgMaterial hasNewRevisions", model.hasNewRevisions(hgMaterial.config()), is(true)); assertThat("all materials hasNewRevisions", model.hasNewRevisions(), is(true)); } @Test public void shouldUnderstandIfItHasNeverCheckedForRevisions() { StageInstanceModels stages = new StageInstanceModels(); stages.addStage("unit1", JobHistory.withJob("test", JobState.Completed, JobResult.Passed, new Date())); stages.addFutureStage("unit2", false); PipelineInstanceModel pim = PipelineInstanceModel.createPipeline("pipeline", -1, "label", BuildCause.createNeverRun(), stages); pim.setLatestRevisions(MaterialRevisions.EMPTY); assertThat("pim.hasNeverCheckedForRevisions()", pim.hasNeverCheckedForRevisions(), is(true)); } @Test public void shouldReturnTrueIfThePipelineHasStage() { PipelineInstanceModel pim = PipelineHistoryMother.pipelineHistoryItemWithOneStage("pipeline", "stage", new Date()); assertThat(pim.hasStage(pim.getStageHistory().first().getIdentifier()), is(true)); assertThat(pim.hasStage(new StageIdentifier("pipeline",1,"1", "stagex", "2")), is(false)); } @Test public void shouldSetAndGetComment() { PipelineInstanceModel pim = PipelineInstanceModel.createEmptyModel(); pim.setComment("test comment"); assertThat("PipelineInstanceModel.getComment()", pim.getComment(), is("test comment")); } }
package com.notnoop.apns; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Date; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import javax.net.ssl.SSLContext; /** * Represents the Apple Feedback server. This allows testing outside of the * Apple servers. */ public class ApnsFeedbackServerSocket extends AbstractApnsServerSocket { private final ApnsServerService requestDelegate; public ApnsFeedbackServerSocket(SSLContext sslContext, int port, ExecutorService executorService, ApnsServerService requestDelegate, ApnsServerExceptionDelegate exceptionDelegate) throws IOException { super(sslContext, port, executorService, exceptionDelegate); this.requestDelegate = requestDelegate; } @Override void handleSocket(Socket socket) throws IOException { Map<byte[], Date> inactiveDevices = requestDelegate .getInactiveDevices(); DataOutputStream dataStream = new DataOutputStream( socket.getOutputStream()); for (Entry<byte[], Date> entry : inactiveDevices.entrySet()) { int time = (int) (entry.getValue().getTime() / 1000L); dataStream.writeInt(time); byte[] bytes = entry.getKey(); dataStream.writeShort(bytes.length); dataStream.write(bytes); } dataStream.close(); } }
/* * Copyright 2017 Republic of Reinvention bvba. 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.beligum.blocks.filesystem.hdfs.monitor; import com.beligum.blocks.filesystem.ifaces.FsMonitor; import org.apache.hadoop.fs.Path; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; /** * Created by bram on 6/20/16. */ public abstract class AbstractFsMonitor implements FsMonitor { //-----CONSTANTS----- //-----VARIABLES----- protected Path rootFolder; protected Set<Listener> listeners; //-----CONSTRUCTORS----- protected AbstractFsMonitor(Path rootFolder) { this.rootFolder = rootFolder; this.listeners = Collections.synchronizedSet(new LinkedHashSet<>()); } //-----PUBLIC METHODS----- @Override public org.apache.hadoop.fs.Path getRootFolder() { return this.rootFolder; } @Override public boolean registerListener(Listener listener) { return this.listeners.add(listener); } @Override public boolean unregisterListener(Listener listener) { return this.listeners.remove(listener); } @Override public Collection<Listener> getListeners() { return this.listeners; } //-----PROTECTED METHODS----- //-----PRIVATE METHODS----- }
package net.teamfruit.projectrtm.rtm.entity.ai; import net.minecraft.entity.ai.EntityAIBase; import net.teamfruit.projectrtm.rtm.electric.SignalLevel; import net.teamfruit.projectrtm.rtm.entity.npc.EntityMotorman; import net.teamfruit.projectrtm.rtm.entity.train.EntityTrainBase; import net.teamfruit.projectrtm.rtm.entity.train.util.EnumNotch; public class EntityAIDrivingWithSignal extends EntityAIBase { protected final EntityMotorman motorman; protected EntityTrainBase train; public EntityAIDrivingWithSignal(EntityMotorman par1) { this.motorman = par1; this.setMutexBits(1); } @Override public boolean shouldExecute() { if (this.motorman.isRiding()&&this.motorman.ridingEntity instanceof EntityTrainBase) { return true; } return false; } @Override public void startExecuting() { this.train = (EntityTrainBase) this.motorman.ridingEntity; } @Override public boolean continueExecuting() { return this.shouldExecute(); } @Override public void updateTask() { int signal = this.train.getSignal(); float prevSpeed = this.train.getSpeed(); float targetSpeed = SignalLevel.getSpeed(signal, prevSpeed); int notch = this.getSuitableNotch(targetSpeed, prevSpeed).id; this.train.setNotch(notch); //NGTLog.debug("set notch : " + notch); } /** * @param par1 : 目標の速度 * @param par2 : 現在の速度 */ private EnumNotch getSuitableNotch(float par1, float par2) { float gap = par1-par2; if (gap>0.0F) { for (EnumNotch notch : EnumNotch.values()) { if (notch.max_speed>=par1) { return notch; } } } else if (gap==0.0F) { return EnumNotch.inertia; } else { /*int i0 = (int)(((gap / 1.5F) * 8.0F) - 0.5F); if(i0 == 0 && gap < 0.0F) { return EnumNotch.brake_1; } return EnumNotch.getNotch(i0);*/ return EnumNotch.brake_4; } return EnumNotch.inertia; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.columniterator; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.*; import org.apache.cassandra.db.filter.ColumnFilter; import org.apache.cassandra.db.rows.*; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.io.sstable.CorruptSSTableException; import org.apache.cassandra.io.sstable.IndexHelper; import org.apache.cassandra.io.util.FileDataInput; import org.apache.cassandra.io.util.FileMark; import org.apache.cassandra.utils.ByteBufferUtil; abstract class AbstractSSTableIterator implements UnfilteredRowIterator { protected final SSTableReader sstable; protected final DecoratedKey key; protected final DeletionTime partitionLevelDeletion; protected final ColumnFilter columns; protected final SerializationHelper helper; protected final Row staticRow; protected final Reader reader; private final boolean isForThrift; private boolean isClosed; protected final Slices slices; protected int slice; @SuppressWarnings("resource") // We need this because the analysis is not able to determine that we do close // file on every path where we created it. protected AbstractSSTableIterator(SSTableReader sstable, FileDataInput file, DecoratedKey key, RowIndexEntry indexEntry, Slices slices, ColumnFilter columnFilter, boolean isForThrift) { this.sstable = sstable; this.key = key; this.columns = columnFilter; this.slices = slices; this.helper = new SerializationHelper(sstable.metadata, sstable.descriptor.version.correspondingMessagingVersion(), SerializationHelper.Flag.LOCAL, columnFilter); this.isForThrift = isForThrift; if (indexEntry == null) { this.partitionLevelDeletion = DeletionTime.LIVE; this.reader = null; this.staticRow = Rows.EMPTY_STATIC_ROW; } else { boolean shouldCloseFile = file == null; try { // We seek to the beginning to the partition if either: // - the partition is not indexed; we then have a single block to read anyway // (and we need to read the partition deletion time). // - we're querying static columns. boolean needSeekAtPartitionStart = !indexEntry.isIndexed() || !columns.fetchedColumns().statics.isEmpty(); // For CQL queries on static compact tables, we only want to consider static value (only those are exposed), // but readStaticRow have already read them and might in fact have consumed the whole partition (when reading // the legacy file format), so set the reader to null so we don't try to read anything more. We can remove this // once we drop support for the legacy file format boolean needsReader = sstable.descriptor.version.storeRows() || isForThrift || !sstable.metadata.isStaticCompactTable(); if (needSeekAtPartitionStart) { // Not indexed (or is reading static), set to the beginning of the partition and read partition level deletion there if (file == null) file = sstable.getFileDataInput(indexEntry.position); else file.seek(indexEntry.position); ByteBufferUtil.skipShortLength(file); // Skip partition key this.partitionLevelDeletion = DeletionTime.serializer.deserialize(file); // Note that this needs to be called after file != null and after the partitionDeletion has been set, but before readStaticRow // (since it uses it) so we can't move that up (but we'll be able to simplify as soon as we drop support for the old file format). this.reader = needsReader ? createReader(indexEntry, file, shouldCloseFile) : null; this.staticRow = readStaticRow(sstable, file, helper, columns.fetchedColumns().statics, isForThrift, reader == null ? null : reader.deserializer); } else { this.partitionLevelDeletion = indexEntry.deletionTime(); this.staticRow = Rows.EMPTY_STATIC_ROW; this.reader = needsReader ? createReader(indexEntry, file, shouldCloseFile) : null; } if (reader != null && slices.size() > 0) reader.setForSlice(slices.get(0)); if (reader == null && file != null && shouldCloseFile) file.close(); } catch (IOException e) { sstable.markSuspect(); String filePath = file.getPath(); if (shouldCloseFile) { try { file.close(); } catch (IOException suppressed) { e.addSuppressed(suppressed); } } throw new CorruptSSTableException(e, filePath); } } } private static Row readStaticRow(SSTableReader sstable, FileDataInput file, SerializationHelper helper, Columns statics, boolean isForThrift, UnfilteredDeserializer deserializer) throws IOException { if (!sstable.descriptor.version.storeRows()) { if (!sstable.metadata.isCompactTable()) { assert deserializer != null; return deserializer.hasNext() && deserializer.nextIsStatic() ? (Row)deserializer.readNext() : Rows.EMPTY_STATIC_ROW; } // For compact tables, we use statics for the "column_metadata" definition. However, in the old format, those // "column_metadata" are intermingled as any other "cell". In theory, this means that we'd have to do a first // pass to extract the static values. However, for thrift, we'll use the ThriftResultsMerger right away which // will re-merge static values with dynamic ones, so we can just ignore static and read every cell as a // "dynamic" one. For CQL, if the table is a "static compact", then is has only static columns exposed and no // dynamic ones. So we do a pass to extract static columns here, but will have no more work to do. Otherwise, // the table won't have static columns. if (statics.isEmpty() || isForThrift) return Rows.EMPTY_STATIC_ROW; assert sstable.metadata.isStaticCompactTable(); // As said above, if it's a CQL query and the table is a "static compact", the only exposed columns are the // static ones. So we don't have to mark the position to seek back later. return LegacyLayout.extractStaticColumns(sstable.metadata, file, statics); } if (!sstable.header.hasStatic()) return Rows.EMPTY_STATIC_ROW; if (statics.isEmpty()) { UnfilteredSerializer.serializer.skipStaticRow(file, sstable.header, helper); return Rows.EMPTY_STATIC_ROW; } else { return UnfilteredSerializer.serializer.deserializeStaticRow(file, sstable.header, helper); } } protected abstract Reader createReader(RowIndexEntry indexEntry, FileDataInput file, boolean shouldCloseFile); public CFMetaData metadata() { return sstable.metadata; } public PartitionColumns columns() { return columns.fetchedColumns(); } public DecoratedKey partitionKey() { return key; } public DeletionTime partitionLevelDeletion() { return partitionLevelDeletion; } public Row staticRow() { return staticRow; } public EncodingStats stats() { // We could return sstable.header.stats(), but this may not be as accurate than the actual sstable stats (see // SerializationHeader.make() for details) so we use the latter instead. return new EncodingStats(sstable.getMinTimestamp(), sstable.getMinLocalDeletionTime(), sstable.getMinTTL()); } public boolean hasNext() { while (true) { if (reader == null) return false; if (reader.hasNext()) return true; if (++slice >= slices.size()) return false; slice(slices.get(slice)); } } public Unfiltered next() { assert reader != null; return reader.next(); } private void slice(Slice slice) { try { if (reader != null) reader.setForSlice(slice); } catch (IOException e) { try { closeInternal(); } catch (IOException suppressed) { e.addSuppressed(suppressed); } sstable.markSuspect(); throw new CorruptSSTableException(e, reader.file.getPath()); } } public void remove() { throw new UnsupportedOperationException(); } private void closeInternal() throws IOException { // It's important to make closing idempotent since it would bad to double-close 'file' as its a RandomAccessReader // and its close is not idemptotent in the case where we recycle it. if (isClosed) return; if (reader != null) reader.close(); isClosed = true; } public void close() { try { closeInternal(); } catch (IOException e) { sstable.markSuspect(); throw new CorruptSSTableException(e, reader.file.getPath()); } } protected abstract class Reader implements Iterator<Unfiltered> { private final boolean shouldCloseFile; public FileDataInput file; protected UnfilteredDeserializer deserializer; // Records the currently open range tombstone (if any) protected DeletionTime openMarker = null; protected Reader(FileDataInput file, boolean shouldCloseFile) { this.file = file; this.shouldCloseFile = shouldCloseFile; if (file != null) createDeserializer(); } private void createDeserializer() { assert file != null && deserializer == null; deserializer = UnfilteredDeserializer.create(sstable.metadata, file, sstable.header, helper, partitionLevelDeletion, isForThrift); } protected void seekToPosition(long position) throws IOException { // This may be the first time we're actually looking into the file if (file == null) { file = sstable.getFileDataInput(position); createDeserializer(); } else { file.seek(position); } } protected void updateOpenMarker(RangeTombstoneMarker marker) { // Note that we always read index blocks in forward order so this method is always called in forward order openMarker = marker.isOpen(false) ? marker.openDeletionTime(false) : null; } protected DeletionTime getAndClearOpenMarker() { DeletionTime toReturn = openMarker; openMarker = null; return toReturn; } public boolean hasNext() { try { return hasNextInternal(); } catch (IOException e) { try { closeInternal(); } catch (IOException suppressed) { e.addSuppressed(suppressed); } sstable.markSuspect(); throw new CorruptSSTableException(e, reader.file.getPath()); } } public Unfiltered next() { try { return nextInternal(); } catch (IOException e) { try { closeInternal(); } catch (IOException suppressed) { e.addSuppressed(suppressed); } sstable.markSuspect(); throw new CorruptSSTableException(e, reader.file.getPath()); } } // Set the reader so its hasNext/next methods return values within the provided slice public abstract void setForSlice(Slice slice) throws IOException; protected abstract boolean hasNextInternal() throws IOException; protected abstract Unfiltered nextInternal() throws IOException; public void close() throws IOException { if (shouldCloseFile && file != null) file.close(); } } // Used by indexed readers to store where they are of the index. protected static class IndexState { private final Reader reader; private final ClusteringComparator comparator; private final RowIndexEntry indexEntry; private final List<IndexHelper.IndexInfo> indexes; private final boolean reversed; private int currentIndexIdx; // Marks the beginning of the block corresponding to currentIndexIdx. private FileMark mark; public IndexState(Reader reader, ClusteringComparator comparator, RowIndexEntry indexEntry, boolean reversed) { this.reader = reader; this.comparator = comparator; this.indexEntry = indexEntry; this.indexes = indexEntry.columnsIndex(); this.reversed = reversed; this.currentIndexIdx = reversed ? indexEntry.columnsIndex().size() : -1; } public boolean isDone() { return reversed ? currentIndexIdx < 0 : currentIndexIdx >= indexes.size(); } // Sets the reader to the beginning of blockIdx. public void setToBlock(int blockIdx) throws IOException { if (blockIdx >= 0 && blockIdx < indexes.size()) { reader.seekToPosition(columnOffset(blockIdx)); reader.deserializer.clearState(); } currentIndexIdx = blockIdx; reader.openMarker = blockIdx > 0 ? indexes.get(blockIdx - 1).endOpenMarker : null; mark = reader.file.mark(); } private long columnOffset(int i) { return indexEntry.position + indexes.get(i).offset; } public int blocksCount() { return indexes.size(); } // Update the block idx based on the current reader position if we're past the current block. // This only makes sense for forward iteration (for reverse ones, when we reach the end of a block we // should seek to the previous one, not update the index state and continue). public void updateBlock() throws IOException { assert !reversed; // If we get here with currentBlockIdx < 0, it means setToBlock() has never been called, so it means // we're about to read from the beginning of the partition, but haven't "prepared" the IndexState yet. // Do so by setting us on the first block. if (currentIndexIdx < 0) { setToBlock(0); return; } while (currentIndexIdx + 1 < indexes.size() && isPastCurrentBlock()) { reader.openMarker = currentIndex().endOpenMarker; ++currentIndexIdx; // We have to set the mark, and we have to set it at the beginning of the block. So if we're not at the beginning of the block, this forces us to a weird seek dance. // This can only happen when reading old file however. long startOfBlock = columnOffset(currentIndexIdx); long currentFilePointer = reader.file.getFilePointer(); if (startOfBlock == currentFilePointer) { mark = reader.file.mark(); } else { reader.seekToPosition(startOfBlock); mark = reader.file.mark(); reader.seekToPosition(currentFilePointer); } } } // Check if we've crossed an index boundary (based on the mark on the beginning of the index block). public boolean isPastCurrentBlock() { assert reader.deserializer != null; long correction = reader.deserializer.bytesReadForUnconsumedData(); return reader.file.bytesPastMark(mark) - correction >= currentIndex().width; } public int currentBlockIdx() { return currentIndexIdx; } public IndexHelper.IndexInfo currentIndex() { return index(currentIndexIdx); } public IndexHelper.IndexInfo index(int i) { return indexes.get(i); } // Finds the index of the first block containing the provided bound, starting at the provided index. // Will be -1 if the bound is before any block, and blocksCount() if it is after every block. public int findBlockIndex(Slice.Bound bound, int fromIdx) { if (bound == Slice.Bound.BOTTOM) return -1; if (bound == Slice.Bound.TOP) return blocksCount(); return IndexHelper.indexFor(bound, indexes, comparator, reversed, fromIdx); } @Override public String toString() { return String.format("IndexState(indexSize=%d, currentBlock=%d, reversed=%b)", indexes.size(), currentIndexIdx, reversed); } } }
/** Read class attribute. */ void readClassAttr(ClassSymbol c, Name attrName, int attrLen) { DEBUG.P(this,"readClassAttr(3)"); DEBUG.P("c="+c); DEBUG.P("attrName="+attrName); DEBUG.P("attrLen="+attrLen); if (attrName == names.SourceFile) { Name n = readName(nextChar()); c.sourcefile = new SourceFileObject(n); } else if (attrName == names.InnerClasses) { readInnerClasses(c); } else if (allowGenerics && attrName == names.Signature) { readingClassAttr = true; try { ClassType ct1 = (ClassType)c.type; assert c == currentOwner; ct1.typarams_field = readTypeParams(nextChar()); ct1.supertype_field = sigToType(); ListBuffer<Type> is = new ListBuffer<Type>(); while (sigp != siglimit) is.append(sigToType()); ct1.interfaces_field = is.toList(); } finally { readingClassAttr = false; } } else { readMemberAttr(c, attrName, attrLen); } DEBUG.P(0,this,"readClassAttr(3)"); } private boolean readingClassAttr = false; private List<Type> missingTypeVariables = List.nil(); private List<Type> foundTypeVariables = List.nil(); /** Read class attributes. */ void readClassAttrs(ClassSymbol c) { DEBUG.P(this,"readClassAttrs(1)"); DEBUG.P("c="+c); char ac = nextChar(); DEBUG.P("ac="+(int)ac); for (int i = 0; i < ac; i++) { Name attrName = readName(nextChar()); DEBUG.P("attrName="+attrName); int attrLen = nextInt(); readClassAttr(c, attrName, attrLen); } DEBUG.P(0,this,"readClassAttrs(1)"); }
package com.arangodb.intellij.aql.ui.actions; import com.arangodb.intellij.aql.util.Icons; import com.arangodb.intellij.aql.util.log; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import com.intellij.ui.treeStructure.Tree; public class EditQueryAction extends BaseQueryAction { private final Tree queryTree; private final Project project; public EditQueryAction(final Project project, final Tree queryTree) { super("Delete Query", "", Icons.ICON_EDIT); this.queryTree = queryTree; this.project = project; } @Override public void actionPerformed(final AnActionEvent e) { log.error("NOT IMPLEMENTED YET"); } }
package shade.cards; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import shade.ShadeMod; import shade.actions.UndeadSpawnAction; import shade.patches.AbstractCardEnum; public class SensePrey extends AbstractShadeCard { public static final String ID = "Shade:SensePrey"; public static final String NAME; public static final String DESCRIPTION; public static String UPGRADED_DESCRIPTION; public static final String IMG_PATH = "cards/SensePrey.png"; private static final AbstractCard.CardType TYPE = AbstractCard.CardType.SKILL; private static final AbstractCard.CardRarity RARITY = AbstractCard.CardRarity.UNCOMMON; private static final AbstractCard.CardTarget TARGET = AbstractCard.CardTarget.SELF; private static final int COST = 0; private static final CardStrings cardStrings; static { cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); NAME = cardStrings.NAME; DESCRIPTION = cardStrings.DESCRIPTION; UPGRADED_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION; } public SensePrey() { super(ID, NAME, ShadeMod.getResourcePath(IMG_PATH), COST, DESCRIPTION, TYPE, AbstractCardEnum.SHADE, RARITY, TARGET); this.exhaust = true; } public void use(AbstractPlayer p, AbstractMonster m) { int count = 0; for (AbstractMonster mon : (AbstractDungeon.getMonsters()).monsters) { if (!mon.isDeadOrEscaped()) { count++; } } AbstractDungeon.actionManager.addToBottom(new UndeadSpawnAction(new shade.orbs.Skeleton(),count)); AbstractDungeon.actionManager.addToBottom(new UndeadSpawnAction(new shade.orbs.Zombie(),count)); } public AbstractCard makeCopy() { return new SensePrey(); } public void upgrade() { if (!this.upgraded) { upgradeName(); this.isInnate = true; this.rawDescription=UPGRADED_DESCRIPTION; initializeDescription(); } } }
package com.doctor.practice01; /** * @author sdcuike * * Created on 2016年4月11日 下午11:33:17 */ @TestAnnotation public interface ITestAnnotation { @TestAnnotation void test(); }
package org.pipecraft.pipes.sync.inter; import org.pipecraft.pipes.sync.Pipe; import org.pipecraft.infra.concurrent.FailableFunction; import org.pipecraft.pipes.serialization.CodecFactory; import org.pipecraft.pipes.sync.inter.reduct.HashReductorPipe; import org.pipecraft.pipes.sync.inter.reduct.ReductorConfig; import java.io.File; import java.util.function.Function; /** * Uses item equality (equals() method) in input pipe items for performing a dedup operation. * Only one arbitrary instance per equivalence set is produced in the output. * * The implementation relies on equals() and on consistency of equals() with hashcode(). * * This pipe makes use of temporary disk space. * The configuration of partitionCount is critical for bounding memory usage. The more partitions are used, the less memory is required. * It's recommended to set this number to {estimated total input data volume} / {max memory allowed for this pipe to use}. * * @param <T> The data type of items in the input pipe * * @author Eyal Schneider */ public class DedupPipe<T> extends HashReductorPipe<T, T> { /** * Constructor * * @param input The input pipe to wrap * @param inputCodec A codec allowing writing/reading input records * @param partitionCount The number of partitions to split input into. * Assuming a good hash function on item keys, and assuming that the families defined by the discriminator are even in size, the caller can assume the partitions are more-less balanced in size. * This number determines the amount of memory to be used, so it should be defined with caution. The more partitions are used, the less total memory is * required. However, note that for each partition the class maintains an open file on disk. * @param tmpFolder The folder where to store temporary data */ public DedupPipe(Pipe<T> input, CodecFactory<T> inputCodec, int partitionCount, File tmpFolder) { super(input, inputCodec, partitionCount, tmpFolder, ReductorConfig.<T, T, T, T>builder() .discriminator(FailableFunction.identity()) .aggregatorCreator(Function.identity()) .aggregationLogic((g, v) -> {}) .postProcessor(Function.identity()).build()); } }
/** * The MIT License * Copyright (c) 2014-2016 Ilkka Seppälä * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.api.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; /** * With the Microservices pattern, a client may need data from multiple different microservices. * If the client called each microservice directly, that could contribute to longer load times, * since the client would have to make a network request for each microservice called. Moreover, * having the client call each microservice directly ties the client to that microservice - if the * internal implementations of the microservices change (for example, if two microservices are * combined sometime in the future) or if the location (host and port) of a microservice changes, * then every client that makes use of those microservices must be updated. * * <p> * The intent of the API Gateway pattern is to alleviate some of these issues. In the API Gateway * pattern, an additional entity (the API Gateway) is placed between the client and the * microservices. The job of the API Gateway is to aggregate the calls to the microservices. * Rather than the client calling each microservice individually, the client calls the API Gateway * a single time. The API Gateway then calls each of the microservices that the client needs. * * <p> * This implementation shows what the API Gateway pattern could look like for an e-commerce site. * The {@link ApiGateway} makes calls to the Image and Price microservices using the * {@link ImageClientImpl} and {@link PriceClientImpl} respectively. Customers viewing the site on a * desktop device can see both price information and an image of a product, so the {@link ApiGateway} * calls both of the microservices and aggregates the data in the {@link DesktopProduct} model. * However, mobile users only see price information; they do not see a product image. For mobile * users, the {@link ApiGateway} only retrieves price information, which it uses to populate the * {@link MobileProduct}. */ @SpringBootApplication @EnableAsync public class App { /** * Program entry point * * @param args * command line args */ public static void main(String[] args) { SpringApplication.run(App.class, args); } @Bean public Executor taskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(2); taskExecutor.setMaxPoolSize(2); taskExecutor.setQueueCapacity(500); taskExecutor.setThreadNamePrefix("async-method-"); taskExecutor.initialize(); return taskExecutor; } }
//////////////////////////////////////////////////////////// // // Anime Warfare // Copyright (C) 2016 TiWinDeTea - contact@tiwindetea.org // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// package org.tiwindetea.animewarfare.net.logicevent; public class OpenStudioEvent extends ActionEvent<OpenStudioEventListener> { private final int zone; public OpenStudioEvent(int playerID, int zone) { super(playerID); this.zone = zone; } @Override public void notify(OpenStudioEventListener listener) { listener.handleOpenStudioEvent(this); } public int getZone() { return this.zone; } }
package be.intecbrussel.testy.views.component; import com.github.appreciated.apexcharts.ApexCharts; import com.github.appreciated.apexcharts.ApexChartsBuilder; import com.github.appreciated.apexcharts.config.builder.ChartBuilder; import com.github.appreciated.apexcharts.config.builder.LegendBuilder; import com.github.appreciated.apexcharts.config.builder.ResponsiveBuilder; import com.github.appreciated.apexcharts.config.chart.Type; import com.github.appreciated.apexcharts.config.legend.Position; import com.github.appreciated.apexcharts.config.responsive.builder.OptionsBuilder; import com.vaadin.flow.component.orderedlayout.VerticalLayout; public class DonutChartLayout extends VerticalLayout { public DonutChartLayout(final Double[] series, final Double breakpoint) { ApexCharts donutChart = ApexChartsBuilder.get() .withChart(ChartBuilder.get().withType(Type.donut).build()) .withLegend(LegendBuilder.get() .withPosition(Position.right) .build()) .withSeries(series) .withResponsive(ResponsiveBuilder.get() .withBreakpoint(breakpoint) .withOptions(OptionsBuilder.get() .withLegend(LegendBuilder.get() .withPosition(Position.bottom) .build()) .build()) .build()) .build(); setWidthFull(); setPadding(false); setAlignItems(Alignment.CENTER); add(donutChart); } }
/* * 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.jmeter.visualizers; import javax.swing.JPanel; /** * Interface for request panel in View Results Tree * All classes which implements this interface is display * on bottom tab in request panel * */ public interface RequestView { /** * Init the panel */ void init(); /** * Clear all data in panel */ void clearData(); /** * Put the result bean to display in panel * @param userObject result to display */ void setSamplerResult(Object userObject); /** * Get the panel * @return the panel viewer */ JPanel getPanel(); /** * Get the label. Use as name for bottom tab * @return the label's panel */ String getLabel(); // return label }
/** * Copyright (c) Lambda Innovation, 2013-2016 * This file is part of LambdaLib modding library. * https://github.com/LambdaInnovation/LambdaLib * Licensed under MIT, see project root for more information. */ package cn.lambdalib.util.key; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import cn.lambdalib.annoreg.base.RegistrationFieldSimple; import cn.lambdalib.annoreg.core.LoadStage; import cn.lambdalib.annoreg.core.RegistryTypeDecl; import cn.lambdalib.util.key.KeyHandlerRegistration.RegKeyHandler; /** * @author WeAthFolD */ @RegistryTypeDecl public class KeyHandlerRegistration extends RegistrationFieldSimple<RegKeyHandler, KeyHandler> { @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface RegKeyHandler { String name(); int keyID(); } public KeyHandlerRegistration() { super(RegKeyHandler.class, "KeyHandler"); setLoadStage(LoadStage.INIT); } @Override protected void register(KeyHandler value, RegKeyHandler anno, String field) throws Exception { KeyManager.dynamic.addKeyHandler(anno.name(), anno.keyID(), value); } }
package bastion.settings; import bastion.utils.FileManager; import java.util.List; public class BastionConfig { public String discordToken; public String chatBridgePrefix; public long chatChannelID; public boolean isRunning; public boolean adminLog; public long adminChatID; public List<Long> whitelistChat; public List<Long> allowedChat; public List<String> commandWhitelist; public BastionConfig(String discordToken, String chatBridgePrefix, long chatChannelID, boolean isRunning, boolean adminLog, long adminChatID, List<Long> whitelistChat, List<Long> allowedChat, List<String> commandWhitelist) { this.discordToken = discordToken; this.chatBridgePrefix = chatBridgePrefix; this.chatChannelID = chatChannelID; this.isRunning = isRunning; this.adminLog = adminLog; this.adminChatID = adminChatID; this.whitelistChat = whitelistChat; this.allowedChat = allowedChat; this.commandWhitelist = commandWhitelist; } public void setDiscordToken(String discordToken) { this.discordToken = discordToken; FileManager.updateFile(); } public void setChatChannelID(long chatChannelID) { this.chatChannelID = chatChannelID; FileManager.updateFile(); } public void setRunning(boolean running) { isRunning = running; FileManager.updateFile(); } public long getChatChannelID() { return chatChannelID; } public String getDiscordToken() { return discordToken; } public void setChatBridgePrefix(String chatBridgePrefix) { this.chatBridgePrefix = chatBridgePrefix; FileManager.updateFile(); } public long getAdminChatID() { return adminChatID; } public void setAdminLog(boolean adminLog) { this.adminLog = adminLog; FileManager.updateFile(); } public void addWhitelist(long ID) { this.whitelistChat.add(ID); FileManager.updateFile(); } public void removeWhitelist(long ID) { this.whitelistChat.remove(ID); FileManager.updateFile(); } public void addAllowed(long ID) { this.allowedChat.add(ID); FileManager.updateFile(); } public void removeAllowed(long ID) { this.allowedChat.remove(ID); FileManager.updateFile(); } public void addCommand(String cmd) { this.commandWhitelist.add(cmd); FileManager.updateFile(); } public void removeCommand(String cmd) { this.commandWhitelist.remove(cmd); FileManager.updateFile(); } public List<Long> getWhitelistChat() { return whitelistChat; } public List<Long> getAllowedChat() { return allowedChat; } @Override public String toString() { return "Config{" + "discordToken='" + discordToken + '\'' + ", chatBridgePrefix='" + chatBridgePrefix + '\'' + ", chatChannelID=" + chatChannelID + ", isRunning=" + isRunning + ", adminLog=" + adminLog + ", adminChatID=" + adminChatID + ", whitelistChat=" + whitelistChat + ", allowedChat=" + allowedChat + ", commandWhitelist=" + commandWhitelist + '}'; } }
/* * 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 org.yqj.source.demo.basic.netty.example.socksproxy; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.concurrent.Promise; public final class DirectClientHandler extends ChannelInboundHandlerAdapter { private final Promise<Channel> promise; public DirectClientHandler(Promise<Channel> promise) { this.promise = promise; } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.pipeline().remove(this); promise.setSuccess(ctx.channel()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) { promise.setFailure(throwable); } }
/* * MIT License * * Copyright (c) 2020 Liu Yamin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ymliu.effectivejava.chapter11.section79; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.ymliu.effectivejava.chapter4.section18.ForwardingSet; /** * @param <E> * @author LYM * @see ObservableSet1 , no synchonized with CopyOnWriteArrayList */ public class ObservableSet2<E> extends ForwardingSet<E> implements BaseObservableSet<E> { private final List<SetObserver<E>> observers = new CopyOnWriteArrayList<>(); public ObservableSet2(Set<E> s) { super(s); } @Override public void addObserver(SetObserver<E> observer) { this.observers.add(observer);} @Override public boolean removeObserver(SetObserver<E> observer) { return this.observers.remove(observer); } @Override public void notifyElementAdded(E element) { for (SetObserver<E> observer : this.observers) {observer.added(this, element);} } @Override public boolean add(E e) { boolean added = super.add(e); if (added) {notifyElementAdded(e);} return added; } @Override public boolean addAll(Collection<? extends E> c) { boolean result = false; for (E element : c) {result |= add(element);} return result; } public static void test(String... args) { ObservableSet2<Integer> set = new ObservableSet2<>(new HashSet<>()); set.addObserver(new SetObserver<>() { @Override public void added(BaseObservableSet<Integer> set, Integer element) { System.out.println("ObservableSet2: " + element); if (element == 25) { ExecutorService exec = Executors.newSingleThreadExecutor(); try { exec.submit(() -> set.removeObserver(this)).get(); } catch (ExecutionException | InterruptedException ex) { throw new AssertionError(ex); } finally { exec.shutdown(); } } } }); for (int i = 0; i < 100; i++) {set.add(i);} } }
package com.google.commerce.tapandpay.merchantapp.validation; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; public final class AutoValue_Schema$GsonTypeAdapter extends TypeAdapter<Schema> { private final TypeAdapter<String> nameAdapter; private final TypeAdapter<ArrayList<Session>> sessionsAdapter; private final TypeAdapter<Type> typeAdapter; public AutoValue_Schema$GsonTypeAdapter(Gson gson) { this.nameAdapter = gson.getAdapter(String.class); this.typeAdapter = gson.getAdapter(Type.class); this.sessionsAdapter = gson.getAdapter(new TypeToken<ArrayList<Session>>(this) { }); } public void write(JsonWriter jsonWriter, Schema schema) throws IOException { jsonWriter.beginObject(); jsonWriter.name("name"); this.nameAdapter.write(jsonWriter, schema.name()); jsonWriter.name("type"); this.typeAdapter.write(jsonWriter, schema.type()); jsonWriter.name("sessions"); this.sessionsAdapter.write(jsonWriter, schema.sessions()); jsonWriter.endObject(); } public Schema read(JsonReader jsonReader) throws IOException { ArrayList arrayList = null; jsonReader.beginObject(); Type type = null; String str = null; while (jsonReader.hasNext()) { String nextName = jsonReader.nextName(); if (jsonReader.peek() == JsonToken.NULL) { jsonReader.skipValue(); } else { Type type2; String str2; ArrayList arrayList2; byte b = (byte) -1; switch (nextName.hashCode()) { case 3373707: if (nextName.equals("name")) { b = (byte) 0; break; } break; case 3575610: if (nextName.equals("type")) { b = (byte) 1; break; } break; case 1405079709: if (nextName.equals("sessions")) { b = (byte) 2; break; } break; } switch (b) { case (byte) 0: ArrayList arrayList3 = arrayList; type2 = type; str2 = (String) this.nameAdapter.read(jsonReader); arrayList2 = arrayList3; break; case (byte) 1: str2 = str; arrayList2 = arrayList; type2 = (Type) this.typeAdapter.read(jsonReader); break; case (byte) 2: arrayList2 = (ArrayList) this.sessionsAdapter.read(jsonReader); type2 = type; str2 = str; break; default: jsonReader.skipValue(); arrayList2 = arrayList; type2 = type; str2 = str; break; } str = str2; type = type2; arrayList = arrayList2; } } jsonReader.endObject(); return new C$AutoValue_Schema(str, type, arrayList, (byte) 0); } }
package com.liueq.keyper.ui.main; import com.liueq.keyper.base.Presenter; import com.liueq.keyper.data.model.Account; import com.liueq.keyper.data.model.Tag; import com.liueq.keyper.domain.interactor.AddTagUC; import com.liueq.keyper.domain.interactor.GetAccountListUC; import com.liueq.keyper.domain.interactor.GetStarListUC; import com.liueq.keyper.domain.interactor.SearchAccountUC; import com.liueq.keyper.domain.interactor.StarUC; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by liueq on 13/7/15. * MainActivity Presenter * include: ListFragment, SearchDialogFragment */ public class MainActivityPresenter extends Presenter { public final static String TAG = "MainActivityPresenter"; private MainActivity mainActivity; GetAccountListUC getAccountListUC; SearchAccountUC searchAccountUC; StarUC mStarUC; GetStarListUC getStarListUC; AddTagUC addTagUC; public MainActivityPresenter(MainActivity mainActivity, GetAccountListUC getAccountListUC, SearchAccountUC searchAccountUC, StarUC starUC, GetStarListUC starListUC, AddTagUC addTagUC) { this.mainActivity = mainActivity; this.getAccountListUC = getAccountListUC; this.searchAccountUC = searchAccountUC; this.mStarUC = starUC; this.getStarListUC = starListUC; this.addTagUC = addTagUC; } /******************** Action ********************/ /** * Load star list - StarListFragment */ public void loadStarListAction(){ loadStarListOb().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(loadStarListSub()); } /** * Load list - ListFragment */ public void loadListAction(){ loadListOb().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(loadListSub()); } /** * Load tag list - TagListFragment */ public void loadTagListAction(){ getAllTagOb().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(divideListFun()) .subscribe(getAllTagSub()); } /** * Do star * @param account */ public void starAction(Account account){ starObj(account).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(starSub()); } /******************** RxJava ********************/ private Observable<List<Account>> loadListOb(){ return Observable.create(new Observable.OnSubscribe<List<Account>>() { @Override public void call(Subscriber<? super List<Account>> subscriber) { List<Account> list = loadList(); subscriber.onNext(list); } }); } private Subscriber<List<Account>> loadListSub(){ return new Subscriber<List<Account>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(List<Account> accounts) { ((ListFragment) getFragment(ListFragment.class)).updateUI(accounts); } }; } private Observable<Boolean> starObj(final Account account){ return Observable.create(new Observable.OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { boolean result = starOrUnStar(account); subscriber.onNext(result); } }); } private Subscriber<Boolean> starSub(){ return new Subscriber<Boolean>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Boolean aBoolean) { if(aBoolean){ loadListAction(); loadStarListAction(); } } }; } private Observable<List<Tag>> getAllTagOb(){ return Observable.create(new Observable.OnSubscribe<List<Tag>>() { @Override public void call(Subscriber<? super List<Tag>> subscriber) { subscriber.onNext(addTagUC.getAllTag()); } }); } private Func1<List<Tag>, List<RecyclerTagListAdapter.TagItem>> divideListFun(){ return new Func1<List<Tag>, List<RecyclerTagListAdapter.TagItem>>() { @Override public List<RecyclerTagListAdapter.TagItem> call(List<Tag> tags) { HashMap<String, List<Tag>> mapCharToTags = new HashMap<>(); final String WIDE = "*"; for(Tag t : tags){ String c = t.tag_name.substring(0, 1); if(Character.isLetter(c.charAt(0))){ c = c.toUpperCase(); } if(!Character.isLetter(c.charAt(0))){ //当不是字母的情况,用一个字符标示 if(mapCharToTags.get(WIDE) == null){ List<Tag> map_list = new ArrayList<Tag>(); map_list.add(t); mapCharToTags.put(WIDE, map_list); }else{ List<Tag> map_list = mapCharToTags.get(c); map_list.add(t); mapCharToTags.put(WIDE, map_list); } }else if(mapCharToTags.get(c) == null){ //没有该字母 List<Tag> map_list = new ArrayList<Tag>(); map_list.add(t); mapCharToTags.put(c, map_list); }else{ //已经有了该字母 List<Tag> map_list = mapCharToTags.get(c); map_list.add(t); mapCharToTags.put(c, map_list); } } List<RecyclerTagListAdapter.TagItem> item_list = new ArrayList<>(); for(String key : mapCharToTags.keySet()){ RecyclerTagListAdapter.TagItem item = new RecyclerTagListAdapter.TagItem(key, mapCharToTags.get(key)); item_list.add(item); } Collections.sort(item_list); return item_list; } }; } private Action1<List<RecyclerTagListAdapter.TagItem>> getAllTagSub(){ return new Action1<List<RecyclerTagListAdapter.TagItem>>() { @Override public void call(List<RecyclerTagListAdapter.TagItem> tagItems) { ((TagListFragment) getFragment(TagListFragment.class)).updateList(tagItems); } }; } private Observable<List<Account>> loadStarListOb(){ return Observable.create(new Observable.OnSubscribe<List<Account>>() { @Override public void call(Subscriber<? super List<Account>> subscriber) { List<Account> list = loadStarList(); subscriber.onNext(list); } }); } private Subscriber<List<Account>> loadStarListSub(){ return new Subscriber<List<Account>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(List<Account> accounts) { ((StarListFragment) getFragment(StarListFragment.class)).updateUI(accounts); } }; } public List<Account> loadList(){ return getAccountListUC.executeDB(); } public List<Account> loadStarList(){ return getStarListUC.executeDB(); } public List<Account> search(String searchKey){ return searchAccountUC.execute(searchKey); } public boolean starOrUnStar(Account account){ boolean result = false; if(account.is_stared){ result = mStarUC.unStarAccount(account); }else{ result = mStarUC.starAccount(account); } return result; } }
package com.mail.member.controller; import java.util.Arrays; import java.util.Map; //import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.mail.member.entity.GrowthChangeHistoryEntity; import com.mail.member.service.GrowthChangeHistoryService; import com.mail.common.utils.PageUtils; import com.mail.common.utils.R; /** * 成长值变化历史记录 * * @author chenshun * @email sunlightcs@gmail.com * @date 2022-03-10 14:41:42 */ @RestController @RequestMapping("member/growthchangehistory") public class GrowthChangeHistoryController { @Autowired private GrowthChangeHistoryService growthChangeHistoryService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("member:growthchangehistory:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = growthChangeHistoryService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("member:growthchangehistory:info") public R info(@PathVariable("id") Long id){ GrowthChangeHistoryEntity growthChangeHistory = growthChangeHistoryService.getById(id); return R.ok().put("growthChangeHistory", growthChangeHistory); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("member:growthchangehistory:save") public R save(@RequestBody GrowthChangeHistoryEntity growthChangeHistory){ growthChangeHistoryService.save(growthChangeHistory); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("member:growthchangehistory:update") public R update(@RequestBody GrowthChangeHistoryEntity growthChangeHistory){ growthChangeHistoryService.updateById(growthChangeHistory); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("member:growthchangehistory:delete") public R delete(@RequestBody Long[] ids){ growthChangeHistoryService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
package ch15generics.coffee; public class Cappuccino extends Coffee { }
package com.sandrowinkler.example_apps.splashscreen; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.sandrowinkler.example_apps.splashscreen", appContext.getPackageName()); } }
package fr.orsys.ama.tp2; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("fr.orsys.ama.tp2", appContext.getPackageName()); } }
package com.github.stephanelemaire.simpleDI.parentObject; import com.github.stephanelemaire.simpleDI.AutoInject; import com.github.stephanelemaire.simpleDI.basicObject.BasicObject; public class ParentObjectWithConstructorError { @AutoInject public ParentObjectWithConstructorError(BasicObject basicObject){ int[] arr = new int[2]; System.out.println(String.valueOf(arr[100])); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.raft.jraft.rpc.impl; import java.net.ConnectException; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import org.apache.ignite.lang.IgniteLogger; import org.apache.ignite.network.ClusterNode; import org.apache.ignite.network.TopologyEventHandler; import org.apache.ignite.raft.jraft.Status; import org.apache.ignite.raft.jraft.error.InvokeTimeoutException; import org.apache.ignite.raft.jraft.error.RaftError; import org.apache.ignite.raft.jraft.error.RemotingException; import org.apache.ignite.raft.jraft.option.RpcOptions; import org.apache.ignite.raft.jraft.rpc.ClientService; import org.apache.ignite.raft.jraft.rpc.InvokeCallback; import org.apache.ignite.raft.jraft.rpc.InvokeContext; import org.apache.ignite.raft.jraft.rpc.Message; import org.apache.ignite.raft.jraft.rpc.RpcClient; import org.apache.ignite.raft.jraft.rpc.RpcRequests; import org.apache.ignite.raft.jraft.rpc.RpcRequests.ErrorResponse; import org.apache.ignite.raft.jraft.rpc.RpcResponseClosure; import org.apache.ignite.raft.jraft.util.Endpoint; import org.apache.ignite.raft.jraft.util.Utils; import org.apache.ignite.raft.jraft.util.concurrent.ConcurrentHashSet; import org.apache.ignite.raft.jraft.util.internal.ThrowUtil; /** * Abstract RPC client service based. */ public abstract class AbstractClientService implements ClientService, TopologyEventHandler { protected static final IgniteLogger LOG = IgniteLogger.forClass(AbstractClientService.class); protected volatile RpcClient rpcClient; protected ExecutorService rpcExecutor; protected RpcOptions rpcOptions; /** * The set of pinged addresses */ protected Set<String> readyAddresses = new ConcurrentHashSet<>(); public RpcClient getRpcClient() { return this.rpcClient; } @Override public synchronized boolean init(final RpcOptions rpcOptions) { if (this.rpcClient != null) { return true; } this.rpcOptions = rpcOptions; return initRpcClient(this.rpcOptions.getRpcProcessorThreadPoolSize()); } @Override public void onAppeared(ClusterNode member) { // No-op. TODO asch https://issues.apache.org/jira/browse/IGNITE-14843 } @Override public void onDisappeared(ClusterNode member) { readyAddresses.remove(member.address().toString()); } protected void configRpcClient(final RpcClient rpcClient) { rpcClient.registerConnectEventListener(this); } protected boolean initRpcClient(final int rpcProcessorThreadPoolSize) { this.rpcClient = rpcOptions.getRpcClient(); configRpcClient(this.rpcClient); // TODO asch should the client be created lazily? A client doesn't make sence without a server IGNITE-14832 this.rpcClient.init(null); this.rpcExecutor = rpcOptions.getClientExecutor(); return true; } @Override public synchronized void shutdown() { if (this.rpcClient != null) { this.rpcClient.shutdown(); this.rpcClient = null; } } @Override public boolean connect(final Endpoint endpoint) { try { return connectAsync(endpoint).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.error("Interrupted while connecting to {}, exception: {}.", endpoint, e.getMessage()); } catch (ExecutionException e) { LOG.error("Fail to connect {}, exception: {}.", endpoint, e.getMessage()); } return false; } @Override public CompletableFuture<Boolean> connectAsync(Endpoint endpoint) { final RpcClient rc = this.rpcClient; if (rc == null) { throw new IllegalStateException("Client service is uninitialized."); } // Remote node is alive and pinged, safe to continue. if (readyAddresses.contains(endpoint.toString())) { return CompletableFuture.completedFuture(true); } final RpcRequests.PingRequest req = rpcOptions.getRaftMessagesFactory() .pingRequest() .sendTimestamp(System.currentTimeMillis()) .build(); CompletableFuture<Message> fut = invokeWithDone(endpoint, req, null, null, rpcOptions.getRpcConnectTimeoutMs(), rpcExecutor); return fut.thenApply(msg -> { ErrorResponse resp = (ErrorResponse) msg; if (resp != null && resp.errorCode() == 0) { readyAddresses.add(endpoint.toString()); return true; } else { return false; } }); } @Override public <T extends Message> CompletableFuture<Message> invokeWithDone(final Endpoint endpoint, final Message request, final RpcResponseClosure<T> done, final int timeoutMs) { return invokeWithDone(endpoint, request, done, timeoutMs, this.rpcExecutor); } public <T extends Message> CompletableFuture<Message> invokeWithDone(final Endpoint endpoint, final Message request, final RpcResponseClosure<T> done, final int timeoutMs, final Executor rpcExecutor) { return invokeWithDone(endpoint, request, null, done, timeoutMs, rpcExecutor); } public <T extends Message> CompletableFuture<Message> invokeWithDone(final Endpoint endpoint, final Message request, final InvokeContext ctx, final RpcResponseClosure<T> done, final int timeoutMs) { return invokeWithDone(endpoint, request, ctx, done, timeoutMs, this.rpcExecutor); } public <T extends Message> CompletableFuture<Message> invokeWithDone(final Endpoint endpoint, final Message request, final InvokeContext ctx, final RpcResponseClosure<T> done, final int timeoutMs, final Executor rpcExecutor) { final RpcClient rc = this.rpcClient; final FutureImpl<Message> future = new FutureImpl<>(); final Executor currExecutor = rpcExecutor != null ? rpcExecutor : this.rpcExecutor; try { if (rc == null) { // TODO asch replace with ignite exception, check all places IGNITE-14832 future.completeExceptionally(new IllegalStateException("Client service is uninitialized.")); // should be in another thread to avoid dead locking. Utils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTERNAL, "Client service is uninitialized.")); return future; } return rc.invokeAsync(endpoint, request, ctx, new InvokeCallback() { @Override public void complete(final Object result, final Throwable err) { if (err == null) { Status status = Status.OK(); Message msg; if (result instanceof ErrorResponse) { status = handleErrorResponse((ErrorResponse) result); msg = (Message) result; } else { msg = (Message) result; } if (done != null) { try { if (status.isOk()) { done.setResponse((T) msg); } done.run(status); } catch (final Throwable t) { LOG.error("Fail to run RpcResponseClosure, the request is {}.", t, request); } } if (!future.isDone()) { future.complete(msg); } } else { if (ThrowUtil.hasCause(err, null, ConnectException.class)) readyAddresses.remove(endpoint.toString()); // Force logical reconnect. if (done != null) { try { done.run(new Status(err instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT : RaftError.EINTERNAL, "RPC exception:" + err.getMessage())); } catch (final Throwable t) { LOG.error("Fail to run RpcResponseClosure, the request is {}.", t, request); } } if (!future.isDone()) { future.completeExceptionally(err); } } } @Override public Executor executor() { return currExecutor; } }, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); future.completeExceptionally(e); // should be in another thread to avoid dead locking. Utils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTR, "Sending rpc was interrupted")); } catch (final RemotingException e) { future.completeExceptionally(e); // should be in another thread to avoid dead locking. Utils.runClosureInExecutor(currExecutor, done, new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage())); } return future; } private static Status handleErrorResponse(final ErrorResponse eResp) { final Status status = new Status(); status.setCode(eResp.errorCode()); status.setErrorMsg(eResp.errorMsg()); return status; } }
package com.business; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.security.SecureRandom; import java.util.Base64; public class PasswordHash { private static Integer saltSize = 0X10; private static Integer hashSize = 0X14; private static Integer iterations = 0X2710; private static String delimiter = ","; public static String compute(String password) throws Exception { byte[] salt = salt(); byte[] pbkdf = pbkdf(password.toCharArray(), salt); Base64.Encoder encoder = Base64.getEncoder(); return String.format("%s%s%s", new String(encoder.encode(salt)), delimiter, new String(encoder.encode(pbkdf))); } public static boolean isValid(String hash, String password) throws Exception { String[] splitHash = hash.split(delimiter); Base64.Decoder decoder = Base64.getDecoder(); byte[] salt = decoder.decode(splitHash[0]); byte[] fromHash = decoder.decode(splitHash[1]); byte[] fromPassword = pbkdf(password.toCharArray(), salt); return areEqual(fromHash, fromPassword); } private static boolean areEqual(byte[] a, byte[] b) { int difference = a.length ^ b.length; for (int i = 0; i < a.length && i < b.length; ++i) difference |= (a[i] ^ b[i]); return difference == 0; } private static byte[] salt() { SecureRandom random = new SecureRandom(); byte[] salt = new byte[saltSize]; random.nextBytes(salt); return salt; } private static byte[] pbkdf(char[] password, byte[] salt) throws Exception { SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, hashSize); SecretKey key = skf.generateSecret(spec); return key.getEncoded(); } }
/* * Copyright 2015 Laukviks Bedrifter. * * 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 no.laukvik.csv.query; import no.laukvik.csv.columns.Column; import no.laukvik.csv.columns.DoubleColumn; /** * Compares a IntegerColumn to be less than a value. */ public final class DoubleLessThanMatcher implements ValueMatcher<Double> { /** * The value to match. */ private final double value; /** * The column to match. */ private final DoubleColumn column; /** * The value of the column must be value. * * @param doubleColumn the column * @param value the value */ public DoubleLessThanMatcher(final DoubleColumn doubleColumn, final double value) { super(); this.column = doubleColumn; this.value = value; } @Override public Column getColumn() { return column; } @Override public boolean matches(final Double i) { return i != null && i < value; } }
/* Derby - Class org.apache.derbyTesting.functionTests.harness.procedure 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.derbyTesting.functionTests.tests.store; import org.apache.derby.iapi.services.sanity.SanityManager; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.derby.tools.ij; public class oc_rec4 extends OnlineCompressTest { public oc_rec4() { } /** * setup for restart recovery test. * <p> * Do setup to test restart recovery of online compress. Real work * is done in next test oc_rec4 which will run restart recovery on * the work done in this test. * **/ private void test1( Connection conn, String test_name, String table_name) throws SQLException { beginTest(conn, test_name); // oc_rec3 left the table with no rows, but compress command // did not commit. String table_name_2 = table_name + "_2"; if (!checkConsistency(conn, "APP", table_name_2)) { logError("conistency check failed."); } // make sure we can add data to the existing table after redo // recovery. createAndLoadTable(conn, false, table_name_2, 6000, 0); if (!checkConsistency(conn, "APP", table_name_2)) { logError("conistency check failed."); } endTest(conn, test_name); } public void testList(Connection conn) throws SQLException { test1(conn, "test1", "TEST1"); } public static void main(String[] argv) throws Throwable { oc_rec4 test = new oc_rec4(); ij.getPropertyArg(argv); Connection conn = ij.startJBMS(); conn.setAutoCommit(false); try { test.testList(conn); } catch (SQLException sqle) { org.apache.derby.tools.JDBCDisplayUtil.ShowSQLException( System.out, sqle); sqle.printStackTrace(System.out); } } }
// // ======================================================================== // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.ant; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectHelper; import org.eclipse.jetty.toolchain.test.IO; import org.eclipse.jetty.toolchain.test.MavenTestingUtils; public class AntBuild { private Thread _process; private String _ant; private int _port; private String _host; public AntBuild(String ant) { _ant = ant; } private class AntBuildProcess implements Runnable { List<String[]> connList; @Override public void run() { File buildFile = new File(_ant); Project antProject = new Project(); try { antProject.setBaseDir(MavenTestingUtils.getBasedir()); antProject.setUserProperty("ant.file",buildFile.getAbsolutePath()); DefaultLogger logger = new DefaultLogger(); ConsoleParser parser = new ConsoleParser(); //connList = parser.newPattern(".*([0-9]+\\.[0-9]*\\.[0-9]*\\.[0-9]*):([0-9]*)",1); connList = parser.newPattern("Jetty AntTask Started",1); PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); PipedOutputStream pose = new PipedOutputStream(); PipedInputStream pise = new PipedInputStream(pose); startPump("STDOUT",parser,pis); startPump("STDERR",parser,pise); logger.setErrorPrintStream(new PrintStream(pos)); logger.setOutputPrintStream(new PrintStream(pose)); logger.setMessageOutputLevel(Project.MSG_VERBOSE); antProject.addBuildListener(logger); antProject.fireBuildStarted(); antProject.init(); ProjectHelper helper = ProjectHelper.getProjectHelper(); antProject.addReference("ant.projectHelper",helper); helper.parse(antProject,buildFile); antProject.executeTarget("jetty.run"); parser.waitForDone(10000,TimeUnit.MILLISECONDS); } catch (Exception e) { antProject.fireBuildFinished(e); } } public void waitForStarted() throws Exception { while (connList == null || connList.isEmpty()) { Thread.sleep(10); } } } public void start() throws Exception { System.out.println("Starting Ant Build ..."); AntBuildProcess abp = new AntBuildProcess(); _process = new Thread(abp); _process.start(); abp.waitForStarted(); // once this has returned we should have the connection info we need //_host = abp.getConnectionList().get(0)[0]; //_port = Integer.parseInt(abp.getConnectionList().get(0)[1]); } public int getJettyPort() { return Integer.parseInt(System.getProperty("jetty.ant.server.port")); } public String getJettyHost() { return System.getProperty("jetty.ant.server.host"); } /** * Stop the jetty server */ public void stop() { System.out.println("Stopping Ant Build ..."); _process.interrupt(); } private static class ConsoleParser { private List<ConsolePattern> patterns = new ArrayList<ConsolePattern>(); private CountDownLatch latch; private int count; public List<String[]> newPattern(String exp, int cnt) { ConsolePattern pat = new ConsolePattern(exp,cnt); patterns.add(pat); count += cnt; return pat.getMatches(); } public void parse(String line) { for (ConsolePattern pat : patterns) { Matcher mat = pat.getMatcher(line); if (mat.find()) { int num = 0, count = mat.groupCount(); String[] match = new String[count]; while (num++ < count) { match[num - 1] = mat.group(num); } pat.getMatches().add(match); if (pat.getCount() > 0) { getLatch().countDown(); } } } } public void waitForDone(long timeout, TimeUnit unit) throws InterruptedException { getLatch().await(timeout,unit); } private CountDownLatch getLatch() { synchronized (this) { if (latch == null) { latch = new CountDownLatch(count); } } return latch; } } private static class ConsolePattern { private Pattern pattern; private List<String[]> matches; private int count; ConsolePattern(String exp, int cnt) { pattern = Pattern.compile(exp); matches = new ArrayList<String[]>(); count = cnt; } public Matcher getMatcher(String line) { return pattern.matcher(line); } public List<String[]> getMatches() { return matches; } public int getCount() { return count; } } private void startPump(String mode, ConsoleParser parser, InputStream inputStream) { ConsoleStreamer pump = new ConsoleStreamer(mode,inputStream); pump.setParser(parser); Thread thread = new Thread(pump,"ConsoleStreamer/" + mode); thread.start(); } /** * Simple streamer for the console output from a Process */ private static class ConsoleStreamer implements Runnable { private String mode; private BufferedReader reader; private ConsoleParser parser; public ConsoleStreamer(String mode, InputStream is) { this.mode = mode; this.reader = new BufferedReader(new InputStreamReader(is)); } public void setParser(ConsoleParser connector) { this.parser = connector; } public void run() { String line; //System.out.printf("ConsoleStreamer/%s initiated%n",mode); try { while ((line = reader.readLine()) != (null)) { if (parser != null) { parser.parse(line); } System.out.println("[" + mode + "] " + line); } } catch (IOException ignore) { /* ignore */ } finally { IO.close(reader); } //System.out.printf("ConsoleStreamer/%s finished%n",mode); } } }
package ru.amalnev.jnms.common.model.repositories; import ru.amalnev.jnms.common.model.entities.AbstractEntity; import java.lang.annotation.*; /** * Данная аннотация применяется к Spring Data репозиториям, для того, чтобы * во время выполнения с помощью рефлексии можно было определить за какую * сущность отвечает тот или иной репозиторий. * * @author Aleksei Malnev */ @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface EntityClass { /** * Класс сущностей, находящихся в репозитории, отмеченном * данной аннотацией. * * @return */ Class<? extends AbstractEntity> value(); }
/* * Copyright 2015 Adaptris 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.adaptris.core.mail; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import com.adaptris.annotation.AdapterComponent; import com.adaptris.annotation.AdvancedConfig; import com.adaptris.annotation.ComponentProfile; import com.adaptris.annotation.DisplayOrder; import com.adaptris.core.AdaptrisMessage; import com.adaptris.core.CoreConstants; import com.adaptris.core.CoreException; import com.adaptris.core.NullConnection; import com.adaptris.mail.Attachment; import com.adaptris.mail.MailException; import com.adaptris.mail.MessageParser; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * Default Email implementation of the AdaptrisMessageConsumer interface. * <p> * Each Mime part of the incoming email message will become a separate AdaptrisMessage; attachments are processed separately from * the mail body itelf. * </p> * * * @config default-mail-consumer * * * @see MailConsumerImp */ @XStreamAlias("default-mail-consumer") @AdapterComponent @ComponentProfile(summary = "Pickup messages from a email account parsing the MIME message", tag = "consumer,email", metadata = { "emailmessageid", "emailtotalattachments", "emailattachmentfilename", "emailattachmentcontenttype" }, recommended = {NullConnection.class}) @DisplayOrder(order = {"poller", "username", "password", "mailReceiverFactory", "partSelector", "headerHandler"}) public class DefaultMailConsumer extends ParsingMailConsumerImpl { @AdvancedConfig @Deprecated private Boolean preserveHeaders; @AdvancedConfig @Deprecated private String headerPrefix; /** * <p> * Creates a new instance. * </p> */ public DefaultMailConsumer() { } @Override protected List<AdaptrisMessage> createMessages(MimeMessage mime) throws MailException, CoreException { List<AdaptrisMessage> result = new ArrayList<AdaptrisMessage>(); try { MessageParser mp = new MessageParser(mime, getPartSelector()); log.trace("Start Processing [{}]", mp.getMessageId()); if (mp.getMessage() != null) { AdaptrisMessage msg = decode(mp.getMessage()); if (mp.getMessageId() != null) { msg.addMetadata(CoreConstants.EMAIL_MESSAGE_ID, mp.getMessageId()); } headerHandler().handle(mime, msg); if (mp.hasAttachments()) { msg.addMetadata(CoreConstants.EMAIL_TOTAL_ATTACHMENTS, String.valueOf(mp.numberOfAttachments())); } result.add(msg); } if (mp.hasAttachments()) { while (mp.hasMoreAttachments()) { Attachment a = mp.nextAttachment(); AdaptrisMessage msg = decode(a.getBytes()); msg.addMetadata(CoreConstants.EMAIL_MESSAGE_ID, mp.getMessageId()); msg.addMetadata(CoreConstants.EMAIL_ATTACH_FILENAME, a.getFilename()); msg.addMetadata(CoreConstants.EMAIL_ATTACH_CONTENT_TYPE, a.getContentType()); headerHandler().handle(mime, msg); msg.addMetadata(CoreConstants.EMAIL_TOTAL_ATTACHMENTS, String.valueOf(mp.numberOfAttachments())); result.add(msg); } } } catch (MessagingException | IOException e) { throw new MailException(e); } return result; } /** * @see com.adaptris.core.AdaptrisComponent#init() */ @Override protected void initConsumer() throws CoreException { if (getPreserveHeaders() != null) { log.warn("preserve-headers is deprecated; use header-handler instead"); } } /** * Get the preserve headers flag. * * @return the flag. * @deprecated since 3.6.5 use {link {@link #setHeaderHandler(MailHeaderHandler)} instead. */ @Deprecated public Boolean getPreserveHeaders() { return preserveHeaders; } /** * Set the preserve headers flag. * <p> * If set to true, then an attempt is made to copy all the email headers from the email message as metadata to the AdaptrisMessage * object. Each header can optionally be prefixed with the value specfied by <code> * getHeaderPrefix()</code> * </p> * * @param b true or false. * @deprecated since 3.6.5 use {link {@link #setHeaderHandler(MailHeaderHandler)} instead. */ @Deprecated public void setPreserveHeaders(Boolean b) { preserveHeaders = b; } /** * Set the header prefix. * <p> * The header prefix is used to prefix any headers that are preserved from the email message. * </p> * * @param s the prefix. * @deprecated since 3.6.5 use {link {@link #setHeaderHandler(MailHeaderHandler)} instead. */ @Deprecated public void setHeaderPrefix(String s) { headerPrefix = s; } /** * Get the header prefix. * * @return the header prefix * @deprecated since 3.6.5 use {link {@link #setHeaderHandler(MailHeaderHandler)} instead. */ @Deprecated public String getHeaderPrefix() { return headerPrefix; } @Override protected MailHeaderHandler headerHandler() { MailHeaderHandler result = super.headerHandler(); if (getPreserveHeaders() != null) { result = getPreserveHeaders() == Boolean.TRUE ? new MetadataMailHeaders(getHeaderPrefix()) : new IgnoreMailHeaders(); } return result; } }
package com.hyperledger.export.models; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import com.archimatetool.model.IArchimateConcept; import com.archimatetool.model.IProperty; /** * Класс модели asset hyperledger composer */ public class Asset extends HLModel { //Ранг модели (для сортировки) public final static int rank = 2; public Asset(IArchimateConcept concept, String namespace) throws ParseException { super(concept, HLModel.HLModelType.ASSET, namespace, true); } /** * Получить ранг */ @Override public int getRank() { return rank; } /** * Получить HL Modeling представление модели */ @Override public String getHLView() { String res = super.getHLView(); if (!this.hasId) { HLModel current = this; while (current != null && current.isExtends()) { if (current.hasId) { this.hasId = true; break; } else { current = current.getSuperModel(); } } if (!this.hasId) res = "abstract " + res; } return res; } }
/** * Copyright (C) 2012, Rapid7 LLC, Boston, MA, USA. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.rapid7.nexpose.api.generators; import org.rapid7.nexpose.api.domain.ContactAddress; import org.rapid7.nexpose.utils.StringUtils; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Element; /** * Generates Silo Organization element tags inside of the SiloCreate Silo Config * * @author Leonardo Varela */ public class SiloCreateOrganizationGenerator implements IContentGenerator { // /////////////////////////////////////////////////////////////////////// // Public methods // /////////////////////////////////////////////////////////////////////// /** * Creates a new Storage Properties generator for the silo config. */ public SiloCreateOrganizationGenerator() { m_url = new String(); } /** * Knows how to print the xml output for properties elements inside of a <SiloConfig> element on the silo Config. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("<Organization "); sb.append("url=\""); sb.append(StringUtils.xmlEscape(m_url)); sb.append("\" company=\""); sb.append(StringUtils.xmlEscape(m_company)); sb.append("\" email-address=\""); sb.append(StringUtils.xmlEscape(m_emailAddress)); sb.append("\" first-name=\""); sb.append(StringUtils.xmlEscape(m_firstName)); sb.append("\" last-name=\""); sb.append(StringUtils.xmlEscape(m_lastName)); sb.append("\" phone-number=\""); sb.append(StringUtils.xmlEscape(m_phoneNumber)); sb.append("\" title=\""); sb.append(StringUtils.xmlEscape(m_title)); if (m_address != null) { sb.append("\"><Address city=\""); sb.append(StringUtils.xmlEscape(m_address.getCity())); sb.append("\" country=\""); sb.append(StringUtils.xmlEscape(m_address.getCountry())); sb.append("\" line1=\""); sb.append(StringUtils.xmlEscape(m_address.getLine1())); sb.append("\" line2=\""); sb.append(StringUtils.xmlEscape(m_address.getLine2())); sb.append("\" state=\""); sb.append(StringUtils.xmlEscape(m_address.getState())); sb.append("\" zip=\""); sb.append(StringUtils.xmlEscape(m_address.getZip())); sb.append("\"/></Organization>"); } else { sb.append("\"/>"); } return sb.toString(); } /* (non-Javadoc) * @see org.rapid7.nexpose.api.IContentGenerator#setContents(org.w3c.dom.Element) */ @Override public void setContents(Element contents) { try { final Element elementOrganization = (Element) XPathFactory.newInstance().newXPath().evaluate("Organization", contents, XPathConstants.NODE); m_url = elementOrganization.getAttribute("url"); m_company = elementOrganization.getAttribute("company"); m_emailAddress = elementOrganization.getAttribute("email-address"); m_firstName = elementOrganization.getAttribute("first-name"); m_lastName = elementOrganization.getAttribute("last-name"); m_phoneNumber = elementOrganization.getAttribute("phone-number"); m_title = elementOrganization.getAttribute("title"); final Element addressElement = (Element) XPathFactory.newInstance().newXPath().evaluate("Address", elementOrganization, XPathConstants.NODE); if (addressElement != null) { m_address.setCity(addressElement.getAttribute("city")); m_address.setCountry(addressElement.getAttribute("country")); m_address.setLine1(addressElement.getAttribute("line1")); m_address.setLine2(addressElement.getAttribute("line2")); m_address.setState(addressElement.getAttribute("state")); m_address.setZip(addressElement.getAttribute("zip")); } } catch (XPathExpressionException e) { System.out.println("Could not parse the generator for SiloCreateMerchantGenerator: " + e.toString()); throw new RuntimeException("The PCI Merchant could not be generated: " + e.toString()); } } /** * Retrieves the Organization's url associated with the Silo Create config. * * @return the url associated with the Silo Create config. */ public String getURL() { return m_url; } /** * Sets the URL of the organization associated with the Silo Create config. * * @param url The URL to be set. */ public void setURL(String url) { m_url = url; } /** * Sets the address associated with this organization generator. * * @param address The address to set. */ public void setAddress(ContactAddress address) { m_address = address; } /** * Retrieves the address associated with this organization. * * @return The address of this organization. */ public ContactAddress getAddress() { return m_address; } /** * Sets the company associated with the organization. * * @param company The company to set. */ public void setCompany(String company) { m_company = company; } /** * Retrieves the company associated with the organization. * * @return The company associated with the organization. */ public String getCompany() { return m_company; } /** * Sets the email address associated with the organization. * * @param emaiAddress The email address to set. */ public void setEmailAddress(String emaiAddress) { m_emailAddress = emaiAddress; } /** * Retrieves the email address associated with the organization. * * @return The email address associated with the organization. */ public String getEmailAddress() { return m_emailAddress; } /** * Sets the first name associated with the organization. * * @param firstName The first name to set. */ public void setFirstName(String firstName) { m_firstName = firstName; } /** * Retrieves the first name associated with the organization. * * @return The first name associated with the organization. */ public String getFirstName() { return m_firstName; } /** * Sets the last name associated with the organization. * * @param lastName The last name to set. */ public void setLastName(String lastName) { m_lastName = lastName; } /** * Retrieves the last name associated with the organization. * * @return The last name associated with the organization. */ public String getLastName() { return m_lastName; } /** * Sets the phone number associated with the organization. * * @param phoneNumber The phone number to set. */ public void setPhoneNumber(String phoneNumber) { m_phoneNumber = phoneNumber; } /** * Retrieves the phone number associated with the organization. * * @return The phone number associated with the organization. */ public String getPhoneNumber() { return m_phoneNumber; } /** * Sets the title associated with the organization. * * @param title The title to set */ public void setTitle(String title) { m_title = title; } /** * Retrieves the title associated with the organization. * * @return The title */ public String getTitle() { return m_title; } // /////////////////////////////////////////////////////////////////////// // non-Public fields // /////////////////////////////////////////////////////////////////////// /** The url associated with the organization. */ private String m_url; /** The Address associated with the organization */ private ContactAddress m_address; /** The name of the company for the organization */ private String m_company; /** The email address associated with the organization */ private String m_emailAddress; /** The first name associated with the organization */ private String m_firstName; /** The last name associated with the organization */ private String m_lastName; /** The phone number associated with the organization. */ private String m_phoneNumber; /** The title associated with the organization */ private String m_title; }
package seedu.address.model; import static seedu.address.testutil.Assert.assertThrows; import org.junit.jupiter.api.Test; public class UserPrefsTest { @Test public void setGuiSettings_nullGuiSettings_throwsNullPointerException() { UserPrefs userPref = new UserPrefs(); assertThrows(NullPointerException.class, () -> userPref.setGuiSettings(null)); } @Test public void setTutorAidFilePath_nullPath_throwsNullPointerException() { UserPrefs userPrefs = new UserPrefs(); assertThrows(NullPointerException.class, () -> userPrefs.setTutorAidFilePath(null)); } }
/* Portions of this file are copyright by the authors of Jackson under the Apache 2.0 or LGPL license. */ package com.bazaarvoice.jackson.rison; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.SerializableString; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.core.format.InputAccessor; import com.fasterxml.jackson.core.format.MatchStrength; import com.fasterxml.jackson.core.io.IOContext; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.charset.StandardCharsets; /** * See the <a href="http://mjtemplate.org/examples/rison.html">Rison spec</a>. */ public class RisonFactory extends JsonFactory { public final static String FORMAT_NAME_RISON = "Rison"; final static int DEFAULT_RISON_PARSER_FEATURE_FLAGS = RisonParser.Feature.collectDefaults(); final static int DEFAULT_RISON_GENERATOR_FEATURE_FLAGS = RisonGenerator.Feature.collectDefaults(); protected int _risonParserFeatures = DEFAULT_RISON_PARSER_FEATURE_FLAGS; protected int _risonGeneratorFeatures = DEFAULT_RISON_GENERATOR_FEATURE_FLAGS; public RisonFactory() { this(null); } public RisonFactory(ObjectCodec codec) { super(codec); } @Override public RisonFactory copy() { _checkInvalidCopy(RisonFactory.class); return new RisonFactory(null); } @Override protected Object readResolve() { return new RisonFactory(_objectCodec); } @Override public String getFormatName() { return FORMAT_NAME_RISON; } @Override public MatchStrength hasFormat(InputAccessor acc) throws IOException { return MatchStrength.SOLID_MATCH; // format detection isn't supported } @Override public Version version() { return PackageVersion.version(); } // // Parser configuration // public final RisonFactory configure(RisonParser.Feature f, boolean state) { if (state) { enable(f); } else { disable(f); } return this; } public RisonFactory enable(RisonParser.Feature f) { _risonParserFeatures |= f.getMask(); return this; } public RisonFactory disable(RisonParser.Feature f) { _risonParserFeatures &= ~f.getMask(); return this; } public boolean isEnabled(RisonParser.Feature f) { return (_risonParserFeatures & f.getMask()) != 0; } // // Generator configuration // public RisonFactory configure(RisonGenerator.Feature f, boolean state) { if (state) { enable(f); } else { disable(f); } return this; } public RisonFactory enable(RisonGenerator.Feature f) { _risonGeneratorFeatures |= f.getMask(); return this; } public RisonFactory disable(RisonGenerator.Feature f) { _risonGeneratorFeatures &= ~f.getMask(); return this; } public final boolean isEnabled(RisonGenerator.Feature f) { return (_risonGeneratorFeatures & f.getMask()) != 0; } @Override public boolean canUseCharArrays() { return false; } // // Internal factory methods // @Override protected RisonParser _createParser(InputStream in, IOContext ctxt) throws IOException, JsonParseException { return _createJsonParser(in, ctxt); } @Override protected RisonParser _createParser(Reader r, IOContext ctxt) throws IOException, JsonParseException { return _createJsonParser(r, ctxt); } @Override protected RisonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException, JsonParseException { return _createJsonParser(data, offset, len, ctxt); } @Deprecated protected RisonParser _createJsonParser(InputStream in, IOContext ctxt) throws IOException, JsonParseException { return _createJsonParser(new InputStreamReader(in, StandardCharsets.UTF_8), ctxt); } @Deprecated protected RisonParser _createJsonParser(Reader r, IOContext ctxt) throws IOException, JsonParseException { return new RisonParser(ctxt, _parserFeatures, _risonParserFeatures, r, _objectCodec, _rootCharSymbols.makeChild( (isEnabled(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES) ? JsonFactory.Feature.CANONICALIZE_FIELD_NAMES.getMask() : 0) | (isEnabled(JsonFactory.Feature.INTERN_FIELD_NAMES) ? JsonFactory.Feature.INTERN_FIELD_NAMES.getMask() : 0))); } @Deprecated protected RisonParser _createJsonParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException, JsonParseException { return _createJsonParser(new ByteArrayInputStream(data, offset, len), ctxt); } @Override protected RisonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException { return _createJsonGenerator(out, ctxt); } @Deprecated protected RisonGenerator _createJsonGenerator(Writer out, IOContext ctxt) throws IOException { RisonGenerator gen = new RisonGenerator(ctxt, _generatorFeatures, _risonGeneratorFeatures, _objectCodec, out); SerializableString rootSep = _rootValueSeparator; if (rootSep != DefaultPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR) { gen.setRootValueSeparator(rootSep); } return gen; } @Override protected RisonGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException { return _createUTF8JsonGenerator(out, ctxt); } @Deprecated protected RisonGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt) throws IOException { return _createJsonGenerator(_createWriter(out, JsonEncoding.UTF8, ctxt), ctxt); } }
package org.ovirt.engine.core.common.businessentities; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.ovirt.engine.core.common.businessentities.comparators.BusinessEntityComparator; import org.ovirt.engine.core.compat.Guid; import com.fasterxml.jackson.annotation.JsonIgnore; public class VmDynamic implements BusinessEntityWithStatus<Guid, VMStatus>, Comparable<VmDynamic> { private static final long serialVersionUID = 7789482445091432555L; private Guid id; private VMStatus status; @UnchangeableByVdsm private String ip; private String fqdn; @UnchangeableByVdsm private String vmHost; @UnchangeableByVdsm private Date bootTime; @UnchangeableByVdsm private long downtime; @UnchangeableByVdsm private Date lastStartTime; @UnchangeableByVdsm private Date lastStopTime; private String guestCurUserName; /** Last connected user name */ @UnchangeableByVdsm private String consoleCurrentUserName; /** Last connected user id */ @UnchangeableByVdsm private Guid consoleUserId; private String guestOs; @UnchangeableByVdsm private Guid migratingToVds; @UnchangeableByVdsm private Guid runOnVds; private String appList; private Boolean acpiEnabled; private SessionState session; private String vncKeyboardLayout; private Integer utcDiff; private String clientIp; private Integer guestRequestedMemory; @UnchangeableByVdsm private BootSequence bootSequence; private VmExitStatus exitStatus; private VmPauseStatus pauseStatus; private int guestAgentNicsHash; @UnchangeableByVdsm private String exitMessage; private Long lastWatchdogEvent; private String lastWatchdogAction; @UnchangeableByVdsm private boolean runOnce; @UnchangeableByVdsm private boolean volatileRun; /** * cpuName contains one of two possible values: * * - CpuId VDSM verb for standard VMs (model + extra flags) * - List of host CPU flags present on the host where * the VM was started for VMs with CPU flag passthrough */ @UnchangeableByVdsm private String cpuName; @UnchangeableByVdsm private GuestAgentStatus ovirtGuestAgentStatus; @UnchangeableByVdsm private GuestAgentStatus qemuGuestAgentStatus; @UnchangeableByVdsm private String emulatedMachine; private String currentCd; @UnchangeableByVdsm private String stopReason; private VmExitReason exitReason; private int guestCpuCount; private Map<GraphicsType, GraphicsInfo> graphicsInfos; private String guestOsVersion; private String guestOsDistribution; private String guestOsCodename; private ArchitectureType guestOsArch; private OsType guestOsType; private String guestOsKernelVersion; private String guestOsTimezoneName; private int guestOsTimezoneOffset; private List<GuestContainer> guestContainers; @UnchangeableByVdsm private Map<String, String> leaseInfo; @UnchangeableByVdsm private String runtimeName; public static final String APPLICATIONS_LIST_FIELD_NAME = "appList"; @Override public int hashCode() { return Objects.hash( id, acpiEnabled, appList, bootSequence, clientIp, vncKeyboardLayout, consoleCurrentUserName, guestCurUserName, consoleUserId, guestOs, guestRequestedMemory, exitMessage, exitStatus, migratingToVds, pauseStatus, runOnVds, session, status, utcDiff, vmHost, ip, fqdn, lastStartTime, bootTime, downtime, lastStopTime, lastWatchdogEvent, lastWatchdogAction, runOnce, volatileRun, cpuName, ovirtGuestAgentStatus, qemuGuestAgentStatus, currentCd, stopReason, exitReason, emulatedMachine, graphicsInfos, guestOsTimezoneName, guestOsTimezoneOffset, guestOsArch, guestOsCodename, guestOsDistribution, guestOsKernelVersion, guestOsVersion, guestOsType, guestContainers, leaseInfo ); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof VmDynamic)) { return false; } VmDynamic other = (VmDynamic) obj; return Objects.equals(id, other.id) && Objects.equals(acpiEnabled, other.acpiEnabled) && Objects.equals(appList, other.appList) && bootSequence == other.bootSequence && Objects.equals(clientIp, other.clientIp) && Objects.equals(vncKeyboardLayout, other.vncKeyboardLayout) && Objects.equals(consoleCurrentUserName, other.consoleCurrentUserName) && Objects.equals(guestCurUserName, other.guestCurUserName) && Objects.equals(consoleUserId, other.consoleUserId) && Objects.equals(guestOs, other.guestOs) && Objects.equals(guestRequestedMemory, other.guestRequestedMemory) && Objects.equals(exitMessage, other.exitMessage) && exitStatus == other.exitStatus && Objects.equals(migratingToVds, other.migratingToVds) && pauseStatus == other.pauseStatus && Objects.equals(runOnVds, other.runOnVds) && session == other.session && status == other.status && Objects.equals(utcDiff, other.utcDiff) && Objects.equals(vmHost, other.vmHost) && Objects.equals(ip, other.ip) && Objects.equals(fqdn, other.fqdn) && Objects.equals(lastStartTime, other.lastStartTime) && Objects.equals(bootTime, other.bootTime) && Objects.equals(downtime, other.downtime) && Objects.equals(lastStopTime, other.lastStopTime) && Objects.equals(lastWatchdogEvent, other.lastWatchdogEvent) && Objects.equals(lastWatchdogAction, other.lastWatchdogAction) && runOnce == other.runOnce && volatileRun == other.volatileRun && Objects.equals(cpuName, other.cpuName) && Objects.equals(ovirtGuestAgentStatus, other.ovirtGuestAgentStatus) && Objects.equals(qemuGuestAgentStatus, other.qemuGuestAgentStatus) && Objects.equals(currentCd, other.currentCd) && Objects.equals(stopReason, other.stopReason) && exitReason == other.exitReason && Objects.equals(emulatedMachine, other.emulatedMachine) && Objects.equals(graphicsInfos, other.getGraphicsInfos()) && Objects.equals(guestOsTimezoneName, other.guestOsTimezoneName) && guestOsTimezoneOffset == other.guestOsTimezoneOffset && Objects.equals(guestOsVersion, other.guestOsVersion) && Objects.equals(guestOsDistribution, other.guestOsDistribution) && Objects.equals(guestOsCodename, other.guestOsCodename) && Objects.equals(guestOsKernelVersion, other.guestOsKernelVersion) && Objects.equals(guestOsArch, other.guestOsArch) && Objects.equals(guestOsType, other.guestOsType) && Objects.equals(guestContainers, other.guestContainers) && Objects.equals(leaseInfo, other.leaseInfo); } public Date getBootTime() { return bootTime; } public void setBootTime(Date bootTime) { this.bootTime = bootTime; } public long getDowntime() { return downtime; } public void setDowntime(long downtime) { this.downtime = downtime; } public String getExitMessage() { return exitMessage; } public void setExitMessage(String value) { exitMessage = value; } public VmExitStatus getExitStatus() { return this.exitStatus; } public void setExitStatus(VmExitStatus value) { exitStatus = value; } public int getGuestAgentNicsHash() { return guestAgentNicsHash; } public void setGuestAgentNicsHash(int guestAgentNicsHash) { this.guestAgentNicsHash = guestAgentNicsHash; } public VmDynamic() { id = Guid.Empty; status = VMStatus.Down; pauseStatus = VmPauseStatus.NONE; exitStatus = VmExitStatus.Normal; acpiEnabled = true; session = SessionState.Unknown; bootSequence = BootSequence.C; exitReason = VmExitReason.Unknown; graphicsInfos = new HashMap<>(); ovirtGuestAgentStatus = GuestAgentStatus.DoesntExist; qemuGuestAgentStatus = GuestAgentStatus.DoesntExist; guestOsTimezoneName = ""; guestOsTimezoneOffset = 0; guestOsVersion = ""; guestOsDistribution = ""; guestOsCodename = ""; guestOsKernelVersion = ""; guestOsArch = ArchitectureType.undefined; guestOsType = OsType.Other; guestContainers = new ArrayList<>(); } public VmDynamic(VmDynamic template) { id = template.getId(); status = template.getStatus(); ip = template.getIp(); fqdn = template.getFqdn(); vmHost = template.getVmHost(); lastStartTime = template.getLastStartTime(); bootTime = template.getBootTime(); downtime = template.getDowntime(); lastStopTime = template.getLastStopTime(); guestCurUserName = template.getGuestCurrentUserName(); consoleCurrentUserName = template.getConsoleCurrentUserName(); consoleUserId = template.getConsoleUserId(); guestOs = template.getGuestOs(); migratingToVds = template.getMigratingToVds(); runOnVds = template.getRunOnVds(); appList = template.getAppList(); acpiEnabled = template.getAcpiEnable(); session = template.getSession(); vncKeyboardLayout = template.getVncKeyboardLayout(); utcDiff = template.getUtcDiff(); clientIp = template.getClientIp(); guestRequestedMemory = template.getGuestRequestedMemory(); bootSequence = template.getBootSequence(); exitStatus = template.getExitStatus(); pauseStatus = template.getPauseStatus(); guestAgentNicsHash = template.getGuestAgentNicsHash(); exitMessage = template.getExitMessage(); lastWatchdogEvent = template.getLastWatchdogEvent(); lastWatchdogAction = template.getLastWatchdogAction(); runOnce = template.isRunOnce(); cpuName = template.getCpuName(); ovirtGuestAgentStatus = template.getOvirtGuestAgentStatus(); qemuGuestAgentStatus = template.getQemuGuestAgentStatus(); emulatedMachine = template.getEmulatedMachine(); currentCd = template.getCurrentCd(); stopReason = template.getStopReason(); exitReason = template.getExitReason(); guestCpuCount = template.getGuestCpuCount(); graphicsInfos = new HashMap<>(template.getGraphicsInfos()); guestOsVersion = template.getGuestOsVersion(); guestOsDistribution = template.getGuestOsDistribution(); guestOsCodename = template.getGuestOsCodename(); guestOsArch = template.getGuestOsArch(); guestOsType = template.getGuestOsType(); guestOsKernelVersion = template.getGuestOsKernelVersion(); guestOsTimezoneName = template.getGuestOsTimezoneName(); guestOsTimezoneOffset = template.getGuestOsTimezoneOffset(); guestContainers = template.getGuestContainers(); volatileRun = template.isVolatileRun(); leaseInfo = template.leaseInfo; } public String getAppList() { return this.appList; } public void setAppList(String value) { if (value != null) { this.appList = value.intern(); } else { this.appList = null; } } public String getConsoleCurrentUserName() { return consoleCurrentUserName; } public void setConsoleCurrentUserName(String consoleCurUserName) { this.consoleCurrentUserName = consoleCurUserName; } public String getGuestCurrentUserName() { return this.guestCurUserName; } public void setGuestCurrentUserName(String value) { this.guestCurUserName = value; } public Guid getConsoleUserId() { return this.consoleUserId; } public void setConsoleUserId(Guid value) { this.consoleUserId = value; } public String getGuestOs() { return this.guestOs; } public void setGuestOs(String value) { this.guestOs = value; } public Guid getMigratingToVds() { return this.migratingToVds; } public void setMigratingToVds(Guid value) { this.migratingToVds = value; } public Guid getRunOnVds() { return this.runOnVds; } public void setRunOnVds(Guid value) { this.runOnVds = value; } @Override public VMStatus getStatus() { return this.status; } @Override public void setStatus(VMStatus value) { this.status = value; } @Override public Guid getId() { return this.id; } @Override public void setId(Guid value) { this.id = value; } public String getVmHost() { return this.vmHost; } public void setVmHost(String value) { this.vmHost = value; } public String getFqdn() { return this.fqdn; } public void setFqdn(String fqdn) { this.fqdn = fqdn; } public String getIp() { return this.ip; } public void setIp(String value) { this.ip = value; } public Date getLastStartTime() { return this.lastStartTime; } public void setLastStartTime(Date value) { this.lastStartTime = value; } public Date getLastStopTime() { return this.lastStopTime; } public void setLastStopTime(Date value) { this.lastStopTime = value; } public Map<GraphicsType, GraphicsInfo> getGraphicsInfos() { return graphicsInfos; } /* * DON'T use this setter. It's here only for serizalization. */ public void setGraphicsInfos(Map<GraphicsType, GraphicsInfo> graphicsInfos) { this.graphicsInfos = graphicsInfos; } public Boolean getAcpiEnable() { return this.acpiEnabled; } public void setAcpiEnable(Boolean value) { this.acpiEnabled = value; } public String getVncKeyboardLayout() { return vncKeyboardLayout; } public void setVncKeyboardLayout(String vncKeyboardLayout) { this.vncKeyboardLayout = vncKeyboardLayout; } public SessionState getSession() { return this.session; } public void setSession(SessionState value) { this.session = value; } public BootSequence getBootSequence() { return this.bootSequence; } public void setBootSequence(BootSequence value) { this.bootSequence = value; } public Integer getUtcDiff() { return this.utcDiff; } public void setUtcDiff(Integer value) { this.utcDiff = value; } public String getClientIp() { return this.clientIp; } public void setClientIp(String value) { this.clientIp = value; } public Integer getGuestRequestedMemory() { return this.guestRequestedMemory; } public void setGuestRequestedMemory(Integer value) { this.guestRequestedMemory = value; } public void setPauseStatus(VmPauseStatus pauseStatus) { this.pauseStatus = pauseStatus; } public VmPauseStatus getPauseStatus() { return this.pauseStatus; } @Override public int compareTo(VmDynamic o) { return BusinessEntityComparator.<VmDynamic, Guid>newInstance().compare(this, o); } public Long getLastWatchdogEvent() { return lastWatchdogEvent; } public void setLastWatchdogEvent(Long lastWatchdogEvent) { this.lastWatchdogEvent = lastWatchdogEvent; } public String getLastWatchdogAction() { return lastWatchdogAction; } public void setLastWatchdogAction(String lastWatchdogAction) { this.lastWatchdogAction = lastWatchdogAction; } public boolean isRunOnce() { return runOnce; } public void setRunOnce(boolean runOnce) { this.runOnce = runOnce; } public boolean isVolatileRun() { return volatileRun; } public void setVolatileRun(boolean volatileRun) { this.volatileRun = volatileRun; } public String getCpuName() { return cpuName; } public void setCpuName(String cpuName) { this.cpuName = cpuName; } public GuestAgentStatus getOvirtGuestAgentStatus() { return ovirtGuestAgentStatus; } public GuestAgentStatus getQemuGuestAgentStatus() { return qemuGuestAgentStatus; } public void setOvirtGuestAgentStatus(GuestAgentStatus ovirtGuestAgentStatus) { this.ovirtGuestAgentStatus = ovirtGuestAgentStatus; } public void setQemuGuestAgentStatus(GuestAgentStatus qemuGuestAgentStatus) { this.qemuGuestAgentStatus = qemuGuestAgentStatus; } public String getCurrentCd() { return currentCd; } public void setCurrentCd(String currentCd) { this.currentCd = currentCd; } public String getStopReason() { return stopReason; } public void setStopReason(String stopReason) { this.stopReason = stopReason; } public VmExitReason getExitReason() { return exitReason; } public void setExitReason(VmExitReason value) { exitReason = value; } public void setGuestCpuCount(int guestCpuCount) { this.guestCpuCount = guestCpuCount; } public int getGuestCpuCount() { return guestCpuCount; } public String getEmulatedMachine() { return emulatedMachine; } public void setEmulatedMachine(String emulatedMachine) { this.emulatedMachine = emulatedMachine; } public int getGuestOsTimezoneOffset() { return guestOsTimezoneOffset; } public void setGuestOsTimezoneOffset(int guestOsTimezoneOffset) { this.guestOsTimezoneOffset = guestOsTimezoneOffset; } public String getGuestOsTimezoneName() { return guestOsTimezoneName; } public void setGuestOsTimezoneName(String guestOsTimezoneName) { this.guestOsTimezoneName = guestOsTimezoneName; } public String getGuestOsVersion() { return guestOsVersion; } public void setGuestOsVersion(String guestOsVersion) { this.guestOsVersion = guestOsVersion; } public String getGuestOsDistribution() { return guestOsDistribution; } public void setGuestOsDistribution(String guestOsDistribution) { this.guestOsDistribution = guestOsDistribution; } public String getGuestOsCodename() { return guestOsCodename; } public void setGuestOsCodename(String guestOsCodename) { this.guestOsCodename = guestOsCodename; } public ArchitectureType getGuestOsArch() { return guestOsArch; } public void setGuestOsArch(ArchitectureType guestOsArch) { this.guestOsArch = guestOsArch; } @JsonIgnore public void setGuestOsArch(Integer arch) { this.guestOsArch = ArchitectureType.forValue(arch); } @JsonIgnore public void setGuestOsArch(String arch) { this.guestOsArch = ArchitectureType.valueOf(arch); } public OsType getGuestOsType() { return guestOsType; } public void setGuestOsType(OsType guestOsType) { this.guestOsType = guestOsType; } public String getGuestOsKernelVersion() { return guestOsKernelVersion; } public void setGuestOsKernelVersion(String guestOsKernelVersion) { this.guestOsKernelVersion = guestOsKernelVersion; } public List<GuestContainer> getGuestContainers() { return guestContainers; } public void setGuestContainers(List<GuestContainer> guestContainers) { this.guestContainers = guestContainers; } public Map<String, String> getLeaseInfo() { return leaseInfo; } public void setLeaseInfo(Map<String, String> leaseInfo) { this.leaseInfo = leaseInfo; } public String getRuntimeName() { return runtimeName; } public void setRuntimeName(String runtimeName) { this.runtimeName = runtimeName; } /** * Update data that was received from VDSM * @param vm - the reported VM from VDSM * @param vdsId - the host that it was reported from */ public void updateRuntimeData(VmDynamic vm, Guid vdsId) { setStatus(vm.getStatus()); if (vm.getStatus().isUpOrPaused()) { // migratingToVds is usually cleared by the migrate command or by ResourceManager#resetVmAttributes, this is just a // safety net in case those are missed, e.g., when the engine restarts and the migration ends before the engine is up. setMigratingToVds(null); } setRunOnVds(vdsId); setVmHost(vm.getVmHost()); setFqdn(vm.getFqdn()); // update only if vdsm actually provides some value, otherwise engine has more information if (vm.getCurrentCd() != null) { setCurrentCd(vm.getCurrentCd()); } setAppList(vm.getAppList()); setGuestOs(vm.getGuestOs()); setVncKeyboardLayout(vm.getVncKeyboardLayout()); setAcpiEnable(vm.getAcpiEnable()); setGuestCurrentUserName(vm.getGuestCurrentUserName()); setUtcDiff(vm.getUtcDiff()); setExitStatus(vm.getExitStatus()); setExitMessage(vm.getExitMessage()); setExitReason(vm.getExitReason()); setClientIp(vm.getClientIp()); setPauseStatus(vm.getPauseStatus()); setLastWatchdogEvent(vm.getLastWatchdogEvent()); setGuestCpuCount(vm.getGuestCpuCount()); setGraphicsInfos(new HashMap<>(vm.getGraphicsInfos())); setGuestOsArch(vm.getGuestOsArch()); setGuestOsCodename(vm.getGuestOsCodename()); setGuestOsDistribution(vm.getGuestOsDistribution()); setGuestOsKernelVersion(vm.getGuestOsKernelVersion()); setGuestOsType(vm.getGuestOsType()); setGuestOsVersion(vm.getGuestOsVersion()); setGuestOsTimezoneName(vm.getGuestOsTimezoneName()); setGuestOsTimezoneOffset(vm.getGuestOsTimezoneOffset()); setGuestContainers(vm.getGuestContainers()); setGuestAgentNicsHash(vm.getGuestAgentNicsHash()); setQemuGuestAgentStatus(vm.getQemuGuestAgentStatus()); setSession(vm.getSession()); } }
package uk.dangrew.dinosaurs.game.model.dinosaur; import static java.util.Collections.unmodifiableCollection; import java.util.Collection; import java.util.HashSet; import uk.dangrew.dinosaurs.game.world.World; import uk.dangrew.dinosaurs.game.world.WorldLocation; /** * Represents the area around the dinosaur that it can interact with other assets in the world. */ public class InteractionZone { private final Dinosaur dinosaur; private final int range; private final Collection<WorldLocation> interactionZone; public InteractionZone(Dinosaur dinosaur, int range) { this.interactionZone = new HashSet<>(); this.dinosaur = dinosaur; this.range = range; } public Collection<WorldLocation> calculateInteractionZone(World world) { interactionZone.clear(); WorldLocation topLeft = dinosaur.expectLocation().translate(-range, -range, world); int zoneDimension = range * 2 + 1; for (int i = 0; i < zoneDimension; i++) { for (int j = 0; j < zoneDimension; j++) { interactionZone.add(topLeft.translate(i, j, world)); } } return unmodifiableCollection(interactionZone); } public int getRange() { return range; } public boolean contains(WorldLocation worldLocation) { return interactionZone.contains(worldLocation); } }
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengl; import org.lwjgl.system.*; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.JNI.*; /** * Native bindings to the <a target="_blank" href="https://www.khronos.org/registry/OpenGL/extensions/NV/NV_copy_image.txt">WGL_NV_copy_image</a> extension. * * <p>This extension enables efficient image data transfer between image objects (i.e. textures and renderbuffers) without the need to bind the objects or * otherwise configure the rendering pipeline. The WGL version allows copying between images in different contexts, even if those contexts are in * different sharelists or even on different physical devices.</p> */ public class WGLNVCopyImage { protected WGLNVCopyImage() { throw new UnsupportedOperationException(); } static boolean isAvailable(WGLCapabilities caps) { return checkFunctions( caps.wglCopyImageSubDataNV ); } // --- [ wglCopyImageSubDataNV ] --- /** * Behaves identically to the core function {@link #wglCopyImageSubDataNV CopyImageSubDataNV}, except that the {@code srcRC} and {@code dstRC} parameters specify * the contexts in which to look up the source and destination objects, respectively. A value of zero indicates that the currently bound context should be * used instead. * * @param srcRC the source OpenGL context * @param srcName the source object * @param srcTarget the source object target * @param srcLevel the source level-of-detail number * @param srcX the source texel x coordinate * @param srcY the source texel y coordinate * @param srcZ the source texel z coordinate * @param dstRC the destination OpenGL context * @param dstName the destination object * @param dstTarget the destination object target * @param dstLevel the destination level-of-detail number * @param dstX the destination texel x coordinate * @param dstY the destination texel y coordinate * @param dstZ the destination texel z coordinate * @param width the number of texels to copy in the x-dimension * @param height the number of texels to copy in the y-dimension * @param depth the number of texels to copy in the z-dimension */ @NativeType("BOOL") public static boolean wglCopyImageSubDataNV(@NativeType("HGLRC") long srcRC, @NativeType("GLuint") int srcName, @NativeType("GLenum") int srcTarget, @NativeType("GLint") int srcLevel, @NativeType("GLint") int srcX, @NativeType("GLint") int srcY, @NativeType("GLint") int srcZ, @NativeType("HGLRC") long dstRC, @NativeType("GLuint") int dstName, @NativeType("GLenum") int dstTarget, @NativeType("GLint") int dstLevel, @NativeType("GLint") int dstX, @NativeType("GLint") int dstY, @NativeType("GLint") int dstZ, @NativeType("GLsizei") int width, @NativeType("GLsizei") int height, @NativeType("GLsizei") int depth) { long __functionAddress = GL.getCapabilitiesWGL().wglCopyImageSubDataNV; if (CHECKS) { check(__functionAddress); check(srcRC); check(dstRC); } return callPPI(__functionAddress, srcRC, srcName, srcTarget, srcLevel, srcX, srcY, srcZ, dstRC, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, width, height, depth) != 0; } }
/* * This code is subject to the HIEOS License, Version 1.0 * * Copyright(c) 2008-2009 Vangent, Inc. All rights reserved. * * 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.vangent.hieos.xutil.db.support; import com.vangent.hieos.xutil.exception.XdsInternalException; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * Centralized class to get database connection instances given a JNDI/JDBC * resource name. * * @author Bernie Thuman */ public class SQLConnectionWrapper { // Place here to centralize naming (not a great solution, but it works). /** * HIEOS logger JNDI/JDBC resource name. */ static final public String logJNDIResourceName = "jdbc/hieos-log"; /** * HIEOS ADT JNDI/JDBC resource name. */ static final public String adtJNDIResourceName = "jdbc/hieos-adt"; /** * HIEOS Registry JNDI/JDBC resource name. */ static final public String registryJNDIResourceName = "jdbc/hieos-registry"; /** * HIEOS Repository JNDI/JDBC resource name. */ static final public String repoJNDIResourceName = "jdbc/hieos-repo"; /** * Returns a Connection instance for a given JNDI resource name. * * @param jndiResourceName Name of JNDI resource. * @return Database connection. * @throws XdsInternalException */ public Connection getConnection(String jndiResourceName) throws XdsInternalException { Connection con = null; try { DataSource source = (DataSource) new InitialContext().lookup(jndiResourceName); con = source.getConnection(); } catch (SQLException ex) { // log error Logger.getLogger(SQLConnectionWrapper.class.getName()).log(Level.SEVERE, null, ex); throw new XdsInternalException("Could not get repository data source: " + ex.getMessage()); } catch (NamingException ex) { // DataSource wasn't found in JNDI Logger.getLogger(SQLConnectionWrapper.class.getName()).log(Level.SEVERE, null, ex); throw new XdsInternalException("Could not get repository data source: " + ex.getMessage()); } return con; // All should be well here. } }
/* MIT License Copyright (c) 2017 Wolfgang Almeida Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.wolfterro.fourdowndroid; /** * Created by Wolfterro on 15/06/2017. */ import android.util.Log; import java.net.*; public class FourAPIURL { // Propriedades protegidas // ======================= protected int FourAPIURLStatus = 0; protected String board = ""; protected String threadNum = ""; protected String host = ""; protected String apiURL = ""; // Construtor da classe // ==================== public FourAPIURL(String board, String threadNum) { this.board = board; this.threadNum = threadNum; convertURL(); } // Métodos privados // ================ // Convertendo a URL do tópico para a URL da API // ============================================= private void convertURL() { URL u = null; String urlAssembled = assembleUrl(); try { u = new URL(urlAssembled); } catch (MalformedURLException e) { e.printStackTrace(); return; } host = u.getHost(); if((u.getPath().split("/")).length > 4) { String path = ""; String[] sPath = u.getPath().split("/"); for(int i = 1; i < sPath.length - 1; i++) { path += "/" + sPath[i]; } apiURL = String.format("%s%s%s", GlobalVars.apiURL1, path, GlobalVars.jsonExt); } else { apiURL = String.format("%s%s%s", GlobalVars.apiURL1, u.getPath(), GlobalVars.jsonExt); } Log.println(Log.INFO, "CHECK THIS THING TOO!", apiURL); } private String assembleUrl() { String[] splittedBoard = this.board.split(" - "); String selectedBoard = splittedBoard[0]; String url = String.format("https://boards.4chan.org%sthread/%s", selectedBoard, this.threadNum); Log.println(Log.INFO, "CHECK THIS THING OUT!", url); return url; } // Métodos públicos // ================ // Resgatando a URL da API já processada // ===================================== public String getAPIURL() { return apiURL; } // Resgatando o host da URL inserida // ================================= public String getURLHost() { return host; } }
package de.thetaphi.forbiddenapis; /* * (C) Copyright 2013 Uwe Schindler (Generics Policeman) and others. * Parts of this work are licensed to the Apache Software Foundation (ASF) * under one or more contributor license agreements. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectComponent; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.FileList; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.FileResource; import org.apache.tools.ant.types.resources.Resources; import org.apache.tools.ant.types.resources.StringResource; import java.io.IOException; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; /** * Task to check if a set of class files contains calls to forbidden APIs * from a given classpath and list of API signatures (either inline or as pointer to files). * In contrast to other ANT tasks, this tool does only visit the given classpath * and the system classloader, not ANT's class loader. */ public final class AntTask extends Task { private final Resources classFiles = new Resources(); private final Resources apiSignatures = new Resources(); private final List<BundledSignaturesType> bundledSignatures = new ArrayList<BundledSignaturesType>(); private Path classpath = null; private boolean failOnUnsupportedJava = false; private boolean internalRuntimeForbidden = false; private boolean restrictClassFilename = true; private boolean failOnMissingClasses = true; private boolean failOnUnresolvableSignatures = true; private boolean ignoreEmptyFileset = false; @Override public void execute() throws BuildException { AntClassLoader antLoader = null; try { final ClassLoader loader; if (classpath != null) { classpath.setProject(getProject()); loader = antLoader = getProject().createClassLoader(ClassLoader.getSystemClassLoader(), classpath); antLoader.setParentFirst(true); // use default classloader delegation } else { loader = ClassLoader.getSystemClassLoader(); } classFiles.setProject(getProject()); apiSignatures.setProject(getProject()); final Checker checker = new Checker(loader, internalRuntimeForbidden, failOnMissingClasses, failOnUnresolvableSignatures) { @Override protected void logError(String msg) { log(msg, Project.MSG_ERR); } @Override protected void logWarn(String msg) { // ANT has no real log levels printed, so prefix with "WARNING": log("WARNING: " + msg, Project.MSG_WARN); } @Override protected void logInfo(String msg) { log(msg, Project.MSG_INFO); } }; if (!checker.isSupportedJDK) { final String msg = String.format(Locale.ENGLISH, "Your Java runtime (%s %s) is not supported by <%s/>. Please run the checks with a supported JDK!", System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version"), getTaskName()); if (failOnUnsupportedJava) { throw new BuildException(msg); } else { log("WARNING: " + msg, Project.MSG_WARN); return; } } try { for (BundledSignaturesType bs : bundledSignatures) { final String name = bs.getName(); if (name == null) { throw new BuildException("<bundledSignatures/> must have the mandatory attribute 'name' referring to a bundled signatures file."); } log("Reading bundled API signatures: " + name, Project.MSG_INFO); checker.parseBundledSignatures(name, null); } @SuppressWarnings("unchecked") final Iterator<Resource> iter = apiSignatures.iterator(); while (iter.hasNext()) { final Resource r = iter.next(); if (r instanceof StringResource) { final String s = ((StringResource) r).getValue(); if (s != null && s.trim().length() > 0) { log("Reading inline API signatures...", Project.MSG_INFO); checker.parseSignaturesString(s); } } else { log("Reading API signatures: " + r, Project.MSG_INFO); checker.parseSignaturesFile(r.getInputStream()); } } } catch (IOException ioe) { throw new BuildException("IO problem while reading files with API signatures: " + ioe); } catch (ParseException pe) { throw new BuildException("Parsing signatures failed: " + pe.getMessage()); } if (checker.hasNoSignatures()) { throw new BuildException("No API signatures found; use signaturesFile=, <signaturesFileSet/>, <bundledSignatures/> or inner text to define those!"); } log("Loading classes to check...", Project.MSG_INFO); try { @SuppressWarnings("unchecked") final Iterator<Resource> iter = classFiles.iterator(); boolean foundClass = false; while (iter.hasNext()) { final Resource r = iter.next(); final String name = r.getName(); if (restrictClassFilename && name != null && !name.endsWith(".class")) { continue; } checker.addClassToCheck(r.getInputStream()); foundClass = true; } if (!foundClass) { if (ignoreEmptyFileset) { log("There is no <fileset/> or other resource collection given, or the collection does not contain any class files to check.", Project.MSG_WARN); log("Scanned 0 class files.", Project.MSG_INFO); return; } else { throw new BuildException("There is no <fileset/> or other resource collection given, or the collection does not contain any class files to check."); } } } catch (IOException ioe) { throw new BuildException("Failed to load one of the given class files: " + ioe); } log("Scanning for API signatures and dependencies...", Project.MSG_INFO); try { checker.run(); } catch (ForbiddenApiException fae) { throw new BuildException(fae.getMessage()); } } finally { if (antLoader != null) antLoader.cleanup(); } } /** Set of class files to check */ public void add(ResourceCollection rc) { classFiles.add(rc); } /** Sets a directory as base for class files. The implicit pattern '**&#47;*.class' is used to only scan class files. */ public void setDir(File dir) { final FileSet fs = new FileSet(); fs.setProject(getProject()); fs.setDir(dir); // needed if somebody sets restrictClassFilename=false: fs.setIncludes("**/*.class"); classFiles.add(fs); } private <T extends ResourceCollection> T addSignaturesResource(T res) { ((ProjectComponent) res).setProject(getProject()); apiSignatures.add(res); return res; } /** Set of files with API signatures as <signaturesFileSet/> nested element */ public FileSet createSignaturesFileSet() { return addSignaturesResource(new FileSet()); } /** List of files with API signatures as <signaturesFileList/> nested element */ public FileList createSignaturesFileList() { return addSignaturesResource(new FileList()); } /** Single file with API signatures as <signaturesFile/> nested element */ public FileResource createSignaturesFile() { return addSignaturesResource(new FileResource()); } /** A file with API signatures signaturesFile= attribute */ public void setSignaturesFile(File file) { createSignaturesFile().setFile(file); } /** Support for API signatures list as nested text */ public void addText(String text) { addSignaturesResource(new StringResource(text)); } public BundledSignaturesType createBundledSignatures() { final BundledSignaturesType s = new BundledSignaturesType(); s.setProject(getProject()); bundledSignatures.add(s); return s; } /** A bundled signatures name */ public void setBundledSignatures(String name) { createBundledSignatures().setName(name); } /** Classpath as classpath= attribute */ public void setClasspath(Path classpath) { createClasspath().append(classpath); } /** Classpath as classpathRef= attribute */ public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } /** Classpath as <classpath/> nested element */ public Path createClasspath() { if (this.classpath == null) { this.classpath = new Path(getProject()); } return this.classpath.createPath(); } /** * Fail the build, if the bundled ASM library cannot read the class file format * of the runtime library or the runtime library cannot be discovered. * Defaults to {@code false}. */ public void setFailOnUnsupportedJava(boolean failOnUnsupportedJava) { this.failOnUnsupportedJava = failOnUnsupportedJava; } /** * Fail the build, if a referenced class is missing. This requires * that you pass the whole classpath including all dependencies. * If you don't have all classes in the filesets, the application classes * must be reachable through this classpath, too. * Defaults to {@code true}. */ public void setFailOnMissingClasses(boolean failOnMissingClasses) { this.failOnMissingClasses = failOnMissingClasses; } /** * Fail the build if a signature is not resolving. If this parameter is set to * to false, then such signatures are silently ignored. * Defaults to {@code true}. */ public void setFailOnUnresolvableSignatures(boolean failOnUnresolvableSignatures) { this.failOnUnresolvableSignatures = failOnUnresolvableSignatures; } /** * Forbids calls to classes from the internal java runtime (like sun.misc.Unsafe) * Defaults to {@code false}. */ public void setInternalRuntimeForbidden(boolean internalRuntimeForbidden) { this.internalRuntimeForbidden = internalRuntimeForbidden; } /** Automatically restrict resource names included to files with a name ending in '.class'. * This makes filesets easier, as the includes="**&#47;*.class" is not needed. * Defaults to {@code true}. */ public void setRestrictClassFilename(boolean restrictClassFilename) { this.restrictClassFilename = restrictClassFilename; } /** Ignore empty fileset/resource collection and print a warning instead. * Defaults to {@code false}. */ public void setIgnoreEmptyFileSet(boolean ignoreEmptyFileset) { this.ignoreEmptyFileset = ignoreEmptyFileset; } }
package com.egoveris.sharedorganismo.base.service; import com.egoveris.sharedorganismo.base.exception.ReparticionGenericDAOException; import com.egoveris.sharedorganismo.base.model.ReparticionBean; import java.util.List; /** * * @author agambina * */ public interface ReparticionServ { /** * Este método se inicia cuando se inicia cuando se inicia el Bean. Inicializa * el thread de carga de reparticiones. * * @return listaReparticiones cargadas. Thread inicializado. * */ public void loadReparticiones(); /** * Devuelve el listado de reparticiones. * * @return Listado de reparticiones. */ public List<ReparticionBean> buscarTodasLasReparticiones(); /** * Devuelve el listado de reparticiones que contienen la subcadena ingresada * como parámetro dentro del código de repartición o del nombre de la * repartición. * * @param textoBusqueda * Subcadena que contiene el código de repartición o el nombre de la * repartición. * @return Listado de reparticiones existentes que contienen como subcadena el * parametro ingresado dentro del código de repartición o del nombre * de la repartición. */ public List<ReparticionBean> buscarTodasLasReparticiones(String textoBusqueda); /** * Devuelve el listado de reparticiones que contienen la subcadena ingresada * como parámetro dentro del nombre de la repartición. * * @param textoBusqueda * Subcadena que contiene el nombre de la repartición. * @return Listado de reparticiones existentes que contienen como subcadena el * parametro ingresado dentro del nombre de la repartición. */ public List<ReparticionBean> buscarTodasLasReparticionesNombre(String textoBusqueda); /** * Devuelve el listado de reparticiones que contienen la subcadena ingresada * como parámetro dentro del código de repartición. * * @param textoBusqueda * Subcadena que contiene el código de repartición. * @return Listado de reparticiones existentes que contienen como subcadena el * parametro ingresado dentro del código de repartición. */ public List<ReparticionBean> buscarTodasLasReparticionesCodigo(String textoBusqueda); /** * Se ingresa como parametro el código de la repartición buscada y devuelve la * repartición buscada. * * @param codigoReparticion * Código de repartición buscada. * * @return Repartición que tiene como código el parámetro ingresado. */ public ReparticionBean buscarReparticionPorCodigo(String codigoReparticion); public String buscarNombreReparticionPorCodigo(String codigoReparticion); /** * Se ingresa como parametro el id de la repartición buscada y devuelve la * repartición buscada. * * @param idReparticion * id de la repartición buscada. * * @return Repartición que tiene como id el parámetro ingresado. */ public ReparticionBean buscarReparticionPorId(Long idReparticion); /** * Se ingresa como parametro el nombre de usuario de la repartición buscada. * En caso de no existir se retorna null por compatibilidad con el código * existente. Todas las otras excepciones se propagan como * ReparticionGenericDAOException * * @param username * usuario de la repartición buscada o nulo si no se encuentra * * @return Repartición a la cual el usuario pertenece. */ public ReparticionBean buscarReparticionPorUsuario(String username) throws ReparticionGenericDAOException; /** * Valida que el código de repartición exista. * * @param codigo * es el código de repartición * @return True en el caso que el código de repartición exista, False en caso * contrario. */ public boolean validarCodigoReparticion(String codigoReparticion); /** * Devuelve el listado de reparticiones vigentes y activas. * * @return Listado de reparticiones vigentes y activas. */ public List<ReparticionBean> buscarReparticionesVigentesActivas(); /** * Devuelve el listado de las reparticiones que esten vigentes, activas y * esDgtal = 1. * * @return Listado de las reparticiones que esten vigentes, activas y esDgtal * = 1. */ public List<ReparticionBean> buscarTodasLasReparticionesDGTAL(); /** * * @param codReparticion * @return */ public ReparticionBean buscarDGTALByReparticion(String codReparticion); }
/* * 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.dolphinscheduler.common.utils; import org.apache.dolphinscheduler.common.task.AbstractParameters; import org.apache.dolphinscheduler.common.task.conditions.ConditionsParameters; import org.apache.dolphinscheduler.common.task.datax.DataxParameters; import org.apache.dolphinscheduler.common.task.dependent.DependentParameters; import org.apache.dolphinscheduler.common.task.flink.FlinkParameters; import org.apache.dolphinscheduler.common.task.http.HttpParameters; import org.apache.dolphinscheduler.common.task.mr.MapReduceParameters; import org.apache.dolphinscheduler.common.task.procedure.ProcedureParameters; import org.apache.dolphinscheduler.common.task.python.PythonParameters; import org.apache.dolphinscheduler.common.task.shell.ShellParameters; import org.apache.dolphinscheduler.common.task.spark.SparkParameters; import org.apache.dolphinscheduler.common.task.sql.SqlParameters; import org.apache.dolphinscheduler.common.task.sqoop.SqoopParameters; import org.apache.dolphinscheduler.common.task.subprocess.SubProcessParameters; import org.apache.dolphinscheduler.common.task.switchtask.SwitchParameters; import org.apache.dolphinscheduler.common.task.tis.PigeonCommonParameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * task parameters utils */ public class TaskParametersUtils { private static final Logger logger = LoggerFactory.getLogger(TaskParametersUtils.class); private TaskParametersUtils() { throw new UnsupportedOperationException("Construct TaskParametersUtils"); } /** * get task parameters * * @param taskType task type * @param parameter parameter * @return task parameters */ public static AbstractParameters getParameters(String taskType, String parameter) { switch (taskType) { case "SUB_PROCESS": return JSONUtils.parseObject(parameter, SubProcessParameters.class); case "SHELL": case "SEATUNNEL": return JSONUtils.parseObject(parameter, ShellParameters.class); case "PROCEDURE": return JSONUtils.parseObject(parameter, ProcedureParameters.class); case "SQL": return JSONUtils.parseObject(parameter, SqlParameters.class); case "MR": return JSONUtils.parseObject(parameter, MapReduceParameters.class); case "SPARK": return JSONUtils.parseObject(parameter, SparkParameters.class); case "PYTHON": return JSONUtils.parseObject(parameter, PythonParameters.class); case "DEPENDENT": return JSONUtils.parseObject(parameter, DependentParameters.class); case "FLINK": return JSONUtils.parseObject(parameter, FlinkParameters.class); case "HTTP": return JSONUtils.parseObject(parameter, HttpParameters.class); case "DATAX": return JSONUtils.parseObject(parameter, DataxParameters.class); case "CONDITIONS": return JSONUtils.parseObject(parameter, ConditionsParameters.class); case "SQOOP": return JSONUtils.parseObject(parameter, SqoopParameters.class); case "SWITCH": return JSONUtils.parseObject(parameter, SwitchParameters.class); case "PIGEON": return JSONUtils.parseObject(parameter, PigeonCommonParameters.class); default: logger.error("not support task type: {}", taskType); return null; } } }
package com.genohm.jeno.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HasLogger is a feature interface that provides Logging capability for anyone * implementing it where logger needs to operate in serializable environment * without being static. */ public interface HasLogger { default Logger getLogger() { return LoggerFactory.getLogger(getClass()); } }
package org.mule.tooling.lang.dw.migrator; import com.intellij.codeInsight.editorActions.CopyPastePostProcessor; import com.intellij.codeInsight.editorActions.TextBlockTransferableData; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.mule.tooling.lang.dw.WeaveFileType; import org.mule.weave.v2.V2LangMigrant; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.util.Collections; import java.util.List; public class V1ToV2PostProcessor extends CopyPastePostProcessor<TextBlockTransferableData> { @NotNull @Override public List<TextBlockTransferableData> collectTransferableData(PsiFile file, Editor editor, int[] startOffsets, int[] endOffsets) { return Collections.emptyList(); } private boolean isV1Text(String textBetweenOffsets) { return textBetweenOffsets.trim().startsWith("%dw 1.0") || textBetweenOffsets.contains("%input ") || textBetweenOffsets.contains("%output ") || textBetweenOffsets.contains("%function ") || textBetweenOffsets.contains("%var "); } @Override public void processTransferableData(Project project, Editor editor, RangeMarker bounds, int caretOffset, Ref<? super Boolean> indented, List<? extends TextBlockTransferableData> values) { if (values.size() == 1 && values.get(0) instanceof ConvertedCode) { PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if(psiFile != null && psiFile.getFileType() == WeaveFileType.getInstance()) { YesNoDialog migrate_to_v2 = new YesNoDialog("Migrate To V2", "Do you want to migrate the DW 1.0 to DW 2.0", null, project); if (migrate_to_v2.showAndGet()) { final String v2 = V2LangMigrant.migrateToV2(((ConvertedCode) values.get(0)).data); WriteAction.run(() -> { editor.getDocument().replaceString(bounds.getStartOffset(), bounds.getEndOffset(), v2); }); } } } } @NotNull @Override public List<TextBlockTransferableData> extractTransferableData(Transferable content) { if (content.isDataFlavorSupported(ConvertedCode.FLAVOR)) { try { return Collections.singletonList((TextBlockTransferableData) content.getTransferData(ConvertedCode.FLAVOR)); } catch (UnsupportedFlavorException | IOException e) { e.printStackTrace(); } } if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String text = content.getTransferData(DataFlavor.stringFlavor).toString(); if (isV1Text(text)) { return Collections.singletonList(new ConvertedCode(text)); } } catch (UnsupportedFlavorException | IOException e) { e.printStackTrace(); } } return super.extractTransferableData(content); } public static class ConvertedCode implements TextBlockTransferableData { public static DataFlavor FLAVOR = new DataFlavor(ConvertedCode.class, "DWV1ToV2Migrator"); private String data; public ConvertedCode(String data) { this.data = data; } @Override public DataFlavor getFlavor() { return FLAVOR; } @Override public int getOffsetCount() { return 1; } @Override public int getOffsets(int[] offsets, int index) { return index; } @Override public int setOffsets(int[] offsets, int index) { return index; } } }
package com.litianyi.supermall.coupon.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.litianyi.supermall.coupon.entity.CouponHistoryEntity; import com.litianyi.supermall.coupon.service.CouponHistoryService; import com.litianyi.common.utils.PageUtils; import com.litianyi.common.utils.R; /** * 优惠券领取历史记录 * * @author litianyi * @email stringli@qq.com * @date 2022-01-02 13:21:58 */ @RestController @RequestMapping("coupon/couponhistory") public class CouponHistoryController { @Autowired private CouponHistoryService couponHistoryService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = couponHistoryService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id){ CouponHistoryEntity couponHistory = couponHistoryService.getById(id); return R.ok().put("couponHistory", couponHistory); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody CouponHistoryEntity couponHistory){ couponHistoryService.save(couponHistory); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody CouponHistoryEntity couponHistory){ couponHistoryService.updateById(couponHistory); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] ids){ couponHistoryService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
package se.mickelus.tetra.data; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraft.advancements.criterion.ItemPredicate; import net.minecraft.block.Block; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraftforge.event.AddReloadListenerEvent; import net.minecraftforge.event.TagsUpdatedEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import se.mickelus.tetra.TetraMod; import se.mickelus.tetra.blocks.PropertyMatcher; import se.mickelus.tetra.blocks.workbench.action.ConfigActionImpl; import se.mickelus.tetra.craftingeffect.CraftingEffect; import se.mickelus.tetra.craftingeffect.condition.CraftingEffectCondition; import se.mickelus.tetra.craftingeffect.outcome.CraftingEffectOutcome; import se.mickelus.tetra.data.deserializer.*; import se.mickelus.tetra.generation.FeatureParameters; import se.mickelus.tetra.module.Priority; import se.mickelus.tetra.module.ReplacementDefinition; import se.mickelus.tetra.module.data.*; import se.mickelus.tetra.module.improvement.DestabilizationEffect; import se.mickelus.tetra.module.schematic.OutcomeDefinition; import se.mickelus.tetra.module.schematic.OutcomeMaterial; import se.mickelus.tetra.module.schematic.RepairDefinition; import java.util.Arrays; import java.util.Map; public class DataManager { private final Logger logger = LogManager.getLogger(); // todo: use the same naming for all deserializers? public static final Gson gson = new GsonBuilder() .registerTypeAdapter(ToolData.class, new ToolData.Deserializer()) .registerTypeAdapter(EffectData.class, new EffectData.Deserializer()) .registerTypeAdapter(GlyphData.class, new GlyphDeserializer()) .registerTypeAdapter(ModuleModel.class, new ModuleModelDeserializer()) .registerTypeAdapter(Priority.class, new Priority.Deserializer()) .registerTypeAdapter(ItemPredicate.class, new ItemPredicateDeserializer()) .registerTypeAdapter(PropertyMatcher.class, new PropertyMatcherDeserializer()) .registerTypeAdapter(OutcomeMaterial.class, new OutcomeMaterial.Deserializer()) .registerTypeAdapter(ReplacementDefinition.class, new ReplacementDeserializer()) .registerTypeAdapter(BlockPos.class, new BlockPosDeserializer()) .registerTypeAdapter(Block.class, new BlockDeserializer()) .registerTypeAdapter(AttributesDeserializer.typeToken.getRawType(), new AttributesDeserializer()) .registerTypeAdapter(VariantData.class, new VariantData.Deserializer()) .registerTypeAdapter(ImprovementData.class, new ImprovementData.Deserializer()) .registerTypeAdapter(OutcomeDefinition.class, new OutcomeDefinition.Deserializer()) .registerTypeAdapter(MaterialColors.class, new MaterialColors.Deserializer()) .registerTypeAdapter(CraftingEffectCondition.class, new CraftingEffectCondition.Deserializer()) .registerTypeAdapter(CraftingEffectOutcome.class, new CraftingEffectOutcome.Deserializer()) .registerTypeAdapter(Item.class, new ItemDeserializer()) .registerTypeAdapter(Enchantment.class, new EnchantmentDeserializer()) .registerTypeAdapter(ResourceLocation.class, new ResourceLocationDeserializer()) .create(); public static DataStore<TweakData[]> tweakData = new DataStore<>(gson, "tweaks", TweakData[].class); public static DataStore<MaterialData> materialData = new MaterialStore(gson, "materials"); public static DataStore<ImprovementData[]> improvementData = new ImprovementStore(gson, "improvements"); public static DataStore<ModuleData> moduleData = new ModuleStore(gson, "modules"); public static DataStore<RepairDefinition> repairData = new DataStore<>(gson, "repairs", RepairDefinition.class); public static DataStore<EnchantmentMapping[]> enchantmentData = new DataStore<>(gson, "enchantments", EnchantmentMapping[].class); public static DataStore<SynergyData[]> synergyData = new DataStore<>(gson, "synergies", SynergyData[].class); public static DataStore<ReplacementDefinition[]> replacementData = new DataStore<>(gson, "replacements", ReplacementDefinition[].class); public static SchematicStore schematicData = new SchematicStore(gson, "schematics"); public static DataStore<CraftingEffect> craftingEffectData = new CraftingEffectStore(gson, "crafting_effects"); public static DataStore<ItemPredicate[]> predicateData = new DataStore<>(gson, "predicatus", ItemPredicate[].class); public static DataStore<ConfigActionImpl[]> actionData = new DataStore<>(gson, "actions", ConfigActionImpl[].class); public static DataStore<DestabilizationEffect[]> destabilizationData = new DataStore<>(gson, "destabilization", DestabilizationEffect[].class); public static DataStore<FeatureParameters> featureData = new FeatureStore(gson, "structures"); private final DataStore[] dataStores = new DataStore[] { tweakData, materialData, improvementData, moduleData, enchantmentData, synergyData, replacementData, schematicData, craftingEffectData, repairData, predicateData, actionData, destabilizationData, featureData }; public static DataManager instance; public DataManager() { instance = this; } @SubscribeEvent public void addReloadListener(AddReloadListenerEvent event) { logger.debug("Setting up datastore reload listeners"); Arrays.stream(dataStores).forEach(event::addListener); } @SubscribeEvent public void tagsUpdated(TagsUpdatedEvent event) { logger.debug("Reloaded tags"); } @SubscribeEvent public void playerConnected(PlayerEvent.PlayerLoggedInEvent event) { // todo: stop this from sending to player in singleplayer (while still sending to others in lan worlds) logger.info("Sending data to client: {}", event.getPlayer().getName().getUnformattedComponentText()); for (DataStore dataStore : dataStores) { dataStore.sendToPlayer((ServerPlayerEntity) event.getPlayer()); } } public void onDataRecieved(String directory, Map<ResourceLocation, String> data) { Arrays.stream(dataStores) .filter(dataStore -> dataStore.getDirectory().equals(directory)) .forEach(dataStore -> dataStore.loadFromPacket(data)); } /** * Wrapped data getter for synergy data so that data may be ordered in such a way that it's efficiently compared. Skipping this step * would cause items to incorrectly gain synergies. * @param path The path to the synergy data * @return An array of synergy data */ public SynergyData[] getSynergyData(String path) { SynergyData[] data = synergyData.getDataIn(new ResourceLocation(TetraMod.MOD_ID, path)).stream() .flatMap(Arrays::stream) .toArray(SynergyData[]::new); for (SynergyData entry : data) { Arrays.sort(entry.moduleVariants); Arrays.sort(entry.modules); } return data; } }
package de.unidue.ltl.ctest.difficulty.experiments; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.dkpro.lab.reporting.BatchReportBase; import org.dkpro.tc.api.features.TcFeatureSet; public class Experiment { private String experimentName = Long.toString(new Date().getTime()); private boolean isRegression = true; private TcFeatureSet features = new TcFeatureSet(); private List<AnalysisEngineDescription> preprocessingEngines = new ArrayList<>(); private List<Class<? extends BatchReportBase>> reports = new ArrayList<>(); public String getExperimentName() { return experimentName; } public void setExperimentName(String name) { experimentName = name; } public TcFeatureSet getFeatureSet() { return features; } public void setFeatureSet(TcFeatureSet features) { this.features = features; } public boolean isRegression() { return this.isRegression; } public void setIsRegression(boolean isRegression) { this.isRegression = isRegression; } public List<AnalysisEngineDescription> getPreprocessing() { return preprocessingEngines; } public void setPreprocessing(List<AnalysisEngineDescription> engines) { this.preprocessingEngines = engines; } public List<Class <? extends BatchReportBase>> getReports() { return this.reports; } public void setReports(List<Class <? extends BatchReportBase>> reports) { this.reports = reports; } }
/* * Copyright 2012 Vaadin Community. * * 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.vaadin.addon.leaflet.client; import java.util.HashMap; import java.util.Map; import org.vaadin.addon.leaflet.shared.LayerControlInfo; import com.vaadin.shared.Connector; /** * * @author mattitahvonenitmill */ public class LeafletLayersState extends LeafletControlState { public Map<Connector, LayerControlInfo> layerContolInfo = new HashMap<Connector, LayerControlInfo>(); }
/* * This file was automatically generated by EvoSuite * Sat Nov 07 23:19:07 GMT 2020 */ package com.densebrain.rif.client; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import com.densebrain.rif.client.RIFClassLoader; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class RIFClassLoader_ESTest extends RIFClassLoader_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test0() throws Throwable { RIFClassLoader rIFClassLoader0 = new RIFClassLoader(); byte[] byteArray0 = new byte[6]; // Undeclared exception! try { rIFClassLoader0.registerClass("8,vV&*B&/", byteArray0); fail("Expecting exception: NoClassDefFoundError"); } catch(NoClassDefFoundError e) { } } /** //Test case number: 1 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test1() throws Throwable { RIFClassLoader rIFClassLoader0 = new RIFClassLoader(); byte[] byteArray0 = new byte[5]; // Undeclared exception! try { rIFClassLoader0.registerClass("", byteArray0); fail("Expecting exception: ClassFormatError"); } catch(ClassFormatError e) { } } /** //Test case number: 2 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test2() throws Throwable { RIFClassLoader rIFClassLoader0 = new RIFClassLoader(); // Undeclared exception! try { rIFClassLoader0.findClass((String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 3 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test3() throws Throwable { RIFClassLoader rIFClassLoader0 = new RIFClassLoader(); // Undeclared exception! try { rIFClassLoader0.registerClass((String) null, (byte[]) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.densebrain.rif.client.RIFClassLoader", e); } } /** //Test case number: 4 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test4() throws Throwable { RIFClassLoader rIFClassLoader0 = new RIFClassLoader(); Class<?> class0 = rIFClassLoader0.findClass(""); assertNull(class0); } }
package org.arnolds.agileappproject.agileappmodule.ui.frags; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import org.arnolds.agileappproject.agileappmodule.R; import org.arnolds.agileappproject.agileappmodule.git.GitHubBroker; import org.arnolds.agileappproject.agileappmodule.git.GitHubBrokerListener; import org.arnolds.agileappproject.agileappmodule.ui.activities.DrawerLayoutFragmentActivity; import org.arnolds.agileappproject.agileappmodule.utils.AgileAppModuleUtils; import org.kohsuke.github.GHRepository; import java.util.ArrayList; import java.util.List; public class NavigationDrawerFragment extends Fragment { private static final long REPOS_POLL_RATE_SECONDS = Long.MAX_VALUE; private static int LAST_SELECTED_ITEM_INDEX = 0; private NavigationDrawerCallbacks mCallbacks; private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private Spinner mRepoSelectionSpinner; private String latestSelectedRepoName = ""; private final SelectionListener selectionListener = new SelectionListener(); @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(Boolean.TRUE); } public void invalidateListView() { mDrawerListView.invalidateViews(); } private class SelectionListener extends GitHubBrokerListener { @Override public void onRepoSelected(boolean result) { Log.wtf("BLAH", "----- STOP LOAD ----"); mCallbacks.onStopLoad(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View ret = inflater.inflate( R.layout.fragment_navigation_drawer_layout, container, false); mDrawerListView = (ListView) ret.findViewById(R.id.navigation_drawer_list_view); mRepoSelectionSpinner = (Spinner) ret.findViewById(R.id.repo_selector_view); mRepoSelectionSpinner.setBackgroundColor(getResources().getColor(R.color.theme_white)); final List<String> allRepositories = new ArrayList<String>(); for (GHRepository repository : GitHubBroker.getInstance().getCurrentRepositories().values()) allRepositories.add(repository.getName()); final ArrayAdapter<String> adapter = new ArrayAdapter<String>( getActivity().getApplicationContext(), R.layout.repo_selector_spinner_selected_item, allRepositories); adapter.setDropDownViewResource( R.layout.repo_selector_dropdown_item); final String newSelectedRepoName = mRepoSelectionSpinner.getSelectedItem() == null ? "" : mRepoSelectionSpinner.getSelectedItem().toString(); mRepoSelectionSpinner.setAdapter(adapter); adapter.notifyDataSetChanged(); if (newSelectedRepoName.isEmpty()) { mRepoSelectionSpinner .setSelection(LAST_SELECTED_ITEM_INDEX, false); } mRepoSelectionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { LAST_SELECTED_ITEM_INDEX = position; String repoName = mRepoSelectionSpinner.getItemAtPosition(position).toString(); if (!repoName.isEmpty() && !repoName.contentEquals(latestSelectedRepoName)) { NavigationDrawerFragment.this.latestSelectedRepoName = repoName; try { GitHubBroker.getInstance().selectRepo(repoName, selectionListener); } catch (GitHubBroker.AlreadyNotConnectedException e) { Log.wtf("debug", e.getClass().getName(), e); } catch (GitHubBroker.NullArgumentException e) { Log.wtf("debug", e.getClass().getName(), e); } mCallbacks.onStartLoad(); Log.wtf("BLAH", "----- START LOAD ----"); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } }); final NavigationDrawerArrayAdapter navigationAdapter = new NavigationDrawerArrayAdapter(); mDrawerListView.setAdapter(navigationAdapter); return ret; } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } /** * Users of this fragment must call this method to set up the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = getActionBar(); actionBar.setHomeButtonEnabled(Boolean.TRUE); actionBar.setDisplayHomeAsUpEnabled(Boolean.TRUE); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } restoreActionBar(); getActivity().invalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); showGlobalContextActionBar(); } }; // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(Boolean.TRUE); actionBar.setTitle( AgileAppModuleUtils.getString(getActivity(), "title_section" + ( DrawerLayoutFragmentActivity.getLastSelectedFragmentIndex() + 1), "Home" ) ); } private void selectItem(int position) { if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null && (!(position == 0 || position == 4 || position == 7))) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { if (!(position == 0 || position == 4 || position == 7)) { int aux; if (position < 4) { aux = position - 1; } else if (position < 7) { aux = position - 2; } else { aux = position - 3; } mCallbacks.onNavigationDrawerItemSelected(aux); } } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mDrawerLayout != null) { if (isDrawerOpen()) { showGlobalContextActionBar(); } } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } /** * Per the navigation drawer design guidelines, updates the action bar to show the actionbar app * 'context', rather than just what's in the current screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(Boolean.TRUE); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return getActivity().getActionBar(); } /** * Callbacks interface that all activities using this fragment must implement. */ public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position); void onStartLoad(); void onStopLoad(); } private class NavigationDrawerArrayAdapter extends ArrayAdapter<String> { private static final int mEntryResource = R.layout.list_item_navigation_drawer_list, mDividerResource = R.layout.list_item_navigation_drawer_list_divider; public NavigationDrawerArrayAdapter() { super(getActivity().getApplicationContext(), mEntryResource); } @Override public int getCount() { Context context = getActivity().getApplicationContext(); for (int i = 1; ; i++) { if (AgileAppModuleUtils.getString(context, "title_section" + i, null) == null) { return i - 1 + 3;//3 is the number of sections } } } @Override public String getItem(int i) { int temp = i + 1; if (i == 0 | i == 4 | i == 7) { return AgileAppModuleUtils .getString(getActivity().getApplicationContext(), "title_header" + i, null); } return AgileAppModuleUtils .getString(getActivity().getApplicationContext(), "title_section" + temp, ""); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); Log.d("debug", "position on getView:" + position); if (position == 0 || position == 4 || position == 7) { String text = AgileAppModuleUtils .getString(getActivity().getApplicationContext(), "title_header" + position, null); convertView = inflater.inflate(mDividerResource, parent, false); ((TextView) convertView.findViewById(R.id.divider_title_view)).setText(text); return convertView; } convertView = inflater.inflate(mEntryResource, parent, false); int temp = position + 1; if (position < 4) { temp = temp - 1; } else if (position < 7) { temp = temp - 2; } else { temp = temp - 3; } TextView textView = (TextView) convertView.findViewById(R.id.navigation_drawer_item_title); ImageView imageView = (ImageView) convertView.findViewById(R.id.navigation_drawer_item_icon); if (temp == (DrawerLayoutFragmentActivity.getLastSelectedFragmentIndex() + 1)) { convertView.setBackgroundColor(getResources().getColor(R.color.theme_orange)); textView.setTypeface(null, Typeface.BOLD); } textView.setText(AgileAppModuleUtils .getString(getActivity().getApplicationContext(), "title_section" + +temp, "")); imageView.setImageResource( AgileAppModuleUtils.getDrawableAsId("icon_section" + temp, -1)); return convertView; } } }
package org.infinispan.cli.interpreter.logging; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; /** * Informational CLI messages. These start from 19500 so as not to overlap with the logging messages defined in {@link Log} * Messages. * * @author Tristan Tarrant * @since 5.2 */ @MessageBundle(projectCode = "ISPN") public interface Messages { Messages MSG = org.jboss.logging.Messages.getBundle(Messages.class); @Message(value="Synchronized %d entries using migrator '%s' on cache '%s'", id=19500) String synchronizedEntries(long count, String cacheName, String migrator); @Message(value="Disconnected '%s' migrator source on cache '%s'", id=19501) String disonnectedSource(String migratorName, String cacheNname); @Message(value="Dumped keys for cache %s", id=19502) String dumpedKeys(String cacheName); }
package org.bndly.common.service.decorator.api; /*- * #%L * Service Decorator API * %% * Copyright (C) 2013 - 2020 Cybercon GmbH * %% * 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% */ public interface ServiceDecoratorChain { Object doContinue() throws Throwable; }
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. */ /* * 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. */ /* * $Id: AttributeSet.java,v 1.5 2005/09/28 13:48:04 pvedula Exp $ */ package goodman.com.sun.org.apache.xalan.internal.xsltc.compiler; import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen; import com.sun.org.apache.bcel.internal.generic.INVOKESPECIAL; import com.sun.org.apache.bcel.internal.generic.InstructionList; import com.sun.org.apache.xalan.internal.xsltc.compiler.*; import com.sun.org.apache.xalan.internal.xsltc.compiler.Constants; import com.sun.org.apache.xalan.internal.xsltc.compiler.Parser; import com.sun.org.apache.xalan.internal.xsltc.compiler.QName; import com.sun.org.apache.xalan.internal.xsltc.compiler.SymbolTable; import com.sun.org.apache.xalan.internal.xsltc.compiler.Text; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.AttributeSetMethodGenerator; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util; import com.sun.org.apache.xml.internal.utils.XML11Char; import goodman.java.util.Iterator; import goodman.java.util.List; /** * @author Jacek Ambroziak * @author Santiago Pericas-Geertsen * @author Morten Jorgensen */ final class AttributeSet extends TopLevelElement { // This prefix is used for the method name of attribute set methods private static final String AttributeSetPrefix = "$as$"; // Element contents private com.sun.org.apache.xalan.internal.xsltc.compiler.QName _name; private UseAttributeSets _useSets; private AttributeSet _mergeSet; private String _method; private boolean _ignore = false; /** * Returns the QName of this attribute set */ public com.sun.org.apache.xalan.internal.xsltc.compiler.QName getName() { return _name; } /** * Returns the method name of this attribute set. This method name is * generated by the compiler (XSLTC) */ public String getMethodName() { return _method; } /** * Call this method to prevent a method for being compiled for this set. * This is used in case several <xsl:attribute-set...> elements constitute * a single set (with one name). The last element will merge itself with * any previous set(s) with the same name and disable the other set(s). */ public void ignore() { _ignore = true; } /** * Parse the contents of this attribute set. Recognised attributes are * "name" (required) and "use-attribute-sets" (optional). */ public void parseContents(Parser parser) { // Get this attribute set's name final String name = getAttribute("name"); if (!XML11Char.isXML11ValidQName(name)) { ErrorMsg err = new ErrorMsg(ErrorMsg.INVALID_QNAME_ERR, name, this); parser.reportError(com.sun.org.apache.xalan.internal.xsltc.compiler.Constants.ERROR, err); } _name = parser.getQNameIgnoreDefaultNs(name); if ((_name == null) || (_name.equals(EMPTYSTRING))) { ErrorMsg msg = new ErrorMsg(ErrorMsg.UNNAMED_ATTRIBSET_ERR, this); parser.reportError(com.sun.org.apache.xalan.internal.xsltc.compiler.Constants.ERROR, msg); } // Get any included attribute sets (similar to inheritance...) final String useSets = getAttribute("use-attribute-sets"); if (useSets.length() > 0) { if (!Util.isValidQNames(useSets)) { ErrorMsg err = new ErrorMsg(ErrorMsg.INVALID_QNAME_ERR, useSets, this); parser.reportError(com.sun.org.apache.xalan.internal.xsltc.compiler.Constants.ERROR, err); } _useSets = new UseAttributeSets(useSets, parser); } // Parse the contents of this node. All child elements must be // <xsl:attribute> elements. Other elements cause an error. final List<SyntaxTreeNode> contents = getContents(); final int count = contents.size(); for (int i=0; i<count; i++) { SyntaxTreeNode child = contents.get(i); if (child instanceof XslAttribute) { parser.getSymbolTable().setCurrentNode(child); child.parseContents(parser); } else if (child instanceof com.sun.org.apache.xalan.internal.xsltc.compiler.Text) { // ignore } else { ErrorMsg msg = new ErrorMsg(ErrorMsg.ILLEGAL_CHILD_ERR, this); parser.reportError(Constants.ERROR, msg); } } // Point the symbol table back at us... parser.getSymbolTable().setCurrentNode(this); } /** * Type check the contents of this element */ public Type typeCheck(com.sun.org.apache.xalan.internal.xsltc.compiler.SymbolTable stable) throws TypeCheckError { if (_ignore) return (Type.Void); // _mergeSet Point to any previous definition of this attribute set _mergeSet = stable.addAttributeSet(this); _method = AttributeSetPrefix + getXSLTC().nextAttributeSetSerial(); if (_useSets != null) _useSets.typeCheck(stable); typeCheckContents(stable); return Type.Void; } /** * Compile a method that outputs the attributes in this set */ public void translate(ClassGenerator classGen, MethodGenerator methodGen) { if (_ignore) return; // Create a new method generator for an attribute set method methodGen = new AttributeSetMethodGenerator(_method, classGen); // Generate a reference to previous attribute-set definitions with the // same name first. Those later in the stylesheet take precedence. if (_mergeSet != null) { final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); final String methodName = _mergeSet.getMethodName(); il.append(classGen.loadTranslet()); il.append(methodGen.loadDOM()); il.append(methodGen.loadIterator()); il.append(methodGen.loadHandler()); il.append(methodGen.loadCurrentNode()); final int method = cpg.addMethodref(classGen.getClassName(), methodName, ATTR_SET_SIG); il.append(new INVOKESPECIAL(method)); } // Translate other used attribute sets first, as local attributes // take precedence (last attributes overrides first) if (_useSets != null) _useSets.translate(classGen, methodGen); // Translate all local attributes final Iterator<SyntaxTreeNode> attributes = elements(); while (attributes.hasNext()) { SyntaxTreeNode element = attributes.next(); if (element instanceof XslAttribute) { final XslAttribute attribute = (XslAttribute)element; attribute.translate(classGen, methodGen); } } final InstructionList il = methodGen.getInstructionList(); il.append(RETURN); classGen.addMethod(methodGen); } public String toString() { StringBuffer buf = new StringBuffer("attribute-set: "); // Translate all local attributes final Iterator<SyntaxTreeNode> attributes = elements(); while (attributes.hasNext()) { final XslAttribute attribute = (XslAttribute)attributes.next(); buf.append(attribute); } return(buf.toString()); } }
/* * This file is part of QuickStart Module Loader, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package uk.co.drnaylor.quickstart; import uk.co.drnaylor.quickstart.config.AbstractConfigAdapter; import uk.co.drnaylor.quickstart.exceptions.MissingDependencyException; import java.util.Optional; /** * This class defines what a module is, what it loads, and how it works. It should be paired with the * {@link uk.co.drnaylor.quickstart.annotations.ModuleData} annotation in order to define metadata about it. */ public interface Module { /** * Gets a {@link AbstractConfigAdapter}, should one be required for the main config file. * * @return An {@link Optional} containing an {@link AbstractConfigAdapter} if the module wishes. */ default Optional<AbstractConfigAdapter<?>> getConfigAdapter() { return Optional.empty(); } /** * Performs additional checks to ensure the module has everything it requires loaded. * * <p> * If a dependency check fails, modules should throw a {@link MissingDependencyException} * along with a suitable message. * </p> * * @throws MissingDependencyException thrown if a dependency is missing */ default void checkExternalDependencies() throws MissingDependencyException {} }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.search.stats; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.metrics.CounterMetric; import org.elasticsearch.common.metrics.MeanMetric; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.util.CollectionUtils; import org.elasticsearch.index.shard.SearchOperationListener; import org.elasticsearch.search.internal.ReaderContext; import org.elasticsearch.search.internal.SearchContext; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static java.util.Collections.emptyMap; public final class ShardSearchStats implements SearchOperationListener { private final StatsHolder totalStats = new StatsHolder(); private final CounterMetric openContexts = new CounterMetric(); private volatile Map<String, StatsHolder> groupsStats = emptyMap(); /** * Returns the stats, including group specific stats. If the groups are null/0 length, then nothing * is returned for them. If they are set, then only groups provided will be returned, or * {@code _all} for all groups. */ public SearchStats stats(String... groups) { SearchStats.Stats total = totalStats.stats(); Map<String, SearchStats.Stats> groupsSt = null; if (CollectionUtils.isEmpty(groups) == false) { groupsSt = new HashMap<>(groupsStats.size()); if (groups.length == 1 && groups[0].equals("_all")) { for (Map.Entry<String, StatsHolder> entry : groupsStats.entrySet()) { groupsSt.put(entry.getKey(), entry.getValue().stats()); } } else { for (Map.Entry<String, StatsHolder> entry : groupsStats.entrySet()) { if (Regex.simpleMatch(groups, entry.getKey())) { groupsSt.put(entry.getKey(), entry.getValue().stats()); } } } } return new SearchStats(total, openContexts.count(), groupsSt); } @Override public void onPreQueryPhase(SearchContext searchContext) { computeStats(searchContext, statsHolder -> { if (searchContext.hasOnlySuggest()) { statsHolder.suggestCurrent.inc(); } else { statsHolder.queryCurrent.inc(); } }); } @Override public void onFailedQueryPhase(SearchContext searchContext) { computeStats(searchContext, statsHolder -> { if (searchContext.hasOnlySuggest()) { statsHolder.suggestCurrent.dec(); assert statsHolder.suggestCurrent.count() >= 0; } else { statsHolder.queryCurrent.dec(); assert statsHolder.queryCurrent.count() >= 0; } }); } @Override public void onQueryPhase(SearchContext searchContext, long tookInNanos) { computeStats(searchContext, statsHolder -> { if (searchContext.hasOnlySuggest()) { statsHolder.suggestMetric.inc(tookInNanos); statsHolder.suggestCurrent.dec(); assert statsHolder.suggestCurrent.count() >= 0; } else { statsHolder.queryMetric.inc(tookInNanos); statsHolder.queryCurrent.dec(); assert statsHolder.queryCurrent.count() >= 0; } }); } @Override public void onPreFetchPhase(SearchContext searchContext) { computeStats(searchContext, statsHolder -> statsHolder.fetchCurrent.inc()); } @Override public void onFailedFetchPhase(SearchContext searchContext) { computeStats(searchContext, statsHolder -> statsHolder.fetchCurrent.dec()); } @Override public void onFetchPhase(SearchContext searchContext, long tookInNanos) { computeStats(searchContext, statsHolder -> { statsHolder.fetchMetric.inc(tookInNanos); statsHolder.fetchCurrent.dec(); assert statsHolder.fetchCurrent.count() >= 0; }); } private void computeStats(SearchContext searchContext, Consumer<StatsHolder> consumer) { consumer.accept(totalStats); if (searchContext.groupStats() != null) { for (String group : searchContext.groupStats()) { consumer.accept(groupStats(group)); } } } private StatsHolder groupStats(String group) { StatsHolder stats = groupsStats.get(group); if (stats == null) { synchronized (this) { stats = groupsStats.get(group); if (stats == null) { stats = new StatsHolder(); groupsStats = MapBuilder.newMapBuilder(groupsStats).put(group, stats).immutableMap(); } } } return stats; } @Override public void onNewReaderContext(ReaderContext readerContext) { openContexts.inc(); } @Override public void onFreeReaderContext(ReaderContext readerContext) { openContexts.dec(); } @Override public void onNewScrollContext(ReaderContext readerContext) { totalStats.scrollCurrent.inc(); } @Override public void onFreeScrollContext(ReaderContext readerContext) { totalStats.scrollCurrent.dec(); assert totalStats.scrollCurrent.count() >= 0; totalStats.scrollMetric.inc(TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - readerContext.getStartTimeInNano())); } static final class StatsHolder { final MeanMetric queryMetric = new MeanMetric(); final MeanMetric fetchMetric = new MeanMetric(); /* We store scroll statistics in microseconds because with nanoseconds we run the risk of overflowing the total stats if there are * many scrolls. For example, on a system with 2^24 scrolls that have been executed, each executing for 2^10 seconds, then using * nanoseconds would require a numeric representation that can represent at least 2^24 * 2^10 * 10^9 > 2^24 * 2^10 * 2^29 = 2^63 * which exceeds the largest value that can be represented by a long. By using microseconds, we enable capturing one-thousand * times as many scrolls (i.e., billions of scrolls which at one per second would take 32 years to occur), or scrolls that execute * for one-thousand times as long (i.e., scrolls that execute for almost twelve days on average). */ final MeanMetric scrollMetric = new MeanMetric(); final MeanMetric suggestMetric = new MeanMetric(); final CounterMetric queryCurrent = new CounterMetric(); final CounterMetric fetchCurrent = new CounterMetric(); final CounterMetric scrollCurrent = new CounterMetric(); final CounterMetric suggestCurrent = new CounterMetric(); SearchStats.Stats stats() { return new SearchStats.Stats( queryMetric.count(), TimeUnit.NANOSECONDS.toMillis(queryMetric.sum()), queryCurrent.count(), fetchMetric.count(), TimeUnit.NANOSECONDS.toMillis(fetchMetric.sum()), fetchCurrent.count(), scrollMetric.count(), TimeUnit.MICROSECONDS.toMillis(scrollMetric.sum()), scrollCurrent.count(), suggestMetric.count(), TimeUnit.NANOSECONDS.toMillis(suggestMetric.sum()), suggestCurrent.count() ); } } }
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.jaxrs.v3_0; import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter; import io.opentelemetry.javaagent.instrumentation.jaxrs.HandlerData; import io.opentelemetry.javaagent.instrumentation.jaxrs.JaxrsInstrumenterFactory; public final class ResteasySingletons { private static final Instrumenter<HandlerData, Void> INSTANCE = JaxrsInstrumenterFactory.createInstrumenter("io.opentelemetry.resteasy-6.0"); public static Instrumenter<HandlerData, Void> instrumenter() { return INSTANCE; } private ResteasySingletons() {} }
/* * Copyright 2013 serso aka se.solovyev * * 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. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Contact details * * Email: se.solovyev@gmail.com * Site: http://se.solovyev.org/java/jcl */ package org.solovyev.common.listeners; import javax.annotation.Nonnull; import java.util.Collection; /** * User: serso * Date: 2/1/13 * Time: 9:17 PM */ public interface JEventListeners<L extends JEventListener<? extends E>, E extends JEvent> { /** * Calls {@link JEventListener#onEvent(E)} for every listener added to container. * Note: method calls may be done on current thread or on some background thread depending on implementation * * @param event to be fired event */ void fireEvent(@Nonnull E event); /** * Calls {@link JEventListener#onEvent(E)} for every listener added to container for each event in <var>events</var> * Note: method calls may be done on current thread or on some background thread depending on implementation * * @param events to be fired events */ void fireEvents(@Nonnull Collection<E> events); /** * Adds <var>listener</var> to container. * <p/> * Note: implementation of this interface may accept or may not accept same listener objects * * @param listener listener to be added to container * @return true if listener was added to the container, false otherwise */ boolean addListener(@Nonnull L listener); /** * Removes <var>listener</var> from container. * * @param listener listener to be removed from container * @return true if listener was removed, false if listener was not in container */ boolean removeListener(@Nonnull L listener); /** * Removes all registered listeners */ void removeListeners(); }
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.micrometer1shim; import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; import static io.opentelemetry.sdk.testing.assertj.MetricAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Metrics; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; class CounterTest { @RegisterExtension static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); @Test void testCounter() { Counter counter = Counter.builder("testCounter") .description("This is a test counter") .tags("tag", "value") .baseUnit("items") .register(Metrics.globalRegistry); counter.increment(); counter.increment(2); assertThat(testing.collectAllMetrics()) .satisfiesExactlyInAnyOrder( metric -> assertThat(metric) .hasName("testCounter") .hasInstrumentationScope( InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) .hasDescription("This is a test counter") .hasUnit("items") .hasDoubleSum() .isMonotonic() .points() .satisfiesExactly( point -> assertThat(point) .hasValue(3) .attributes() .containsOnly(attributeEntry("tag", "value")))); Metrics.globalRegistry.remove(counter); counter.increment(); // Synchronous instruments will continue to report previous value after removal assertThat(testing.collectAllMetrics()) .satisfiesExactlyInAnyOrder( metric -> assertThat(metric) .hasName("testCounter") .hasDoubleSum() .points() .satisfiesExactly(point -> assertThat(point).hasValue(3))); } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediapackage.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.mediapackage.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CmafPackage JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CmafPackageJsonUnmarshaller implements Unmarshaller<CmafPackage, JsonUnmarshallerContext> { public CmafPackage unmarshall(JsonUnmarshallerContext context) throws Exception { CmafPackage cmafPackage = new CmafPackage(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("encryption", targetDepth)) { context.nextToken(); cmafPackage.setEncryption(CmafEncryptionJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("hlsManifests", targetDepth)) { context.nextToken(); cmafPackage.setHlsManifests(new ListUnmarshaller<HlsManifest>(HlsManifestJsonUnmarshaller.getInstance()) .unmarshall(context)); } if (context.testExpression("segmentDurationSeconds", targetDepth)) { context.nextToken(); cmafPackage.setSegmentDurationSeconds(context.getUnmarshaller(Integer.class).unmarshall(context)); } if (context.testExpression("segmentPrefix", targetDepth)) { context.nextToken(); cmafPackage.setSegmentPrefix(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("streamSelection", targetDepth)) { context.nextToken(); cmafPackage.setStreamSelection(StreamSelectionJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return cmafPackage; } private static CmafPackageJsonUnmarshaller instance; public static CmafPackageJsonUnmarshaller getInstance() { if (instance == null) instance = new CmafPackageJsonUnmarshaller(); return instance; } }
import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * @author Vivant Sakore on 1/29/2020 */ public class BuggyIntDListTest { private BuggyIntDList l, m; /** * Test mergeIntDList */ @Test public void testMergeIntDList() { l = new BuggyIntDList(1, 15, 23, 37, 90, 101, 105, 107, 120, 135, 140); m = new BuggyIntDList(3, 10, 27, 45, 83, 88, 94, 111, 115, 138); l.mergeIntDList(m); assertEquals("Size after merge should be 21", 21, l.size()); assertEquals(".getFront() should be 1", 1, l.getFront()); assertEquals(".getBack() should be 140", 140, l.getBack()); assertEquals("First item should be 1", 1, l.get(0)); assertEquals("Second item should be 3", 3, l.get(1)); assertEquals("Third item should be 10", 10, l.get(2)); assertEquals("Fourth item should be 15", 15, l.get(3)); assertEquals("Fifth item should be 23", 23, l.get(4)); assertEquals("Sixth item should be 23", 27, l.get(5)); assertEquals("Seventh item should be 37", 37, l.get(6)); assertEquals("Eighth item should be 45", 45, l.get(7)); assertEquals("Ninth item should be 83", 83, l.get(8)); assertEquals("Tenth item should be 88", 88, l.get(9)); assertEquals("Eleventh item should be 90", 90, l.get(10)); assertEquals("Twelfth item should be 94", 94, l.get(11)); assertEquals("Thirteenth item should be 101", 101, l.get(12)); assertEquals("Fourteenth item should be 105", 105, l.get(13)); assertEquals("Fifteenth item should be 107", 107, l.get(14)); assertEquals("Sixteenth item should be 111", 111, l.get(15)); assertEquals("Seventeenth item should be 115", 115, l.get(16)); assertEquals("Eighteenth item should be 120", 120, l.get(17)); assertEquals("Nineteenth item should be 135", 135, l.get(18)); assertEquals("Twentieth item should be 138", 138, l.get(19)); assertEquals("Twenty first item should be 140", 140, l.get(20)); l = new BuggyIntDList(1, 3, 5); m = new BuggyIntDList(1, 3, 5); l.mergeIntDList(m); assertEquals("Size after merge should be 6", 6, l.size()); assertEquals(".getFront() should be 1", 1, l.getFront()); assertEquals(".getBack() should be 5", 5, l.getBack()); assertEquals("First item should be 1", 1, l.get(0)); assertEquals("Second item should be 1", 1, l.get(1)); assertEquals("Third item should be 3", 3, l.get(2)); assertEquals("Fourth item should be 3", 3, l.get(3)); assertEquals("Fifth item should be 5", 5, l.get(4)); assertEquals("Sixth item should be 5", 5, l.get(5)); l = new BuggyIntDList(5); m = new BuggyIntDList(); l.mergeIntDList(m); assertEquals("Size after merge should be 1", 1, l.size()); assertEquals(".getFront() should be 1", 5, l.getFront()); assertEquals(".getBack() should be 1", 5, l.getBack()); assertEquals("First item should be 1", 5, l.get(0)); assertEquals("Last item should be 1", 5, l.get(-1)); } /** * Test reverse */ @Test public void testReverse() { l = new BuggyIntDList(); l.reverse(); assertEquals("Size after reversal should be 0", 0, l.size()); assertNull(".getFront() after reversal should be null", l.front); assertNull(".getBack() after reversal should be null", l.back); l = new BuggyIntDList(5); l.reverse(); assertEquals("Size after reversal should be 1", 1, l.size()); assertEquals(".getFront() after reversal should be 5", 5, l.getFront()); assertEquals(".getBack() after reversal should be 5", 5, l.getBack()); assertEquals("First item after reversal should be 5", 5, l.get(0)); assertEquals("Last item after reversal should be 5", 5, l.get(-1)); l = new BuggyIntDList(12, 23, 34, 45, 56); l.reverse(); assertEquals("Size after reversal should be 5", 5, l.size()); assertEquals(".getFront() after reversal should be 56", 56, l.getFront()); assertEquals(".getBack() after reversal should be 12", 12, l.getBack()); assertEquals("First item after reversal should be 56", 56, l.get(0)); assertEquals("Second item after reversal should be 45", 45, l.get(1)); assertEquals("Third item after reversal should be 34", 34, l.get(2)); assertEquals("Fourth item after reversal should be 23", 23, l.get(3)); assertEquals("Fifth item after reversal should be 12", 12, l.get(4)); } }
package com.navercorp.pinpoint.common; public final class Version { public static final String VERSION = "1.6.1-SNAPSHOT"; }
/* * 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.hop.core.extension; import org.apache.hop.core.exception.HopException; import org.apache.hop.core.logging.ILogChannel; import org.apache.hop.core.variables.IVariables; public class ExtensionPointHandler { /** * This method looks up the extension point plugins with the given ID in the plugin registry. If one or more are * found, their corresponding interfaces are instantiated and the callExtensionPoint() method is invoked. * * @param log the logging channel to write debugging information to * @param variables * @param id The ID of the extension point to call * @param object The parent object that is passed to the plugin * @throws HopException In case something goes wrong in the plugin and we need to stop what we're doing. */ public static void callExtensionPoint( final ILogChannel log, IVariables variables, final String id, final Object object ) throws HopException { ExtensionPointMap.getInstance().callExtensionPoint( log, variables, id, object ); } }
package org.sunbird.portal.department.repo; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.sunbird.portal.department.dto.Role; public interface RoleRepository extends CrudRepository<Role, Integer> { Role findRoleByRoleName(String roleName); List<Role> findAllByRoleNameIn(List<String> roleNames); }
package com.atguigu.gmall.pms.service.impl; import com.atguigu.gmall.pms.entity.AttrEntity; import com.atguigu.gmall.pms.mapper.AttrMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.atguigu.gmall.common.bean.PageResultVo; import com.atguigu.gmall.common.bean.PageParamVo; import com.atguigu.gmall.pms.mapper.AttrGroupMapper; import com.atguigu.gmall.pms.entity.AttrGroupEntity; import com.atguigu.gmall.pms.service.AttrGroupService; import org.springframework.util.CollectionUtils; @Service("attrGroupService") public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupMapper, AttrGroupEntity> implements AttrGroupService { @Autowired private AttrMapper attrMapper; @Override public PageResultVo queryPage(PageParamVo paramVo) { IPage<AttrGroupEntity> page = this.page( paramVo.getPage(), new QueryWrapper<AttrGroupEntity>() ); return new PageResultVo(page); } @Override public List<AttrGroupEntity> queryGroupsWithAttrsByCid(Long cid) { // 1. 根据分类id查询分组 List<AttrGroupEntity> groupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("category_id", cid)); if (CollectionUtils.isEmpty(groupEntities)) { return null; } // 2. 遍历分组的id查询组下的规格参数 groupEntities.forEach(group -> { List<AttrEntity> attrEntities = this.attrMapper.selectList(new QueryWrapper<AttrEntity>().eq("group_id", group.getId()).eq("type", 1)); group.setAttrEntities(attrEntities); }); return groupEntities; } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated by: // mojo/public/tools/bindings/mojom_bindings_generator.py // For: // services/service_manager/public/mojom/service_manager.mojom // package org.chromium.service_manager.mojom; import org.chromium.mojo.bindings.DeserializationException; class ServiceManagerListener_Internal { public static final org.chromium.mojo.bindings.Interface.Manager<ServiceManagerListener, ServiceManagerListener.Proxy> MANAGER = new org.chromium.mojo.bindings.Interface.Manager<ServiceManagerListener, ServiceManagerListener.Proxy>() { @Override public String getName() { return "service_manager.mojom.ServiceManagerListener"; } @Override public int getVersion() { return 0; } @Override public Proxy buildProxy(org.chromium.mojo.system.Core core, org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) { return new Proxy(core, messageReceiver); } @Override public Stub buildStub(org.chromium.mojo.system.Core core, ServiceManagerListener impl) { return new Stub(core, impl); } @Override public ServiceManagerListener[] buildArray(int size) { return new ServiceManagerListener[size]; } }; private static final int ON_INIT_ORDINAL = 0; private static final int ON_SERVICE_CREATED_ORDINAL = 1; private static final int ON_SERVICE_STARTED_ORDINAL = 2; private static final int ON_SERVICE_PID_RECEIVED_ORDINAL = 3; private static final int ON_SERVICE_FAILED_TO_START_ORDINAL = 4; private static final int ON_SERVICE_STOPPED_ORDINAL = 5; static final class Proxy extends org.chromium.mojo.bindings.Interface.AbstractProxy implements ServiceManagerListener.Proxy { Proxy(org.chromium.mojo.system.Core core, org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) { super(core, messageReceiver); } @Override public void onInit( RunningServiceInfo[] runningServices) { ServiceManagerListenerOnInitParams _message = new ServiceManagerListenerOnInitParams(); _message.runningServices = runningServices; getProxyHandler().getMessageReceiver().accept( _message.serializeWithHeader( getProxyHandler().getCore(), new org.chromium.mojo.bindings.MessageHeader(ON_INIT_ORDINAL))); } @Override public void onServiceCreated( RunningServiceInfo service) { ServiceManagerListenerOnServiceCreatedParams _message = new ServiceManagerListenerOnServiceCreatedParams(); _message.service = service; getProxyHandler().getMessageReceiver().accept( _message.serializeWithHeader( getProxyHandler().getCore(), new org.chromium.mojo.bindings.MessageHeader(ON_SERVICE_CREATED_ORDINAL))); } @Override public void onServiceStarted( Identity identity, int pidDeprecated) { ServiceManagerListenerOnServiceStartedParams _message = new ServiceManagerListenerOnServiceStartedParams(); _message.identity = identity; _message.pidDeprecated = pidDeprecated; getProxyHandler().getMessageReceiver().accept( _message.serializeWithHeader( getProxyHandler().getCore(), new org.chromium.mojo.bindings.MessageHeader(ON_SERVICE_STARTED_ORDINAL))); } @Override public void onServicePidReceived( Identity identity, int pid) { ServiceManagerListenerOnServicePidReceivedParams _message = new ServiceManagerListenerOnServicePidReceivedParams(); _message.identity = identity; _message.pid = pid; getProxyHandler().getMessageReceiver().accept( _message.serializeWithHeader( getProxyHandler().getCore(), new org.chromium.mojo.bindings.MessageHeader(ON_SERVICE_PID_RECEIVED_ORDINAL))); } @Override public void onServiceFailedToStart( Identity identity) { ServiceManagerListenerOnServiceFailedToStartParams _message = new ServiceManagerListenerOnServiceFailedToStartParams(); _message.identity = identity; getProxyHandler().getMessageReceiver().accept( _message.serializeWithHeader( getProxyHandler().getCore(), new org.chromium.mojo.bindings.MessageHeader(ON_SERVICE_FAILED_TO_START_ORDINAL))); } @Override public void onServiceStopped( Identity identity) { ServiceManagerListenerOnServiceStoppedParams _message = new ServiceManagerListenerOnServiceStoppedParams(); _message.identity = identity; getProxyHandler().getMessageReceiver().accept( _message.serializeWithHeader( getProxyHandler().getCore(), new org.chromium.mojo.bindings.MessageHeader(ON_SERVICE_STOPPED_ORDINAL))); } } static final class Stub extends org.chromium.mojo.bindings.Interface.Stub<ServiceManagerListener> { Stub(org.chromium.mojo.system.Core core, ServiceManagerListener impl) { super(core, impl); } @Override public boolean accept(org.chromium.mojo.bindings.Message message) { try { org.chromium.mojo.bindings.ServiceMessage messageWithHeader = message.asServiceMessage(); org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader(); if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.NO_FLAG)) { return false; } switch(header.getType()) { case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_OR_CLOSE_PIPE_MESSAGE_ID: return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRunOrClosePipe( ServiceManagerListener_Internal.MANAGER, messageWithHeader); case ON_INIT_ORDINAL: { ServiceManagerListenerOnInitParams data = ServiceManagerListenerOnInitParams.deserialize(messageWithHeader.getPayload()); getImpl().onInit(data.runningServices); return true; } case ON_SERVICE_CREATED_ORDINAL: { ServiceManagerListenerOnServiceCreatedParams data = ServiceManagerListenerOnServiceCreatedParams.deserialize(messageWithHeader.getPayload()); getImpl().onServiceCreated(data.service); return true; } case ON_SERVICE_STARTED_ORDINAL: { ServiceManagerListenerOnServiceStartedParams data = ServiceManagerListenerOnServiceStartedParams.deserialize(messageWithHeader.getPayload()); getImpl().onServiceStarted(data.identity, data.pidDeprecated); return true; } case ON_SERVICE_PID_RECEIVED_ORDINAL: { ServiceManagerListenerOnServicePidReceivedParams data = ServiceManagerListenerOnServicePidReceivedParams.deserialize(messageWithHeader.getPayload()); getImpl().onServicePidReceived(data.identity, data.pid); return true; } case ON_SERVICE_FAILED_TO_START_ORDINAL: { ServiceManagerListenerOnServiceFailedToStartParams data = ServiceManagerListenerOnServiceFailedToStartParams.deserialize(messageWithHeader.getPayload()); getImpl().onServiceFailedToStart(data.identity); return true; } case ON_SERVICE_STOPPED_ORDINAL: { ServiceManagerListenerOnServiceStoppedParams data = ServiceManagerListenerOnServiceStoppedParams.deserialize(messageWithHeader.getPayload()); getImpl().onServiceStopped(data.identity); return true; } default: return false; } } catch (org.chromium.mojo.bindings.DeserializationException e) { System.err.println(e.toString()); return false; } } @Override public boolean acceptWithResponder(org.chromium.mojo.bindings.Message message, org.chromium.mojo.bindings.MessageReceiver receiver) { try { org.chromium.mojo.bindings.ServiceMessage messageWithHeader = message.asServiceMessage(); org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader(); if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG)) { return false; } switch(header.getType()) { case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_MESSAGE_ID: return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRun( getCore(), ServiceManagerListener_Internal.MANAGER, messageWithHeader, receiver); default: return false; } } catch (org.chromium.mojo.bindings.DeserializationException e) { System.err.println(e.toString()); return false; } } } static final class ServiceManagerListenerOnInitParams extends org.chromium.mojo.bindings.Struct { private static final int STRUCT_SIZE = 16; private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)}; private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0]; public RunningServiceInfo[] runningServices; private ServiceManagerListenerOnInitParams(int version) { super(STRUCT_SIZE, version); } public ServiceManagerListenerOnInitParams() { this(0); } public static ServiceManagerListenerOnInitParams deserialize(org.chromium.mojo.bindings.Message message) { return decode(new org.chromium.mojo.bindings.Decoder(message)); } /** * Similar to the method above, but deserializes from a |ByteBuffer| instance. * * @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure. */ public static ServiceManagerListenerOnInitParams deserialize(java.nio.ByteBuffer data) { return deserialize(new org.chromium.mojo.bindings.Message( data, new java.util.ArrayList<org.chromium.mojo.system.Handle>())); } @SuppressWarnings("unchecked") public static ServiceManagerListenerOnInitParams decode(org.chromium.mojo.bindings.Decoder decoder0) { if (decoder0 == null) { return null; } decoder0.increaseStackDepth(); ServiceManagerListenerOnInitParams result; try { org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY); final int elementsOrVersion = mainDataHeader.elementsOrVersion; result = new ServiceManagerListenerOnInitParams(elementsOrVersion); { org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false); { org.chromium.mojo.bindings.DataHeader si1 = decoder1.readDataHeaderForPointerArray(org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH); result.runningServices = new RunningServiceInfo[si1.elementsOrVersion]; for (int i1 = 0; i1 < si1.elementsOrVersion; ++i1) { org.chromium.mojo.bindings.Decoder decoder2 = decoder1.readPointer(org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i1, false); result.runningServices[i1] = RunningServiceInfo.decode(decoder2); } } } } finally { decoder0.decreaseStackDepth(); } return result; } @SuppressWarnings("unchecked") @Override protected final void encode(org.chromium.mojo.bindings.Encoder encoder) { org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); if (this.runningServices == null) { encoder0.encodeNullPointer(8, false); } else { org.chromium.mojo.bindings.Encoder encoder1 = encoder0.encodePointerArray(this.runningServices.length, 8, org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH); for (int i0 = 0; i0 < this.runningServices.length; ++i0) { encoder1.encode(this.runningServices[i0], org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i0, false); } } } } static final class ServiceManagerListenerOnServiceCreatedParams extends org.chromium.mojo.bindings.Struct { private static final int STRUCT_SIZE = 16; private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)}; private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0]; public RunningServiceInfo service; private ServiceManagerListenerOnServiceCreatedParams(int version) { super(STRUCT_SIZE, version); } public ServiceManagerListenerOnServiceCreatedParams() { this(0); } public static ServiceManagerListenerOnServiceCreatedParams deserialize(org.chromium.mojo.bindings.Message message) { return decode(new org.chromium.mojo.bindings.Decoder(message)); } /** * Similar to the method above, but deserializes from a |ByteBuffer| instance. * * @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure. */ public static ServiceManagerListenerOnServiceCreatedParams deserialize(java.nio.ByteBuffer data) { return deserialize(new org.chromium.mojo.bindings.Message( data, new java.util.ArrayList<org.chromium.mojo.system.Handle>())); } @SuppressWarnings("unchecked") public static ServiceManagerListenerOnServiceCreatedParams decode(org.chromium.mojo.bindings.Decoder decoder0) { if (decoder0 == null) { return null; } decoder0.increaseStackDepth(); ServiceManagerListenerOnServiceCreatedParams result; try { org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY); final int elementsOrVersion = mainDataHeader.elementsOrVersion; result = new ServiceManagerListenerOnServiceCreatedParams(elementsOrVersion); { org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false); result.service = RunningServiceInfo.decode(decoder1); } } finally { decoder0.decreaseStackDepth(); } return result; } @SuppressWarnings("unchecked") @Override protected final void encode(org.chromium.mojo.bindings.Encoder encoder) { org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); encoder0.encode(this.service, 8, false); } } static final class ServiceManagerListenerOnServiceStartedParams extends org.chromium.mojo.bindings.Struct { private static final int STRUCT_SIZE = 24; private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(24, 0)}; private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0]; public Identity identity; public int pidDeprecated; private ServiceManagerListenerOnServiceStartedParams(int version) { super(STRUCT_SIZE, version); } public ServiceManagerListenerOnServiceStartedParams() { this(0); } public static ServiceManagerListenerOnServiceStartedParams deserialize(org.chromium.mojo.bindings.Message message) { return decode(new org.chromium.mojo.bindings.Decoder(message)); } /** * Similar to the method above, but deserializes from a |ByteBuffer| instance. * * @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure. */ public static ServiceManagerListenerOnServiceStartedParams deserialize(java.nio.ByteBuffer data) { return deserialize(new org.chromium.mojo.bindings.Message( data, new java.util.ArrayList<org.chromium.mojo.system.Handle>())); } @SuppressWarnings("unchecked") public static ServiceManagerListenerOnServiceStartedParams decode(org.chromium.mojo.bindings.Decoder decoder0) { if (decoder0 == null) { return null; } decoder0.increaseStackDepth(); ServiceManagerListenerOnServiceStartedParams result; try { org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY); final int elementsOrVersion = mainDataHeader.elementsOrVersion; result = new ServiceManagerListenerOnServiceStartedParams(elementsOrVersion); { org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false); result.identity = Identity.decode(decoder1); } { result.pidDeprecated = decoder0.readInt(16); } } finally { decoder0.decreaseStackDepth(); } return result; } @SuppressWarnings("unchecked") @Override protected final void encode(org.chromium.mojo.bindings.Encoder encoder) { org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); encoder0.encode(this.identity, 8, false); encoder0.encode(this.pidDeprecated, 16); } } static final class ServiceManagerListenerOnServicePidReceivedParams extends org.chromium.mojo.bindings.Struct { private static final int STRUCT_SIZE = 24; private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(24, 0)}; private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0]; public Identity identity; public int pid; private ServiceManagerListenerOnServicePidReceivedParams(int version) { super(STRUCT_SIZE, version); } public ServiceManagerListenerOnServicePidReceivedParams() { this(0); } public static ServiceManagerListenerOnServicePidReceivedParams deserialize(org.chromium.mojo.bindings.Message message) { return decode(new org.chromium.mojo.bindings.Decoder(message)); } /** * Similar to the method above, but deserializes from a |ByteBuffer| instance. * * @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure. */ public static ServiceManagerListenerOnServicePidReceivedParams deserialize(java.nio.ByteBuffer data) { return deserialize(new org.chromium.mojo.bindings.Message( data, new java.util.ArrayList<org.chromium.mojo.system.Handle>())); } @SuppressWarnings("unchecked") public static ServiceManagerListenerOnServicePidReceivedParams decode(org.chromium.mojo.bindings.Decoder decoder0) { if (decoder0 == null) { return null; } decoder0.increaseStackDepth(); ServiceManagerListenerOnServicePidReceivedParams result; try { org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY); final int elementsOrVersion = mainDataHeader.elementsOrVersion; result = new ServiceManagerListenerOnServicePidReceivedParams(elementsOrVersion); { org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false); result.identity = Identity.decode(decoder1); } { result.pid = decoder0.readInt(16); } } finally { decoder0.decreaseStackDepth(); } return result; } @SuppressWarnings("unchecked") @Override protected final void encode(org.chromium.mojo.bindings.Encoder encoder) { org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); encoder0.encode(this.identity, 8, false); encoder0.encode(this.pid, 16); } } static final class ServiceManagerListenerOnServiceFailedToStartParams extends org.chromium.mojo.bindings.Struct { private static final int STRUCT_SIZE = 16; private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)}; private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0]; public Identity identity; private ServiceManagerListenerOnServiceFailedToStartParams(int version) { super(STRUCT_SIZE, version); } public ServiceManagerListenerOnServiceFailedToStartParams() { this(0); } public static ServiceManagerListenerOnServiceFailedToStartParams deserialize(org.chromium.mojo.bindings.Message message) { return decode(new org.chromium.mojo.bindings.Decoder(message)); } /** * Similar to the method above, but deserializes from a |ByteBuffer| instance. * * @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure. */ public static ServiceManagerListenerOnServiceFailedToStartParams deserialize(java.nio.ByteBuffer data) { return deserialize(new org.chromium.mojo.bindings.Message( data, new java.util.ArrayList<org.chromium.mojo.system.Handle>())); } @SuppressWarnings("unchecked") public static ServiceManagerListenerOnServiceFailedToStartParams decode(org.chromium.mojo.bindings.Decoder decoder0) { if (decoder0 == null) { return null; } decoder0.increaseStackDepth(); ServiceManagerListenerOnServiceFailedToStartParams result; try { org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY); final int elementsOrVersion = mainDataHeader.elementsOrVersion; result = new ServiceManagerListenerOnServiceFailedToStartParams(elementsOrVersion); { org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false); result.identity = Identity.decode(decoder1); } } finally { decoder0.decreaseStackDepth(); } return result; } @SuppressWarnings("unchecked") @Override protected final void encode(org.chromium.mojo.bindings.Encoder encoder) { org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); encoder0.encode(this.identity, 8, false); } } static final class ServiceManagerListenerOnServiceStoppedParams extends org.chromium.mojo.bindings.Struct { private static final int STRUCT_SIZE = 16; private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)}; private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0]; public Identity identity; private ServiceManagerListenerOnServiceStoppedParams(int version) { super(STRUCT_SIZE, version); } public ServiceManagerListenerOnServiceStoppedParams() { this(0); } public static ServiceManagerListenerOnServiceStoppedParams deserialize(org.chromium.mojo.bindings.Message message) { return decode(new org.chromium.mojo.bindings.Decoder(message)); } /** * Similar to the method above, but deserializes from a |ByteBuffer| instance. * * @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure. */ public static ServiceManagerListenerOnServiceStoppedParams deserialize(java.nio.ByteBuffer data) { return deserialize(new org.chromium.mojo.bindings.Message( data, new java.util.ArrayList<org.chromium.mojo.system.Handle>())); } @SuppressWarnings("unchecked") public static ServiceManagerListenerOnServiceStoppedParams decode(org.chromium.mojo.bindings.Decoder decoder0) { if (decoder0 == null) { return null; } decoder0.increaseStackDepth(); ServiceManagerListenerOnServiceStoppedParams result; try { org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY); final int elementsOrVersion = mainDataHeader.elementsOrVersion; result = new ServiceManagerListenerOnServiceStoppedParams(elementsOrVersion); { org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false); result.identity = Identity.decode(decoder1); } } finally { decoder0.decreaseStackDepth(); } return result; } @SuppressWarnings("unchecked") @Override protected final void encode(org.chromium.mojo.bindings.Encoder encoder) { org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO); encoder0.encode(this.identity, 8, false); } } }
package org.aksw.commons.converters; import com.google.common.base.Converter; public class CastConverter<I, O> extends Converter<I, O> { @SuppressWarnings("unchecked") @Override protected O doForward(I a) { return (O)a; } @SuppressWarnings("unchecked") @Override protected I doBackward(O b) { return (I)b; } }
/* * ==================================================================== * 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.poi.xslf.usermodel.tutorial; import org.apache.poi.xslf.usermodel.SlideLayout; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.apache.poi.xslf.usermodel.XSLFSlideLayout; import org.apache.poi.xslf.usermodel.XSLFSlideMaster; import org.apache.poi.xslf.usermodel.XSLFTextShape; import java.io.FileOutputStream; /** * Create slides from pre-defined slide layouts */ public class Step2 { public static void main(String[] args) throws Exception{ XMLSlideShow ppt = new XMLSlideShow(); // first see what slide layouts are available by default System.out.println("Available slide layouts:"); for(XSLFSlideMaster master : ppt.getSlideMasters()){ for(XSLFSlideLayout layout : master.getSlideLayouts()){ System.out.println(layout.getType()); } } // blank slide /*XSLFSlide blankSlide =*/ ppt.createSlide(); XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0); // title slide XSLFSlideLayout titleLayout = defaultMaster.getLayout(SlideLayout.TITLE); XSLFSlide slide1 = ppt.createSlide(titleLayout); XSLFTextShape title1 = slide1.getPlaceholder(0); title1.setText("First Title"); // title and content XSLFSlideLayout titleBodyLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); XSLFSlide slide2 = ppt.createSlide(titleBodyLayout); XSLFTextShape title2 = slide2.getPlaceholder(0); title2.setText("Second Title"); XSLFTextShape body2 = slide2.getPlaceholder(1); body2.clearText(); // unset any existing text body2.addNewTextParagraph().addNewTextRun().setText("First paragraph"); body2.addNewTextParagraph().addNewTextRun().setText("Second paragraph"); body2.addNewTextParagraph().addNewTextRun().setText("Third paragraph"); FileOutputStream out = new FileOutputStream("step2.pptx"); ppt.write(out); out.close(); ppt.close(); } }
package com.lglab.goutam.simple_cms.connection; /** * This class in charge to fill the status updater */ public class StatusUpdater implements Runnable { private volatile boolean cancelled; private LGConnectionManager lgConnectionManager; StatusUpdater(LGConnectionManager lgConnectionManager) { this.lgConnectionManager = lgConnectionManager; } public void run() { try { while (!cancelled) { lgConnectionManager.tick(); Thread.sleep(200L); //TICKS every 200ms } } catch (InterruptedException ignored) { } } public void cancel() { cancelled = true; } }
package com.raizlabs.android.dbflow; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.structure.BaseModel; /** * Description: */ @Table(databaseName = "SecondApp") public class SecondModel extends BaseModel { @Column @PrimaryKey String name; }
/* * Copyright (c) 2016 André Mion * * 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.andremion.music; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.TypedArray; import android.transition.Transition; import android.transition.TransitionValues; import android.util.AttributeSet; import android.util.Property; import android.view.ViewGroup; import com.andremion.music.cover.R; import java.util.ArrayList; import java.util.List; public class MusicCoverViewTransition extends Transition { private static final String PROPNAME_RADIUS = MusicCoverViewTransition.class.getName() + ":radius"; private static final String PROPNAME_ALPHA = MusicCoverViewTransition.class.getName() + ":alpha"; private static final String[] sTransitionProperties = {PROPNAME_RADIUS, PROPNAME_ALPHA}; private static final Property<MusicCoverView, Float> RADIUS_PROPERTY = new Property<MusicCoverView, Float>(Float.class, "radius") { @Override public void set(MusicCoverView view, Float radius) { view.setTransitionRadius(radius); } @Override public Float get(MusicCoverView view) { return view.getTransitionRadius(); } }; private static final Property<MusicCoverView, Integer> ALPHA_PROPERTY = new Property<MusicCoverView, Integer>(Integer.class, "alpha") { @Override public void set(MusicCoverView view, Integer alpha) { view.setTransitionAlpha(alpha); } @Override public Integer get(MusicCoverView view) { return view.getTransitionAlpha(); } }; private final int mStartShape; public MusicCoverViewTransition(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MusicCoverView); int shape = a.getInt(R.styleable.MusicCoverView_shape, MusicCoverView.SHAPE_RECTANGLE); a.recycle(); mStartShape = shape; } public MusicCoverViewTransition(int shape) { mStartShape = shape; } @Override public String[] getTransitionProperties() { return sTransitionProperties; } @Override public void captureStartValues(TransitionValues transitionValues) { // Add fake value to force calling of createAnimator method captureValues(transitionValues, "start"); } @Override public void captureEndValues(TransitionValues transitionValues) { // Add fake value to force calling of createAnimator method captureValues(transitionValues, "end"); } private void captureValues(TransitionValues transitionValues, Object value) { if (transitionValues.view instanceof MusicCoverView) { transitionValues.values.put(PROPNAME_RADIUS, value); transitionValues.values.put(PROPNAME_ALPHA, value); } } @Override public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) { if (endValues == null || !(endValues.view instanceof MusicCoverView)) { return null; } MusicCoverView coverView = (MusicCoverView) endValues.view; final float minRadius = coverView.getMinRadius(); final float maxRadius = coverView.getMaxRadius(); final float fixRadius = coverView.getFixRadius(); float startRadius = 0.00f; float endRadius = 0.00f; int startTrackAlpha = 0; int endTrackAlpha = 0; if (MusicCoverView.SHAPE_CIRCLE == mStartShape) { startRadius = minRadius; endRadius = maxRadius; startTrackAlpha = MusicCoverView.ALPHA_OPAQUE; endTrackAlpha = MusicCoverView.ALPHA_TRANSPARENT; } else if (MusicCoverView.SHAPE_RECTANGLE == mStartShape) { startRadius = maxRadius; endRadius = minRadius; startTrackAlpha = MusicCoverView.ALPHA_TRANSPARENT; endTrackAlpha = MusicCoverView.ALPHA_OPAQUE; } else if (MusicCoverView.SHAPE_SQUARE == mStartShape) { startRadius = fixRadius; endRadius = fixRadius; if (!coverView.getTransitionSquareAsCircle()) { startTrackAlpha = MusicCoverView.ALPHA_OPAQUE; endTrackAlpha = MusicCoverView.ALPHA_TRANSPARENT; } else { startTrackAlpha = MusicCoverView.ALPHA_TRANSPARENT; endTrackAlpha = MusicCoverView.ALPHA_OPAQUE; } } List<Animator> animatorList = new ArrayList<>(); coverView.setTransitionRadius(startRadius); animatorList.add(ObjectAnimator.ofFloat(coverView, RADIUS_PROPERTY, startRadius, endRadius)); coverView.setTransitionAlpha(startTrackAlpha); animatorList.add(ObjectAnimator.ofInt(coverView, ALPHA_PROPERTY, startTrackAlpha, endTrackAlpha)); AnimatorSet animator = new AnimatorSet(); animator.playTogether(animatorList); return animator; } }
/* * Copyright (C) 2011 Thomas Akehurst * * 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.tomakehurst.wiremock.http; import com.github.tomakehurst.wiremock.core.Options; public interface HttpServerFactory { HttpServer buildHttpServer( Options options, AdminRequestHandler adminRequestHandler, StubRequestHandler stubRequestHandler ); }
/* * This file is part of spiget-java-client, licensed under the MIT License (MIT). * * Copyright (c) 2022 Pasqual K. and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dev.derklaro.spiget.request.resource; import dev.derklaro.spiget.Request; import dev.derklaro.spiget.SpigetClient; import dev.derklaro.spiget.annotation.RequestData; import dev.derklaro.spiget.data.Sort; import dev.derklaro.spiget.model.Resource; import java.util.Set; import java.util.concurrent.CompletableFuture; import lombok.Data; import lombok.NonNull; import lombok.experimental.Accessors; @Data @Accessors(fluent = true, chain = true) @RequestData(uri = "resources/new", method = "GET") public final class NewResourceList implements Request<Set<Resource>> { private final transient SpigetClient client; private int size; private int page; private Sort sort; private Set<String> fields; @Override public @NonNull CompletableFuture<Set<Resource>> exec() { return this.client.sendRequest(this); } }
/* * 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 sm.net.calc.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * * @author shahzadmasud */ @Entity public class PriceUnit implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String description; public PriceUnit(String name) { this.name = name; } public PriceUnit(Long id, String name, String desc) { this.id = id; this.name = name; this.description = desc; } public PriceUnit() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return description; } public void setDesc(String desc) { this.description = desc; } }
package org.apache.maven.wagon; /* * 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 org.apache.maven.wagon.resource.Resource; import java.io.OutputStream; /** * @author <a href="mailto:michal@codehaus.org">Michal Maczka</a> * */ public class OutputData { private OutputStream outputStream; private Resource resource; public OutputStream getOutputStream() { return outputStream; } public void setOutputStream( OutputStream outputStream ) { this.outputStream = outputStream; } public Resource getResource() { return resource; } public void setResource( Resource resource ) { this.resource = resource; } }
// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.cf; import com.android.tools.r8.NeverInline; import com.android.tools.r8.NoMethodStaticizing; import com.android.tools.r8.R8TestRunResult; import com.android.tools.r8.TestBase; import com.android.tools.r8.TestParameters; import com.android.tools.r8.TestParametersCollection; import com.android.tools.r8.ToolHelper; import com.android.tools.r8.utils.StringUtils; import java.nio.file.Path; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class MissingClassJoinsToObjectTest extends TestBase { static final String EXPECTED = StringUtils.lines("A::foo"); private final TestParameters parameters; @Parameterized.Parameters(name = "{0}") public static TestParametersCollection data() { return getTestParameters().withAllRuntimes().withAllApiLevels().build(); } public MissingClassJoinsToObjectTest(TestParameters parameters) { this.parameters = parameters; } private List<Path> getRuntimeClasspath() throws Exception { return buildOnDexRuntime(parameters, ToolHelper.getClassFileForTestClass(B.class)); } @Test public void testReference() throws Exception { testForRuntime(parameters) .addProgramClasses(TestClass.class, A.class, B.class) .run(parameters.getRuntime(), TestClass.class) .assertSuccessWithOutput(EXPECTED); } @Test public void testR8() throws Exception { R8TestRunResult result = testForR8(parameters.getBackend()) .enableInliningAnnotations() .addProgramClasses(TestClass.class, A.class) .addKeepMainRule(TestClass.class) .addDontWarn(B.class) .enableNoMethodStaticizingAnnotations() .setMinApi(parameters.getApiLevel()) .compile() .addRunClasspathFiles(getRuntimeClasspath()) .run(parameters.getRuntime(), TestClass.class); if (parameters.isCfRuntime()) { // TODO(b/154792347): The analysis of types in the presence of undefined is incomplete. result.assertFailureWithErrorThatThrows(VerifyError.class); } else { result.assertSuccessWithOutput(EXPECTED); } } static class A { @NeverInline @NoMethodStaticizing public void foo() { System.out.println("A::foo"); } } // Missing at compile time. static class B extends A { // Intentionally empty. } static class TestClass { public static void main(String[] args) { // Due to the missing class B, the join is assigned Object. A join = args.length == 0 ? new A() : new B(); // The call to Object::foo fails. join.foo(); } } }
package test; import cz.mg.collections.Collection; import cz.mg.collections.array.Array; import cz.mg.toolkit.component.controls.spinners.IntegerSpinner; import cz.mg.toolkit.event.events.*; import cz.mg.toolkit.graphics.designer.Designer; import cz.mg.toolkit.graphics.designer.StructuredDesigner; import cz.mg.toolkit.graphics.designer.designers.DesignersLocation; import cz.mg.toolkit.graphics.designer.loader.task.DesignerLoader; import cz.mg.toolkit.layout.layouts.*; import cz.mg.toolkit.component.window.*; import cz.mg.toolkit.component.contents.*; import cz.mg.toolkit.component.Container; import cz.mg.toolkit.component.containers.*; import cz.mg.toolkit.component.wrappers.*; import cz.mg.toolkit.component.controls.*; import cz.mg.toolkit.component.controls.buttons.*; import cz.mg.toolkit.component.controls.menuitems.*; import cz.mg.toolkit.component.controls.sliders.horizontal.*; import cz.mg.toolkit.component.controls.sliders.vertical.*; import cz.mg.toolkit.component.wrappers.decorations.SystemDecoration; import cz.mg.toolkit.component.wrappers.decorations.ToolkitDecoration; import cz.mg.toolkit.utilities.Debug; import cz.mg.toolkit.environment.device.devices.Keyboard; import cz.mg.toolkit.event.adapters.*; import cz.mg.toolkit.graphics.*; import cz.mg.toolkit.graphics.images.BitmapImage; import cz.mg.toolkit.impl.Impl; import cz.mg.toolkit.impl.swing.SwingImplApi; import cz.mg.toolkit.layout.layouts.GridLayout.Column; import cz.mg.toolkit.utilities.shapes.OvalShape; import cz.mg.toolkit.utilities.SelectionGroup; import cz.mg.toolkit.utilities.keyboardshortcuts.StandardKeyboardCharacterShortcut; import java.io.IOException; import static cz.mg.toolkit.utilities.properties.SimplifiedPropertiesInterface.*; import cz.mg.toolkit.utilities.sizepolices.*; import cz.mg.toolkit.utilities.text.textarrangements.MultilineTextArrangement; public class ToolkitTest { private static boolean DEBUG = false; public static void main(String[] args) throws IOException { Impl.setImplApi(new SwingImplApi()); Impl.getImplApi().getPrimaryDisplay().setPhysicalWidth(312); Impl.getImplApi().getPrimaryDisplay().setPhysicalHeight(178); Window.defaultDesigner = loadDesigner(); TextContent label; SelectionGroup selectionGroup = new SelectionGroup(); MenuItem m1 = new StandardMenuItem(new BitmapImage(ToolkitTest2.class.getResourceAsStream("mg.png")), "yay", new StandardKeyboardCharacterShortcut(true, false, false, 's'), null, null); MenuItem m2 = new StandardMenuItem(null, "nayyyyyyyyyyyyyyyyyyyyyy", null, true, null); MenuItem m3 = new SeparatorMenuItem(); MenuItem m4 = new StandardMenuItem(null, "option 1", null, false, selectionGroup); MenuItem m5 = new StandardMenuItem(null, "option 2", null, false, selectionGroup); MenuItem m6 = new StandardMenuItem(null, "option 3", null, false, selectionGroup); ContextMenu contextMenu = new ContextMenu(); contextMenu.getMenu().getItems().addLast(m1); contextMenu.getMenu().getItems().addLast(m2); contextMenu.getMenu().getItems().addLast(m3); contextMenu.getMenu().getItems().addLast(m4); contextMenu.getMenu().getItems().addLast(m5); contextMenu.getMenu().getItems().addLast(m6); contextMenu.getMenu().updateComponents(); Window window = new Window(); window.setSize(180, 140); window.setTitle("Yay!"); window.setIcon(new BitmapImage(ToolkitTest2.class.getResourceAsStream("mg.png"))); window.center(); PonyDialog ponyDialog = new PonyDialog(window); window.getEventListeners().addLast(new KeyboardButtonAdapter() { @Override public void onKeyboardButtonEventEnter(KeyboardButtonEvent e) { if(!wasButtonPressed(e)) return; if(e.getLogicalButton() == Keyboard.Button.F1) window.setDecorated(!window.isDecorated()); if(e.getLogicalButton() == Keyboard.Button.F1) window.setDecoration(new SystemDecoration()); if(e.getLogicalButton() == Keyboard.Button.F2) { window.setDecoration(new ToolkitDecoration()); } if(e.getLogicalButton() == Keyboard.Button.F3) ; if(e.getLogicalButton() == Keyboard.Button.F4) ; if(e.getLogicalButton() == Keyboard.Button.F5) ; if(e.getLogicalButton() == Keyboard.Button.F6) ; if(e.getLogicalButton() == Keyboard.Button.F7) window.setMinimized(true); if(e.getLogicalButton() == Keyboard.Button.F8) window.setMaximized(!window.isMaximized()); if(e.getLogicalButton() == Keyboard.Button.F9) {setDebug(window); setDebug(contextMenu);} if(e.getLogicalButton() == Keyboard.Button.F10) {setDebug(window); setDebug(contextMenu);} window.relayout(); } }); window.getEventListeners().addLast(new LocalMouseButtonAdapter() { @Override public void onMouseButtonEventLeave(MouseButtonEvent e) { if(wasPressed(e) && wasRightButton(e)){ contextMenu.open(); contextMenu.setX(e.getMouse().getScreenX()); contextMenu.setY(e.getMouse().getScreenY()); } } }); Container windowPanel = window.getContentPanel(); windowPanel.setLayout(new VerticalLayout()); CompactHorizontalScrollArea tabsArea = new CompactHorizontalScrollArea(); tabsArea.setParent(windowPanel); Container bigTextContainer = tabsArea.getContentPanel(); setDesignName(bigTextContainer, "big text container"); bigTextContainer.setLayout(new HorizontalLayout()); int n = 5; for(int i = 0; i <= n; i++){ label = new TextContent(i + "" + i + "" + i + "" + i + "" + i); setDesignName(label, "big text content"); label.setParent(bigTextContainer); if(i < n){ bigTextContainer.getChildren().addLast(new HorizontalSeparator()); } } ScrollArea scrollArea = new ScrollArea(); scrollArea.setParent(windowPanel); setHorizontalContentAlignment(scrollArea.getContentPanel(), 0.5); Panel v1 = new Panel(); setDesignName(v1, "page panel"); v1.setLayout(new VerticalLayout()); v1.setParent(scrollArea.getContentPanel()); LayoutPanel h0 = new LayoutPanel(); h0.setLayout(new HorizontalLayout()); h0.setParent(v1); setHorizontalSizePolicy(h0, new WrapAndFillSizePolicy()); TextButton tb = new TextButton(); tb.getTextContent().setText("Pony"); tb.setParent(h0); setSizePolicy(tb, new WrapContentSizePolicy()); tb.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { e.consume(); ponyDialog.open(); } }); ImageButton ib = new ImageButton(); ib.getImageContent().setImage(new BitmapImage(ToolkitTest2.class.getResourceAsStream("mg.png"))); ib.setParent(h0); setSizePolicy(ib, new NoSizePolicy()); setFixedSize(ib, 64*3/10, 24*3/10); ib.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { e.consume(); System.out.println("Image button!"); } }); TextInput ti = new TextInput(); setSizePolicy(ti, new NoSizePolicy()); setMinWidth(ti, 0*3/10); setMaxWidth(ti, 160*3/10); setMinHeight(ti, 64*3/10); setMaxHeight(ti, 64*3/10); ti.setParent(h0); ti.getTextContent().setText("Try typing here!"); ti.getTextContent().getPlaceholderTextModel().setTextArrangement(new MultilineTextArrangement()); TextContent alignmentTest = new TextContent("Yay!"); alignmentTest.setParent(h0); setSizePolicy(alignmentTest, new FillParentSizePolicy()); setContentAlignment(alignmentTest, 0.5); LayoutPanel h1 = new LayoutPanel(); h1.setLayout(new HorizontalLayout()); h1.setParent(v1); setHorizontalSizePolicy(h1, new WrapAndFillSizePolicy()); label = new TextContent("Lorem ipsum 1"); label.setParent(h1); label = new TextContent("Lorem ipsum 2"); label.setParent(h1); label = new TextContent("Lorem ipsum 3"); label.setParent(h1); LayoutPanel h2 = new LayoutPanel(); h2.setLayout(new HorizontalLayout()); h2.setParent(v1); setHorizontalAlignment(h2, 1.0); label = new TextContent("Lorem ipsum 4"); label.setParent(h2); label = new TextContent("Lorem ipsum 5"); label.setParent(h2); label = new TextContent("Lorem ipsum 6"); label.setParent(h2); label = new TextContent("Lorem ipsum 7"); label.getEventListeners().addLast(new LocalMouseButtonAdapter() { @Override public void onMouseButtonEventLeave(MouseButtonEvent e) { if(!e.wasPressed() || !wasLeftButton(e)) return; e.consume(); System.out.println("Lucky!"); } }); label.setParent(h2); LayoutPanel h4 = new LayoutPanel(); h4.setLayout(new HorizontalLayout()); h4.setParent(v1); label = new TextContent("Lorem ipsum 8"); label.setParent(h4); label = new TextContent("Lorem ipsum 9999999999999999999999999999999999999999999999999999"); label.setParent(h4); OvalButton ovalButton = new OvalButton(); setShape(ovalButton, new OvalShape()); setSizePolicy(ovalButton, new NoSizePolicy()); setFixedSize(ovalButton, 64*2*3/10, 32*2*3/10); ovalButton.setParent(v1); setForeground(ovalButton, null); SingleSelectionList<Pony> listOfPonies = new SingleSelectionList<>(); listOfPonies.setItems(PONIES); listOfPonies.setParent(v1); listOfPonies.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { e.consume(); System.out.println("Your favourite pony in a list is " + listOfPonies.getSelectedItem()); } }); MultipleSelectionList<Pony> anotherListOfPonies = new MultipleSelectionList<>(); anotherListOfPonies.setItems(PONIES); anotherListOfPonies.setParent(v1); anotherListOfPonies.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { e.consume(); System.out.println("Your favurite ponies in a list are " + anotherListOfPonies.getSelectedItems().toString(", ")); } }); IntegerSpinner integerSpinner = new IntegerSpinner(); integerSpinner.setParent(v1); integerSpinner.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { e.consume(); System.out.println("Integer: " + integerSpinner.getValue() + " ;; " + e.getSource().getClass().getSimpleName()); } }); // // LongSpinner longSpinner = new LongSpinner(); // longSpinner.setParent(v1); // longSpinner.getEventListeners().addLast(new ActionAdapter() { // @Override // public void onEventEnter(ActionEvent e) { // System.out.println("Long: " + longSpinner.getValue()); // } // }); // // FloatSpinner floatSpinner = new FloatSpinner(); // floatSpinner.setParent(v1); // floatSpinner.getEventListeners().addLast(new ActionAdapter() { // @Override // public void onEventEnter(ActionEvent e) { // System.out.println("Float: " + floatSpinner.getValue()); // } // }); // // DoubleSpinner doubleSpinner = new DoubleSpinner(); // doubleSpinner.setParent(v1); // doubleSpinner.getEventListeners().addLast(new ActionAdapter() { // @Override // public void onEventEnter(ActionEvent e) { // System.out.println("Double: " + doubleSpinner.getValue()); // } // }); IntegerHorizontalSlider ihs = new IntegerHorizontalSlider(0, 10, -10); ihs.setParent(v1); ihs.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { System.out.println("Sl-Integer: " + ihs.getValue()); } }); LongHorizontalSlider lhs = new LongHorizontalSlider(0L, 10L, -10L); lhs.setParent(v1); lhs.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { System.out.println("Sl-Long: " + lhs.getValue()); } }); FloatHorizontalSlider fhs = new FloatHorizontalSlider(0.0f, -10.0f, 10.0f); fhs.setParent(v1); fhs.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { System.out.println("Sl-Float: " + fhs.getValue()); } }); DoubleHorizontalSlider dhs = new DoubleHorizontalSlider(0.0, -10.0, 10.0); dhs.setParent(v1); dhs.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { System.out.println("Sl-Double: " + dhs.getValue()); } }); LayoutPanel vvp = new LayoutPanel(); setHorizontalSizePolicy(vvp, new WrapContentSizePolicy()); setVerticalSizePolicy(vvp, new NoSizePolicy()); setFixedHeight(vvp, 256*3/10); vvp.setLayout(new HorizontalLayout()); vvp.setParent(v1); IntegerVerticalSlider ivs = new IntegerVerticalSlider(0, -10, 10); ivs.setParent(vvp); ivs.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { System.out.println("Slv-Integer: " + ivs.getValue()); } }); LongVerticalSlider lvs = new LongVerticalSlider(0L, -10L, 10L); lvs.setParent(vvp); lvs.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { System.out.println("Slv-Long: " + lvs.getValue()); } }); FloatVerticalSlider fvs = new FloatVerticalSlider(0.0f, 10.0f, -10.0f); fvs.setParent(vvp); fvs.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { System.out.println("Slv-Float: " + fvs.getValue()); } }); DoubleVerticalSlider dvs = new DoubleVerticalSlider(0.0, 10.0, -10.0); dvs.setParent(vvp); dvs.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { System.out.println("Slv-Double: " + dvs.getValue()); } }); TextInput mti = new TextInput(); setSizePolicy(mti, new NoSizePolicy()); setFixedSize(mti, 128*3/10, 64*3/10); mti.getTextContent().getPlaceholderTextModel().setText("Yay!\nYaay!\nYaaay!"); mti.setParent(v1); mti.getTextContent().setText("Twilight Sparkle\nRarity\nFluttershy\nRainbow Dash\nApplejack\nPinkie Pie"); // // InteractiveTextContent mtc = new InteractiveTextContent("Twilight Sparkle\nRarity\nFluttershy\nRainbow Dash\nApplejack\nPinkie Pie"); // mtc.setParent(v1); // mtc.setEditable(true); // setHorizontalContentAlignment(mtc, 0.5); LayoutPanel grid = new LayoutPanel(); // setPadding(grid, 8); GridLayout gridLayout = new GridLayout(3, 35); grid.setLayout(gridLayout); grid.setParent(v1); // setVerticalSpacing(grid, 8); setHorizontalSizePolicy(grid, new WrapAndFillSizePolicy()); for(Column column : gridLayout.getColumns()){ setHorizontalSizePolicy(column, new FillParentSizePolicy()); } for(int i = 0; i < 80; i++){ int x = i % 3; int y = i / 3; label = new TextContent("Lorem ipsum i " + i); label.setParent(grid); setHorizontalAlignment(label, 0.5); setCell(label, x, y); if(i == 42) setHidden(label, true); if(i == 43) setHidden(label, true); if(i == 44) setHidden(label, true); } Debug.setIds(window); window.redesign(); window.open(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private static class OvalButton extends Button { public OvalButton() { getEventListeners().addLast(new GraphicsDrawAdapter() { @Override public void onDrawEventLeave(Graphics g) { g.setColor(Color.WHITE); g.drawOval(0, 0, getWidth(), getHeight()); } }); getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { e.consume(); System.out.println("Clicked oval!!!"); } }); } } private static class PonyDialog extends DialogWindow { private ComboBox<Pony> boxOfPonies; public PonyDialog(Window parent) { super(parent); initComponent(); initComponents(); getEventListeners().addLast(new KeyboardButtonAdapter() { @Override public void onKeyboardButtonEventEnter(KeyboardButtonEvent e) { if(e.wasPressed() && e.getLogicalButton() == Keyboard.Button.F9) {setDebug(PonyDialog.this);} } }); } private void initComponent(){ setSize(640, 320); center(); setLayout(new OverlayLayout()); } private void initComponents(){ boxOfPonies = new ComboBox<>(); boxOfPonies.setItems(PONIES); boxOfPonies.setParent(getContentPanel()); boxOfPonies.getEventListeners().addLast(new ActionAdapter() { @Override public void onEventEnter(ActionEvent e) { e.consume(); System.out.println("Your favourite pony in a box is " + boxOfPonies.getSelectedItem()); } }); } } public static void setDebug(Window window){ if(!DEBUG) Debug.setIds(window); if(!DEBUG) Debug.setMouseButtonPrintInfo(window); Debug.sendRandomColors(window); window.redraw(); DEBUG = true; Debug.printComponentInfo(window); } private static class Pony { private final String name; public Pony(String name) { this.name = name; } @Override public String toString() { return name; } } private static Collection<Pony> PONIES = new Array<>(new Pony[]{ new Pony("Twilight Sparkle"), new Pony("Rainbow Dash"), new Pony("Pinkie Pie"), new Pony("Rarity"), new Pony("Applejack"), new Pony("Fluttershy") }); private static Designer loadDesigner(){ DesignerLoader loader = new DesignerLoader(); StructuredDesigner designer = (StructuredDesigner) loader.load( DesignersLocation.class.getResourceAsStream("DefaultDesigner"), ToolkitTest.class.getResourceAsStream("ToolkitTestDesigner") ); System.out.println("LOADED DESIGNS: " + designer.getDesigns().count()); return designer; } }
/* * Copyright (c) 2004-2012, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @author bobj */ @XmlSchema( namespace = "http://dhis2.org/schema/dxf/2.0", xmlns = { @XmlNs(namespaceURI = "http://dhis2.org/schema/dxf/2.0", prefix = "d") }, elementFormDefault = XmlNsForm.QUALIFIED) package org.hisp.dhis.hierarchy; import javax.xml.bind.annotation.XmlSchema; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm;
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.query; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Collector; import org.apache.lucene.search.EarlyTerminatingSortingCollector; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MultiCollector; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TotalHitCountCollector; import org.apache.lucene.search.Weight; import org.elasticsearch.common.lucene.MinimumScoreCollector; import org.elasticsearch.common.lucene.search.FilteredCollector; import org.elasticsearch.search.profile.query.InternalProfileCollector; import org.elasticsearch.tasks.TaskCancelledException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.IntSupplier; import static org.elasticsearch.search.profile.query.CollectorResult.REASON_SEARCH_CANCELLED; import static org.elasticsearch.search.profile.query.CollectorResult.REASON_SEARCH_MIN_SCORE; import static org.elasticsearch.search.profile.query.CollectorResult.REASON_SEARCH_MULTI; import static org.elasticsearch.search.profile.query.CollectorResult.REASON_SEARCH_POST_FILTER; import static org.elasticsearch.search.profile.query.CollectorResult.REASON_SEARCH_TERMINATE_AFTER_COUNT; import static org.elasticsearch.search.query.TopDocsCollectorContext.shortcutTotalHitCount; abstract class QueryCollectorContext { private String profilerName; QueryCollectorContext(String profilerName) { this.profilerName = profilerName; } /** * Creates a collector that delegates documents to the provided <code>in</code> collector. * @param in The delegate collector */ abstract Collector create(Collector in) throws IOException; /** * Wraps this collector with a profiler */ protected InternalProfileCollector createWithProfiler(InternalProfileCollector in) throws IOException { final Collector collector = create(in); return new InternalProfileCollector(collector, profilerName, in != null ? Collections.singletonList(in) : Collections.emptyList()); } /** * A value of <code>false</code> indicates that the underlying collector can infer * its results directly from the context (search is not needed). * Default to true (search is needed). */ boolean shouldCollect() { return true; } /** * Post-process <code>result</code> after search execution. * * @param result The query search result to populate * @param hasCollected True if search was executed */ void postProcess(QuerySearchResult result, boolean hasCollected) throws IOException {} /** * Creates the collector tree from the provided <code>collectors</code> * @param collectors Ordered list of collector context */ static Collector createQueryCollector(List<QueryCollectorContext> collectors) throws IOException { Collector collector = null; for (QueryCollectorContext ctx : collectors) { collector = ctx.create(collector); } return collector; } /** * Creates the collector tree from the provided <code>collectors</code> and wraps each collector with a profiler * @param collectors Ordered list of collector context */ static InternalProfileCollector createQueryCollectorWithProfiler(List<QueryCollectorContext> collectors) throws IOException { InternalProfileCollector collector = null; for (QueryCollectorContext ctx : collectors) { collector = ctx.createWithProfiler(collector); } return collector; } /** * Filters documents with a query score greater than <code>minScore</code> * @param minScore The minimum score filter */ static QueryCollectorContext createMinScoreCollectorContext(float minScore) { return new QueryCollectorContext(REASON_SEARCH_MIN_SCORE) { @Override Collector create(Collector in) { return new MinimumScoreCollector(in, minScore); } }; } /** * Filters documents based on the provided <code>query</code> */ static QueryCollectorContext createFilteredCollectorContext(IndexSearcher searcher, Query query) { return new QueryCollectorContext(REASON_SEARCH_POST_FILTER) { @Override Collector create(Collector in ) throws IOException { final Weight filterWeight = searcher.createNormalizedWeight(query, false); return new FilteredCollector(in, filterWeight); } }; } /** * Creates a multi collector from the provided <code>subs</code> */ static QueryCollectorContext createMultiCollectorContext(Collection<Collector> subs) { return new QueryCollectorContext(REASON_SEARCH_MULTI) { @Override Collector create(Collector in) throws IOException { List<Collector> subCollectors = new ArrayList<> (); subCollectors.add(in); subCollectors.addAll(subs); return MultiCollector.wrap(subCollectors); } @Override protected InternalProfileCollector createWithProfiler(InternalProfileCollector in) throws IOException { final List<InternalProfileCollector> subCollectors = new ArrayList<> (); subCollectors.add(in); if (subs.stream().anyMatch((col) -> col instanceof InternalProfileCollector == false)) { throw new IllegalArgumentException("non-profiling collector"); } for (Collector collector : subs) { subCollectors.add((InternalProfileCollector) collector); } final Collector collector = MultiCollector.wrap(subCollectors); return new InternalProfileCollector(collector, REASON_SEARCH_MULTI, subCollectors); } }; } /** * Creates a collector that throws {@link TaskCancelledException} if the search is cancelled */ static QueryCollectorContext createCancellableCollectorContext(BooleanSupplier cancelled) { return new QueryCollectorContext(REASON_SEARCH_CANCELLED) { @Override Collector create(Collector in) throws IOException { return new CancellableCollector(cancelled, in); } @Override boolean shouldCollect() { return false; } }; } /** * Creates collector limiting the collection to the first <code>numHits</code> documents */ static QueryCollectorContext createEarlyTerminationCollectorContext(int numHits) { return new QueryCollectorContext(REASON_SEARCH_TERMINATE_AFTER_COUNT) { private EarlyTerminatingCollector collector; @Override Collector create(Collector in) throws IOException { assert collector == null; this.collector = new EarlyTerminatingCollector(in, numHits); return collector; } @Override void postProcess(QuerySearchResult result, boolean hasCollected) throws IOException { if (hasCollected && collector.terminatedEarly()) { result.terminatedEarly(true); } } }; } /** * Creates a sorting termination collector limiting the collection to the first <code>numHits</code> per segment. * The total hit count matching the query is also computed if <code>trackTotalHits</code> is true. */ static QueryCollectorContext createEarlySortingTerminationCollectorContext(IndexReader reader, Query query, Sort indexSort, int numHits, boolean trackTotalHits, boolean shouldCollect) { return new QueryCollectorContext(REASON_SEARCH_TERMINATE_AFTER_COUNT) { private BooleanSupplier terminatedEarlySupplier; private IntSupplier countSupplier = null; @Override Collector create(Collector in) throws IOException { EarlyTerminatingSortingCollector sortingCollector = new EarlyTerminatingSortingCollector(in, indexSort, numHits); terminatedEarlySupplier = sortingCollector::terminatedEarly; Collector collector = sortingCollector; if (trackTotalHits) { int count = shouldCollect ? -1 : shortcutTotalHitCount(reader, query); if (count == -1) { TotalHitCountCollector countCollector = new TotalHitCountCollector(); collector = MultiCollector.wrap(sortingCollector, countCollector); this.countSupplier = countCollector::getTotalHits; } else { this.countSupplier = () -> count; } } return collector; } @Override void postProcess(QuerySearchResult result, boolean hasCollected) throws IOException { if (terminatedEarlySupplier.getAsBoolean()) { result.terminatedEarly(true); } if (countSupplier != null) { final TopDocs topDocs = result.topDocs(); topDocs.totalHits = countSupplier.getAsInt(); result.topDocs(topDocs, result.sortValueFormats()); } } }; } }
/* * Copyright 2019 Uriah Shaul Mandel * * 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.bald.uriah.baldphone.databases.calls; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.CallLog; import android.provider.ContactsContract; import com.bald.uriah.baldphone.BuildConfig; import com.bald.uriah.baldphone.adapters.CallsRecyclerViewAdapter; import com.bald.uriah.baldphone.databases.contacts.Contact; import java.util.ArrayList; import java.util.List; import java.util.Locale; import static android.provider.CallLog.Calls.IS_READ; import static android.provider.CallLog.Calls.NEW; import static android.provider.CallLog.Calls.TYPE; /** * Simple Helper to get the call log. */ public class CallLogsHelper { public static List<Call> getAllCalls(ContentResolver contentResolver) { try (Cursor cursor = contentResolver.query(CallLog.Calls.CONTENT_URI, Call.PROJECTION, null, null, CallLog.Calls.DATE + " DESC")) { final List<Call> calls = new ArrayList<>(cursor.getCount()); while (cursor.moveToNext()) { calls.add(new Call(cursor)); } return calls; } catch (SecurityException e) { throw new RuntimeException(e); } } public static List<Call> getForSpecificContact(ContentResolver contentResolver, Contact contact) { if (BuildConfig.FLAVOR.equals("gPlay")) return new ArrayList<>(); final Uri contactUri = ContactsContract.Contacts.getLookupUri(contact.getId(), contact.getLookupKey()); try (Cursor cursor = contentResolver.query(CallLog.Calls.CONTENT_URI, Call.PROJECTION, CallLog.Calls.CACHED_LOOKUP_URI + "=?", new String[]{contactUri.toString()}, CallLog.Calls.DATE + " DESC")) { final List<Call> calls = new ArrayList<>(cursor.getCount()); while (cursor.moveToNext()) { calls.add(new Call(cursor)); } return calls; } catch (SecurityException e) { throw new RuntimeException(e); } } public static void markAllAsRead(ContentResolver contentResolver) { final ContentValues values = new ContentValues(); values.put(IS_READ, true); values.put(CallLog.Calls.NEW, false); try { contentResolver.update(CallLog.Calls.CONTENT_URI, values, null, null); } catch (Exception e) { throw new RuntimeException(e); } } public static boolean isAllReadSafe(ContentResolver contentResolver) { try (final Cursor cursor = contentResolver.query(CallLog.Calls.CONTENT_URI, new String[]{TYPE, IS_READ, NEW}, String.format(Locale.US, "%s=0 AND %s=1 AND %s=%d", IS_READ, NEW, TYPE, CallsRecyclerViewAdapter.MISSED_TYPE), null, null)) { return cursor.getCount() == 0; } catch (SecurityException ignore) { return true; } } }
package com.example.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ReimbDbConnection { private final String URL = "jdbc:postgresql://rev-can-training.cevrrymkkbmb.us-east-2.rds.amazonaws.com:5432/project1db"; private final String USERNAME="project1user"; private final String PASSWORD= "passgyvyutkykfyg/uhoihouiyuftdryxgfchgygut7ir68dtgjkgut7i6tfujkug/iy.w0rd"; public Connection getDbConnection() throws SQLException{ try { Class.forName("org.postgresql.Driver").newInstance(); return DriverManager.getConnection(URL, USERNAME, PASSWORD); }catch(Exception e) { e.printStackTrace(); } return DriverManager.getConnection(URL, USERNAME, PASSWORD); } }
package com.sequenceiq.it.cloudbreak.newway; import com.sequenceiq.cloudbreak.api.model.DirectoryType; import com.sequenceiq.cloudbreak.api.model.ldap.LdapConfigRequest; import javax.annotation.Nonnull; import javax.validation.constraints.NotEmpty; import java.util.Optional; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.ADMIN_GROUP; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.BIND_DN; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.BIND_PASSWORD; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.DIRECTORY_TYPE; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.GROUP_MEMBER_ATTRIBUTE; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.GROUP_NAME_ATTRIBUTE; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.GROUP_OBJECT_CLASS; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.GROUP_SEARCH_BASE; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.LDAP_CONFIG_NAME; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.LDAP_DOMAIN; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.SERVER_HOST; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.SERVER_PORT; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.SERVER_PROTOCOL; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.USER_DN_PATTERN; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.USER_NAME_ATTRIBUTE; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.USER_OBJECT_CLASS; import static com.sequenceiq.it.cloudbreak.parameters.RequiredInputParameters.Ldap.USER_SEARCH_BASE; public class LdapConfigRequestDataCollector { private LdapConfigRequestDataCollector() { } public static LdapConfigRequest createLdapRequestWithProperties(TestParameter testParameter) { return createLdapRequestWithPropertiesAndName(testParameter, getParam(LDAP_CONFIG_NAME, testParameter)); } public static LdapConfigRequest createLdapRequestWithPropertiesAndName(TestParameter testParameter, @Nonnull @NotEmpty String name) { LdapConfigRequest request = new LdapConfigRequest(); request.setServerHost(getParam(SERVER_HOST, testParameter)); request.setServerPort(Integer.parseInt(getParam(SERVER_PORT, testParameter))); request.setBindDn(getParam(BIND_DN, testParameter)); request.setBindPassword(getParam(BIND_PASSWORD, testParameter)); request.setUserSearchBase(getParam(USER_SEARCH_BASE, testParameter)); request.setUserNameAttribute(getParam(USER_NAME_ATTRIBUTE, testParameter)); request.setUserDnPattern(getParam(USER_DN_PATTERN, testParameter)); request.setUserObjectClass(getParam(USER_OBJECT_CLASS, testParameter)); request.setGroupSearchBase(getParam(GROUP_SEARCH_BASE, testParameter)); request.setGroupNameAttribute(getParam(GROUP_NAME_ATTRIBUTE, testParameter)); request.setGroupObjectClass(getParam(GROUP_OBJECT_CLASS, testParameter)); request.setGroupMemberAttribute(getParam(GROUP_MEMBER_ATTRIBUTE, testParameter)); request.setName(name); request.setAdminGroup(getParam(ADMIN_GROUP, testParameter)); request.setDirectoryType(DirectoryType.valueOf(getParam(DIRECTORY_TYPE, testParameter))); request.setProtocol(getParam(SERVER_PROTOCOL, testParameter)); request.setDomain(getParam(LDAP_DOMAIN, testParameter)); return request; } private static String getParam(String key, TestParameter testParameter) { return Optional.ofNullable(testParameter.get(key)).orElseThrow(() -> new MissingExpectedParameterException(key)); } }