text
stringlengths
7
1.01M
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package resultsearch; import java.sql.*; /** * * @author sherif */ public class Connect { private static String [][] ResultArray ; private static int NumOfCols ; private static int NumOfRows ; public static Connection con; public static boolean testConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); // String connectionUrl = "jdbc:mysql://198.71.227.83:3306/mbanoun_?" + // "user=root&password=root1234&useUnicode=yes&characterEncoding=UTF-8"; String connectionUrl = "jdbc:mysql://212.24.107.233:3306/admin_mu?" + "user=admin_mu&password=asas123&useUnicode=yes&characterEncoding=UTF-8"; con = DriverManager.getConnection(connectionUrl); return con.isValid(5); } public static String[][] Conn(String Query,boolean Insert) { // TODO code application logic here // String Result=""; try { Class.forName("com.mysql.jdbc.Driver"); String connectionUrl = "jdbc:mysql://212.24.107.233:3306/admin_mu?" + "user=admin_mu&password=asas123&useUnicode=yes&characterEncoding=UTF-8"; con = DriverManager.getConnection(connectionUrl); Statement stmt = null; stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = null; if(Insert) { stmt = con.createStatement(); int rowsEffected = stmt.executeUpdate(Query); System.out.println(rowsEffected + " rows effected"); ResultArray = new String [1][1]; ResultArray[0][0]=String.valueOf(rowsEffected); return ResultArray; } else { stmt = con.createStatement(); rs = stmt.executeQuery(Query); ResultSetMetaData rsmd = rs.getMetaData(); NumOfCols = rsmd.getColumnCount(); rs.last(); NumOfRows = rs.getRow(); rs.beforeFirst(); ResultArray = new String [NumOfRows][NumOfCols]; // System.out.println(NumOfRows); // System.out.println(NumOfCols); while (rs.next()) { for(int j = 1 ; j <= NumOfCols ; j++) { // System.out.println(rs.getString(j)); ResultArray [rs.getRow()-1][j-1] = rs.getString(j); } } } } catch (SQLException e) { System.out.println("SQL Exception: "+ e.toString()); System.out.println("SQL CAUSED THE PROBLEM :" + Query); } catch (ClassNotFoundException cE) { System.out.println("Class Not Found Exception: "+ cE.toString()); } return ResultArray; } public static String GetResultArray(int row , int col) { return ResultArray [row][col]; } public static String[][] GetResultArray() { return ResultArray; } public static void SetResultArray(String Arr[][]) { ResultArray = Arr ; } }
package sktest.ling.persistence.entity.sql.mysql; import lombok.ToString; import lombok.experimental.Accessors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.shaneking.ling.persistence.entity.sql.mysql.MysqlSqlEntities; import org.shaneking.ling.test.SKUnit; import org.shaneking.ling.zero.lang.String0; import org.shaneking.ling.zero.time.ZDT0; import org.shaneking.ling.zero.util.UUID0; import sktest.ling.persistence.entity.sql.AbstractDialectSqlEntityPrepare1; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import java.io.IOException; import java.nio.file.Files; import static org.junit.jupiter.api.Assertions.assertEquals; public class MysqlSqlEntityTest extends SKUnit { String dateTimeSssZone = ZDT0.on().dTSZ(); String id = UUID0.cUl33(); String userId = UUID0.cUl33(); MysqlSqlEntityPrepare1 mysqlSqlEntityPrepare1 = new MysqlSqlEntityPrepare1(); @BeforeEach void beforeEach() { mysqlSqlEntityPrepare1.setHasLength("hasLength").setNoGetMethod("noGetMethod").setNotNullCol("notNullCol").setUniqueCol("uniqueCol").setWithoutAnnotation("withoutAnnotation").setReName("reName").setLongText("longText"); // mysqlIdAdtVerEntity.setVersion(1).setLastModifyDateTime(ZDT0.on().dateTimesZone()).setLastModifyUserId(userId).setInvalid(String0.N).setId(id); mysqlSqlEntityPrepare1.initWithUidAndId(userId, id); mysqlSqlEntityPrepare1.setLmDsz(dateTimeSssZone); } @Test void createTableAndIndexIfNotExistSql() throws IOException { Files.write(tstOFiles().toPath(), mysqlSqlEntityPrepare1.createTableAndIndexIfNotExistSql().getBytes()); assertEquals(String.join(String0.BR_LINUX, Files.readAllLines(tstOFiles().toPath())), mysqlSqlEntityPrepare1.createTableAndIndexIfNotExistSql().trim()); } @Test void testToString() { // assertEquals("{\"id\":\"" + id + "\",\"ivd\":\"N\",\"lmDsz\":\"" + dateTime + "\",\"lmUid\":\"" + userId + "\",\"ver\":0,\"hasLength\":\"hasLength\",\"notNullCol\":\"notNullCol\",\"uniqueCol\":\"uniqueCol\",\"withoutAnnotation\":\"withoutAnnotation\",\"reName\":\"reName\",\"longText\":\"longText\"}", OM3.writeValueAsString(mysqlIdAdtVerEntity)); assertEquals("MysqlSqlEntityTest.MysqlSqlEntityPrepare1(super=AbstractDialectSqlEntityPrepare1(super=AbstractDialectSqlEntity(id=" + id + ", ver=0, dd=N, ivd=N, lmDsz=" + dateTimeSssZone + ", lmUid=" + userId + ", no=" + id + "), hasLength=hasLength, noGetMethod=noGetMethod, notNullCol=notNullCol, uniqueCol=uniqueCol, withoutAnnotation=withoutAnnotation, reName=reName, longText=longText))", mysqlSqlEntityPrepare1.toString()); } @Accessors(chain = true) @Table(schema = "sktest1_schema", name = "sktest1_table", uniqueConstraints = {@UniqueConstraint(columnNames = {"has_length", "not_null_col"})}) @ToString(callSuper = true) public static class MysqlSqlEntityPrepare1 extends AbstractDialectSqlEntityPrepare1 implements MysqlSqlEntities { } }
package wusc.edu.pay.core.cost.biz.cal; import java.util.List; import wusc.edu.pay.core.cost.biz.CalFeeRateFormulaBiz; import wusc.edu.pay.facade.cost.entity.CalFeeRateFormula; import wusc.edu.pay.facade.cost.entity.CalFeeWay; import wusc.edu.pay.facade.cost.exceptions.CostBizException; /** * 计费成本 * * @author yzyue * */ public interface BankCost { /** * <pre> * 根据计费约束获取计费公式 * 由于免计费订单、包年和事后计费订单均不需要获取计费公式, * 而单笔、区间和阶梯类型的订单需要查询计费公式,故在此接口中定 * 义此方法。 * </pre> * @param formulaBiz 计费公式的业务处理类 * @param calFeeWay 计费约束 * @return */ public List<CalFeeRateFormula> getFormula(CalFeeRateFormulaBiz formulaBiz, CalFeeWay calFeeWay) throws CostBizException; /** * 根据计费公式计算成本 * @param formulas 计费公式 * * @return */ public boolean calculate(List<CalFeeRateFormula> formulas) throws CostBizException; /** * <pre> * 保存计费流量信息 * 只有阶梯计费类型的订单才涉及到计费流量,才需要保存计费流量。 * </pre> * @return * @throws CostBizException */ public boolean saveFlowInfo() throws CostBizException; }
/** * 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.fineract.portfolio.loanproduct; import java.math.BigDecimal; public interface LoanProductConstants { public static final String useBorrowerCycleParameterName = "useBorrowerCycle"; public static final String principalVariationsForBorrowerCycleParameterName = "principalVariationsForBorrowerCycle"; public static final String interestRateVariationsForBorrowerCycleParameterName = "interestRateVariationsForBorrowerCycle"; public static final String numberOfRepaymentVariationsForBorrowerCycleParameterName = "numberOfRepaymentVariationsForBorrowerCycle"; public static final String defaultValueParameterName = "defaultValue"; public static final String minValueParameterName = "minValue"; public static final String maxValueParameterName = "maxValue"; public static final String valueConditionTypeParamName = "valueConditionType"; public static final String borrowerCycleNumberParamName = "borrowerCycleNumber"; public static final String borrowerCycleIdParameterName = "id"; public static final String principalPerCycleParameterName = "principalPerCycle"; public static final String minPrincipalPerCycleParameterName = "minPrincipalPerCycle"; public static final String maxPrincipalPerCycleParameterName = "maxPrincipalPerCycle"; public static final String principalValueUsageConditionParamName = "principalValueUsageCondition"; public static final String principalCycleNumbersParamName = "principalCycleNumbers"; public static final String numberOfRepaymentsPerCycleParameterName = "numberOfRepaymentsPerCycle"; public static final String minNumberOfRepaymentsPerCycleParameterName = "minNumberOfRepaymentsPerCycle"; public static final String maxNumberOfRepaymentsPerCycleParameterName = "maxNumberOfRepaymentsPerCycle"; public static final String repaymentValueUsageConditionParamName = "repaymentValueUsageCondition"; public static final String repaymentCycleNumberParamName = "repaymentCycleNumber"; public static final String interestRatePerPeriodPerCycleParameterName = "interestRatePerPeriodPerCycle"; public static final String minInterestRatePerPeriodPerCycleParameterName = "minInterestRatePerPeriodPerCycle"; public static final String maxInterestRatePerPeriodPerCycleParameterName = "maxInterestRatePerPeriodPerCycle"; public static final String interestRateValueUsageConditionParamName = "interestRateValueUsageCondition"; public static final String interestRateCycleNumberParamName = "interestRateCycleNumber"; public static final String principal = "principal"; public static final String minPrincipal = "minPrincipal"; public static final String maxPrincipal = "maxPrincipalValue"; public static final String interestRatePerPeriod = "interestRatePerPeriod"; public static final String minInterestRatePerPeriod = "minInterestRatePerPeriod"; public static final String maxInterestRatePerPeriod = "maxInterestRatePerPeriod"; public static final String numberOfRepayments = "numberOfRepayments"; public static final String minNumberOfRepayments = "minNumberOfRepayments"; public static final String maxNumberOfRepayments = "maxNumberOfRepayments"; public static final String VALUE_CONDITION_END_WITH_ERROR = "condition.type.must.end.with.greterthan"; public static final String VALUE_CONDITION_START_WITH_ERROR = "condition.type.must.start.with.equal"; public static final String shortName = "shortName"; public static final String multiDisburseLoanParameterName = "multiDisburseLoan"; public static final String maxTrancheCountParameterName = "maxTrancheCount"; public static final String outstandingLoanBalanceParameterName = "outstandingLoanBalance"; public static final String graceOnArrearsAgeingParameterName = "graceOnArrearsAgeing"; public static final String overdueDaysForNPAParameterName = "overdueDaysForNPA"; public static final String minimumDaysBetweenDisbursalAndFirstRepayment = "minimumDaysBetweenDisbursalAndFirstRepayment"; public static final String accountMovesOutOfNPAOnlyOnArrearsCompletionParamName = "accountMovesOutOfNPAOnlyOnArrearsCompletion"; // Interest recalculation related public static final String isInterestRecalculationEnabledParameterName = "isInterestRecalculationEnabled"; public static final String daysInYearTypeParameterName = "daysInYearType"; public static final String daysInMonthTypeParameterName = "daysInMonthType"; public static final String interestRecalculationCompoundingMethodParameterName = "interestRecalculationCompoundingMethod"; public static final String rescheduleStrategyMethodParameterName = "rescheduleStrategyMethod"; public static final String recalculationRestFrequencyTypeParameterName = "recalculationRestFrequencyType"; public static final String recalculationRestFrequencyIntervalParameterName = "recalculationRestFrequencyInterval"; public static final String recalculationRestFrequencyWeekdayParamName = "recalculationRestFrequencyDayOfWeekType"; public static final String recalculationRestFrequencyNthDayParamName = "recalculationRestFrequencyNthDayType"; public static final String recalculationRestFrequencyOnDayParamName = "recalculationRestFrequencyOnDayType"; public static final String isArrearsBasedOnOriginalScheduleParamName = "isArrearsBasedOnOriginalSchedule"; public static final String preClosureInterestCalculationStrategyParamName = "preClosureInterestCalculationStrategy"; public static final String recalculationCompoundingFrequencyTypeParameterName = "recalculationCompoundingFrequencyType"; public static final String recalculationCompoundingFrequencyIntervalParameterName = "recalculationCompoundingFrequencyInterval"; public static final String recalculationCompoundingFrequencyWeekdayParamName = "recalculationCompoundingFrequencyDayOfWeekType"; public static final String recalculationCompoundingFrequencyNthDayParamName = "recalculationCompoundingFrequencyNthDayType"; public static final String recalculationCompoundingFrequencyOnDayParamName = "recalculationCompoundingFrequencyOnDayType"; public static final String isCompoundingToBePostedAsTransactionParamName = "isCompoundingToBePostedAsTransaction"; // Guarantee related public static final String holdGuaranteeFundsParamName = "holdGuaranteeFunds"; public static final String mandatoryGuaranteeParamName = "mandatoryGuarantee"; public static final String minimumGuaranteeFromOwnFundsParamName = "minimumGuaranteeFromOwnFunds"; public static final String minimumGuaranteeFromGuarantorParamName = "minimumGuaranteeFromGuarantor"; public static final String principalThresholdForLastInstallmentParamName = "principalThresholdForLastInstallment"; public static final BigDecimal DEFAULT_PRINCIPAL_THRESHOLD_FOR_MULTI_DISBURSE_LOAN = BigDecimal.valueOf(50); public static final BigDecimal DEFAULT_PRINCIPAL_THRESHOLD_FOR_SINGLE_DISBURSE_LOAN = BigDecimal.valueOf(0); // Fixed installment configuration related public static final String canDefineEmiAmountParamName = "canDefineInstallmentAmount"; public static final String installmentAmountInMultiplesOfParamName = "installmentAmountInMultiplesOf"; //Loan Configurable Attributes public static final String allowAttributeOverridesParamName = "allowAttributeOverrides"; public static final String amortizationTypeParamName = "amortizationType"; public static final String interestTypeParamName = "interestType"; public static final String transactionProcessingStrategyIdParamName = "transactionProcessingStrategyId"; public static final String interestCalculationPeriodTypeParamName = "interestCalculationPeriodType"; public static final String inArrearsToleranceParamName = "inArrearsTolerance"; public static final String repaymentEveryParamName = "repaymentEvery"; public static final String graceOnPrincipalAndInterestPaymentParamName = "graceOnPrincipalAndInterestPayment"; public static final String allowCompoundingOnEodParamName = "allowCompoundingOnEod"; //Variable Installments Settings public static final String allowVariableInstallmentsParamName = "allowVariableInstallments" ; public static final String minimumGapBetweenInstallments = "minimumGap" ; public static final String maximumGapBetweenInstallments = "maximumGap" ; public static final String allowPartialPeriodInterestCalcualtionParamName = "allowPartialPeriodInterestCalcualtion"; }
// Copyright 2017 JanusGraph 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.janusgraph.graphdb.embedded; import org.janusgraph.CassandraStorageSetup; import org.janusgraph.diskstorage.configuration.WriteConfiguration; import org.janusgraph.graphdb.JanusGraphEventualGraphTest; import org.janusgraph.graphdb.JanusGraphPartitionGraphTest; import org.junit.BeforeClass; public class EmbeddedPartitionGraphTest extends JanusGraphPartitionGraphTest { @BeforeClass public static void startEmbeddedCassandra() { CassandraStorageSetup.startCleanEmbedded(); } @Override public WriteConfiguration getBaseConfiguration() { return CassandraStorageSetup.getEmbeddedCassandraPartitionGraphConfiguration(getClass().getSimpleName()); } }
package com.orientechnologies.orient.core.metadata.schema; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener; import com.orientechnologies.orient.core.db.ODatabaseListener; import com.orientechnologies.orient.core.db.viewmanager.ViewCreationListener; import com.orientechnologies.orient.core.exception.OSchemaException; import com.orientechnologies.orient.core.metadata.security.ORole; import com.orientechnologies.orient.core.metadata.security.ORule; import com.orientechnologies.orient.core.record.impl.ODocument; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** Created by tglman on 13/06/17. */ public class OSchemaRemote extends OSchemaShared { private AtomicBoolean skipPush = new AtomicBoolean(false); public OSchemaRemote() { super(); } @Override public OClass getOrCreateClass( ODatabaseDocumentInternal database, String iClassName, OClass... superClasses) { if (iClassName == null) return null; acquireSchemaReadLock(); try { OClass cls = classes.get(iClassName.toLowerCase(Locale.ENGLISH)); if (cls != null) return cls; } finally { releaseSchemaReadLock(); } OClass cls; int[] clusterIds = null; acquireSchemaWriteLock(database); try { cls = classes.get(iClassName.toLowerCase(Locale.ENGLISH)); if (cls != null) return cls; cls = createClass(database, iClassName, clusterIds, superClasses); addClusterClassMap(cls); } finally { releaseSchemaWriteLock(database); } return cls; } protected OClassImpl createClassInstance(ODocument c) { return new OClassRemote(this, c, (String) c.field("name")); } protected OViewImpl createViewInstance(ODocument c) { return new OViewRemote(this, c, (String) c.field("name")); } public OClass createClass( ODatabaseDocumentInternal database, final String className, int[] clusterIds, OClass... superClasses) { final Character wrongCharacter = OSchemaShared.checkClassNameIfValid(className); if (wrongCharacter != null) throw new OSchemaException( "Invalid class name found. Character '" + wrongCharacter + "' cannot be used in class name '" + className + "'"); OClass result; database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_CREATE); if (superClasses != null) OClassImpl.checkParametersConflict(Arrays.asList(superClasses)); acquireSchemaWriteLock(database); try { final String key = className.toLowerCase(Locale.ENGLISH); if (classes.containsKey(key)) throw new OSchemaException("Class '" + className + "' already exists in current database"); checkClustersAreAbsent(clusterIds); StringBuilder cmd = new StringBuilder("create class "); cmd.append('`'); cmd.append(className); cmd.append('`'); List<OClass> superClassesList = new ArrayList<OClass>(); if (superClasses != null && superClasses.length > 0) { boolean first = true; for (OClass superClass : superClasses) { // Filtering for null if (superClass != null) { if (first) cmd.append(" extends "); else cmd.append(", "); cmd.append('`').append(superClass.getName()).append('`'); first = false; superClassesList.add(superClass); } } } if (clusterIds != null) { if (clusterIds.length == 1 && clusterIds[0] == -1) cmd.append(" abstract"); else { cmd.append(" cluster "); for (int i = 0; i < clusterIds.length; ++i) { if (i > 0) cmd.append(','); else cmd.append(' '); cmd.append(clusterIds[i]); } } } database.command(cmd.toString()).close(); reload(database); result = classes.get(className.toLowerCase(Locale.ENGLISH)); // WAKE UP DB LIFECYCLE LISTENER for (Iterator<ODatabaseLifecycleListener> it = Orient.instance().getDbLifecycleListeners(); it.hasNext(); ) it.next().onCreateClass(database, result); for (Iterator<ODatabaseListener> it = database.getListeners().iterator(); it.hasNext(); ) it.next().onCreateClass(database, result); } finally { releaseSchemaWriteLock(database); } return result; } public OClass createClass( ODatabaseDocumentInternal database, final String className, int clusters, OClass... superClasses) { final Character wrongCharacter = OSchemaShared.checkClassNameIfValid(className); if (wrongCharacter != null) throw new OSchemaException( "Invalid class name found. Character '" + wrongCharacter + "' cannot be used in class name '" + className + "'"); OClass result; database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_CREATE); if (superClasses != null) OClassImpl.checkParametersConflict(Arrays.asList(superClasses)); acquireSchemaWriteLock(database); try { final String key = className.toLowerCase(Locale.ENGLISH); if (classes.containsKey(key)) throw new OSchemaException("Class '" + className + "' already exists in current database"); StringBuilder cmd = new StringBuilder("create class "); cmd.append('`'); cmd.append(className); cmd.append('`'); List<OClass> superClassesList = new ArrayList<OClass>(); if (superClasses != null && superClasses.length > 0) { boolean first = true; for (OClass superClass : superClasses) { // Filtering for null if (superClass != null) { if (first) cmd.append(" extends "); else cmd.append(", "); cmd.append(superClass.getName()); first = false; superClassesList.add(superClass); } } } if (clusters == 0) cmd.append(" abstract"); else { cmd.append(" clusters "); cmd.append(clusters); } database.command(cmd.toString()).close(); reload(database); result = classes.get(className.toLowerCase(Locale.ENGLISH)); // WAKE UP DB LIFECYCLE LISTENER for (Iterator<ODatabaseLifecycleListener> it = Orient.instance().getDbLifecycleListeners(); it.hasNext(); ) it.next().onCreateClass(database, result); for (Iterator<ODatabaseListener> it = database.getListeners().iterator(); it.hasNext(); ) it.next().onCreateClass(database, result); } finally { releaseSchemaWriteLock(database); } return result; } public OView createView( ODatabaseDocumentInternal database, OViewConfig cfg, ViewCreationListener listener) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public OView createView(ODatabaseDocumentInternal database, OViewConfig cfg) { final Character wrongCharacter = OSchemaShared.checkClassNameIfValid(cfg.getName()); if (wrongCharacter != null) throw new OSchemaException( "Invalid view name found. Character '" + wrongCharacter + "' cannot be used in view name '" + cfg.getName() + "'"); OView result; database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_CREATE); acquireSchemaWriteLock(database); try { final String key = cfg.getName().toLowerCase(Locale.ENGLISH); if (views.containsKey(key)) throw new OSchemaException( "View '" + cfg.getName() + "' already exists in current database"); StringBuilder cmd = new StringBuilder("create view "); cmd.append('`'); cmd.append(cfg.getName()); cmd.append('`'); cmd.append(" FROM (" + cfg.getQuery() + ") "); if (cfg.isUpdatable()) { cmd.append(" UPDATABLE"); } // TODO METADATA!!! database.command(cmd.toString()).close(); reload(database); result = views.get(cfg.getName().toLowerCase(Locale.ENGLISH)); // WAKE UP DB LIFECYCLE LISTENER for (Iterator<ODatabaseLifecycleListener> it = Orient.instance().getDbLifecycleListeners(); it.hasNext(); ) it.next().onCreateView(database, result); for (Iterator<ODatabaseListener> it = database.getListeners().iterator(); it.hasNext(); ) it.next().onCreateView(database, result); } finally { releaseSchemaWriteLock(database); } return result; } @Override public OView createView( ODatabaseDocumentInternal database, String name, String statement, Map<String, Object> metadata) { final Character wrongCharacter = OSchemaShared.checkClassNameIfValid(name); if (wrongCharacter != null) throw new OSchemaException( "Invalid class name found. Character '" + wrongCharacter + "' cannot be used in view name '" + name + "'"); OView result; database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_CREATE); acquireSchemaWriteLock(database); try { final String key = name.toLowerCase(Locale.ENGLISH); if (views.containsKey(key)) throw new OSchemaException("View '" + name + "' already exists in current database"); StringBuilder cmd = new StringBuilder("create view "); cmd.append('`'); cmd.append(name); cmd.append('`'); cmd.append(" FROM (" + statement + ") "); // if (metadata!=null) {//TODO // cmd.append(" METADATA"); // } database.command(cmd.toString()).close(); reload(database); result = views.get(name.toLowerCase(Locale.ENGLISH)); // WAKE UP DB LIFECYCLE LISTENER for (Iterator<ODatabaseLifecycleListener> it = Orient.instance().getDbLifecycleListeners(); it.hasNext(); ) it.next().onCreateView(database, result); for (Iterator<ODatabaseListener> it = database.getListeners().iterator(); it.hasNext(); ) it.next().onCreateView(database, result); } finally { releaseSchemaWriteLock(database); } return result; } private void checkClustersAreAbsent(final int[] iClusterIds) { if (iClusterIds == null) return; for (int clusterId : iClusterIds) { if (clusterId < 0) continue; if (clustersToClasses.containsKey(clusterId)) throw new OSchemaException( "Cluster with id " + clusterId + " already belongs to class " + clustersToClasses.get(clusterId)); } } public void dropClass(ODatabaseDocumentInternal database, final String className) { acquireSchemaWriteLock(database); try { if (database.getTransaction().isActive()) throw new IllegalStateException("Cannot drop a class inside a transaction"); if (className == null) throw new IllegalArgumentException("Class name is null"); database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE); final String key = className.toLowerCase(Locale.ENGLISH); OClass cls = classes.get(key); if (cls == null) throw new OSchemaException("Class '" + className + "' was not found in current database"); if (!cls.getSubclasses().isEmpty()) throw new OSchemaException( "Class '" + className + "' cannot be dropped because it has sub classes " + cls.getSubclasses() + ". Remove the dependencies before trying to drop it again"); final StringBuilder cmd = new StringBuilder("drop class `"); cmd.append(className); cmd.append("` unsafe"); database.command(cmd.toString()).close(); reload(database); // FREE THE RECORD CACHE database.getLocalCache().freeCluster(cls.getDefaultClusterId()); } finally { releaseSchemaWriteLock(database); } } public void dropView(ODatabaseDocumentInternal database, final String name) { acquireSchemaWriteLock(database); try { if (database.getTransaction().isActive()) throw new IllegalStateException("Cannot drop a class inside a transaction"); if (name == null) throw new IllegalArgumentException("View name is null"); database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE); final String key = name.toLowerCase(Locale.ENGLISH); OClass cls = views.get(key); if (cls == null) throw new OSchemaException("View '" + name + "' was not found in current database"); if (!cls.getSubclasses().isEmpty()) throw new OSchemaException( "View '" + name + "' cannot be dropped because it has sub classes " + cls.getSubclasses() + ". Remove the dependencies before trying to drop it again"); final StringBuilder cmd = new StringBuilder("drop view "); cmd.append(name); cmd.append(" unsafe"); database.command(cmd.toString()).close(); reload(database); // FREE THE RECORD CACHE database.getLocalCache().freeCluster(cls.getDefaultClusterId()); } finally { releaseSchemaWriteLock(database); } } @Override public void acquireSchemaWriteLock(ODatabaseDocumentInternal database) { skipPush.set(true); } @Override public void releaseSchemaWriteLock(ODatabaseDocumentInternal database, final boolean iSave) { skipPush.set(false); } @Override public void checkEmbedded() { throw new OSchemaException( "'Internal' schema modification methods can be used only inside of embedded database"); } public void update(ODocument schema) { if (!skipPush.get()) { this.document = schema; super.fromStream(); this.snapshot = null; } } @Override public int addBlobCluster(ODatabaseDocumentInternal database, int clusterId) { throw new OSchemaException( "Not supported operation use instead ODatabaseSession.addBlobCluster"); } @Override public void removeBlobCluster(ODatabaseDocumentInternal database, String clusterName) { throw new OSchemaException("Not supported operation use instead ODatabaseSession.dropCluster"); } }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.cscore.UsbCamera; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.CommandScheduler; /** * The VM is configured to automatically run this class, and to call the functions corresponding to * each mode, as described in the TimedRobot documentation. If you change the name of this class or * the package after creating this project, you must also update the build.gradle file in the * project. */ public class Robot extends TimedRobot { private Command m_autonomousCommand; private RobotContainer m_robotContainer; /** * This function is run when the robot is first started up and should be used for any * initialization code. */ @Override public void robotInit() { // Instantiate our RobotContainer. This will perform all our button bindings, and put our // autonomous chooser on the dashboard. UsbCamera camera = CameraServer.startAutomaticCapture(0); m_robotContainer = new RobotContainer(); } /** * This function is called every robot packet, no matter the mode. Use this for items like * diagnostics that you want ran during disabled, autonomous, teleoperated and test. * * <p>This runs after the mode specific periodic functions, but before LiveWindow and * SmartDashboard integrated updating. */ @Override public void robotPeriodic() { // Runs the Scheduler. This is responsible for polling buttons, adding newly-scheduled // commands, running already-scheduled commands, removing finished or interrupted commands, // and running subsystem periodic() methods. This must be called from the robot's periodic // block in order for anything in the Command-based framework to work. CommandScheduler.getInstance().run(); } /** This function is called once each time the robot enters Disabled mode. */ @Override public void disabledInit() {} @Override public void disabledPeriodic() {} /** This autonomous runs the autonomous command selected by your {@link RobotContainer} class. */ @Override public void autonomousInit() { m_autonomousCommand = m_robotContainer.getAutonomousCommand(); // schedule the autonomous command (example) if (m_autonomousCommand != null) { m_autonomousCommand.schedule(); } } /** This function is called periodically during autonomous. */ @Override public void autonomousPeriodic() {} @Override public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (m_autonomousCommand != null) { m_autonomousCommand.cancel(); } } /** This function is called periodically during operator control. */ @Override public void teleopPeriodic() {} @Override public void testInit() { // Cancels all running commands at the start of test mode. CommandScheduler.getInstance().cancelAll(); } /** This function is called periodically during test mode. */ @Override public void testPeriodic() {} }
package com.store.domain.dao.catalog; import java.util.List; import com.store.domain.model.product.Product; import com.store.domain.model.product.data.ProductCreationData; public interface ProductDao { public List<Product> create(Long userId, ProductCreationData... prodDataArray); public Product getById(Long productId); public List<Long> getProductsIds(); }
package com.rymcu.forest.wx.mp.service.impl; import com.rymcu.forest.wx.mp.service.WxMenuService; import me.chanjar.weixin.common.bean.menu.WxMenu; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.util.Scanner; /** * @author ronger */ @Service public class WxMenuServiceImpl implements WxMenuService { @Value("classpath:wxMpMenus.json") private Resource menuResource; @Override public WxMenu getMenus() throws IOException { File file = menuResource.getFile(); String menuJson = this.jsonRead(file); WxMenu wxMenu = WxMenu.fromJson(menuJson); return wxMenu; } private String jsonRead(File file) { Scanner scanner = null; StringBuilder buffer = new StringBuilder(); try { scanner = new Scanner(file, "utf-8"); while (scanner.hasNextLine()) { buffer.append(scanner.nextLine()); } } catch (Exception e) { } finally { if (scanner != null) { scanner.close(); } } return buffer.toString(); } }
package com.cmput301f21t34.habittrak.social; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import com.cmput301f21t34.habittrak.R; import com.cmput301f21t34.habittrak.user.Habit; import com.google.android.material.button.MaterialButton; import com.google.android.material.progressindicator.LinearProgressIndicator; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; /** * SocialViewHabit class for viewing the habit list of the user that the current user clicks on. * * @author Pranav */ public class SocialViewHabit extends AppCompatActivity { private Habit habit; // Views private MaterialButton mondayButton; private MaterialButton tuesdayButton; private MaterialButton wednesdayButton; private MaterialButton thursdayButton; private MaterialButton fridayButton; private MaterialButton saturdayButton; private MaterialButton sundayButton; // Other Variables private int buttonOffColor = Color.WHITE; private int tealColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_social_view_habit); int nightModeCheck = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; if (nightModeCheck == Configuration.UI_MODE_NIGHT_YES) { buttonOffColor = Color.BLACK; } // get data Intent intent = getIntent(); habit = intent.getParcelableExtra("HABIT"); String username = intent.getStringExtra("USERNAME"); // set up toolbar Toolbar toolbar = findViewById(R.id.social_view_habit_toolbar); toolbar.setTitle(username + "'s habit"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); // set views TextView name = findViewById(R.id.social_habit_name); TextView reason = findViewById(R.id.social_habit_reason); TextView date = findViewById(R.id.social_habit_date); mondayButton = findViewById(R.id.monday_button); tuesdayButton = findViewById(R.id.tuesday_button); wednesdayButton = findViewById(R.id.wednesday_button); thursdayButton = findViewById(R.id.thursday_button); fridayButton = findViewById(R.id.friday_button); saturdayButton = findViewById(R.id.saturday_button); sundayButton = findViewById(R.id.sunday_button); tealColor = ContextCompat.getColor(getBaseContext(), R.color.teal_200); TextView totalEventsCompleted = findViewById(R.id.social_view_total_events); LinearProgressIndicator progressBar = findViewById(R.id.social_view_habit_progress); TextView progressBarText = findViewById(R.id.social_view_habit_streak); TextView bestStreakStart = findViewById(R.id.social_streak_start); TextView bestStreakEnd = findViewById(R.id.social_best_streak_end); TextView bestStreakTotal = findViewById(R.id.social_best_streak_count); // set data for views name.setText(habit.getTitle()); reason.setText(habit.getReason()); date.setText(getDate(habit.getStartDate())); setDaysSelector(); totalEventsCompleted.setText(String.valueOf(habit.getHabitEvents().size())); progressBar.setProgress((habit.getCurrentStreak() * 100) / 30); String currentStreakText = habit.getCurrentStreak() + "/30"; progressBarText.setText(currentStreakText); SimpleDateFormat streakDateFormat = new SimpleDateFormat("MMM dd, yyyy"); if (habit.getBestStreakDate() == null || habit.getBestStreakDateEnd() == null) { bestStreakStart.setText("N/A"); bestStreakEnd.setText("N/A"); } else { bestStreakStart.setText(streakDateFormat.format(habit.getBestStreakDate().getTime())); bestStreakEnd.setText(streakDateFormat.format(habit.getBestStreakDateEnd().getTime())); bestStreakTotal.setText(String.valueOf(habit.getBestStreak())); } // setting listeners to null mondayButton.setOnClickListener(null); tuesdayButton.setOnClickListener(null); wednesdayButton.setOnClickListener(null); thursdayButton.setOnClickListener(null); fridayButton.setOnClickListener(null); saturdayButton.setOnClickListener(null); sundayButton.setOnClickListener(null); } /** * get the String value from calendar * * @param calendar date to convert to string * @return string value of type Month, Day */ public String getDate(Calendar calendar) { String month = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()); String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)); return month + ", " + day; } /** * setDaysSelector. * * @author Pranav * <p> * sets the state of the days of week buttons. */ public void setDaysSelector() { boolean[] daysOfWeek = habit.getOnDaysObj().getAll(); setButtonState(mondayButton, daysOfWeek[0]); setButtonState(tuesdayButton, daysOfWeek[1]); setButtonState(wednesdayButton, daysOfWeek[2]); setButtonState(thursdayButton, daysOfWeek[3]); setButtonState(fridayButton, daysOfWeek[4]); setButtonState(saturdayButton, daysOfWeek[5]); setButtonState(sundayButton, daysOfWeek[6]); } /** * setButtonState. * * @param button MaterialButton for setting state * @param state bool value for on/off state * @author Pranav * <p> * set the button on/off state */ public void setButtonState(MaterialButton button, Boolean state) { if (state) { button.setBackgroundColor(tealColor); } else { button.setBackgroundColor(buttonOffColor); } } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } }
package org.michenux.drodrolib.ui.recyclerview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; public class DividerItemDecoration extends RecyclerView.ItemDecoration { private Drawable mDivider; private boolean mShowFirstDivider = false; private boolean mShowLastDivider = false; public DividerItemDecoration(Context context, AttributeSet attrs) { final TypedArray a = context .obtainStyledAttributes(attrs, new int[]{android.R.attr.listDivider}); mDivider = a.getDrawable(0); a.recycle(); } public DividerItemDecoration(Context context, AttributeSet attrs, boolean showFirstDivider, boolean showLastDivider) { this(context, attrs); mShowFirstDivider = showFirstDivider; mShowLastDivider = showLastDivider; } public DividerItemDecoration(Drawable divider) { mDivider = divider; } public DividerItemDecoration(Drawable divider, boolean showFirstDivider, boolean showLastDivider) { this(divider); mShowFirstDivider = showFirstDivider; mShowLastDivider = showLastDivider; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); if (mDivider == null) { return; } if (parent.getChildPosition(view) < 1) { return; } if (getOrientation(parent) == LinearLayoutManager.VERTICAL) { outRect.top = mDivider.getIntrinsicHeight(); } else { outRect.left = mDivider.getIntrinsicWidth(); } } @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { if (mDivider == null) { super.onDrawOver(c, parent, state); return; } // Initialization needed to avoid compiler warning int left = 0, right = 0, top = 0, bottom = 0, size; int orientation = getOrientation(parent); int childCount = parent.getChildCount(); if (orientation == LinearLayoutManager.VERTICAL) { size = mDivider.getIntrinsicHeight(); left = parent.getPaddingLeft(); right = parent.getWidth() - parent.getPaddingRight(); } else { //horizontal size = mDivider.getIntrinsicWidth(); top = parent.getPaddingTop(); bottom = parent.getHeight() - parent.getPaddingBottom(); } for (int i = mShowFirstDivider ? 0 : 1; i < childCount; i++) { View child = parent.getChildAt(i); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (orientation == LinearLayoutManager.VERTICAL) { top = child.getTop() - params.topMargin; bottom = top + size; } else { //horizontal left = child.getLeft() - params.leftMargin; right = left + size; } mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } // show last divider if (mShowLastDivider && childCount > 0) { View child = parent.getChildAt(childCount - 1); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (orientation == LinearLayoutManager.VERTICAL) { top = child.getBottom() + params.bottomMargin; bottom = top + size; } else { // horizontal left = child.getRight() + params.rightMargin; right = left + size; } mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } private int getOrientation(RecyclerView parent) { if (parent.getLayoutManager() instanceof LinearLayoutManager) { LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager(); return layoutManager.getOrientation(); } else { throw new IllegalStateException( "DividerItemDecoration can only be used with a LinearLayoutManager."); } } }
package com.mageddo.kafka.client; import org.apache.kafka.clients.consumer.Consumer; public interface ConsumerSupplier<K, V> { Consumer<K, V> get(ConsumerCreateConfig<K, V> config); }
package uk.co.jakelee.daggerexperiments.baeldung; public class Brand { private String brand; public Brand(String brand) { this.brand = brand; } }
package com.gonzalezp.apps.androidfunwithflags; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.support.v4.app.DialogFragment; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.util.Log; import com.gonzalezp.apps.lifecyclehelpers.psgs_QuizViewModel; public class psgs_ResultsDialogFragment extends DialogFragment{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final psgs_QuizViewModel psgsQuizViewModel = ViewModelProviders.of(getActivity()).get(psgs_QuizViewModel.class); int totalGuesses = psgsQuizViewModel.getTotalGuesses(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage( getString(R.string.results, totalGuesses, (1000 / (double) totalGuesses))); builder.setPositiveButton(R.string.reset_quiz, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try{ psgs_MainActivityFragment quizFragment = (psgs_MainActivityFragment) getParentFragment(); try{ quizFragment.resetQuiz(); }catch (Exception e){ Log.e(psgsQuizViewModel.getTag(),"Unable to call resetQuiz()", e); } } catch (Exception e){ Log.e(psgsQuizViewModel.getTag(),"Unable to get ActivityMainFragment", e); } } }); return builder.create(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.edurt.gcm.redis.provider; import io.edurt.gcm.redis.client.RedisHashClient; import javax.inject.Provider; import java.util.Properties; public class RedisHashProvider extends RedisProvider implements Provider<RedisHashClient> { public RedisHashProvider(Properties configuration) { super(configuration); } @Override public RedisHashClient get() { return new RedisHashClient(this.getJedisPool()); } }
package gnu.kawa.slib; import com.google.appinventor.components.common.PropertyTypeConstants; import gnu.expr.Keyword; import gnu.expr.ModuleBody; import gnu.expr.ModuleInfo; import gnu.expr.ModuleMethod; import gnu.kawa.functions.Format; import gnu.kawa.functions.GetNamedPart; import gnu.kawa.lispexpr.LispLanguage; import gnu.kawa.models.Box; import gnu.kawa.models.Button; import gnu.kawa.models.Display; import gnu.kawa.models.Label; import gnu.kawa.models.Model; import gnu.kawa.models.Text; import gnu.kawa.models.Window; import gnu.kawa.reflect.Invoke; import gnu.kawa.reflect.SlotGet; import gnu.kawa.xml.KAttr; import gnu.lists.Consumer; import gnu.lists.LList; import gnu.lists.Pair; import gnu.lists.PairWithPosition; import gnu.mapping.CallContext; import gnu.mapping.Location; import gnu.mapping.SimpleSymbol; import gnu.mapping.ThreadLocation; import gnu.mapping.UnboundLocationException; import gnu.mapping.Values; import gnu.mapping.WrongType; import gnu.math.IntNum; import gnu.text.Path; import java.awt.Color; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import kawa.lang.Macro; import kawa.lang.SyntaxPattern; import kawa.lang.SyntaxRule; import kawa.lang.SyntaxRules; import kawa.lib.misc; import kawa.standard.Scheme; /* compiled from: gui.scm */ public class gui extends ModuleBody { public static final gui $instance = new gui(); public static final ModuleMethod Button; public static final ModuleMethod Column; public static final Macro Image = Macro.make(Lit12, Lit13, $instance); public static final ModuleMethod Label; static final Class Lit0 = Color.class; static final SimpleSymbol Lit1 = ((SimpleSymbol) new SimpleSymbol(PropertyTypeConstants.PROPERTY_TYPE_TEXT).readResolve()); static final SimpleSymbol Lit10 = ((SimpleSymbol) new SimpleSymbol("button").readResolve()); static final SimpleSymbol Lit11 = ((SimpleSymbol) new SimpleSymbol("Button").readResolve()); static final SimpleSymbol Lit12 = ((SimpleSymbol) new SimpleSymbol("Image").readResolve()); static final SyntaxRules Lit13; static final SimpleSymbol Lit14 = ((SimpleSymbol) new SimpleSymbol("image-read").readResolve()); static final SimpleSymbol Lit15 = ((SimpleSymbol) new SimpleSymbol("image-width").readResolve()); static final SimpleSymbol Lit16 = ((SimpleSymbol) new SimpleSymbol("image-height").readResolve()); static final SimpleSymbol Lit17 = ((SimpleSymbol) new SimpleSymbol("Label").readResolve()); static final SimpleSymbol Lit18 = ((SimpleSymbol) new SimpleSymbol("Text").readResolve()); static final SimpleSymbol Lit19 = ((SimpleSymbol) new SimpleSymbol("Row").readResolve()); static final SimpleSymbol Lit2 = ((SimpleSymbol) new SimpleSymbol("cell-spacing").readResolve()); static final SimpleSymbol Lit20 = ((SimpleSymbol) new SimpleSymbol("Column").readResolve()); static final SimpleSymbol Lit21 = ((SimpleSymbol) new SimpleSymbol("set-content").readResolve()); static final SimpleSymbol Lit22 = ((SimpleSymbol) new SimpleSymbol("Window").readResolve()); static final SimpleSymbol Lit23; static final SyntaxRules Lit24; static final SimpleSymbol Lit25 = ((SimpleSymbol) new SimpleSymbol("::").readResolve()); static final SimpleSymbol Lit26 = ((SimpleSymbol) new SimpleSymbol("<int>").readResolve()); static final SimpleSymbol Lit27 = ((SimpleSymbol) new SimpleSymbol("i").readResolve()); static final SimpleSymbol Lit28 = ((SimpleSymbol) new SimpleSymbol("num-args").readResolve()); static final SimpleSymbol Lit29 = ((SimpleSymbol) new SimpleSymbol("arg").readResolve()); static final SimpleSymbol Lit3 = ((SimpleSymbol) new SimpleSymbol("*.getWidth").readResolve()); static final SimpleSymbol Lit30 = ((SimpleSymbol) new SimpleSymbol("$lookup$").readResolve()); static final SimpleSymbol Lit31 = ((SimpleSymbol) new SimpleSymbol(LispLanguage.quasiquote_sym).readResolve()); static final SimpleSymbol Lit32 = ((SimpleSymbol) new SimpleSymbol("primitive-array-get").readResolve()); static final SimpleSymbol Lit33 = ((SimpleSymbol) new SimpleSymbol("<object>").readResolve()); static final SimpleSymbol Lit34 = ((SimpleSymbol) new SimpleSymbol("loop").readResolve()); static final SimpleSymbol Lit35 = ((SimpleSymbol) new SimpleSymbol("+").readResolve()); static final SimpleSymbol Lit36 = ((SimpleSymbol) new SimpleSymbol(GetNamedPart.INSTANCEOF_METHOD_NAME).readResolve()); static final SimpleSymbol Lit37 = ((SimpleSymbol) new SimpleSymbol("<gnu.kawa.xml.KAttr>").readResolve()); static final SimpleSymbol Lit38 = ((SimpleSymbol) new SimpleSymbol("attr").readResolve()); static final SimpleSymbol Lit39 = ((SimpleSymbol) new SimpleSymbol(LispLanguage.quote_sym).readResolve()); static final SimpleSymbol Lit4 = ((SimpleSymbol) new SimpleSymbol("*.getHeight").readResolve()); static final SimpleSymbol Lit40 = ((SimpleSymbol) new SimpleSymbol("getName").readResolve()); static final SimpleSymbol Lit41 = ((SimpleSymbol) new SimpleSymbol("invoke").readResolve()); static final SimpleSymbol Lit42 = ((SimpleSymbol) new SimpleSymbol("name").readResolve()); static final SimpleSymbol Lit43 = ((SimpleSymbol) new SimpleSymbol("value").readResolve()); static final IntNum Lit44 = IntNum.make(1); static final SimpleSymbol Lit5 = ((SimpleSymbol) new SimpleSymbol("<gnu.kawa.models.Row>").readResolve()); static final SimpleSymbol Lit6 = ((SimpleSymbol) new SimpleSymbol("<gnu.kawa.models.Column>").readResolve()); static final SimpleSymbol Lit7; static final SyntaxRules Lit8; static final SimpleSymbol Lit9 = ((SimpleSymbol) new SimpleSymbol("as-color").readResolve()); public static final ModuleMethod Row; public static final ModuleMethod Text; public static final ModuleMethod Window; public static final ModuleMethod as$Mncolor; public static final ModuleMethod button; public static final ModuleMethod image$Mnheight; public static final ModuleMethod image$Mnread; public static final ModuleMethod image$Mnwidth; static final Location loc$$Lsgnu$Dtkawa$Dtmodels$DtColumn$Gr = ThreadLocation.getInstance(Lit6, null); static final Location loc$$Lsgnu$Dtkawa$Dtmodels$DtRow$Gr = ThreadLocation.getInstance(Lit5, null); static final Location loc$$St$DtgetHeight = ThreadLocation.getInstance(Lit4, null); static final Location loc$$St$DtgetWidth = ThreadLocation.getInstance(Lit3, null); public static final Macro process$Mnkeywords = Macro.make(Lit7, Lit8, $instance); public static final Macro run$Mnapplication = Macro.make(Lit23, Lit24, $instance); public static final ModuleMethod set$Mncontent; static { Object[] objArr = new Object[1]; SimpleSymbol simpleSymbol = (SimpleSymbol) new SimpleSymbol("run-application").readResolve(); Lit23 = simpleSymbol; objArr[0] = simpleSymbol; SyntaxRule[] syntaxRuleArr = new SyntaxRule[1]; Object[] objArr2 = new Object[1]; objArr2[0] = PairWithPosition.make(Lit30, Pair.make((SimpleSymbol) new SimpleSymbol("gnu.kawa.models.Window").readResolve(), Pair.make(Pair.make(Lit31, Pair.make((SimpleSymbol) new SimpleSymbol("open").readResolve(), LList.Empty)), LList.Empty)), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 749575); syntaxRuleArr[0] = new SyntaxRule(new SyntaxPattern("\f\u0018\f\u0007\b", new Object[0], 1), "\u0001", "\u0011\u0018\u0004\b\u0003", objArr2, 0); Lit24 = new SyntaxRules(objArr, syntaxRuleArr, 1); Object[] objArr3 = new Object[]{(SimpleSymbol) new SimpleSymbol("text-field").readResolve()}; SyntaxRule[] syntaxRuleArr2 = new SyntaxRule[1]; syntaxRuleArr2[0] = new SyntaxRule(new SyntaxPattern("\f\u0018\u0003", new Object[0], 1), "\u0000", "\u0011\u0018\u0004\u0011\u0018\f\u0002", new Object[]{(SimpleSymbol) new SimpleSymbol("make").readResolve(), (SimpleSymbol) new SimpleSymbol("<gnu.kawa.models.DrawImage>").readResolve()}, 0); Lit13 = new SyntaxRules(objArr3, syntaxRuleArr2, 1); objArr3 = new Object[1]; simpleSymbol = (SimpleSymbol) new SimpleSymbol("process-keywords").readResolve(); Lit7 = simpleSymbol; objArr3[0] = simpleSymbol; syntaxRuleArr2 = new SyntaxRule[1]; objArr2 = new Object[27]; objArr2[0] = (SimpleSymbol) new SimpleSymbol("let").readResolve(); objArr2[1] = Lit28; objArr2[2] = Lit25; objArr2[3] = Lit26; objArr2[4] = (SimpleSymbol) new SimpleSymbol("field").readResolve(); objArr2[5] = PairWithPosition.make(PairWithPosition.make(Lit39, PairWithPosition.make((SimpleSymbol) new SimpleSymbol("length").readResolve(), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 16426), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 16426), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 16425); objArr2[6] = Lit34; objArr2[7] = PairWithPosition.make(PairWithPosition.make(Lit27, PairWithPosition.make(Lit25, PairWithPosition.make(Lit26, PairWithPosition.make(IntNum.make(0), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 20509), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 20503), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 20500), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 20497), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 20496); objArr2[8] = (SimpleSymbol) new SimpleSymbol("if").readResolve(); objArr2[9] = PairWithPosition.make((SimpleSymbol) new SimpleSymbol("<").readResolve(), PairWithPosition.make(Lit27, PairWithPosition.make(Lit28, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 24593), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 24591), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 24588); objArr2[10] = Lit29; objArr2[11] = PairWithPosition.make(Lit32, PairWithPosition.make(Lit33, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 28710), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 28689); objArr2[12] = PairWithPosition.make(Lit27, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 28725); objArr2[13] = (SimpleSymbol) new SimpleSymbol("cond").readResolve(); objArr2[14] = PairWithPosition.make(Lit36, PairWithPosition.make(Lit29, PairWithPosition.make((SimpleSymbol) new SimpleSymbol("<gnu.expr.Keyword>").readResolve(), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 32797), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 32793), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 32782); objArr2[15] = PairWithPosition.make(PairWithPosition.make(Lit30, Pair.make((SimpleSymbol) new SimpleSymbol("gnu.expr.Keyword").readResolve(), Pair.make(Pair.make(Lit31, Pair.make(Lit40, LList.Empty)), LList.Empty)), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 40970), PairWithPosition.make(Lit29, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 40995), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 40969); objArr2[16] = PairWithPosition.make(Lit32, PairWithPosition.make(Lit33, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 45087), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 45066); objArr2[17] = PairWithPosition.make(PairWithPosition.make(Lit35, PairWithPosition.make(Lit27, PairWithPosition.make(Lit44, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 45107), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 45105), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 45102), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 45102); objArr2[18] = PairWithPosition.make(PairWithPosition.make(Lit34, PairWithPosition.make(PairWithPosition.make(Lit35, PairWithPosition.make(Lit27, PairWithPosition.make(IntNum.make(2), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 49170), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 49168), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 49165), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 49165), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 49159), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 49159); objArr2[19] = PairWithPosition.make(Lit36, PairWithPosition.make(Lit29, PairWithPosition.make(Lit37, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 53270), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 53266), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 53255); objArr2[20] = (SimpleSymbol) new SimpleSymbol("let*").readResolve(); objArr2[21] = PairWithPosition.make(PairWithPosition.make(Lit38, PairWithPosition.make(Lit25, PairWithPosition.make(Lit37, PairWithPosition.make(Lit29, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 57388), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 57367), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 57364), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 57358), PairWithPosition.make(PairWithPosition.make(Lit42, PairWithPosition.make(Lit25, PairWithPosition.make((SimpleSymbol) new SimpleSymbol("<java.lang.String>").readResolve(), PairWithPosition.make(PairWithPosition.make(Lit41, PairWithPosition.make(Lit38, PairWithPosition.make(PairWithPosition.make(Lit39, PairWithPosition.make(Lit40, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61489), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61489), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61488), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61483), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61475), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61475), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61456), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61453), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61447), PairWithPosition.make(PairWithPosition.make(Lit43, PairWithPosition.make(PairWithPosition.make(Lit41, PairWithPosition.make(Lit38, PairWithPosition.make(PairWithPosition.make(Lit39, PairWithPosition.make((SimpleSymbol) new SimpleSymbol("getObjectValue").readResolve(), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 65564), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 65564), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 65563), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 65558), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 65550), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 65550), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 65543), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 65543), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 61447), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 57357); objArr2[22] = PairWithPosition.make(Lit42, PairWithPosition.make(Lit43, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 69666), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 69661); objArr2[23] = PairWithPosition.make(PairWithPosition.make(Lit34, PairWithPosition.make(PairWithPosition.make(Lit35, PairWithPosition.make(Lit27, PairWithPosition.make(Lit44, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 73746), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 73744), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 73741), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 73741), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 73735), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 73735); objArr2[24] = (SimpleSymbol) new SimpleSymbol("else").readResolve(); objArr2[25] = PairWithPosition.make(Lit29, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 81951); objArr2[26] = PairWithPosition.make(PairWithPosition.make(Lit34, PairWithPosition.make(PairWithPosition.make(Lit35, PairWithPosition.make(Lit27, PairWithPosition.make(Lit44, LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 86034), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 86032), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 86029), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 86029), "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 86023), LList.Empty, "/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 86023); syntaxRuleArr2[0] = new SyntaxRule(new SyntaxPattern("\f\u0018\f\u0007\f\u000f\f\u0017\f\u001f\b", new Object[0], 4), "\u0001\u0001\u0001\u0001", "\u0011\u0018\u0004‘\b\u0011\u0018\f\u0011\u0018\u0014\u0011\u0018\u001c\b\u0011\u0018$\t\u000b\u0018,\b\u0011\u0018\u0004\u0011\u00184\u0011\u0018<\b\u0011\u0018D\u0011\u0018L\b\u0011\u0018\u0004a\b\u0011\u0018T\b\u0011\u0018\\\t\u000b\u0018d\b\u0011\u0018l©\u0011\u0018ty\t\u0013\t\u0003\u0011\u0018|\b\u0011\u0018„\t\u000b\u0018Œ\u0018”™\u0011\u0018œi\u0011\u0018¤\u0011\u0018¬\b\t\u0013\t\u0003\u0018´\u0018¼\b\u0011\u0018Ä1\t\u001b\t\u0003\u0018Ì\u0018Ô", objArr2, 0); Lit8 = new SyntaxRules(objArr3, syntaxRuleArr2, 4); ModuleBody moduleBody = $instance; as$Mncolor = new ModuleMethod(moduleBody, 1, Lit9, 4097); button = new ModuleMethod(moduleBody, 2, Lit10, -4096); Button = new ModuleMethod(moduleBody, 3, Lit11, -4096); image$Mnread = new ModuleMethod(moduleBody, 4, Lit14, 4097); image$Mnwidth = new ModuleMethod(moduleBody, 5, Lit15, 4097); image$Mnheight = new ModuleMethod(moduleBody, 6, Lit16, 4097); Label = new ModuleMethod(moduleBody, 7, Lit17, -4096); Text = new ModuleMethod(moduleBody, 8, Lit18, -4096); Row = new ModuleMethod(moduleBody, 9, Lit19, -4096); Column = new ModuleMethod(moduleBody, 10, Lit20, -4096); set$Mncontent = new ModuleMethod(moduleBody, 11, Lit21, 8194); Window = new ModuleMethod(moduleBody, 12, Lit22, -4096); $instance.run(); } public gui() { ModuleInfo.register(this); } public final void run(CallContext $ctx) { Consumer $result = $ctx.consumer; } public static Color asColor(Object value) { if (value instanceof Color) { return (Color) value; } if (value instanceof Integer) { try { return new Color(((Integer) value).intValue()); } catch (ClassCastException e) { throw new WrongType(e, "java.lang.Integer.intValue()", 1, value); } } else if (value instanceof IntNum) { return new Color(IntNum.intValue(value)); } else { return (Color) SlotGet.staticField.apply2(Lit0, value.toString()); } } public int match1(ModuleMethod moduleMethod, Object obj, CallContext callContext) { switch (moduleMethod.selector) { case 1: callContext.value1 = obj; callContext.proc = moduleMethod; callContext.pc = 1; return 0; case 4: if (Path.coerceToPathOrNull(obj) == null) { return -786431; } callContext.value1 = obj; callContext.proc = moduleMethod; callContext.pc = 1; return 0; case 5: if (!(obj instanceof BufferedImage)) { return -786431; } callContext.value1 = obj; callContext.proc = moduleMethod; callContext.pc = 1; return 0; case 6: if (!(obj instanceof BufferedImage)) { return -786431; } callContext.value1 = obj; callContext.proc = moduleMethod; callContext.pc = 1; return 0; default: return super.match1(moduleMethod, obj, callContext); } } static Object buttonKeyword(Button button, String name, Object value) { boolean z = true; if (name == "foreground") { button.setForeground(asColor(value)); return Values.empty; } else if (name == "background") { button.setBackground(asColor(value)); return Values.empty; } else if (name == "action") { button.setAction(value); return Values.empty; } else if (name == PropertyTypeConstants.PROPERTY_TYPE_TEXT) { button.setText(value == null ? null : value.toString()); return Values.empty; } else if (name == "disabled") { try { if (value == Boolean.FALSE) { z = false; } button.setDisabled(z); return Values.empty; } catch (ClassCastException e) { throw new WrongType(e, "gnu.kawa.models.Button.setDisabled(boolean)", 2, value); } } else { return misc.error$V(Format.formatToString(0, "unknown button attribute ~s", name), new Object[0]); } } static Boolean buttonNonKeyword(Button button, Object arg) { return Boolean.TRUE; } public static Button button(Object... args) { Button button = new Button(); int num$Mnargs = args.length; int i = 0; while (i < num$Mnargs) { Object arg = args[i]; if (arg instanceof Keyword) { try { buttonKeyword(button, ((Keyword) arg).getName(), args[i + 1]); i += 2; } catch (ClassCastException e) { throw new WrongType(e, "gnu.expr.Keyword.getName()", 1, arg); } } else if (arg instanceof KAttr) { try { KAttr attr = (KAttr) arg; buttonKeyword(button, attr.getName(), attr.getObjectValue()); i++; } catch (ClassCastException e2) { throw new WrongType(e2, "attr", -2, arg); } } else { buttonNonKeyword(button, arg); i++; } } return button; } public int matchN(ModuleMethod moduleMethod, Object[] objArr, CallContext callContext) { switch (moduleMethod.selector) { case 2: callContext.values = objArr; callContext.proc = moduleMethod; callContext.pc = 5; return 0; case 3: callContext.values = objArr; callContext.proc = moduleMethod; callContext.pc = 5; return 0; case 7: callContext.values = objArr; callContext.proc = moduleMethod; callContext.pc = 5; return 0; case 8: callContext.values = objArr; callContext.proc = moduleMethod; callContext.pc = 5; return 0; case 9: callContext.values = objArr; callContext.proc = moduleMethod; callContext.pc = 5; return 0; case 10: callContext.values = objArr; callContext.proc = moduleMethod; callContext.pc = 5; return 0; case 12: callContext.values = objArr; callContext.proc = moduleMethod; callContext.pc = 5; return 0; default: return super.matchN(moduleMethod, objArr, callContext); } } public static Button Button(Object... args) { Button button = new Button(); int num$Mnargs = args.length; int i = 0; while (i < num$Mnargs) { Object arg = args[i]; if (arg instanceof Keyword) { try { buttonKeyword(button, ((Keyword) arg).getName(), args[i + 1]); i += 2; } catch (ClassCastException e) { throw new WrongType(e, "gnu.expr.Keyword.getName()", 1, arg); } } else if (arg instanceof KAttr) { try { KAttr attr = (KAttr) arg; buttonKeyword(button, attr.getName(), attr.getObjectValue()); i++; } catch (ClassCastException e2) { throw new WrongType(e2, "attr", -2, arg); } } else { buttonNonKeyword(button, arg); i++; } } return button; } public static BufferedImage imageRead(Path uri) { return ImageIO.read(uri.openInputStream()); } public static int imageWidth(BufferedImage image) { try { return ((Number) Scheme.applyToArgs.apply2(loc$$St$DtgetWidth.get(), image)).intValue(); } catch (UnboundLocationException e) { e.setLine("/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 74, 3); throw e; } } public static int imageHeight(BufferedImage image) { try { return ((Number) Scheme.applyToArgs.apply2(loc$$St$DtgetHeight.get(), image)).intValue(); } catch (UnboundLocationException e) { e.setLine("/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 77, 3); throw e; } } public Object apply1(ModuleMethod moduleMethod, Object obj) { switch (moduleMethod.selector) { case 1: return asColor(obj); case 4: try { return imageRead(Path.valueOf(obj)); } catch (ClassCastException e) { throw new WrongType(e, "image-read", 1, obj); } case 5: try { return Integer.valueOf(imageWidth((BufferedImage) obj)); } catch (ClassCastException e2) { throw new WrongType(e2, "image-width", 1, obj); } case 6: try { return Integer.valueOf(imageHeight((BufferedImage) obj)); } catch (ClassCastException e22) { throw new WrongType(e22, "image-height", 1, obj); } default: return super.apply1(moduleMethod, obj); } } static Object labelKeyword(Label instance, String name, Object value) { if (name == Lit1) { String str; if (value == null) { str = null; } else { str = value.toString(); } instance.setText(str); return Values.empty; } return misc.error$V(Format.formatToString(0, "unknown label attribute ~s", name), new Object[0]); } static void labelNonKeyword(Label instance, Object arg) { instance.setText(arg == null ? null : arg.toString()); } public static Label Label(Object... args) { Label instance = new Label(); int num$Mnargs = args.length; int i = 0; while (i < num$Mnargs) { Object arg = args[i]; if (arg instanceof Keyword) { try { labelKeyword(instance, ((Keyword) arg).getName(), args[i + 1]); i += 2; } catch (ClassCastException e) { throw new WrongType(e, "gnu.expr.Keyword.getName()", 1, arg); } } else if (arg instanceof KAttr) { try { KAttr attr = (KAttr) arg; labelKeyword(instance, attr.getName(), attr.getObjectValue()); i++; } catch (ClassCastException e2) { throw new WrongType(e2, "attr", -2, arg); } } else { labelNonKeyword(instance, arg); i++; } } return instance; } static Object textKeyword(Text instance, String name, Object value) { if (name == Lit1) { String str; if (value == null) { str = null; } else { str = value.toString(); } instance.setText(str); return Values.empty; } return misc.error$V(Format.formatToString(0, "unknown text attribute ~s", name), new Object[0]); } static void textNonKeyword(Text instance, Object arg) { instance.setText(arg == null ? null : arg.toString()); } public static Text Text(Object... args) { Text instance = new Text(); int num$Mnargs = args.length; int i = 0; while (i < num$Mnargs) { Object arg = args[i]; if (arg instanceof Keyword) { try { textKeyword(instance, ((Keyword) arg).getName(), args[i + 1]); i += 2; } catch (ClassCastException e) { throw new WrongType(e, "gnu.expr.Keyword.getName()", 1, arg); } } else if (arg instanceof KAttr) { try { KAttr attr = (KAttr) arg; textKeyword(instance, attr.getName(), attr.getObjectValue()); i++; } catch (ClassCastException e2) { throw new WrongType(e2, "attr", -2, arg); } } else { textNonKeyword(instance, arg); i++; } } return instance; } static Object boxKeyword(Box instance, String name, Object value) { if (name == Lit2) { instance.setCellSpacing(value); return Values.empty; } return misc.error$V(Format.formatToString(0, "unknown box attribute ~s", name), new Object[0]); } static Model asModel(Object arg) { return Display.getInstance().coerceToModel(arg); } static void boxNonKeyword(Box box, Object arg) { box.add(asModel(arg)); } public static Object Row(Object... args) { try { Object instance = Invoke.make.apply1(loc$$Lsgnu$Dtkawa$Dtmodels$DtRow$Gr.get()); int num$Mnargs = args.length; int i = 0; while (i < num$Mnargs) { Object arg = args[i]; if (arg instanceof Keyword) { try { try { boxKeyword((Box) instance, ((Keyword) arg).getName(), args[i + 1]); i += 2; } catch (ClassCastException e) { throw new WrongType(e, "gnu.expr.Keyword.getName()", 1, arg); } } catch (ClassCastException e2) { throw new WrongType(e2, "box-keyword", 0, instance); } } else if (arg instanceof KAttr) { try { KAttr attr = (KAttr) arg; try { boxKeyword((Box) instance, attr.getName(), attr.getObjectValue()); i++; } catch (ClassCastException e22) { throw new WrongType(e22, "box-keyword", 0, instance); } } catch (ClassCastException e222) { throw new WrongType(e222, "attr", -2, arg); } } else { try { boxNonKeyword((Box) instance, arg); i++; } catch (ClassCastException e2222) { throw new WrongType(e2222, "box-non-keyword", 0, instance); } } } return instance; } catch (UnboundLocationException e3) { e3.setLine("/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 146, 25); throw e3; } } public static Object Column(Object... args) { try { Object instance = Invoke.make.apply1(loc$$Lsgnu$Dtkawa$Dtmodels$DtColumn$Gr.get()); int num$Mnargs = args.length; int i = 0; while (i < num$Mnargs) { Object arg = args[i]; if (arg instanceof Keyword) { try { try { boxKeyword((Box) instance, ((Keyword) arg).getName(), args[i + 1]); i += 2; } catch (ClassCastException e) { throw new WrongType(e, "gnu.expr.Keyword.getName()", 1, arg); } } catch (ClassCastException e2) { throw new WrongType(e2, "box-keyword", 0, instance); } } else if (arg instanceof KAttr) { try { KAttr attr = (KAttr) arg; try { boxKeyword((Box) instance, attr.getName(), attr.getObjectValue()); i++; } catch (ClassCastException e22) { throw new WrongType(e22, "box-keyword", 0, instance); } } catch (ClassCastException e222) { throw new WrongType(e222, "attr", -2, arg); } } else { try { boxNonKeyword((Box) instance, arg); i++; } catch (ClassCastException e2222) { throw new WrongType(e2222, "box-non-keyword", 0, instance); } } } return instance; } catch (UnboundLocationException e3) { e3.setLine("/Users/ewpatton/Programming/mit/ai2-kawa/gnu/kawa/slib/gui.scm", 151, 25); throw e3; } } public static void setContent(Window window, Object pane) { window.setContent(pane); } public Object apply2(ModuleMethod moduleMethod, Object obj, Object obj2) { if (moduleMethod.selector != 11) { return super.apply2(moduleMethod, obj, obj2); } try { setContent((Window) obj, obj2); return Values.empty; } catch (ClassCastException e) { throw new WrongType(e, "set-content", 1, obj); } } public int match2(ModuleMethod moduleMethod, Object obj, Object obj2, CallContext callContext) { if (moduleMethod.selector != 11) { return super.match2(moduleMethod, obj, obj2, callContext); } if (!(obj instanceof Window)) { return -786431; } callContext.value1 = obj; callContext.value2 = obj2; callContext.proc = moduleMethod; callContext.pc = 2; return 0; } static Object windowKeyword(Window instance, String name, Object value) { if (name == "title") { instance.setTitle(value == null ? null : value.toString()); return Values.empty; } else if (name == "content") { instance.setContent(value); return Values.empty; } else if (name == "menubar") { instance.setMenuBar(value); return Values.empty; } else { return misc.error$V(Format.formatToString(0, "unknown window attribute ~s", name), new Object[0]); } } static void windowNonKeyword(Window instance, Object arg) { instance.setContent(arg); } public static Window Window(Object... args) { Window instance = Display.getInstance().makeWindow(); int num$Mnargs = args.length; int i = 0; while (i < num$Mnargs) { Object arg = args[i]; if (arg instanceof Keyword) { try { windowKeyword(instance, ((Keyword) arg).getName(), args[i + 1]); i += 2; } catch (ClassCastException e) { throw new WrongType(e, "gnu.expr.Keyword.getName()", 1, arg); } } else if (arg instanceof KAttr) { try { KAttr attr = (KAttr) arg; windowKeyword(instance, attr.getName(), attr.getObjectValue()); i++; } catch (ClassCastException e2) { throw new WrongType(e2, "attr", -2, arg); } } else { windowNonKeyword(instance, arg); i++; } } return instance; } public Object applyN(ModuleMethod moduleMethod, Object[] objArr) { switch (moduleMethod.selector) { case 2: return button(objArr); case 3: return Button(objArr); case 7: return Label(objArr); case 8: return Text(objArr); case 9: return Row(objArr); case 10: return Column(objArr); case 12: return Window(objArr); default: return super.applyN(moduleMethod, objArr); } } }
package com.google.android.core.audio; import android.media.AudioTrack; import android.media.audiofx.AudioEffect; import androidx.annotation.Nullable; /** * Represents auxiliary effect information, which can be used to attach an auxiliary effect to an * underlying {@link AudioTrack}. * * <p>Auxiliary (辅助的) effects can only be applied if the application has the * {@ocde MODIFY_AUDIO_SETTINGS} permission. Apps are responsible for retaining the associated audio * effect instance and releasing it when it's no longer needed. See the documentation of * {@link android.media.audiofx.AudioEffect} for more inforamtion. */ public class AuxEffectInfo { /** Value for {@link #effectId} representing no auxiliary effect. */ public static final int NO_AUX_EFFECT_ID = 0; /** * The identifier of the effect, or {@link #NO_AUX_EFFECT_ID} if there is no effect. * * @see AudioTrack#attachAuxEffect(int) */ public final int effectId; /** * The send level for the effect. * * @see AudioTrack#setAuxEffectSendLevel(float) */ public final float sendLevel; /** * Creates an instance with the given effect identifier and send level. * * @param effectId The effect identifier. This is the value returned by {@link * AudioEffect#getId()} on the effect, or {@value NO_AUX_EFFECT_ID} which represents no * effect. This value is passed to {@link AudioTrack#attachAuxEffect(int)} on the underlying * audio track. * @param sendLevel The send level for the effect, where 0 represents no effect and a value of 1 * is full send. If {@code effectId} is not {@value #NO_AUX_EFFECT_ID}, this value is passed * to {@link AudioTrack#setAuxEffectSendLevel(float)} on the underlying audio track. */ public AuxEffectInfo(int effectId, float sendLevel) { this.effectId = effectId; this.sendLevel = sendLevel; } @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } AuxEffectInfo auxEffectInfo = (AuxEffectInfo) obj; return effectId == auxEffectInfo.effectId && Float.compare(auxEffectInfo.sendLevel, sendLevel) == 0; } @Override public int hashCode() { // 计算hash值 int result = 17; result = 31 * result + effectId; result = 31 * result + Float.floatToIntBits(sendLevel); return result; } }
package com.brin.denonremotefree.BrinObj; /** * Created by Luca on 24.05.2016. */ public class ScanItem { public String itemIp; public String itemHostName; public String itemMac; public boolean itemOnline; public boolean itemSuprt; public String itemGatewaymac; }
package com.bibabo.fragment.watch.child; import com.bibabo.api.CacheRetrofit; import com.bibabo.base.list.ListBasePresenterImpl; import com.bibabo.entity.QVMovieInfo; import java.util.List; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; /** * * Created by zijian.cheng on 2017/6/13. */ public class BabyWatchItemPresenter extends ListBasePresenterImpl<BabyWatchItemContract.View, QVMovieInfo> implements BabyWatchItemContract.Presenter { /** * 获取tx某个类别下的视频列表,支持分页 * @param itype * @param offset */ @Override public void fetchQVChildrenVideoList(String itype, String offset) { CacheRetrofit.api().<List<QVMovieInfo>>fetchQVChildrenVideoList(itype, offset) .compose(view.<List<QVMovieInfo>>bindToLife()) .doOnNext(new Consumer<List<QVMovieInfo>>() { @Override public void accept(@NonNull List<QVMovieInfo> models) throws Exception { if(models.size() > 0){ view.setEnd(!models.get(0).hasNextPage()); models.remove(0); } } }) .compose(applyCommonOperators()) .subscribe(new Consumer<List<QVMovieInfo>>() { @Override public void accept(@NonNull List<QVMovieInfo> result) throws Exception { view.updateCurrentList(result); } }); } }
/* * MIT License * * Copyright (c) 2022 MASES s.r.l. * * 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. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.windows.forms; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.windows.forms.ListViewGroup; import system.windows.forms.ListViewGroupCollection; import system.Array; /** * The base .NET class managing System.Windows.Forms.ListViewGroupCollection, System.Windows.Forms, Version=5.0.15.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Forms.ListViewGroupCollection" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Forms.ListViewGroupCollection</a> */ public class ListViewGroupCollection extends NetObjectEnumerable { /** * Fully assembly qualified name: System.Windows.Forms, Version=5.0.15.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 */ public static final String assemblyFullName = "System.Windows.Forms, Version=5.0.15.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; /** * Assembly name: System.Windows.Forms */ public static final String assemblyShortName = "System.Windows.Forms"; /** * Qualified class name: System.Windows.Forms.ListViewGroupCollection */ public static final String className = "System.Windows.Forms.ListViewGroupCollection"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public ListViewGroupCollection(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link ListViewGroupCollection}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link ListViewGroupCollection} instance * @throws java.lang.Throwable in case of error during cast operation */ public static ListViewGroupCollection cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new ListViewGroupCollection(from.getJCOInstance()); } // Constructors section public ListViewGroupCollection() throws Throwable { } // Methods section public boolean Contains(ListViewGroup value) throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (boolean)classInstance.Invoke("Contains", value == null ? null : value.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int Add(ListViewGroup group) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.ObjectDisposedException, system.RankException, system.ArrayTypeMismatchException, system.FormatException, system.OutOfMemoryException, system.componentmodel.InvalidEnumArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Invoke("Add", group == null ? null : group.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public int IndexOf(ListViewGroup value) throws Throwable, system.ArgumentNullException, system.PlatformNotSupportedException, system.RankException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.NotSupportedException, system.ArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Invoke("IndexOf", value == null ? null : value.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public ListViewGroup Add(java.lang.String key, java.lang.String headerText) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.globalization.CultureNotFoundException, system.InvalidOperationException, system.PlatformNotSupportedException, system.ObjectDisposedException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.RankException, system.ArrayTypeMismatchException, system.NotSupportedException, system.OutOfMemoryException, system.componentmodel.InvalidEnumArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { JCObject objAdd = (JCObject)classInstance.Invoke("Add", key, headerText); return new ListViewGroup(objAdd); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void AddRange(ListViewGroup[] groups) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.ObjectDisposedException, system.RankException, system.ArrayTypeMismatchException, system.FormatException, system.OutOfMemoryException, system.componentmodel.InvalidEnumArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("AddRange", (java.lang.Object)toObjectFromArray(groups)); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void AddRange(ListViewGroupCollection groups) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.ObjectDisposedException, system.RankException, system.ArrayTypeMismatchException, system.FormatException, system.OutOfMemoryException, system.componentmodel.InvalidEnumArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("AddRange", groups == null ? null : groups.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Clear() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.NotSupportedException, system.ArgumentNullException, system.ObjectDisposedException, system.InvalidOperationException, system.RankException, system.ArrayTypeMismatchException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.componentmodel.InvalidEnumArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Clear"); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void CopyTo(Array array, int index) throws Throwable, system.PlatformNotSupportedException, system.ArgumentException, system.InvalidOperationException, system.ArgumentNullException, system.RankException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.ArrayTypeMismatchException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("CopyTo", array == null ? null : array.getJCOInstance(), index); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Insert(int index, ListViewGroup group) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.InvalidOperationException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.NotSupportedException, system.ObjectDisposedException, system.RankException, system.ArrayTypeMismatchException, system.FormatException, system.OutOfMemoryException, system.componentmodel.InvalidEnumArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Insert", index, group == null ? null : group.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void Remove(ListViewGroup group) throws Throwable, system.ArgumentNullException, system.PlatformNotSupportedException, system.RankException, system.IndexOutOfRangeException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.NotSupportedException, system.ArgumentException, system.ArrayTypeMismatchException, system.ObjectDisposedException, system.FormatException, system.OutOfMemoryException, system.componentmodel.InvalidEnumArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("Remove", group == null ? null : group.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public void RemoveAt(int index) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.NotSupportedException, system.ArgumentNullException, system.ObjectDisposedException, system.InvalidOperationException, system.RankException, system.ArrayTypeMismatchException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.componentmodel.InvalidEnumArgumentException { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { classInstance.Invoke("RemoveAt", index); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public boolean Contains(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public int Add(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public int IndexOf(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public void Insert(int index, NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } /** * @deprecated Not for public use because the method is implemented in .NET with an explicit interface. * Use the static ToIList method available in IList to obtain an object with an invocable method */ @Deprecated public void Remove(NetObject value) throws Throwable { throw new UnsupportedOperationException("Not for public use because the method is implemented with an explicit interface. Use ToIList to obtain the full interface."); } // Properties section public int getCount() throws Throwable { if (classInstance == null) throw new UnsupportedOperationException("classInstance is null."); try { return (int)classInstance.Get("Count"); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Instance Events section }
/* * Copyright 2015-2020 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.wafv2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/wafv2-2019-07-29/GetRegexPatternSet" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetRegexPatternSetRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the set. You cannot change the name after you create the set. * </p> */ private String name; /** * <p> * Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. * </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * </ul> */ private String scope; /** * <p> * A unique identifier for the set. This ID is returned in the responses to create and list commands. You provide it * to operations like update and delete. * </p> */ private String id; /** * <p> * The name of the set. You cannot change the name after you create the set. * </p> * * @param name * The name of the set. You cannot change the name after you create the set. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the set. You cannot change the name after you create the set. * </p> * * @return The name of the set. You cannot change the name after you create the set. */ public String getName() { return this.name; } /** * <p> * The name of the set. You cannot change the name after you create the set. * </p> * * @param name * The name of the set. You cannot change the name after you create the set. * @return Returns a reference to this object so that method calls can be chained together. */ public GetRegexPatternSetRequest withName(String name) { setName(name); return this; } /** * <p> * Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. * </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * </ul> * * @param scope * Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: * <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * @see Scope */ public void setScope(String scope) { this.scope = scope; } /** * <p> * Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. * </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * </ul> * * @return Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: * <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * @see Scope */ public String getScope() { return this.scope; } /** * <p> * Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. * </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * </ul> * * @param scope * Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: * <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see Scope */ public GetRegexPatternSetRequest withScope(String scope) { setScope(scope); return this; } /** * <p> * Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. * </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * </ul> * * @param scope * Specifies whether this is for an AWS CloudFront distribution or for a regional application. A regional * application can be an Application Load Balancer (ALB) or an API Gateway stage. </p> * <p> * To work with CloudFront, you must also specify the Region US East (N. Virginia) as follows: * </p> * <ul> * <li> * <p> * CLI - Specify the Region when you use the CloudFront scope: * <code>--scope=CLOUDFRONT --region=us-east-1</code>. * </p> * </li> * <li> * <p> * API and SDKs - For all calls, use the Region endpoint us-east-1. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. * @see Scope */ public GetRegexPatternSetRequest withScope(Scope scope) { this.scope = scope.toString(); return this; } /** * <p> * A unique identifier for the set. This ID is returned in the responses to create and list commands. You provide it * to operations like update and delete. * </p> * * @param id * A unique identifier for the set. This ID is returned in the responses to create and list commands. You * provide it to operations like update and delete. */ public void setId(String id) { this.id = id; } /** * <p> * A unique identifier for the set. This ID is returned in the responses to create and list commands. You provide it * to operations like update and delete. * </p> * * @return A unique identifier for the set. This ID is returned in the responses to create and list commands. You * provide it to operations like update and delete. */ public String getId() { return this.id; } /** * <p> * A unique identifier for the set. This ID is returned in the responses to create and list commands. You provide it * to operations like update and delete. * </p> * * @param id * A unique identifier for the set. This ID is returned in the responses to create and list commands. You * provide it to operations like update and delete. * @return Returns a reference to this object so that method calls can be chained together. */ public GetRegexPatternSetRequest withId(String id) { setId(id); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getScope() != null) sb.append("Scope: ").append(getScope()).append(","); if (getId() != null) sb.append("Id: ").append(getId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetRegexPatternSetRequest == false) return false; GetRegexPatternSetRequest other = (GetRegexPatternSetRequest) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getScope() == null ^ this.getScope() == null) return false; if (other.getScope() != null && other.getScope().equals(this.getScope()) == false) return false; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getScope() == null) ? 0 : getScope().hashCode()); hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); return hashCode; } @Override public GetRegexPatternSetRequest clone() { return (GetRegexPatternSetRequest) super.clone(); } }
/** * <copyright> * * Copyright (c) 2010 SAP AG. * 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: * Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation * * </copyright> */ package org.eclipse.bpmn2; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Conversation</b></em>'. * <!-- end-user-doc --> * * * @see org.eclipse.bpmn2.Bpmn2Package#getConversation() * @model extendedMetaData="name='tConversation' kind='elementOnly'" * @generated */ public interface Conversation extends ConversationNode { } // Conversation
package io.airlift.http.client.jetty; import com.google.common.collect.ImmutableList; import io.airlift.http.client.AbstractHttpClientTest; import io.airlift.http.client.HttpClientConfig; import io.airlift.http.client.HttpRequestFilter; import io.airlift.http.client.Request; import io.airlift.http.client.ResponseHandler; import io.airlift.http.client.TestingRequestFilter; import io.airlift.http.client.TestingSocksProxy; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import static io.airlift.testing.Closeables.closeQuietly; public class TestJettyHttpClientSocksProxy extends AbstractHttpClientTest { private JettyHttpClient httpClient; private JettyIoPool jettyIoPool; private TestingSocksProxy testingSocksProxy; @BeforeClass public void setUpHttpClient() throws IOException { testingSocksProxy = new TestingSocksProxy().start(); jettyIoPool = new JettyIoPool("test-shared", new JettyIoPoolConfig()); httpClient = new JettyHttpClient(createClientConfig(), jettyIoPool, ImmutableList.<HttpRequestFilter>of(new TestingRequestFilter())); } @AfterClass(alwaysRun = true) public void tearDownHttpClient() { closeQuietly(httpClient); closeQuietly(jettyIoPool); closeQuietly(testingSocksProxy); } @Override protected HttpClientConfig createClientConfig() { return new HttpClientConfig() .setHttp2Enabled(false) .setSocksProxy(testingSocksProxy.getHostAndPort()); } @Override public <T, E extends Exception> T executeRequest(Request request, ResponseHandler<T, E> responseHandler) throws Exception { return httpClient.execute(request, responseHandler); } @Override public <T, E extends Exception> T executeRequest(HttpClientConfig config, Request request, ResponseHandler<T, E> responseHandler) throws Exception { config.setSocksProxy(testingSocksProxy.getHostAndPort()); try ( JettyIoPool jettyIoPool = new JettyIoPool("test-private", new JettyIoPoolConfig()); JettyHttpClient client = new JettyHttpClient(config, jettyIoPool, ImmutableList.<HttpRequestFilter>of(new TestingRequestFilter())) ) { return client.execute(request, responseHandler); } } @Override @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = ".*SOCKS4 .*") public void testBadPort() throws Exception { // todo this should be handled by jetty client before connecting to the socks proxy super.testBadPort(); } @Override @Test(enabled = false) public void testConnectTimeout() throws Exception { // todo jetty client does not timeout the socks proxy connect properly super.testConnectTimeout(); } @Override @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = ".*SOCKS4 .*") public void testConnectionRefused() throws Exception { super.testConnectionRefused(); } @Override @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = ".*SOCKS4 .*") public void testUnresolvableHost() throws Exception { super.testUnresolvableHost(); } }
/* * Copyright © 2017 camunda services GmbH (info@camunda.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.camunda.zeebe.protocol.record.intent; public interface ProcessInstanceRelatedIntent extends Intent { boolean shouldBlacklistInstanceOnError(); }
package edu.neu.coe.info6205.util; import edu.neu.coe.info6205.sort.GenericSort; import edu.neu.coe.info6205.sort.elementary.InsertionSort; import java.util.*; import java.util.function.Supplier; /** * Interface to define the behavior of a Benchmark. * * @param <T> the underlying type which is passed into (or supplied) to the run/runFromSupplier methods. */ public interface Benchmark<T> { /** * Run function f m times and return the average time in milliseconds. * * @param t the value that will in turn be passed to function f. * @param m the number of times the function f will be called. * @return the average number of milliseconds taken for each run of function f. */ default double run(T t, int m) { return runFromSupplier(() -> t, m); } /** * Run function f m times and return the average time in milliseconds. * * @param supplier a Supplier of a T * @param m the number of times the function f will be called. * @return the average number of milliseconds taken for each run of function f. */ double runFromSupplier(Supplier<T> supplier, int m); public static void main(String[] args){ Integer[] ordered; Integer[] reverse; Integer[] random; Integer[] partial; List<Double> orderedTimes = new ArrayList<>(); List<Double> reverseTimes = new ArrayList<>(); List<Double> partialTimes = new ArrayList<>(); List<Double> randomTimes = new ArrayList<>(); int n=50; for(int i=0; i<5; i++){ n *= 2; ordered = new Integer[n]; reverse = new Integer[n]; random = new Integer[n]; partial = new Integer[n]; int rev= n-1; for(int j=0; j<n; ++j) { ordered[j] = j; reverse[n-j-1] = j; Random ran = new Random(); int ind = ran.nextInt(n*2); while(ind<(n/2)){ ind = ran.nextInt(n*2); } if(j<(n/2)){ partial[j] = j; } else{ partial[j] = ind; } random[j] = ind; } //ordered List<Integer> ord = new ArrayList<>(); Collections.addAll(ord, ordered); Benchmark<Integer[]> bm = new Benchmark_Timer<>("Insertion Sort Timer", b->{new InsertionSort().sort(ord);}); orderedTimes.add(bm.run(ordered, 10)); List<Integer> reve = new ArrayList<>(); Collections.addAll(reve, reverse); bm = new Benchmark_Timer<>("Insertion Sort Timer", b->{new InsertionSort().sort(reve);}); reverseTimes.add(bm.run(reverse, 10)); List<Integer> part = new ArrayList<>(); Collections.addAll(part, partial); bm = new Benchmark_Timer<>("Insertion Sort Timer", b->{new InsertionSort().sort(part);}); partialTimes.add(bm.run(partial, 10)); List<Integer> rand = new ArrayList<>(); Collections.addAll(rand, random); bm = new Benchmark_Timer<>("Insertion Sort Timer", b->{new InsertionSort().sort(rand);}); randomTimes.add(bm.run(random, 10)); } System.out.println("size,Ordered,Reverse,Partial,Random"); n=50; for(int i=0; i<orderedTimes.size(); ++i){ n = n*2; System.out.println(n+","+orderedTimes.get(i)+ ","+reverseTimes.get(i)+ ","+partialTimes.get(i)+ ","+randomTimes.get(i)); System.out.println(Math.log(n)/Math.log(2)+","+Math.log(orderedTimes.get(i))/Math.log(2)+ ","+Math.log(reverseTimes.get(i))/Math.log(2)+ ","+Math.log(partialTimes.get(i))/Math.log(2)+ ","+Math.log(randomTimes.get(i))/Math.log(2)); // System.out.println("Ordered," + orderedTimes.get(i)+ ","+ n); // System.out.println("Reverse," + reverseTimes.get(i)+ ","+ n); // System.out.println("Partial," + partialTimes.get(i)+ ","+ n); // System.out.println("Random," + randomTimes.get(i)+ ","+ n); } } }
package configtools.tBOnlineDoc.controller; import configtools.tBOnlineDoc.entity.TBOnlineDocEntity; import configtools.tBOnlineDoc.service.TBOnlineDocServiceI; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jeecgframework.core.annotation.JAuth; import org.jeecgframework.core.enums.Permission; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.ModelMap; import org.springframework.web.servlet.ModelAndView; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.exception.BusinessException; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.web.system.service.SystemService; import org.jeecgframework.core.util.MyBeanUtils; import java.io.OutputStream; import org.jeecgframework.poi.excel.ExcelExportUtil; import org.jeecgframework.poi.excel.ExcelImportUtil; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.ImportParams; import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants; import org.jeecgframework.core.util.ResourceUtil; import java.io.IOException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import java.util.Map; import java.util.HashMap; import org.jeecgframework.core.util.ExceptionUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.jeecgframework.web.cgform.entity.upload.CgUploadEntity; import org.jeecgframework.web.cgform.service.config.CgFormFieldServiceI; import java.util.HashMap; /** * @Title: Controller * @Description: 在线文档一览 * @author onlineGenerator * @date 2019-03-21 12:16:53 * @version V1.0 * */ @Controller @RequestMapping("/tBOnlineDocController") public class TBOnlineDocController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(TBOnlineDocController.class); @Autowired private TBOnlineDocServiceI tBOnlineDocService; @Autowired private SystemService systemService; @Autowired private CgFormFieldServiceI cgFormFieldService; //zczadd begin modify on 2019/3/21 12:33 //tBOnlineDocController.do?displaypdf&docid=1 @RequestMapping(params = "displaypdf") @JAuth(auth= Permission.SKIP_AUTH) public ModelAndView displaypdf(HttpServletRequest request) { String docid=request.getParameter("docid"); String sql="select docpathname from t_b_online_doc where id='"+docid+"'" ; String filename=tBOnlineDocService.getSingleValue(sql) ; request.setAttribute("filename",filename); return new ModelAndView("configtools/tBOnlineDoc/displaypdf"); } //zczadd end modify on 2019/3/21 12:33 /** * 在线文档一览列表 页面跳转 * * @return */ @RequestMapping(params = "list") public ModelAndView list(HttpServletRequest request) { return new ModelAndView("configtools/tBOnlineDoc/tBOnlineDocList"); } /** * easyui AJAX请求数据 * * @param request * @param response * @param dataGrid * @param user */ @RequestMapping(params = "datagrid") public void datagrid(TBOnlineDocEntity tBOnlineDoc,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { CriteriaQuery cq = new CriteriaQuery(TBOnlineDocEntity.class, dataGrid); //查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tBOnlineDoc, request.getParameterMap()); try{ //自定义追加查询条件 }catch (Exception e) { throw new BusinessException(e.getMessage()); } cq.add(); this.tBOnlineDocService.getDataGridReturn(cq, true); TagUtil.datagrid(response, dataGrid); } /** * 删除在线文档一览 * * @return */ @RequestMapping(params = "doDel") @ResponseBody public AjaxJson doDel(TBOnlineDocEntity tBOnlineDoc, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); tBOnlineDoc = systemService.getEntity(TBOnlineDocEntity.class, tBOnlineDoc.getId()); message = "在线文档一览删除成功"; try{ tBOnlineDocService.delete(tBOnlineDoc); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "在线文档一览删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 批量删除在线文档一览 * * @return */ @RequestMapping(params = "doBatchDel") @ResponseBody public AjaxJson doBatchDel(String ids,HttpServletRequest request){ String message = null; AjaxJson j = new AjaxJson(); message = "在线文档一览删除成功"; try{ for(String id:ids.split(",")){ TBOnlineDocEntity tBOnlineDoc = systemService.getEntity(TBOnlineDocEntity.class, id ); tBOnlineDocService.delete(tBOnlineDoc); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); } }catch(Exception e){ e.printStackTrace(); message = "在线文档一览删除失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 添加在线文档一览 * * @param ids * @return */ @RequestMapping(params = "doAdd") @ResponseBody public AjaxJson doAdd(TBOnlineDocEntity tBOnlineDoc, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "在线文档一览添加成功"; try{ tBOnlineDocService.save(tBOnlineDoc); systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); }catch(Exception e){ e.printStackTrace(); message = "在线文档一览添加失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); j.setObj(tBOnlineDoc); return j; } /** * 更新在线文档一览 * * @param ids * @return */ @RequestMapping(params = "doUpdate") @ResponseBody public AjaxJson doUpdate(TBOnlineDocEntity tBOnlineDoc, HttpServletRequest request) { String message = null; AjaxJson j = new AjaxJson(); message = "在线文档一览更新成功"; TBOnlineDocEntity t = tBOnlineDocService.get(TBOnlineDocEntity.class, tBOnlineDoc.getId()); try { MyBeanUtils.copyBeanNotNull2Bean(tBOnlineDoc, t); tBOnlineDocService.saveOrUpdate(t); systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO); } catch (Exception e) { e.printStackTrace(); message = "在线文档一览更新失败"; throw new BusinessException(e.getMessage()); } j.setMsg(message); return j; } /** * 在线文档一览新增页面跳转 * * @return */ @RequestMapping(params = "goAdd") public ModelAndView goAdd(TBOnlineDocEntity tBOnlineDoc, HttpServletRequest req) { if (StringUtil.isNotEmpty(tBOnlineDoc.getId())) { tBOnlineDoc = tBOnlineDocService.getEntity(TBOnlineDocEntity.class, tBOnlineDoc.getId()); req.setAttribute("tBOnlineDocPage", tBOnlineDoc); } return new ModelAndView("configtools/tBOnlineDoc/tBOnlineDoc-add"); } /** * 在线文档一览编辑页面跳转 * * @return */ @RequestMapping(params = "goUpdate") public ModelAndView goUpdate(TBOnlineDocEntity tBOnlineDoc, HttpServletRequest req) { if (StringUtil.isNotEmpty(tBOnlineDoc.getId())) { tBOnlineDoc = tBOnlineDocService.getEntity(TBOnlineDocEntity.class, tBOnlineDoc.getId()); req.setAttribute("tBOnlineDocPage", tBOnlineDoc); } return new ModelAndView("configtools/tBOnlineDoc/tBOnlineDoc-update"); } /** * 导入功能跳转 * * @return */ @RequestMapping(params = "upload") public ModelAndView upload(HttpServletRequest req) { req.setAttribute("controller_name","tBOnlineDocController"); return new ModelAndView("common/upload/pub_excel_upload"); } /** * 导出excel * * @param request * @param response */ @RequestMapping(params = "exportXls") public String exportXls(TBOnlineDocEntity tBOnlineDoc,HttpServletRequest request,HttpServletResponse response , DataGrid dataGrid,ModelMap modelMap) { CriteriaQuery cq = new CriteriaQuery(TBOnlineDocEntity.class, dataGrid); org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tBOnlineDoc, request.getParameterMap()); List<TBOnlineDocEntity> tBOnlineDocs = this.tBOnlineDocService.getListByCriteriaQuery(cq,false); modelMap.put(NormalExcelConstants.FILE_NAME,"在线文档一览"); modelMap.put(NormalExcelConstants.CLASS,TBOnlineDocEntity.class); modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("在线文档一览列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(), "导出信息")); modelMap.put(NormalExcelConstants.DATA_LIST,tBOnlineDocs); return NormalExcelConstants.JEECG_EXCEL_VIEW; } /** * 导出excel 使模板 * * @param request * @param response */ @RequestMapping(params = "exportXlsByT") public String exportXlsByT(TBOnlineDocEntity tBOnlineDoc,HttpServletRequest request,HttpServletResponse response , DataGrid dataGrid,ModelMap modelMap) { modelMap.put(NormalExcelConstants.FILE_NAME,"在线文档一览"); modelMap.put(NormalExcelConstants.CLASS,TBOnlineDocEntity.class); modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("在线文档一览列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(), "导出信息")); modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList()); return NormalExcelConstants.JEECG_EXCEL_VIEW; } @SuppressWarnings("unchecked") @RequestMapping(params = "importExcel", method = RequestMethod.POST) @ResponseBody public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();// 获取上传文件对象 ImportParams params = new ImportParams(); params.setTitleRows(2); params.setHeadRows(1); params.setNeedSave(true); try { List<TBOnlineDocEntity> listTBOnlineDocEntitys = ExcelImportUtil.importExcel(file.getInputStream(),TBOnlineDocEntity.class,params); for (TBOnlineDocEntity tBOnlineDoc : listTBOnlineDocEntitys) { tBOnlineDocService.save(tBOnlineDoc); } j.setMsg("文件导入成功!"); } catch (Exception e) { j.setMsg("文件导入失败!"); logger.error(ExceptionUtil.getExceptionMessage(e)); }finally{ try { file.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } } return j; } /** * 获取文件附件信息 * * @param id tBOnlineDoc主键id */ @RequestMapping(params = "getFiles") @ResponseBody public AjaxJson getFiles(String id){ List<CgUploadEntity> uploadBeans = cgFormFieldService.findByProperty(CgUploadEntity.class, "cgformId", id); List<Map<String,Object>> files = new ArrayList<Map<String,Object>>(0); for(CgUploadEntity b:uploadBeans){ String title = b.getAttachmenttitle();//附件名 String fileKey = b.getId();//附件主键 String path = b.getRealpath();//附件路径 String field = b.getCgformField();//表单中作为附件控件的字段 Map<String, Object> file = new HashMap<String, Object>(); file.put("title", title); file.put("fileKey", fileKey); file.put("path", path); file.put("field", field==null?"":field); files.add(file); } AjaxJson j = new AjaxJson(); j.setObj(files); return j; } }
package com.classicmodels.repository; import java.math.BigDecimal; import jooq.generated.Routines; import static jooq.generated.Routines.netPriceEach; import jooq.generated.routines.NetPriceEach; import static jooq.generated.tables.Orderdetail.ORDERDETAIL; import static jooq.generated.tables.Product.PRODUCT; import org.jooq.DSLContext; import org.jooq.Field; import static org.jooq.impl.DSL.field; import static org.jooq.impl.DSL.name; import static org.jooq.impl.DSL.select; import static org.jooq.impl.DSL.sum; import static org.jooq.impl.DSL.val; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository @Transactional(readOnly = true) public class ClassicModelsRepository { private final DSLContext ctx; public ClassicModelsRepository(DSLContext ctx) { this.ctx = ctx; } public void executeScalarFunction() { // EXECUTION 1 NetPriceEach npe1 = new NetPriceEach(); npe1.setQuantity(25); npe1.setListPrice(BigDecimal.valueOf(15.5)); npe1.setDiscount(BigDecimal.valueOf(0.75)); npe1.execute(ctx.configuration()); System.out.println("Execution 1: " + npe1.getReturnValue()); // EXECUTION 2 NetPriceEach npe2 = new NetPriceEach(); npe2.setQuantity(field(select(PRODUCT.QUANTITY_IN_STOCK) .from(PRODUCT).where(PRODUCT.PRODUCT_ID.eq(1L)))); npe2.setListPrice(field(select(PRODUCT.MSRP) .from(PRODUCT).where(PRODUCT.PRODUCT_ID.eq(1L)))); npe2.setDiscount(BigDecimal.valueOf(0.75)); System.out.println("Execution 2:\n" + ctx.fetchValue(npe2.asField("netPriceEach"))); // or, ctx.select(npe2.asField("netPriceEach")).fetch() // EXECUTION 3 BigDecimal npe3 = Routines.netPriceEach( ctx.configuration(), 25, BigDecimal.valueOf(15.5), BigDecimal.valueOf(0.75)); System.out.println("Execution 3: " + npe3); // EXECUTION 4 Field<BigDecimal> npe4 = Routines.netPriceEach( field(select(PRODUCT.QUANTITY_IN_STOCK) .from(PRODUCT).where(PRODUCT.PRODUCT_ID.eq(1L))), field(select(PRODUCT.MSRP) .from(PRODUCT).where(PRODUCT.PRODUCT_ID.eq(1L))), val(BigDecimal.valueOf(0.75))); System.out.println("Execution 4:\n" + ctx.fetchValue(npe4)); // or, ctx.select(npe4).fetch() // EXECUTION 5 ctx.select(ORDERDETAIL.ORDER_ID, sum(netPriceEach(ORDERDETAIL.QUANTITY_ORDERED.coerce(Integer.class), ORDERDETAIL.PRICE_EACH, val(0.75))).as("sum_net_price")) .from(ORDERDETAIL) .groupBy(ORDERDETAIL.ORDER_ID) .orderBy(field(name("sum_net_price")).desc()) .fetch(); } }
package com.mypurecloud.sdk.v2.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import java.util.Objects; import java.io.IOException; import com.fasterxml.jackson.annotation.JsonProperty; import com.mypurecloud.sdk.v2.model.DomainEntityRef; import com.mypurecloud.sdk.v2.model.FromEmailAddress; import com.mypurecloud.sdk.v2.model.ReplyToEmailAddress; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import java.io.Serializable; /** * EmailConfig */ public class EmailConfig implements Serializable { private List<String> emailColumns = new ArrayList<String>(); private DomainEntityRef contentTemplate = null; private FromEmailAddress fromAddress = null; private ReplyToEmailAddress replyToAddress = null; /** * The contact list columns specifying the email address(es) of the contact. **/ public EmailConfig emailColumns(List<String> emailColumns) { this.emailColumns = emailColumns; return this; } @ApiModelProperty(example = "null", required = true, value = "The contact list columns specifying the email address(es) of the contact.") @JsonProperty("emailColumns") public List<String> getEmailColumns() { return emailColumns; } public void setEmailColumns(List<String> emailColumns) { this.emailColumns = emailColumns; } /** * The content template used to formulate the email to send to the contact. **/ public EmailConfig contentTemplate(DomainEntityRef contentTemplate) { this.contentTemplate = contentTemplate; return this; } @ApiModelProperty(example = "null", value = "The content template used to formulate the email to send to the contact.") @JsonProperty("contentTemplate") public DomainEntityRef getContentTemplate() { return contentTemplate; } public void setContentTemplate(DomainEntityRef contentTemplate) { this.contentTemplate = contentTemplate; } /** * The email address that will be used as the sender of the email. **/ public EmailConfig fromAddress(FromEmailAddress fromAddress) { this.fromAddress = fromAddress; return this; } @ApiModelProperty(example = "null", required = true, value = "The email address that will be used as the sender of the email.") @JsonProperty("fromAddress") public FromEmailAddress getFromAddress() { return fromAddress; } public void setFromAddress(FromEmailAddress fromAddress) { this.fromAddress = fromAddress; } /** * The email address from which any reply will be sent. **/ public EmailConfig replyToAddress(ReplyToEmailAddress replyToAddress) { this.replyToAddress = replyToAddress; return this; } @ApiModelProperty(example = "null", value = "The email address from which any reply will be sent.") @JsonProperty("replyToAddress") public ReplyToEmailAddress getReplyToAddress() { return replyToAddress; } public void setReplyToAddress(ReplyToEmailAddress replyToAddress) { this.replyToAddress = replyToAddress; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EmailConfig emailConfig = (EmailConfig) o; return Objects.equals(this.emailColumns, emailConfig.emailColumns) && Objects.equals(this.contentTemplate, emailConfig.contentTemplate) && Objects.equals(this.fromAddress, emailConfig.fromAddress) && Objects.equals(this.replyToAddress, emailConfig.replyToAddress); } @Override public int hashCode() { return Objects.hash(emailColumns, contentTemplate, fromAddress, replyToAddress); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class EmailConfig {\n"); sb.append(" emailColumns: ").append(toIndentedString(emailColumns)).append("\n"); sb.append(" contentTemplate: ").append(toIndentedString(contentTemplate)).append("\n"); sb.append(" fromAddress: ").append(toIndentedString(fromAddress)).append("\n"); sb.append(" replyToAddress: ").append(toIndentedString(replyToAddress)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
/*___Generated_by_IDEA___*/ package com.happymaau.MathRef; /* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */ public final class BuildConfig { public final static boolean DEBUG = Boolean.parseBoolean(null); }
/* * (c) LibriCore * * Created on Oct 25, 2004 * * CataloguingSourceTag.java */ package org.folio.marccat.dao.persistence; import org.folio.marccat.business.cataloguing.bibliographic.VariableHeaderUsingItemEntity; import org.folio.marccat.model.Subfield; import org.folio.marccat.util.StringText; public class ProjectedPublicationDateTag extends VariableHeaderUsingItemEntity { //TODO subfield a should be validated for yyyymm or - for unknown public ProjectedPublicationDateTag() { super(); setHeaderType((short) 38); } public StringText getStringText() { StringText result = null; String source = "" + ((BIB_ITM) getItemEntity()).getProjectedPublicationDateCode(); if (source == null) { result = new StringText(Subfield.SUBFIELD_DELIMITER + "a"); } else { result = new StringText(source); } return result; } public void setStringText(StringText st) { //TODO need a more definitive way to set to null if (st.toString().equals(Subfield.SUBFIELD_DELIMITER + "a")) { ((BIB_ITM) getItemEntity()).setProjectedPublicationDateCode(null); } else { ((BIB_ITM) getItemEntity()).setProjectedPublicationDateCode(st.toString()); } } }
package com.ua.plamber_android.utils; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; import com.ua.plamber_android.R; public class PlamberAnalytics extends Application { private Tracker mTracker; synchronized public Tracker getTracker() { if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); mTracker = analytics.newTracker(R.xml.global_tracker); } return mTracker; } }
/** * <copyright> * </copyright> * * $Id$ */ package org.reclipse.structure.inference.annotations.impl; import org.eclipse.emf.ecore.EClass; import org.reclipse.structure.inference.annotations.AnnotationsPackage; import org.reclipse.structure.inference.annotations.TemporaryAnnotation; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Temporary Annotation</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class TemporaryAnnotationImpl extends ASGAnnotationImpl implements TemporaryAnnotation { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TemporaryAnnotationImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return AnnotationsPackage.Literals.TEMPORARY_ANNOTATION; } } //TemporaryAnnotationImpl
/** * */ package com.zimbra.qa.selenium.projects.mobile.ui; import com.zimbra.qa.selenium.framework.ui.AbsApplication; import com.zimbra.qa.selenium.framework.ui.AbsPage; import com.zimbra.qa.selenium.framework.ui.AbsTab; import com.zimbra.qa.selenium.framework.ui.Action; import com.zimbra.qa.selenium.framework.ui.Button; import com.zimbra.qa.selenium.framework.util.HarnessException; /** * @author Matt Rhoades * */ public class PageMain extends AbsTab { public static class Locators { public static final String zBtnLogout = "xpath=//*[@id='_logout']"; public static final String zMainCopyright = "//div[@id='copyright_notice']"; public static final String zMainCopyrightText = "//div[@id='copyright_notice']//a"; public static final String zAppbarMail = "//div[@id='appbar']//a[@id='mail']"; public static final String zAppbarContact = "//div[@id='appbar']//a[@id='contact']"; public static final String zAppbarCal = "//div[@id='appbar']//a[@id='cal']"; public static final String zAppbarDocs = "//div[@id='appbar']//a[@id='docs']"; public static final String zAppbarSearch = "//div[@id='appbar']//a[@id='search']"; public static final String zBtnCompose = "//a[@href='zmain?st=newmail']"; public static final String zPreferences = "//a[@href='?st=prefs']"; } public PageMain(AbsApplication application) { super(application); logger.info("new " + PageMain.class.getCanonicalName()); } /* (non-Javadoc) * @see projects.admin.ui.AbsPage#isActive() */ @Override public boolean zIsActive() throws HarnessException { // Make sure the Mobile Client is loaded in the browser if ( !MyApplication.zIsLoaded() ) throw new HarnessException("Admin Console application is not active!"); // Look for the Logout button boolean present = sIsElementPresent(Locators.zBtnLogout); if ( !present ) { logger.debug("isActive() present = "+ present); return (false); } logger.debug("isActive() = "+ true); return (true); } /* (non-Javadoc) * @see projects.admin.ui.AbsPage#myPageName() */ @Override public String myPageName() { return (this.getClass().getName()); } /* (non-Javadoc) * @see projects.admin.ui.AbsPage#navigateTo() */ @Override public void zNavigateTo() throws HarnessException { if ( zIsActive() ) { // This page is already active return; } // 1. Logout // 2. Login as the default account if ( !((AppMobileClient)MyApplication).zPageLogin.zIsActive() ) { ((AppMobileClient)MyApplication).zPageLogin.zNavigateTo(); } ((AppMobileClient)MyApplication).zPageLogin.zLogin(); zWaitForActive(); } /** * Click the logout button * @throws HarnessException */ public void zLogout() throws HarnessException { logger.debug("zLogout()"); zNavigateTo(); if ( !sIsElementPresent(Locators.zBtnLogout) ) { throw new HarnessException("The logoff button is not present " + Locators.zBtnLogout); } // Click on logout sClick(Locators.zBtnLogout); ((AppMobileClient)MyApplication).zPageLogin.zWaitForActive(); ((AppMobileClient)MyApplication).zSetActiveAcount(null); } @Override public AbsPage zListItem(Action action, String item) throws HarnessException { // TODO Auto-generated method stub return null; } @Override public AbsPage zListItem(Action action, Button option, String item) throws HarnessException { // TODO Auto-generated method stub return null; } @Override public AbsPage zListItem(Action action, Button option, Button subOption ,String item) throws HarnessException { throw new HarnessException("Mobile page does not have context menu"); } @Override public AbsPage zToolbarPressButton(Button button) throws HarnessException { // TODO Auto-generated method stub return null; } @Override public AbsPage zToolbarPressPulldown(Button pulldown, Button option) throws HarnessException { // TODO Auto-generated method stub return null; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.render.intermediate; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.DefaultHandler; import org.apache.fop.accessibility.StructureTree2SAXEventAdapter; import org.apache.fop.accessibility.StructureTreeElement; import org.apache.fop.accessibility.StructureTreeEventHandler; import org.apache.fop.fo.extensions.InternalElementMapping; import org.apache.fop.util.XMLConstants; import org.apache.fop.util.XMLUtil; /** * Saves structure tree events as SAX events in order to replay them when it's * time to stream the structure tree to the output. */ final class IFStructureTreeBuilder implements StructureTreeEventHandler { static final class IFStructureTreeElement implements StructureTreeElement { private final String id; IFStructureTreeElement() { this.id = null; } IFStructureTreeElement(String id) { this.id = id; } public String getId() { return id; } } /** A SAX handler that records events to replay them later. */ static class SAXEventRecorder extends DefaultHandler { private final List<SAXEventRecorder.Event> events = new ArrayList<SAXEventRecorder.Event>(); private abstract static class Event { abstract void replay(ContentHandler handler) throws SAXException; } private abstract static class Element extends SAXEventRecorder.Event { protected final String uri; protected final String localName; protected final String qName; private Element(String uri, String localName, String qName) { this.uri = uri; this.localName = localName; this.qName = qName; } } private static final class StartElement extends SAXEventRecorder.Element { private final Attributes attributes; private StartElement(String uri, String localName, String qName, Attributes attributes) { super(uri, localName, qName); this.attributes = attributes; } @Override void replay(ContentHandler handler) throws SAXException { handler.startElement(uri, localName, qName, attributes); } } private static final class EndElement extends SAXEventRecorder.Element { private EndElement(String uri, String localName, String qName) { super(uri, localName, qName); } @Override void replay(ContentHandler handler) throws SAXException { handler.endElement(uri, localName, qName); } } private static final class StartPrefixMapping extends SAXEventRecorder.Event { private final String prefix; private final String uri; private StartPrefixMapping(String prefix, String uri) { this.prefix = prefix; this.uri = uri; } @Override void replay(ContentHandler handler) throws SAXException { handler.startPrefixMapping(prefix, uri); } } private static final class EndPrefixMapping extends SAXEventRecorder.Event { private final String prefix; private EndPrefixMapping(String prefix) { this.prefix = prefix; } @Override void replay(ContentHandler handler) throws SAXException { handler.endPrefixMapping(prefix); } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { events.add(new StartElement(uri, localName, qName, attributes)); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { events.add(new EndElement(uri, localName, qName)); } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { events.add(new StartPrefixMapping(prefix, uri)); } @Override public void endPrefixMapping(String prefix) throws SAXException { events.add(new EndPrefixMapping(prefix)); } /** * Replays the recorded events. * * @param handler {@code ContentHandler} to replay events on */ public void replay(ContentHandler handler) throws SAXException { for (SAXEventRecorder.Event e : events) { e.replay(handler); } } } private StructureTreeEventHandler delegate; private final List<SAXEventRecorder> pageSequenceEventRecorders = new ArrayList<SAXEventRecorder>(); private SAXEventRecorder retrievedMarkersEventRecorder; private int idCounter; /** * Replay SAX events for a page sequence. * @param handler The handler that receives SAX events * @param pageSequenceIndex The index of the page sequence * @throws SAXException */ public void replayEventsForPageSequence(ContentHandler handler, int pageSequenceIndex) throws SAXException { pageSequenceEventRecorders.get(pageSequenceIndex).replay(handler); } public void replayEventsForRetrievedMarkers(ContentHandler handler) throws SAXException { if (!retrievedMarkersEventRecorder.events.isEmpty()) { delegate = StructureTree2SAXEventAdapter.newInstance(handler); delegate.startPageSequence(null, null); retrievedMarkersEventRecorder.replay(handler); delegate.endPageSequence(); prepareRetrievedMarkersEventRecorder(); } } public void startPageSequence(Locale locale, String role) { SAXEventRecorder eventRecorder = new SAXEventRecorder(); pageSequenceEventRecorders.add(eventRecorder); delegate = StructureTree2SAXEventAdapter.newInstance(eventRecorder); delegate.startPageSequence(locale, role); } public void endPageSequence() { delegate.endPageSequence(); prepareRetrievedMarkersEventRecorder(); } private void prepareRetrievedMarkersEventRecorder() { SAXEventRecorder eventRecorder = new SAXEventRecorder(); retrievedMarkersEventRecorder = eventRecorder; delegate = StructureTree2SAXEventAdapter.newInstance(eventRecorder); } public StructureTreeElement startNode(String name, Attributes attributes, StructureTreeElement parent) { if (parent != null) { attributes = addParentAttribute(new AttributesImpl(attributes), parent); } delegate.startNode(name, attributes, null); return new IFStructureTreeElement(); } private AttributesImpl addParentAttribute(AttributesImpl attributes, StructureTreeElement parent) { if (parent != null) { attributes.addAttribute(InternalElementMapping.URI, InternalElementMapping.STRUCT_REF, InternalElementMapping.STANDARD_PREFIX + ":" + InternalElementMapping.STRUCT_REF, XMLConstants.CDATA, ((IFStructureTreeElement) parent).getId()); } return attributes; } public void endNode(String name) { delegate.endNode(name); } public StructureTreeElement startImageNode(String name, Attributes attributes, StructureTreeElement parent) { String id = getNextID(); AttributesImpl atts = addIDAttribute(attributes, id); addParentAttribute(atts, parent); delegate.startImageNode(name, atts, null); return new IFStructureTreeElement(id); } public StructureTreeElement startReferencedNode(String name, Attributes attributes, StructureTreeElement parent) { String id = getNextID(); AttributesImpl atts = addIDAttribute(attributes, id); addParentAttribute(atts, parent); delegate.startReferencedNode(name, atts, null); return new IFStructureTreeElement(id); } private String getNextID() { return Integer.toHexString(idCounter++); } private AttributesImpl addIDAttribute(Attributes attributes, String id) { AttributesImpl atts = new AttributesImpl(attributes); atts.addAttribute(InternalElementMapping.URI, InternalElementMapping.STRUCT_ID, InternalElementMapping.STANDARD_PREFIX + ":" + InternalElementMapping.STRUCT_ID, XMLUtil.CDATA, id); return atts; } }
package org.pitest.mutationtest.engine.gregor.mutators; import java.util.HashMap; import java.util.Map; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.pitest.mutationtest.engine.gregor.AbstractJumpMutator; import org.pitest.mutationtest.engine.gregor.MethodInfo; import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory; import org.pitest.mutationtest.engine.gregor.MutationContext; public enum RORMutator5 implements MethodMutatorFactory { ROR_MUTATOR5; public MethodVisitor create(final MutationContext context, final MethodInfo methodInfo, final MethodVisitor methodVisitor) { return new RORMethodVisitor5(this, context, methodVisitor); } public String getGloballyUniqueId() { return this.getClass().getName(); } public String getName() { return name(); } } class RORMethodVisitor5 extends AbstractJumpMutator { private static final Map<Integer, Substitution> MUTATIONS = new HashMap<Integer, Substitution>(); static { // > to != MUTATIONS.put(Opcodes.IFGT, new Substitution(Opcodes.IFNE, "Replaced greater by not equal")); MUTATIONS.put(Opcodes.IF_ICMPGT, new Substitution(Opcodes.IF_ICMPNE, "Replaced greater by not equal")); // >= to != MUTATIONS.put(Opcodes.IFGE, new Substitution(Opcodes.IFNE, "Replace greater or equal by not equal")); MUTATIONS.put(Opcodes.IF_ICMPGE, new Substitution(Opcodes.IF_ICMPNE, "Replace greater or equal by not equal")); // < to != MUTATIONS.put(Opcodes.IFLT, new Substitution(Opcodes.IFNE, "Replace less by not equal")); MUTATIONS.put(Opcodes.IF_ICMPLT, new Substitution(Opcodes.IF_ICMPNE, "Replace less by not equal")); // <= to != MUTATIONS.put(Opcodes.IFLE, new Substitution(Opcodes.IFNE, "Replace less or not equal")); MUTATIONS.put(Opcodes.IF_ICMPLE, new Substitution(Opcodes.IF_ICMPNE, "Replace less by not equal")); // == to != MUTATIONS.put(Opcodes.IFEQ, new Substitution(Opcodes.IFNE, "Replace equal by not equal")); MUTATIONS.put(Opcodes.IF_ICMPEQ, new Substitution(Opcodes.IF_ICMPNE, "Replace equal by not equal")); // != to == MUTATIONS.put(Opcodes.IFNE, new Substitution(Opcodes.IFEQ, "Replace not equal by equal")); MUTATIONS.put(Opcodes.IF_ICMPNE, new Substitution(Opcodes.IF_ICMPEQ, "Replace not equal by equal")); } RORMethodVisitor5(final MethodMutatorFactory factory, final MutationContext context, final MethodVisitor delegateMethodVisitor) { super(factory, context, delegateMethodVisitor); } @Override protected Map<Integer, Substitution> getMutations() { return MUTATIONS; } }
package edu.nju.service.impl; import com.alibaba.fastjson.JSONObject; import edu.nju.dao.StudentDao; import edu.nju.model.Student; import edu.nju.service.StudentService; import edu.nju.util.HttpClientUtil; import edu.nju.util.ResultData; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.HashMap; import java.util.Map; /** * @Author :lycheeshell * @Date :Created in 16:29 2020/1/8 */ @Service @PropertySource({"classpath:wechat.properties"}) public class StudentServiceImpl implements StudentService { private static Logger logger = Logger.getLogger(StudentServiceImpl.class); @Autowired private StudentDao studentDao; @Value("${appid}") private String appid; private String secret = "c362bebe1979032f8d00b431813388ac"; @Value("${grant_type}") private String grantType; @Value("${url}") private String url; @Override public ResultData wechatLogin(String code) { ResultData result = null; Map<String, String> param = new HashMap<>(4); param.put("appid", appid); param.put("secret", secret); param.put("js_code", code); param.put("grant_type", grantType); //获取session_id String sr = HttpClientUtil.doGet(url, param); // 判断获取的是否有值 if (StringUtils.isBlank(sr)) { result = ResultData.errorMsg("获取微信数据失败"); return result; } //解析相应内容(转换成json对象) JSONObject json = JSONObject.parseObject(sr); String openid = json.getString("openid"); Map<String, Object> map = new HashMap<>(); map.put("openid", openid); ResultData queryResponse = studentDao.queryStudentByOpenid(map); if (!queryResponse.isEmpty()) { return queryResponse; } //获取会话密钥(session_key) String sessionKey = json.getString("session_key"); Student student = new Student(); student.setOpenid(openid); student.setSession_key(sessionKey); student.setCredit(100); ResultData saveResponse = studentDao.insert(student); if (!saveResponse.isOK()) { result = ResultData.errorMsg("Fail to insert student to database"); } else { result = ResultData.ok(saveResponse.getData()); } return result; } @Override public ResultData login(String account, String password) { ResultData result; Map<String, Object> map = new HashMap<>(); map.put("account", account); map.put("password", password); ResultData response = studentDao.login(map); if (!response.isOK()) { result = ResultData.errorMsg("Query student error"); } else if (response.isEmpty()) { result = ResultData.empty(response.getData()); } else { result = ResultData.ok(response.getData()); } return result; } @Override public ResultData register(Student student) { ResultData result = null; Map<String, Object> map = new HashMap<>(); map.put("account", student.getAccount()); ResultData queryResponse = studentDao.query(map); if (!queryResponse.isEmpty()) { result = ResultData.errorMsg("账号已存在"); return result; } ResultData response = studentDao.insert(student); if (!response.isOK()) { result = ResultData.errorMsg("Fail to insert student to database"); } if (response.isOK()) { result = ResultData.ok(response.getData()); } return result; } @Override public ResultData updateStudentImage(String studentId, MultipartFile file, HttpServletRequest request) { ResultData result = null; String fileName = file.getOriginalFilename();//获取文件名加后缀 if (fileName != null && !fileName.equals("")) { String fileSuffix = fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1):"";//文件后缀 String[] suffixArray = {"jpg", "jpeg", "png", "bmp"}; boolean legal = false; for (String suf : suffixArray) { if (suf.equals(fileSuffix.toLowerCase())) { legal = true; break; } } if (!legal) { result = ResultData.errorMsg("图片格式非法"); return result; } fileName = studentId + "." + fileSuffix;//新的文件名: gameId.type String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/static/images/";//存储路径 String path = request.getSession().getServletContext().getRealPath("/"); //文件存储位置 System.out.println("returnUrl: " + returnUrl + "student/"); System.out.println("path: " + path + "static/images/student/"); //先判断文件是否存在 //获取文件夹路径 File folder = new File(path + "static/images/student/"); //如果文件夹不存在则创建 if (!folder.exists()) { folder.mkdirs(); System.out.println("create folder"); } //将图片存入文件夹 File targetFile = new File(folder, fileName); try { //将上传的文件写到服务器上指定的文件。 file.transferTo(targetFile); String url = returnUrl + "student/" + fileName; Student student = new Student(); student.setStudentId(studentId); student.setPhotoUrl(url); ResultData response = studentDao.updateImage(student); if (!response.isOK()) { result = ResultData.errorMsg("Fail to update image of student to database"); } if (response.isOK()) { result = ResultData.ok(response.getData()); } } catch (Exception e) { System.out.println(e.getMessage()); result = ResultData.errorMsg("Fail to upload file"); } } return result; } @Override public ResultData update(Student student) { ResultData result = null; ResultData response = studentDao.update(student); if (!response.isOK()) { result = ResultData.errorMsg("Fail to update student to database"); } if (response.isOK()) { result = ResultData.ok(response.getData()); } return result; } @Override public ResultData query(String studentId) { ResultData result; Map<String, Object> map = new HashMap<>(); map.put("studentId", studentId); ResultData response = studentDao.query(map); if (!response.isOK()) { result = ResultData.errorMsg("Query student error"); } else if (response.isEmpty()) { result = ResultData.empty(response.getData()); } else { result = ResultData.ok(response.getData()); } return result; } }
/* * Copyright 2020 EPAM Systems * * 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.epam.eco.commons.avro.modification; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; /** * @author Andrei_Tytsik */ public class RemoveSchemaProperties implements SchemaModification { private final List<String> keys; public RemoveSchemaProperties(Collection<String> keys) { Validate.notEmpty(keys, "Collection of keys is null or empty"); Validate.noNullElements(keys, "Collection of keys has null elements"); this.keys = Collections.unmodifiableList(new ArrayList<>(keys)); } public List<String> getKeys() { return keys; } @Override public void applyToGeneric(Map<String, Object> schemaMap) { for (String key : keys) { schemaMap.remove(key); } } @Override public String toString() { return String.format( "%s: {keys: %s}", this.getClass().getSimpleName(), StringUtils.join(keys, ", ")); } @Override public int hashCode() { return Objects.hash(keys); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } RemoveSchemaProperties that = (RemoveSchemaProperties)obj; return Objects.equals(this.keys, that.keys); } public static RemoveSchemaProperties with(String ... keys) { return new RemoveSchemaProperties(keys != null ? Arrays.asList(keys) : null); } public static RemoveSchemaProperties with(Collection<String> keys) { return new RemoveSchemaProperties(keys); } }
package uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.pip; import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; import javax.validation.Validator; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.sscs.ccd.callback.PreSubmitCallbackResponse; import uk.gov.hmcts.reform.sscs.ccd.domain.SscsCaseData; import uk.gov.hmcts.reform.sscs.ccd.domain.YesNo; import uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.AwardType; import uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.WriteFinalDecisionMidEventValidationHandlerBase; import uk.gov.hmcts.reform.sscs.service.DecisionNoticeService; @Slf4j @Component public class PipWriteFinalDecisionMidEventValidationHandler extends WriteFinalDecisionMidEventValidationHandlerBase { public PipWriteFinalDecisionMidEventValidationHandler(Validator validator, DecisionNoticeService decisionNoticeService) { super(validator, decisionNoticeService); } @Override protected String getBenefitType() { return "PIP"; } @Override protected void setDefaultFields(SscsCaseData sscsCaseData) { if (sscsCaseData.getWriteFinalDecisionEndDateType() == null && "yes".equalsIgnoreCase(sscsCaseData.getWriteFinalDecisionIsDescriptorFlow())) { if (bothDailyLivingAndMobilityQuestionsAnswered(sscsCaseData) && isNoAwardOrNotConsideredForDailyLiving(sscsCaseData) && isNoAwardOrNotConsideredForMobility(sscsCaseData)) { sscsCaseData.setWriteFinalDecisionEndDateType("na"); } } } @Override protected void setShowPageFlags(SscsCaseData sscsCaseData) { // N/A for PIP } @Override protected void validateAwardTypes(SscsCaseData sscsCaseData, PreSubmitCallbackResponse<SscsCaseData> preSubmitCallbackResponse) { if (((!equalsIgnoreCase(AwardType.NO_AWARD.getKey(), sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion()) && !equalsIgnoreCase(AwardType.NOT_CONSIDERED.getKey(), sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion())) || ((!equalsIgnoreCase(AwardType.NO_AWARD.getKey(), sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion()) && !equalsIgnoreCase(AwardType.NOT_CONSIDERED.getKey(), sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion())))) && sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingActivitiesQuestion() != null && sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityActivitiesQuestion() != null && sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingActivitiesQuestion().isEmpty() && sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityActivitiesQuestion().isEmpty()) { preSubmitCallbackResponse.addError("At least one activity must be selected unless there is no award"); } if (AwardType.NO_AWARD.getKey().equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion()) && "higher".equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionComparedToDwpDailyLivingQuestion())) { preSubmitCallbackResponse.addError("Daily living decision of No Award cannot be higher than DWP decision"); } if (AwardType.NO_AWARD.getKey().equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion()) && "higher".equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionComparedToDwpMobilityQuestion())) { preSubmitCallbackResponse.addError("Mobility decision of No Award cannot be higher than DWP decision"); } if (AwardType.ENHANCED_RATE.getKey().equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion()) && "lower".equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionComparedToDwpDailyLivingQuestion())) { preSubmitCallbackResponse.addError("Daily living award at Enhanced Rate cannot be lower than DWP decision"); } if (AwardType.ENHANCED_RATE.getKey().equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion()) && "lower".equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionComparedToDwpMobilityQuestion())) { preSubmitCallbackResponse.addError("Mobility award at Enhanced Rate cannot be lower than DWP decision"); } if (AwardType.NOT_CONSIDERED.getKey().equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion()) && AwardType.NOT_CONSIDERED.getKey().equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion())) { preSubmitCallbackResponse.addError("At least one of Mobility or Daily Living must be considered"); } if ("yes".equalsIgnoreCase(sscsCaseData.getWriteFinalDecisionIsDescriptorFlow()) && bothDailyLivingAndMobilityQuestionsAnswered(sscsCaseData)) { if (isNoAwardOrNotConsideredForDailyLiving(sscsCaseData) && isNoAwardOrNotConsideredForMobility(sscsCaseData)) { if (sscsCaseData.getWriteFinalDecisionEndDateType() != null && !"na".equals(sscsCaseData.getWriteFinalDecisionEndDateType())) { preSubmitCallbackResponse.addError("End date is not applicable for this decision - please specify 'N/A - No Award'."); } } else { if ("na".equals(sscsCaseData.getWriteFinalDecisionEndDateType())) { preSubmitCallbackResponse.addError("An end date must be provided or set to Indefinite for this decision."); } } } } @Override protected void setShowSummaryOfOutcomePage(SscsCaseData sscsCaseData) { if (sscsCaseData.getWriteFinalDecisionIsDescriptorFlow() != null && sscsCaseData.getWriteFinalDecisionIsDescriptorFlow().equalsIgnoreCase(YesNo.NO.getValue()) && sscsCaseData.getWriteFinalDecisionGenerateNotice() != null && sscsCaseData.getWriteFinalDecisionGenerateNotice().equalsIgnoreCase(YesNo.YES.getValue())) { sscsCaseData.setShowFinalDecisionNoticeSummaryOfOutcomePage(YesNo.YES); return; } sscsCaseData.setShowFinalDecisionNoticeSummaryOfOutcomePage(YesNo.NO); } @Override protected void setDwpReassessAwardPage(SscsCaseData sscsCaseData) { sscsCaseData.setShowDwpReassessAwardPage(YesNo.NO); } private boolean isNoAwardOrNotConsideredForMobility(SscsCaseData sscsCaseData) { return sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion() != null && ("noAward".equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion()) || "notConsidered".equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion())); } private boolean isNoAwardOrNotConsideredForDailyLiving(SscsCaseData sscsCaseData) { return sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion() != null && ("noAward".equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion()) || "notConsidered".equals(sscsCaseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion())); } private boolean bothDailyLivingAndMobilityQuestionsAnswered(SscsCaseData caseData) { return caseData.getSscsPipCaseData().getPipWriteFinalDecisionDailyLivingQuestion() != null && caseData.getSscsPipCaseData().getPipWriteFinalDecisionMobilityQuestion() != null; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2022 the original author or authors. */ package org.assertj.core.api.predicate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ElementsShouldMatch.elementsShouldMatch; import static org.assertj.core.error.ShouldAccept.shouldAccept; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.assertj.core.util.Lists.newArrayList; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.function.Predicate; import org.assertj.core.api.PredicateAssert; import org.assertj.core.api.PredicateAssertBaseTest; import org.assertj.core.presentation.PredicateDescription; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; /** * @author Filip Hrisafov */ @ExtendWith(MockitoExtension.class) class PredicateAssert_accepts_Test extends PredicateAssertBaseTest { @Override protected PredicateAssert<Boolean> invoke_api_method() { return assertions.accepts(true, true); } @Override protected void verify_internal_effects() { verify(iterables).assertAllMatch(getInfo(assertions), newArrayList(true, true), getActual(assertions), PredicateDescription.GIVEN); } @Test void should_fail_when_predicate_is_null() { // GIVEN String[] values = { "first", "second" }; // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat((Predicate<String>) null).accepts(values)); // THEN then(assertionError).hasMessage(actualIsNull()); } @Test void should_fail_when_predicate_does_not_accept_values() { // GIVEN String[] values = { "football", "basketball", "curling" }; Predicate<String> ballSportPredicate = sport -> sport.contains("ball"); // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(ballSportPredicate).accepts(values)); // THEN then(assertionError).hasMessage(elementsShouldMatch(values, "curling", PredicateDescription.GIVEN).create()); } @Test void should_pass_when_predicate_accepts_all_values() { // GIVEN Predicate<String> ballSportPredicate = sport -> sport.contains("ball"); // WHEN/THEN assertThat(ballSportPredicate).accepts("football", "basketball", "handball"); } @Test void should_fail_when_predicate_does_not_accept_value() { // GIVEN Predicate<String> predicate = val -> val.equals("something"); String expectedValue = "something else"; // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(predicate).accepts(expectedValue)); // THEN then(assertionError).hasMessage(shouldAccept(predicate, expectedValue, PredicateDescription.GIVEN).create()); } @Test void should_fail_when_predicate_does_not_accept_value_with_string_description() { // GIVEN Predicate<String> predicate = val -> val.equals("something"); String expectedValue = "something else"; // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(predicate).as("test").accepts(expectedValue)); // THEN then(assertionError).hasMessage("[test] " + shouldAccept(predicate, expectedValue, PredicateDescription.GIVEN).create()); } @Test void should_pass_when_predicate_accepts_value() { // GIVEN Predicate<String> predicate = val -> val.equals("something"); // WHEN/THEN assertThat(predicate).accepts("something"); } @Test void should_pass_and_only_invoke_predicate_once_for_single_value(@Mock Predicate<Object> predicate) { // GIVEN when(predicate.test(any())).thenReturn(true); // WHEN assertThat(predicate).accepts("something"); // THEN verify(predicate).test("something"); } }
/* * Copyright 2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.springframework.geode.boot.autoconfigure; import static org.springframework.data.gemfire.util.CollectionUtils.asSet; import java.util.Properties; import java.util.Set; import org.apache.geode.cache.GemFireCache; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Import; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.geode.boot.autoconfigure.support.EnableSubscriptionConfiguration; import org.springframework.session.Session; import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession; import org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration; import org.springframework.session.web.http.SessionRepositoryFilter; import org.springframework.util.StringUtils; /** * Spring Boot {@link EnableAutoConfiguration auto-configuration} for configuring Apache Geode * as an (HTTP) {@link Session} state management provider in Spring Session. * * @author John Blum * @see java.util.Properties * @see org.apache.geode.cache.GemFireCache * @see org.springframework.boot.SpringApplication * @see org.springframework.boot.SpringBootConfiguration * @see org.springframework.boot.autoconfigure.AutoConfigureAfter * @see org.springframework.boot.autoconfigure.EnableAutoConfiguration * @see org.springframework.boot.autoconfigure.condition.ConditionalOnBean * @see org.springframework.boot.autoconfigure.condition.ConditionalOnClass * @see org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean * @see org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication * @see org.springframework.context.annotation.Condition * @see org.springframework.context.annotation.ConditionContext * @see org.springframework.context.annotation.Conditional * @see org.springframework.context.annotation.Import * @see org.springframework.core.env.ConfigurableEnvironment * @see org.springframework.core.env.PropertiesPropertySource * @see org.springframework.core.env.PropertySource * @see org.springframework.core.type.AnnotatedTypeMetadata * @see org.springframework.geode.boot.autoconfigure.support.EnableSubscriptionConfiguration * @see org.springframework.session.Session * @see org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession * @see org.springframework.session.data.gemfire.config.annotation.web.http.GemFireHttpSessionConfiguration * @see org.springframework.session.web.http.SessionRepositoryFilter * @since 1.0.0 */ @SpringBootConfiguration @AutoConfigureAfter(ClientCacheAutoConfiguration.class) @Conditional(SpringSessionAutoConfiguration.SpringSessionStoreTypeCondition.class) @ConditionalOnBean(GemFireCache.class) @ConditionalOnClass({ GemFireCache.class, GemFireHttpSessionConfiguration.class }) @ConditionalOnMissingBean(SessionRepositoryFilter.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @EnableGemFireHttpSession(poolName = "DEFAULT") @Import(EnableSubscriptionConfiguration.class) @SuppressWarnings("unused") public class SpringSessionAutoConfiguration { protected static final Set<String> SPRING_SESSION_STORE_TYPES = asSet("gemfire", "geode"); protected static final String SERVER_SERVLET_SESSION_TIMEOUT_PROPERTY = "server.servlet.session.timeout"; protected static final String SPRING_SESSION_DATA_GEMFIRE_SESSION_EXPIRATION_TIMEOUT = "spring.session.data.gemfire.session.expiration.max-inactive-interval-seconds"; protected static final String SPRING_SESSION_PROPERTY_SOURCE_NAME = "SpringSessionProperties"; protected static final String SPRING_SESSION_STORE_TYPE_PROPERTY = "spring.session.store-type"; protected static final String SPRING_SESSION_TIMEOUT_PROPERTY = "spring.session.timeout"; public static class SpringSessionPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (isNotSet(environment, SPRING_SESSION_DATA_GEMFIRE_SESSION_EXPIRATION_TIMEOUT)) { Properties springSessionProperties = new Properties(); if (isSet(environment, SPRING_SESSION_TIMEOUT_PROPERTY)) { springSessionProperties.setProperty(SPRING_SESSION_DATA_GEMFIRE_SESSION_EXPIRATION_TIMEOUT, environment.getProperty(SPRING_SESSION_TIMEOUT_PROPERTY)); } else if (isSet(environment, SERVER_SERVLET_SESSION_TIMEOUT_PROPERTY)) { springSessionProperties.setProperty(SPRING_SESSION_DATA_GEMFIRE_SESSION_EXPIRATION_TIMEOUT, environment.getProperty(SERVER_SERVLET_SESSION_TIMEOUT_PROPERTY)); } if (!springSessionProperties.isEmpty()) { environment.getPropertySources() .addFirst(newPropertySource(SPRING_SESSION_PROPERTY_SOURCE_NAME, springSessionProperties)); } } } private PropertySource<?> newPropertySource(String name, Properties properties) { return new PropertiesPropertySource(name, properties); } } protected static boolean isNotSet(ConfigurableEnvironment environment, String propertyName) { return !isSet(environment, propertyName); } protected static boolean isSet(ConfigurableEnvironment environment, String propertyName) { return environment.containsProperty(propertyName) && StringUtils.hasText(environment.getProperty(propertyName)); } protected static class SpringSessionStoreTypeCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String springSessionStoreTypeValue = context.getEnvironment().getProperty(SPRING_SESSION_STORE_TYPE_PROPERTY); return !StringUtils.hasText(springSessionStoreTypeValue) || SPRING_SESSION_STORE_TYPES.contains(springSessionStoreTypeValue.trim().toLowerCase()); } } }
package org.gendut.memory; import java.lang.ref.WeakReference; import java.util.WeakHashMap; public final class SingleAllocator { private WeakHashMap<ManagedNode<?>, WeakReference<ManagedNode<?>>> memorizedNodes; public SingleAllocator(int initialSize) { memorizedNodes = new WeakHashMap<>(initialSize); } @SuppressWarnings("unchecked") public<T extends ManagedNode<T>> ManagedNode<T> unifiedAlloc(ManagedNode<T> node) { synchronized (memorizedNodes) { WeakReference<ManagedNode<?>> entry = memorizedNodes.get(node); if (entry != null) { return (ManagedNode<T>) entry.get(); } else { memorizedNodes.put(node, new WeakReference<ManagedNode<?>>(node)); return node; } } } }
/** * */ /** * @author wessl03 * */ package de.ne0.sonar.plsql.checks.utils;
/* * Copyright 2012-2018 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. */ /** * <fullname>AWS IoT</fullname> * <p> * AWS IoT-Data enables secure, bi-directional communication between Internet-connected things (such as sensors, * actuators, embedded devices, or smart appliances) and the AWS cloud. It implements a broker for applications and * things to publish messages over HTTP (Publish) and retrieve, update, and delete thing shadows. A thing shadow is a * persistent representation of your things and their state in the AWS cloud. * </p> */ package com.amazonaws.services.iotdata;
package org.cryptimeleon.math.structures.groups.elliptic.type1.supersingular; import org.cryptimeleon.math.serialization.Representation; import org.cryptimeleon.math.structures.groups.lazy.LazyBilinearGroup; /** * A type 1 supersingular bilinear group where operations are evaluated lazily. * <p> * Due to lazy evaluation, this group is more efficient than its non-lazy counterpart * {@link SupersingularBasicBilinearGroup}. * * @see SupersingularBasicBilinearGroup for the version without lazy evaluation */ public class SupersingularBilinearGroup extends LazyBilinearGroup { public SupersingularBilinearGroup(int securityParameter) { super(new SupersingularTateGroupImpl(securityParameter)); } public SupersingularBilinearGroup(Representation repr) { super(repr); } }
package jadx.core.clsp; /** * Class node in classpath graph */ public class NClass { private final String name; private NClass[] parents; private int id; public NClass(String name, int id) { this.name = name; this.id = id; } public String getName() { return name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public NClass[] getParents() { return parents; } public void setParents(NClass[] parents) { this.parents = parents; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NClass nClass = (NClass) o; return name.equals(nClass.name); } @Override public String toString() { return name; } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v201805; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Captures a page of {@link ContentMetadataKeyHierarchy} objects. This is deprecated and will be * removed as of V201811. * * * <p>Java class for ContentMetadataKeyHierarchyPage complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ContentMetadataKeyHierarchyPage"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="totalResultSetSize" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="startIndex" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="results" type="{https://www.google.com/apis/ads/publisher/v201805}ContentMetadataKeyHierarchy" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ContentMetadataKeyHierarchyPage", propOrder = { "totalResultSetSize", "startIndex", "results" }) public class ContentMetadataKeyHierarchyPage { protected Integer totalResultSetSize; protected Integer startIndex; protected List<ContentMetadataKeyHierarchy> results; /** * Gets the value of the totalResultSetSize property. * * @return * possible object is * {@link Integer } * */ public Integer getTotalResultSetSize() { return totalResultSetSize; } /** * Sets the value of the totalResultSetSize property. * * @param value * allowed object is * {@link Integer } * */ public void setTotalResultSetSize(Integer value) { this.totalResultSetSize = value; } /** * Gets the value of the startIndex property. * * @return * possible object is * {@link Integer } * */ public Integer getStartIndex() { return startIndex; } /** * Sets the value of the startIndex property. * * @param value * allowed object is * {@link Integer } * */ public void setStartIndex(Integer value) { this.startIndex = value; } /** * Gets the value of the results property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the results property. * * <p> * For example, to add a new item, do as follows: * <pre> * getResults().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ContentMetadataKeyHierarchy } * * */ public List<ContentMetadataKeyHierarchy> getResults() { if (results == null) { results = new ArrayList<ContentMetadataKeyHierarchy>(); } return this.results; } }
package xworker.net.jsch; import java.io.InputStream; import java.io.OutputStream; import org.xmeta.ActionContext; import org.xmeta.Thing; import com.jcraft.jsch.Channel; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class Shell { public static Object run(ActionContext actionContext) throws JSchException{ Thing self = (Thing) actionContext.get("self"); Session session = (Session) self.doAction("getSession", actionContext); InputStream in = (InputStream) self.doAction("getInputStream", actionContext); OutputStream out = (OutputStream) self.doAction("getOutputStream", actionContext); Channel channel=session.openChannel("shell"); channel.setInputStream(in); channel.setOutputStream(out); channel.connect(10000); return channel; } public static Object getInputStream(ActionContext actionContext) throws JSchException{ Thing self = (Thing) actionContext.get("self"); String inputStream = self.getStringBlankAsNull("inputStream"); if(inputStream != null){ return (InputStream) actionContext.get(inputStream); }else{ return System.in; } } public static Object getOutputStream(ActionContext actionContext) throws JSchException{ Thing self = (Thing) actionContext.get("self"); String outputStream = self.getStringBlankAsNull("outputStream"); if(outputStream != null){ return (OutputStream) actionContext.get(outputStream); }else{ return System.out; } } }
package com.compy.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } public ResourceNotFoundException(String message, Throwable cause) { super(message, cause); } }
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.watson.developer_cloud.android.myapplication; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.ibm.watson.developer_cloud.android.library.audio.CameraHelper; import com.ibm.watson.developer_cloud.android.library.audio.GalleryHelper; import com.ibm.watson.developer_cloud.android.library.audio.MicrophoneInputStream; import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer; import com.ibm.watson.developer_cloud.language_translation.v2.LanguageTranslation; import com.ibm.watson.developer_cloud.language_translation.v2.model.Language; import com.ibm.watson.developer_cloud.speech_to_text.v1.SpeechToText; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults; import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.RecognizeCallback; import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice; import com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.DetectedFaces; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.Face; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.VisualRecognitionOptions; public class MainActivity extends AppCompatActivity { private final String TAG = "MainActivity"; private RadioGroup targetLanguage; private EditText input; private ImageButton mic; private Button translate; private ImageButton play; private TextView translatedText; private ImageView loadedImage; private TextView ageMinText; private TextView ageMaxText; private TextView genderText; private SpeechToText speechService; private TextToSpeech textService; private LanguageTranslation translationService; private VisualRecognition visualService; private Language selectedTargetLanguage = Language.SPANISH; private StreamPlayer player = new StreamPlayer(); private CameraHelper cameraHelper; private GalleryHelper galleryHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cameraHelper = new CameraHelper(this); galleryHelper = new GalleryHelper(this); speechService = initSpeechToTextService(); textService = initTextToSpeechService(); translationService = initLanguageTranslationService(); visualService = initVisualRecognitionService(); //setup screen elements targetLanguage = (RadioGroup) findViewById(R.id.target_language); input = (EditText) findViewById(R.id.input); mic = (ImageButton) findViewById(R.id.mic); translate = (Button) findViewById(R.id.translate); play = (ImageButton) findViewById(R.id.play); translatedText = (TextView) findViewById(R.id.translated_text); loadedImage = (ImageView) findViewById(R.id.loaded_image); ageMinText = (TextView) findViewById(R.id.visual_age_min); ageMaxText = (TextView) findViewById(R.id.visual_age_max); genderText = (TextView) findViewById(R.id.visual_gender); //setup buttons for language selection targetLanguage.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.spanish: selectedTargetLanguage = Language.SPANISH; break; case R.id.french: selectedTargetLanguage = Language.FRENCH; break; case R.id.italian: selectedTargetLanguage = Language.ITALIAN; break; } } }); //setup listener for keyboard input input.addTextChangedListener(new EmptyTextWatcher() { @Override public void onEmpty(boolean empty) { if (empty) { translate.setEnabled(false); } else { translate.setEnabled(true); } } }); //setup microphone listener mic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mic.setEnabled(false); new Thread(new Runnable() { @Override public void run() { try { RecognizeOptions options = new RecognizeOptions.Builder() .continuous(true) .contentType(MicrophoneInputStream.CONTENT_TYPE) .model("en-US_BroadbandModel") .interimResults(true) .inactivityTimeout(2000) .build(); speechService.recognizeUsingWebSocket(new MicrophoneInputStream(), options, new MicrophoneRecognizeDelegate()); } catch (Exception e) { showError(e); } } }).start(); } }); //setup translate button listener translate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new TranslationTask().execute(input.getText().toString()); } }); //setup translate text listener translatedText.addTextChangedListener(new EmptyTextWatcher() { @Override public void onEmpty(boolean empty) { if (empty) { play.setEnabled(false); } else { play.setEnabled(true); } } }); //setup play button for text to speech play.setEnabled(false); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new SynthesisTask().execute(translatedText.getText().toString()); } }); } private SpeechToText initSpeechToTextService() { SpeechToText service = new SpeechToText(); String username = getString(R.string.speech_text_username); String password = getString(R.string.speech_text_password); service.setUsernameAndPassword(username, password); service.setEndPoint("https://stream.watsonplatform.net/speech-to-text/api"); return service; } private TextToSpeech initTextToSpeechService() { TextToSpeech service = new TextToSpeech(); String username = getString(R.string.text_speech_username); String password = getString(R.string.text_speech_password); service.setUsernameAndPassword(username, password); return service; } private LanguageTranslation initLanguageTranslationService() { LanguageTranslation service = new LanguageTranslation(); String username = getString(R.string.language_translation_username); String password = getString(R.string.language_translation_password); service.setUsernameAndPassword(username, password); return service; } private VisualRecognition initVisualRecognitionService() { return new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_20, getString(R.string.visual_recognition_api_key)); } private class MicrophoneRecognizeDelegate implements RecognizeCallback { @Override public void onTranscription(SpeechResults speechResults) { String text = speechResults.getResults().get(0).getAlternatives().get(0).getTranscript(); String takeASelfie = "take a selfie "; if (text.equals(takeASelfie) && !input.getText().toString().equals(takeASelfie)) { cameraHelper.dispatchTakePictureIntent(); } showMicText(text); } @Override public void onConnected() { } @Override public void onError(Exception e) { showError(e); enableMicButton(); } @Override public void onDisconnected() { enableMicButton(); } } private class TranslationTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { showTranslation(translationService.translate(params[0], Language.ENGLISH, selectedTargetLanguage).execute().getFirstTranslation()); return "Did translate"; } } private class SynthesisTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { player.playStream(textService.synthesize(params[0], Voice.EN_LISA).execute()); return "Did syntesize"; } } private class VisualTask extends AsyncTask<Integer, Void, String> { @Override protected String doInBackground(Integer... integers) { VisualRecognitionOptions options = new VisualRecognitionOptions.Builder() .images(cameraHelper.getFile(integers[0])) .build(); DetectedFaces faces = visualService.detectFaces(options).execute(); if (!faces.getImages().get(0).getFaces().isEmpty()) { Face face = faces.getImages().get(0).getFaces().get(0); Face.Age age = faces.getImages().get(0).getFaces().get(0).getAge(); showAgeMin(Integer.toString(age.getMin())); showAgeMax(Integer.toString(age.getMax())); showGender(face.getGender().getGender()); } return "Did visual"; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CameraHelper.REQUEST_IMAGE_CAPTURE) { loadedImage.setImageBitmap(cameraHelper.getBitmap(resultCode)); new VisualTask().execute(resultCode); } if (requestCode == GalleryHelper.PICK_IMAGE_REQUEST) { loadedImage.setImageBitmap(galleryHelper.getBitmap(resultCode, data)); } } //------------------UI methods-------------------------------------- private void showTranslation(final String translation) { runOnUiThread(new Runnable() { @Override public void run() { translatedText.setText(translation); } }); } private void showError(final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }); } private void showMicText(final String text) { runOnUiThread(new Runnable() { @Override public void run() { input.setText(text); } }); } private void showAgeMin(final String ageMin) { runOnUiThread(new Runnable() { @Override public void run() { ageMinText.setText(ageMin); } }); } private void showAgeMax(final String ageMax) { runOnUiThread(new Runnable() { @Override public void run() { ageMaxText.setText(ageMax); } }); } private void showGender(final String gender) { runOnUiThread(new Runnable() { @Override public void run() { genderText.setText(gender); } }); } private void enableMicButton() { runOnUiThread(new Runnable() { @Override public void run() { mic.setEnabled(true); } }); } //Watch for keyboard input private abstract class EmptyTextWatcher implements TextWatcher { private boolean isEmpty = true; // assumes text is initially empty @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() == 0) { isEmpty = true; onEmpty(true); } else if (isEmpty) { isEmpty = false; onEmpty(false); } } @Override public void afterTextChanged(Editable s) {} public abstract void onEmpty(boolean empty); } }
package com.outlook.bigkun.demo1; /** * @author zhanghk * @since 2019/8/13 */ public class Main { public static void main(String[] args) { String instruction = "up move 5 and down run 10 and left move 5"; InstructionHandler handler = new InstructionHandler(); handler.handle(instruction); String outString = handler.output(); System.out.println(outString); } }
package us.ihmc.commonWalkingControlModules.desiredFootStep; import us.ihmc.euclid.referenceFrame.FramePoint2D; import us.ihmc.euclid.referenceFrame.FramePoint3D; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.euclid.referenceFrame.interfaces.FramePoint2DReadOnly; import us.ihmc.euclid.referenceFrame.interfaces.FramePoint3DReadOnly; import us.ihmc.humanoidRobotics.footstep.Footstep; import us.ihmc.robotics.robotSide.RobotSide; public class TransferToAndNextFootstepsData { private final FramePoint3D transferToPosition = new FramePoint3D(); private final FramePoint2D comAtEndOfState = new FramePoint2D(); private RobotSide transferToSide; public TransferToAndNextFootstepsData() { comAtEndOfState.setToNaN(); } public FramePoint3DReadOnly getTransferToPosition() { return transferToPosition; } public void setComAtEndOfState(FramePoint3DReadOnly comAtEndOfState) { this.comAtEndOfState.set(comAtEndOfState); } public FramePoint2DReadOnly getCoMAtEndOfState() { return comAtEndOfState; } public void setTransferToPosition(FramePoint3DReadOnly transferToPosition) { this.transferToPosition.set(transferToPosition); } public void setTransferToPosition(ReferenceFrame referenceFrame) { transferToPosition.setToZero(referenceFrame); transferToPosition.changeFrame(ReferenceFrame.getWorldFrame()); } public RobotSide getTransferToSide() { return transferToSide; } public void setTransferToSide(RobotSide transferToSide) { this.transferToSide = transferToSide; } }
/* * #%L * omakase * %% * Copyright (C) 2015 Project Omakase LLC * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.projectomakase.omakase.rest; import org.projectomakase.omakase.broker.rest.v1.BrokerResource; import org.projectomakase.omakase.content.rest.v1.ContentResource; import org.projectomakase.omakase.job.rest.v1.JobManagementResource; import org.projectomakase.omakase.job.rest.v1.interceptor.PostJobInterceptor; import org.projectomakase.omakase.job.rest.v1.interceptor.PutJobConfigInterceptor; import org.projectomakase.omakase.location.rest.v1.LocationResource; import org.projectomakase.omakase.location.rest.v1.interceptor.PutLocationConfigInterceptor; import org.projectomakase.omakase.repository.rest.v1.RepositoryResource; import org.projectomakase.omakase.repository.rest.v1.interceptor.PutRepositoryConfigInterceptor; import org.projectomakase.omakase.rest.exception.EJBExceptionMapper; import org.projectomakase.omakase.rest.exception.InvalidPropertyExceptionMapper; import org.projectomakase.omakase.rest.exception.InvalidSearchConditionExceptionMapper; import org.projectomakase.omakase.rest.exception.InvalidUUIDExceptionMapper; import org.projectomakase.omakase.rest.exception.JaxRsNotFoundExceptionMapper; import org.projectomakase.omakase.rest.exception.JobConfigurationExceptionMapper; import org.projectomakase.omakase.rest.exception.JsonMappingExceptionMapper; import org.projectomakase.omakase.rest.exception.JsonParseExceptionMapper; import org.projectomakase.omakase.rest.exception.NotAuthorizedExceptionMapper; import org.projectomakase.omakase.rest.exception.NotFoundExceptionMapper; import org.projectomakase.omakase.rest.exception.NotUpdateableExceptionMapper; import org.projectomakase.omakase.rest.exception.RepositoryConfigurationExceptionMapper; import org.projectomakase.omakase.rest.exception.ThrowableExceptionMapper; import org.projectomakase.omakase.rest.exception.WebApplicationExceptionMapper; import org.projectomakase.omakase.rest.patch.JsonPatchInterceptor; import org.projectomakase.omakase.rest.provider.JsonProvider; import org.projectomakase.omakase.rest.status.v1.StatusResource; import org.projectomakase.omakase.rest.version.APIVersionRequestFilter; import org.projectomakase.omakase.version.rest.v1.VersionResource; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import java.util.HashSet; import java.util.Set; /** * Omakase REST Application * * @author Richard Lucas */ @ApplicationPath("api") public class OmakaseApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> resources = new HashSet<>(); resources.addAll(getProviders()); resources.addAll(getInterceptorsAndFilters()); resources.addAll(getOmakaseAPIResources()); resources.addAll(getExceptionMappers()); return resources; } private Set<Class<?>> getOmakaseAPIResources() { Set<Class<?>> resources = new HashSet<>(); resources.add(ContentResource.class); resources.add(JobManagementResource.class); resources.add(RepositoryResource.class); resources.add(LocationResource.class); resources.add(BrokerResource.class); resources.add(StatusResource.class); resources.add(VersionResource.class); return resources; } private Set<Class<?>> getExceptionMappers() { Set<Class<?>> resources = new HashSet<>(); resources.add(ThrowableExceptionMapper.class); resources.add(WebApplicationExceptionMapper.class); resources.add(EJBExceptionMapper.class); resources.add(NotAuthorizedExceptionMapper.class); resources.add(NotFoundExceptionMapper.class); resources.add(InvalidPropertyExceptionMapper.class); resources.add(JaxRsNotFoundExceptionMapper.class); resources.add(JsonMappingExceptionMapper.class); resources.add(JsonParseExceptionMapper.class); resources.add(InvalidSearchConditionExceptionMapper.class); resources.add(RepositoryConfigurationExceptionMapper.class); resources.add(NotUpdateableExceptionMapper.class); resources.add(InvalidUUIDExceptionMapper.class); resources.add(JobConfigurationExceptionMapper.class); return resources; } private Set<Class<?>> getProviders() { Set<Class<?>> resources = new HashSet<>(); resources.add(JsonProvider.class); return resources; } private Set<Class<?>> getInterceptorsAndFilters() { Set<Class<?>> resources = new HashSet<>(); resources.add(JsonPatchInterceptor.class); resources.add(PostJobInterceptor.class); resources.add(PutJobConfigInterceptor.class); resources.add(PutRepositoryConfigInterceptor.class); resources.add(PutLocationConfigInterceptor.class); resources.add(APIVersionRequestFilter.class); return resources; } }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands.test; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Magazine_Subsystem; import frc.robot.subsystems.shooter.Shooter_Subsystem; public class dumbshooter extends CommandBase { /** Creates a new dumbshooter. */ double upperTarget; double lowerTarget; double beltSpeed; Shooter_Subsystem shooter; Magazine_Subsystem magazine; public dumbshooter(Shooter_Subsystem shooter, Magazine_Subsystem magazine) { // Use addRequirements() here to declare subsystem dependencies. addRequirements(shooter); this.shooter = shooter; this.magazine = magazine; } // Called when the command is initially scheduled. @Override public void initialize() { upperTarget = 0; lowerTarget = 0; beltSpeed = 0; SmartDashboard.putNumber("UpperTarget%", upperTarget); SmartDashboard.putNumber("BeltSpeed%", beltSpeed); //SmartDashboard.putNumber("LowerTarget%", lowerTarget); } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { upperTarget = SmartDashboard.getNumber("UpperTarget%", 0); //lowerTarget = SmartDashboard.getNumber("LowerTarget%", 0); beltSpeed = SmartDashboard.getNumber("BeltSpeed%", beltSpeed); shooter.onPercent(upperTarget, upperTarget); magazine.driveWheelOn(beltSpeed); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { shooter.off(); magazine.driveWheelOff(); } // Returns true when the command should end. @Override public boolean isFinished() { return false; } }
package org.codehaus.xfire.wsdl11; import javax.wsdl.Definition; import javax.wsdl.Message; import javax.xml.namespace.QName; import org.codehaus.xfire.wsdl11.builder.WSDLBuilder; import org.codehaus.xfire.wsdl11.builder.WSDLBuilderExtension; public class CustomExtension implements WSDLBuilderExtension { public void extend(Definition definition, WSDLBuilder builder) { Message message = definition.createMessage(); message.setQName(new QName("urn:foo", "Test")); message.setUndefined(false); definition.addMessage(message); } }
/* * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.HashMap; import java.util.Map; import android.os.Parcelable; import android.os.Parcel; /** * AdditionalPropertiesString */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class AdditionalPropertiesString extends HashMap<String, String> implements Parcelable { public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) private String name; public AdditionalPropertiesString() { super(); } public AdditionalPropertiesString name(String name) { this.name = name; return this; } /** * Get name * @return name **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AdditionalPropertiesString additionalPropertiesString = (AdditionalPropertiesString) o; return Objects.equals(this.name, additionalPropertiesString.name) && super.equals(o); } @Override public int hashCode() { return Objects.hash(name, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AdditionalPropertiesString {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeValue(name); } AdditionalPropertiesString(Parcel in) { super(in); name = (String)in.readValue(null); } public int describeContents() { return 0; } public static final Parcelable.Creator<AdditionalPropertiesString> CREATOR = new Parcelable.Creator<AdditionalPropertiesString>() { public AdditionalPropertiesString createFromParcel(Parcel in) { return new AdditionalPropertiesString(in); } public AdditionalPropertiesString[] newArray(int size) { return new AdditionalPropertiesString[size]; } }; }
// Targeted by JavaCPP version 1.5.7: DO NOT EDIT THIS FILE package org.bytedeco.libfreenect; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.libfreenect.global.freenect.*; /** Typedef for stream chunk processing callbacks */ @Properties(inherit = org.bytedeco.libfreenect.presets.freenect.class) public class freenect_chunk_cb extends FunctionPointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public freenect_chunk_cb(Pointer p) { super(p); } protected freenect_chunk_cb() { allocate(); } private native void allocate(); public native void call(Pointer buffer, Pointer pkt_data, int pkt_num, int datalen, Pointer user_data); }
package com.qiancheng.charging.login.entity; import com.qiancheng.charging.entity.Employee; import java.sql.Date; public class UserVO { private String id; //用户id private String username; //用户名 private String password; //密码 private int role; //角色 0普通用户 1管理员 private int flag; private String employeeId; //员工id private String name; private Date createTime; private Date updateTime; private String createUser; private String updateUser; private Date lastLoginTime; public UserVO(String id, String username, String password, int role, int flag, String employeeId, String name, Date createTime, Date updateTime, String createUser, String updateUser, Date lastLoginTime) { this.id = id; this.username = username; this.password = password; this.role = role; this.flag = flag; this.employeeId = employeeId; this.name = name; this.createTime = createTime; this.updateTime = updateTime; this.createUser = createUser; this.updateUser = updateUser; this.lastLoginTime = lastLoginTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getRole() { return role; } public void setRole(int role) { this.role = role; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public String getUpdateUser() { return updateUser; } public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } public Date getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(Date lastLoginTime) { this.lastLoginTime = lastLoginTime; } }
package com.xcynice.playxandroid.module.mine.view; import com.xcynice.playxandroid.base.BaseBean; import com.xcynice.playxandroid.base.BaseView; import com.xcynice.playxandroid.bean.MineShare; /** * @Author 许朋友爱玩 * @Date 2020/6/14 19:15 * @Github https://github.com/LoveLifeEveryday * @JueJin https://juejin.im/user/5e429bbc5188254967066d1b/posts * @Description IMineShareView */ public interface IMineShareView extends BaseView { /** * 第一次设置我的分享数据成功 * * @param list 分享的数据 */ void setShareFirstSuccess(MineShare.ShareArticlesBean list); /** * 第一次设置我的分享数据失败 * * @param msg 失败信息 */ void setShareFirstFail(String msg); /** * 加载更多我的分享数据成功 * * @param list 我的分享数据 */ void setShareMoreSuccess(MineShare.ShareArticlesBean list); /** * 加载更多我的分享数据失败 * * @param msg 失败信息 */ void setShareMoreFail(String msg); /** * 刷新我的分享数据成功 * * @param list 我的分享数据 */ void setShareRefreshSuccess(MineShare.ShareArticlesBean list); /** * 刷新我的分享数据失败 * * @param msg 失败信息 */ void setShareRefreshFail(String msg); /** * 显示收藏成功 * * @param successMessage 成功信息 */ void showCollectSuccess(String successMessage); /** * 显示收藏失败 * * @param errorMessage 失败信息 */ void showCollectError(String errorMessage); /** * 显示未收藏成功 * * @param successMessage 成功信息 */ void showUnCollectSuccess(String successMessage); /** * 显示未收藏失败 * * @param errorMessage 失败信息 */ void showUnCollectError(String errorMessage); }
// Targeted by JavaCPP version 1.5.6: DO NOT EDIT THIS FILE package org.bytedeco.gsl; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.openblas.global.openblas_nolapack.*; import static org.bytedeco.openblas.global.openblas.*; import static org.bytedeco.gsl.global.gsl.*; /* tree data structure */ @Properties(inherit = org.bytedeco.gsl.presets.gsl.class) public class gsl_bst_avl_table extends Pointer { static { Loader.load(); } /** Default native constructor. */ public gsl_bst_avl_table() { super((Pointer)null); allocate(); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public gsl_bst_avl_table(long size) { super((Pointer)null); allocateArray(size); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public gsl_bst_avl_table(Pointer p) { super(p); } private native void allocate(); private native void allocateArray(long size); @Override public gsl_bst_avl_table position(long position) { return (gsl_bst_avl_table)super.position(position); } @Override public gsl_bst_avl_table getPointer(long i) { return new gsl_bst_avl_table((Pointer)this).offsetAddress(i); } public native gsl_bst_avl_node avl_root(); public native gsl_bst_avl_table avl_root(gsl_bst_avl_node setter); /* tree's root */ public native gsl_bst_cmp_function avl_compare(); public native gsl_bst_avl_table avl_compare(gsl_bst_cmp_function setter); /* comparison function */ public native Pointer avl_param(); public native gsl_bst_avl_table avl_param(Pointer setter); /* extra argument to |avl_compare| */ public native @Const gsl_bst_allocator avl_alloc(); public native gsl_bst_avl_table avl_alloc(gsl_bst_allocator setter); /* memory allocator */ public native @Cast("size_t") long avl_count(); public native gsl_bst_avl_table avl_count(long setter); /* number of items in tree */ public native @Cast("unsigned long") long avl_generation(); public native gsl_bst_avl_table avl_generation(long setter); /* generation number */ }
package domts.level2.core; import org.w3c.dom.*; import java.util.*; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; /** * The "setAttributeNode(newAttr)" method raises an * "INUSE_ATTRIBUTE_ERR DOMException if the "newAttr" * is already an attribute of another element. * * Retrieve the first emp:address and append * a newly created element. The "createAttributeNS(namespaceURI,qualifiedName)" * and "setAttributeNodeNS(newAttr)" methods are invoked * to create and add a new attribute to the newly created * Element. The "setAttributeNodeNS(newAttr)" method is * once again called to add the new attribute causing an * exception to be raised since the attribute is already * an attribute of another element. * @author NIST * @author Mary Brady * @see <a href="http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-258A00AF')/constant[@name='INUSE_ATTRIBUTE_ERR'])">http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-258A00AF')/constant[@name='INUSE_ATTRIBUTE_ERR'])</a> * @see <a href="http://www.w3.org/TR/DOM-Level-2-Core/core#ID-ElSetAtNodeNS">http://www.w3.org/TR/DOM-Level-2-Core/core#ID-ElSetAtNodeNS</a> * @see <a href="http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-ElSetAtNodeNS')/raises/exception[@name='DOMException']/descr/p[substring-before(.,':')='INUSE_ATTRIBUTE_ERR'])">http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-ElSetAtNodeNS')/raises/exception[@name='DOMException']/descr/p[substring-before(.,':')='INUSE_ATTRIBUTE_ERR'])</a> */ class Set_Attribute_Node_NS_01_Test extends domts.DOMTestCase { @BeforeEach void setup() { // check if loaded documents are supported for content type String contentType = getContentType(); preload(contentType, "staffNS", true); } @Test @DisplayName("http://www.w3.org/2001/DOM_Test_Suite/level2/core/setAttributeNodeNS01") void run() throws Throwable { String namespaceURI = "http://www.newattr.com"; String qualifiedName = "emp:newAttr"; Document doc; Element newElement; Attr newAttr; NodeList elementList; Node testAddr; Node appendedChild; Attr setAttr1; Attr setAttr2; doc = (Document) load("staffNS", true); elementList = doc.getElementsByTagName("emp:address"); testAddr = elementList.item(0); assertNotNull(testAddr, "empAddrNotNull"); newElement = doc.createElement("newElement"); appendedChild = testAddr.appendChild(newElement); newAttr = doc.createAttributeNS(namespaceURI, qualifiedName); setAttr1 = newElement.setAttributeNodeNS(newAttr); { boolean success = false; try { setAttr2 = ((Element) /*Node */testAddr).setAttributeNodeNS(newAttr); } catch (DOMException ex) { success = (ex.code == DOMException.INUSE_ATTRIBUTE_ERR); } assertTrue(success, "throw_INUSE_ATTRIBUTE_ERR"); } } }
package com.naz.PlexDownloader.models.plex; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import java.io.Serializable; @XmlAccessorType(XmlAccessType.FIELD) public class Pin implements Serializable { @XmlAttribute private String expiresIn; @XmlAttribute private String createdAt; @XmlAttribute private String product; @XmlAttribute private String code; @XmlAttribute private String trusted; @XmlAttribute private String clientIdentifier; @XmlAttribute private String authToken; @XmlElement private Location location; @XmlAttribute private String id; @XmlAttribute private String expiresAt; @XmlAttribute private String newRegistration; private transient String resolvedUri; public String getResolvedUri() { return resolvedUri; } public void setResolvedUri(String resolvedUri) { this.resolvedUri = resolvedUri; } public String getExpiresIn () { return expiresIn; } public void setExpiresIn (String expiresIn) { this.expiresIn = expiresIn; } public String getCreatedAt () { return createdAt; } public void setCreatedAt (String createdAt) { this.createdAt = createdAt; } public String getProduct () { return product; } public void setProduct (String product) { this.product = product; } public String getCode () { return code; } public void setCode (String code) { this.code = code; } public String getTrusted () { return trusted; } public void setTrusted (String trusted) { this.trusted = trusted; } public String getClientIdentifier () { return clientIdentifier; } public void setClientIdentifier (String clientIdentifier) { this.clientIdentifier = clientIdentifier; } public String getAuthToken () { return authToken; } public void setAuthToken (String authToken) { this.authToken = authToken; } public Location getLocation () { return location; } public void setLocation (Location location) { this.location = location; } public String getId () { return id; } public void setId (String id) { this.id = id; } public String getExpiresAt () { return expiresAt; } public void setExpiresAt (String expiresAt) { this.expiresAt = expiresAt; } public String getNewRegistration() { return newRegistration; } public void setNewRegistration(String newRegistration) { this.newRegistration = newRegistration; } @Override public String toString() { return "ClassPojo [expiresIn = "+expiresIn+", createdAt = "+createdAt+", product = "+product+", code = "+code+", trusted = "+trusted+", clientIdentifier = "+clientIdentifier+", authToken = "+authToken+", location = "+location+", id = "+id+", expiresAt = "+expiresAt+"]"; } }
package com.dlink.metadata; import com.dlink.metadata.driver.Driver; import com.dlink.metadata.driver.DriverConfig; import com.dlink.metadata.result.JdbcSelectResult; import com.dlink.model.Column; import com.dlink.model.Schema; import com.dlink.model.Table; import org.junit.Before; import org.junit.Test; import java.util.LinkedHashMap; import java.util.List; public class PhoenixTest { private Driver driver; @Before public void init() { DriverConfig config = new DriverConfig(); config.setName("phoenix"); config.setType("Phoenix"); config.setUrl("jdbc:phoenix:zxbd-test-hbase:2181"); try { driver = Driver.build(config); } catch (Exception e) { System.err.println("连接创建失败:" + e.getMessage()); } } @Test public void testSchema() { //schema && table List<Schema> schemasAndTables = driver.getSchemasAndTables(); for (Schema schemasAndTable : schemasAndTables) { List<Table> tables = schemasAndTable.getTables(); for (Table table : tables) { System.out.println(table.getName() + " " + table.getSchema()); } } } @Test public void testListTables() { List<Table> tables = driver.listTables(""); for (Table table : tables) { System.out.println(table.getName() + " " + table.getSchema()); } } @Test public void testColumns() { // columns List<Column> columns = driver.listColumns(null, "ODS_OUTP_PRESC"); for (Column column : columns) { System.out.println(column.getName() + " " + column.getType() + " " + column.getComment()); } } @Test public void query() { JdbcSelectResult selectResult = driver.query("select * from ODS_OUTP_PRESC ", 10); List<LinkedHashMap<String, Object>> rowData = selectResult.getRowData(); for (LinkedHashMap<String, Object> rowDatum : rowData) { System.out.println(rowDatum); } } }
package money.terra.terrawallet.library; //https://github.com/WebOfTrustInfo/txref-conversion-java/blob/master/src/main/java/info/weboftrust/txrefconversion/Bech32.java //MIT license import java.nio.ByteBuffer; public class Bech32 { public static final String CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; private Bech32() { } public static String bech32Encode(byte[] hrp, byte[] data) { byte[] chk = createChecksum(hrp, data); byte[] combined = new byte[chk.length + data.length]; System.arraycopy(data, 0, combined, 0, data.length); System.arraycopy(chk, 0, combined, data.length, chk.length); byte[] xlat = new byte[combined.length]; for (int i = 0; i < combined.length; i++) { xlat[i] = (byte)CHARSET.charAt(combined[i]); } byte[] ret = new byte[hrp.length + xlat.length + 1]; System.arraycopy(hrp, 0, ret, 0, hrp.length); System.arraycopy(new byte[] { 0x31 }, 0, ret, hrp.length, 1); System.arraycopy(xlat, 0, ret, hrp.length + 1, xlat.length); return new String(ret); } public static HrpAndData bech32Decode(String bech) { if (!bech.equals(bech.toLowerCase()) && !bech.equals(bech.toUpperCase())) { throw new IllegalArgumentException("bech32 cannot mix upper and lower case"); } byte[] buffer = bech.getBytes(); for (byte b : buffer) { if (b < 0x21 || b > 0x7e) throw new IllegalArgumentException("bech32 characters out of range"); } bech = bech.toLowerCase(); int pos = bech.lastIndexOf("1"); if (pos < 1) { throw new IllegalArgumentException("bech32 missing separator"); } else if (pos + 7 > bech.length()) { throw new IllegalArgumentException("bech32 separator misplaced"); } else if (bech.length() < 8) { throw new IllegalArgumentException("bech32 input too short"); } else if (bech.length() > 90) { throw new IllegalArgumentException("bech32 input too long"); } String s = bech.substring(pos + 1); for (int i = 0; i < s.length(); i++) { if (CHARSET.indexOf(s.charAt(i)) == -1) { throw new IllegalArgumentException("bech32 characters out of range"); } } byte[] hrp = bech.substring(0, pos).getBytes(); byte[] data = new byte[bech.length() - pos - 1]; for (int j = 0, i = pos + 1; i < bech.length(); i++, j++) { data[j] = (byte)CHARSET.indexOf(bech.charAt(i)); } if (!verifyChecksum(hrp, data)) { throw new IllegalArgumentException("invalid bech32 checksum"); } byte[] ret = new byte[data.length - 6]; System.arraycopy(data, 0, ret, 0, data.length - 6); return new HrpAndData(hrp, ret); } private static int polymod(byte[] values) { final int[] GENERATORS = { 0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3 }; int chk = 1; for (byte b : values) { byte top = (byte)(chk >> 0x19); chk = b ^ ((chk & 0x1ffffff) << 5); for (int i = 0; i < 5; i++) { chk ^= ((top >> i) & 1) == 1 ? GENERATORS[i] : 0; } } return chk; } private static boolean verifyChecksum(byte[] hrp, byte[] data) { byte[] exp = hrpExpand(hrp); byte[] values = new byte[exp.length + data.length]; System.arraycopy(exp, 0, values, 0, exp.length); System.arraycopy(data, 0, values, exp.length, data.length); return (1 == polymod(values)); } private static byte[] hrpExpand(byte[] hrp) { byte[] buf1 = new byte[hrp.length]; byte[] buf2 = new byte[hrp.length]; byte[] mid = new byte[1]; for (int i = 0; i < hrp.length; i++) { buf1[i] = (byte)(hrp[i] >> 5); } mid[0] = 0x00; for (int i = 0; i < hrp.length; i++) { buf2[i] = (byte)(hrp[i] & 0x1f); } byte[] ret = new byte[(hrp.length * 2) + 1]; System.arraycopy(buf1, 0, ret, 0, buf1.length); System.arraycopy(mid, 0, ret, buf1.length, mid.length); System.arraycopy(buf2, 0, ret, buf1.length + mid.length, buf2.length); return ret; } private static byte[] createChecksum(byte[] hrp, byte[] data) { byte[] zeroes = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] expanded = hrpExpand(hrp); byte[] values = new byte[zeroes.length + expanded.length + data.length]; System.arraycopy(expanded, 0, values, 0, expanded.length); System.arraycopy(data, 0, values, expanded.length, data.length); System.arraycopy(zeroes, 0, values, expanded.length + data.length, zeroes.length); int polymod = polymod(values) ^ 1; byte[] ret = new byte[6]; for (int i = 0; i < ret.length; i++) { ret[i] = (byte)((polymod >> 5 * (5 - i)) & 0x1f); } return ret; } public static byte[] toWords(byte[] data) { final int inBits = 8; final int outBits = 5; final boolean pad = true; int value = 0; int bits = 0; int maxV = (1 << outBits) - 1; ByteBuffer result = ByteBuffer.allocate(maxV + 1); for (byte datum : data) { value = (value << inBits) | (datum & 0xFF); bits += inBits; while (bits >= outBits) { bits -= outBits; result.put((byte) ((value >> bits) & maxV)); } } if (pad) { if (bits > 0) { result.put((byte) ((value << (outBits - bits)) & maxV)); } } else { if (bits >= inBits) throw new IllegalStateException("Excess padding"); if (((value << (outBits - bits)) & maxV) > 0) throw new IllegalStateException("Non-zero padding"); } return result.array(); } public static class HrpAndData { public byte[] hrp; public byte[] data; public HrpAndData(byte[] hrp, byte[] data) { this.hrp = hrp; this.data = data; } } }
import java.util.Scanner; public class Main { public static int getNumberOfMaxParam(int a, int b, int c) { // write a body here int max = Math.max(a, Math.max(b, c)); if (max == a) { return 1; } else if (max == b) { return 2; } else { return 3; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); final int a = scanner.nextInt(); final int b = scanner.nextInt(); final int c = scanner.nextInt(); System.out.println(getNumberOfMaxParam(a, b, c)); } }
package com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.aspects; import java.util.Date; import org.apache.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.context.annotation.Configuration; @Configuration @Aspect public class ProductAspect { private Logger logger = Logger.getLogger(ProductAspect.class); private long startTime; private long endTime; @Pointcut("execution(* com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.*(..))") public void applyPointcutDate() { } @Before("applyPointcutDate()") public void showExecutionDate() { System.out.println(""); logger.debug(""); System.out.println("Method Is Calling On :: "+ new Date()); logger.debug("Method Is Calling On :: "+ new Date()); logger.debug(""); } @Before("execution(public * com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.saveProduct(..))") public void showStartTimeOfSaveProduct(JoinPoint jp) { String methodName = jp.getSignature().getName(); int hashCode = jp.getSignature().hashCode(); startTime = System.currentTimeMillis(); System.out.println("Method Name Is :: "+methodName); System.out.println("Method Storing Memory Location Code Is :: "+hashCode); System.out.println("Method Start Time Is :: "+startTime); logger.debug("Method Name Is :: "+methodName); logger.debug("Method Storing Memory Location Code Is :: "+hashCode); logger.debug("Method Start Time Is :: "+startTime); logger.debug(""); logger.debug(""); } @After("execution(public * com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.saveProduct(..))") public void showEndTimeOfSaveProduct(JoinPoint jp) { endTime = System.currentTimeMillis(); System.out.println("Method Declaring Type Is :: "+jp.getSignature().getDeclaringType()); System.out.println("Method End Time Is :: "+endTime); System.out.println("Method Total Time Taken Is :: "+(endTime - startTime)+" MilliSeconds"); System.out.println(""); logger.debug("Method Declaring Type Is :: "+jp.getSignature().getDeclaringType()); logger.debug("Method End Time Is :: "+endTime); logger.debug("Method Total Time Taken Is :: "+(endTime - startTime)+" MilliSeconds"); logger.debug(""); logger.debug(""); } @Before("execution(public * com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.deleteProduct(..))") public void showStartTimeOfDeleteProduct(JoinPoint jp) { String methodName = jp.getSignature().getName(); int hashCode = jp.getSignature().hashCode(); startTime = System.currentTimeMillis(); System.out.println("Method Name Is :: "+methodName); System.out.println("Method Storing Memory Location Code Is :: "+hashCode); System.out.println("Method Start Time Is :: "+startTime); logger.debug("Method Name Is :: "+methodName); logger.debug("Method Storing Memory Location Code Is :: "+hashCode); logger.debug("Method Start Time Is :: "+startTime); logger.debug(""); logger.debug(""); } @After("execution(public * com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.deleteProduct(..))") public void showEndTimeOfDeleteProduct(JoinPoint jp) { endTime = System.currentTimeMillis(); System.out.println("Method Declaring Type Is :: "+jp.getSignature().getDeclaringType()); System.out.println("Method End Time Is :: "+endTime); System.out.println("Method Total Time Taken Is :: "+(endTime - startTime)+" MilliSeconds"); System.out.println(""); logger.debug("Method Declaring Type Is :: "+jp.getSignature().getDeclaringType()); logger.debug("Method End Time Is :: "+endTime); logger.debug("Method Total Time Taken Is :: "+(endTime - startTime)+" MilliSeconds"); logger.debug(""); logger.debug(""); } @Before("execution(public * com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.getProduct(..))") public void showStartTimeOfGetProduct(JoinPoint jp) { String methodName = jp.getSignature().getName(); int hashCode = jp.getSignature().hashCode(); startTime = System.currentTimeMillis(); System.out.println("Method Name Is :: "+methodName); System.out.println("Method Storing Memory Location Code Is :: "+hashCode); System.out.println("Method Start Time Is :: "+startTime); logger.debug("Method Name Is :: "+methodName); logger.debug("Method Storing Memory Location Code Is :: "+hashCode); logger.debug("Method Start Time Is :: "+startTime); logger.debug(""); logger.debug(""); } @After("execution(public * com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.getProduct(..))") public void showEndTimeOfGetProduct(JoinPoint jp) { endTime = System.currentTimeMillis(); System.out.println("Method Declaring Type Is :: "+jp.getSignature().getDeclaringType()); System.out.println("Method End Time Is :: "+endTime); System.out.println("Method Total Time Taken Is :: "+(endTime - startTime)+" MilliSeconds"); System.out.println(""); logger.debug("Method Declaring Type Is :: "+jp.getSignature().getDeclaringType()); logger.debug("Method End Time Is :: "+endTime); logger.debug("Method Total Time Taken Is :: "+(endTime - startTime)+" MilliSeconds"); logger.debug(""); logger.debug(""); } @Before("execution(public * com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.getAllProductsByCategory(..))") public void showStartTimeOfGetAllProductsByCategory(JoinPoint jp) { String methodName = jp.getSignature().getName(); int hashCode = jp.getSignature().hashCode(); startTime = System.currentTimeMillis(); System.out.println("Method Name Is :: "+methodName); System.out.println("Method Storing Memory Location Code Is :: "+hashCode); System.out.println("Method Start Time Is :: "+startTime); logger.debug("Method Name Is :: "+methodName); logger.debug("Method Storing Memory Location Code Is :: "+hashCode); logger.debug("Method Start Time Is :: "+startTime); logger.debug(""); logger.debug(""); } @After("execution(public * com.app.MavenSpringBootMvcAopRestApiOnlineShoppingWithReactReduxAndMongodb.dao.IProductDAO.getAllProductsByCategory(..))") public void showEndTimeOfGetAllProductsByCategory(JoinPoint jp) { endTime = System.currentTimeMillis(); System.out.println("Method Declaring Type Is :: "+jp.getSignature().getDeclaringType()); System.out.println("Method End Time Is :: "+endTime); System.out.println("Method Total Time Taken Is :: "+(endTime - startTime)+" MilliSeconds"); System.out.println(""); logger.debug("Method Declaring Type Is :: "+jp.getSignature().getDeclaringType()); logger.debug("Method End Time Is :: "+endTime); logger.debug("Method Total Time Taken Is :: "+(endTime - startTime)+" MilliSeconds"); logger.debug(""); logger.debug(""); } }
package com.czfx.gulimall.order.vo; import lombok.Data; import lombok.ToString; import java.util.Date; @ToString @Data public class PayAsyncVo { private String gmt_create; private String charset; private String gmt_payment; private Date notify_time; private String subject; private String sign; private String buyer_id;//支付者的id private String body;//订单的信息 private String invoice_amount;//支付金额 private String version; private String notify_id;//通知id private String fund_bill_list; private String notify_type;//通知类型; trade_status_sync private String out_trade_no;//订单号 private String total_amount;//支付的总额 private String trade_status;//交易状态 TRADE_SUCCESS private String trade_no;//流水号 private String auth_app_id;// private String receipt_amount;//商家收到的款 private String point_amount;// private String app_id;//应用id private String buyer_pay_amount;//最终支付的金额 private String sign_type;//签名类型 private String seller_id;//商家的id }
/* * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.codecentric.boot.admin.server.services; import de.codecentric.boot.admin.server.domain.values.InstanceId; import reactor.core.publisher.Mono; import java.time.Duration; import java.util.function.Function; import org.junit.After; import org.junit.Test; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class IntervalCheckTest { private static final InstanceId INSTANCE_ID = InstanceId.of("Test"); @SuppressWarnings("unchecked") private final Function<InstanceId, Mono<Void>> checkFn = mock(Function.class, i -> Mono.empty()); private final IntervalCheck intervalCheck = new IntervalCheck("test", this.checkFn, Duration.ofMillis(10), Duration.ofMillis(10) ); @Test public void should_check_after_being_started() throws InterruptedException { this.intervalCheck.markAsChecked(INSTANCE_ID); this.intervalCheck.start(); Thread.sleep(100); verify(this.checkFn, atLeastOnce()).apply(INSTANCE_ID); } @Test public void should_not_check_when_stopped() throws InterruptedException { this.intervalCheck.markAsChecked(INSTANCE_ID); this.intervalCheck.stop(); Thread.sleep(100); verify(this.checkFn, never()).apply(any()); } @Test public void should_not_check_in_retention_period() throws InterruptedException { this.intervalCheck.setMinRetention(Duration.ofSeconds(100)); this.intervalCheck.markAsChecked(INSTANCE_ID); this.intervalCheck.start(); Thread.sleep(100); verify(this.checkFn, never()).apply(any()); } @Test public void should_recheck_after_retention_period() throws InterruptedException { this.intervalCheck.setMinRetention(Duration.ofMillis(10)); this.intervalCheck.markAsChecked(INSTANCE_ID); this.intervalCheck.start(); Thread.sleep(100); verify(this.checkFn, atLeast(2)).apply(INSTANCE_ID); } @Test public void should_check_after_error() throws InterruptedException { this.intervalCheck.markAsChecked(INSTANCE_ID); when(this.checkFn.apply(any())).thenReturn(Mono.error(new RuntimeException("Test"))).thenReturn(Mono.empty()); this.intervalCheck.start(); Thread.sleep(100); verify(this.checkFn, atLeast(2)).apply(InstanceId.of("Test")); } @After public void tearDown() { this.intervalCheck.stop(); } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.macro; import com.intellij.ide.IdeBundle; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.vfs.VirtualFile; public final class FileExtMacro extends Macro { @Override public String getName() { return "FileExt"; } @Override public String getDescription() { return IdeBundle.message("macro.file.extension"); } @Override public String expand(DataContext dataContext) { VirtualFile file = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext); if (file == null) { return null; } return file.getExtension(); } }
/* * Copyright (c) 2021 Oracle and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oracle.odi.cdispec._26; import com.oracle.odi.test.junit5.OdiTest; import jakarta.inject.Named; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; @OdiTest public class BeanNamesTest { @Test @DisplayName("2.6. Bean names") void testValidBeanNames( @Named("orderManager") OrderManager orderManager, @Named("com.acme.settings") Settings settings) { assertNotNull(orderManager); assertNotNull(settings); } } @Named("orderManager") class OrderManager {} @Named("com.acme.settings") class Settings {}
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v3/services/mutate_job_service.proto package com.google.ads.googleads.v3.services; /** * <pre> * Request message for [MutateJobService.AddMutateJobOperations][google.ads.googleads.v3.services.MutateJobService.AddMutateJobOperations] * </pre> * * Protobuf type {@code google.ads.googleads.v3.services.AddMutateJobOperationsRequest} */ public final class AddMutateJobOperationsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v3.services.AddMutateJobOperationsRequest) AddMutateJobOperationsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use AddMutateJobOperationsRequest.newBuilder() to construct. private AddMutateJobOperationsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AddMutateJobOperationsRequest() { resourceName_ = ""; sequenceToken_ = ""; mutateOperations_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AddMutateJobOperationsRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); resourceName_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); sequenceToken_ = s; break; } case 26: { if (!((mutable_bitField0_ & 0x00000004) != 0)) { mutateOperations_ = new java.util.ArrayList<com.google.ads.googleads.v3.services.MutateOperation>(); mutable_bitField0_ |= 0x00000004; } mutateOperations_.add( input.readMessage(com.google.ads.googleads.v3.services.MutateOperation.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000004) != 0)) { mutateOperations_ = java.util.Collections.unmodifiableList(mutateOperations_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v3.services.MutateJobServiceProto.internal_static_google_ads_googleads_v3_services_AddMutateJobOperationsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v3.services.MutateJobServiceProto.internal_static_google_ads_googleads_v3_services_AddMutateJobOperationsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest.class, com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest.Builder.class); } private int bitField0_; public static final int RESOURCE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object resourceName_; /** * <pre> * Required. The resource name of the MutateJob. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } } /** * <pre> * Required. The resource name of the MutateJob. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SEQUENCE_TOKEN_FIELD_NUMBER = 2; private volatile java.lang.Object sequenceToken_; /** * <pre> * A token used to enforce sequencing. * The first AddMutateJobOperations request for a MutateJob should not set * sequence_token. Subsequent requests must set sequence_token to the value of * next_sequence_token received in the previous AddMutateJobOperations * response. * </pre> * * <code>string sequence_token = 2;</code> */ public java.lang.String getSequenceToken() { java.lang.Object ref = sequenceToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sequenceToken_ = s; return s; } } /** * <pre> * A token used to enforce sequencing. * The first AddMutateJobOperations request for a MutateJob should not set * sequence_token. Subsequent requests must set sequence_token to the value of * next_sequence_token received in the previous AddMutateJobOperations * response. * </pre> * * <code>string sequence_token = 2;</code> */ public com.google.protobuf.ByteString getSequenceTokenBytes() { java.lang.Object ref = sequenceToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sequenceToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MUTATE_OPERATIONS_FIELD_NUMBER = 3; private java.util.List<com.google.ads.googleads.v3.services.MutateOperation> mutateOperations_; /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<com.google.ads.googleads.v3.services.MutateOperation> getMutateOperationsList() { return mutateOperations_; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<? extends com.google.ads.googleads.v3.services.MutateOperationOrBuilder> getMutateOperationsOrBuilderList() { return mutateOperations_; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public int getMutateOperationsCount() { return mutateOperations_.size(); } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v3.services.MutateOperation getMutateOperations(int index) { return mutateOperations_.get(index); } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v3.services.MutateOperationOrBuilder getMutateOperationsOrBuilder( int index) { return mutateOperations_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getResourceNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!getSequenceTokenBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, sequenceToken_); } for (int i = 0; i < mutateOperations_.size(); i++) { output.writeMessage(3, mutateOperations_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getResourceNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!getSequenceTokenBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, sequenceToken_); } for (int i = 0; i < mutateOperations_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, mutateOperations_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest)) { return super.equals(obj); } com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest other = (com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getSequenceToken() .equals(other.getSequenceToken())) return false; if (!getMutateOperationsList() .equals(other.getMutateOperationsList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + SEQUENCE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getSequenceToken().hashCode(); if (getMutateOperationsCount() > 0) { hash = (37 * hash) + MUTATE_OPERATIONS_FIELD_NUMBER; hash = (53 * hash) + getMutateOperationsList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Request message for [MutateJobService.AddMutateJobOperations][google.ads.googleads.v3.services.MutateJobService.AddMutateJobOperations] * </pre> * * Protobuf type {@code google.ads.googleads.v3.services.AddMutateJobOperationsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v3.services.AddMutateJobOperationsRequest) com.google.ads.googleads.v3.services.AddMutateJobOperationsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v3.services.MutateJobServiceProto.internal_static_google_ads_googleads_v3_services_AddMutateJobOperationsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v3.services.MutateJobServiceProto.internal_static_google_ads_googleads_v3_services_AddMutateJobOperationsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest.class, com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest.Builder.class); } // Construct using com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getMutateOperationsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); resourceName_ = ""; sequenceToken_ = ""; if (mutateOperationsBuilder_ == null) { mutateOperations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); } else { mutateOperationsBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v3.services.MutateJobServiceProto.internal_static_google_ads_googleads_v3_services_AddMutateJobOperationsRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest getDefaultInstanceForType() { return com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest build() { com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest buildPartial() { com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest result = new com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.resourceName_ = resourceName_; result.sequenceToken_ = sequenceToken_; if (mutateOperationsBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0)) { mutateOperations_ = java.util.Collections.unmodifiableList(mutateOperations_); bitField0_ = (bitField0_ & ~0x00000004); } result.mutateOperations_ = mutateOperations_; } else { result.mutateOperations_ = mutateOperationsBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest) { return mergeFrom((com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest other) { if (other == com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; onChanged(); } if (!other.getSequenceToken().isEmpty()) { sequenceToken_ = other.sequenceToken_; onChanged(); } if (mutateOperationsBuilder_ == null) { if (!other.mutateOperations_.isEmpty()) { if (mutateOperations_.isEmpty()) { mutateOperations_ = other.mutateOperations_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureMutateOperationsIsMutable(); mutateOperations_.addAll(other.mutateOperations_); } onChanged(); } } else { if (!other.mutateOperations_.isEmpty()) { if (mutateOperationsBuilder_.isEmpty()) { mutateOperationsBuilder_.dispose(); mutateOperationsBuilder_ = null; mutateOperations_ = other.mutateOperations_; bitField0_ = (bitField0_ & ~0x00000004); mutateOperationsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getMutateOperationsFieldBuilder() : null; } else { mutateOperationsBuilder_.addAllMessages(other.mutateOperations_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object resourceName_ = ""; /** * <pre> * Required. The resource name of the MutateJob. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The resource name of the MutateJob. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The resource name of the MutateJob. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; onChanged(); return this; } /** * <pre> * Required. The resource name of the MutateJob. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); onChanged(); return this; } /** * <pre> * Required. The resource name of the MutateJob. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; onChanged(); return this; } private java.lang.Object sequenceToken_ = ""; /** * <pre> * A token used to enforce sequencing. * The first AddMutateJobOperations request for a MutateJob should not set * sequence_token. Subsequent requests must set sequence_token to the value of * next_sequence_token received in the previous AddMutateJobOperations * response. * </pre> * * <code>string sequence_token = 2;</code> */ public java.lang.String getSequenceToken() { java.lang.Object ref = sequenceToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); sequenceToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * A token used to enforce sequencing. * The first AddMutateJobOperations request for a MutateJob should not set * sequence_token. Subsequent requests must set sequence_token to the value of * next_sequence_token received in the previous AddMutateJobOperations * response. * </pre> * * <code>string sequence_token = 2;</code> */ public com.google.protobuf.ByteString getSequenceTokenBytes() { java.lang.Object ref = sequenceToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); sequenceToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * A token used to enforce sequencing. * The first AddMutateJobOperations request for a MutateJob should not set * sequence_token. Subsequent requests must set sequence_token to the value of * next_sequence_token received in the previous AddMutateJobOperations * response. * </pre> * * <code>string sequence_token = 2;</code> */ public Builder setSequenceToken( java.lang.String value) { if (value == null) { throw new NullPointerException(); } sequenceToken_ = value; onChanged(); return this; } /** * <pre> * A token used to enforce sequencing. * The first AddMutateJobOperations request for a MutateJob should not set * sequence_token. Subsequent requests must set sequence_token to the value of * next_sequence_token received in the previous AddMutateJobOperations * response. * </pre> * * <code>string sequence_token = 2;</code> */ public Builder clearSequenceToken() { sequenceToken_ = getDefaultInstance().getSequenceToken(); onChanged(); return this; } /** * <pre> * A token used to enforce sequencing. * The first AddMutateJobOperations request for a MutateJob should not set * sequence_token. Subsequent requests must set sequence_token to the value of * next_sequence_token received in the previous AddMutateJobOperations * response. * </pre> * * <code>string sequence_token = 2;</code> */ public Builder setSequenceTokenBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); sequenceToken_ = value; onChanged(); return this; } private java.util.List<com.google.ads.googleads.v3.services.MutateOperation> mutateOperations_ = java.util.Collections.emptyList(); private void ensureMutateOperationsIsMutable() { if (!((bitField0_ & 0x00000004) != 0)) { mutateOperations_ = new java.util.ArrayList<com.google.ads.googleads.v3.services.MutateOperation>(mutateOperations_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v3.services.MutateOperation, com.google.ads.googleads.v3.services.MutateOperation.Builder, com.google.ads.googleads.v3.services.MutateOperationOrBuilder> mutateOperationsBuilder_; /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<com.google.ads.googleads.v3.services.MutateOperation> getMutateOperationsList() { if (mutateOperationsBuilder_ == null) { return java.util.Collections.unmodifiableList(mutateOperations_); } else { return mutateOperationsBuilder_.getMessageList(); } } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public int getMutateOperationsCount() { if (mutateOperationsBuilder_ == null) { return mutateOperations_.size(); } else { return mutateOperationsBuilder_.getCount(); } } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v3.services.MutateOperation getMutateOperations(int index) { if (mutateOperationsBuilder_ == null) { return mutateOperations_.get(index); } else { return mutateOperationsBuilder_.getMessage(index); } } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setMutateOperations( int index, com.google.ads.googleads.v3.services.MutateOperation value) { if (mutateOperationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMutateOperationsIsMutable(); mutateOperations_.set(index, value); onChanged(); } else { mutateOperationsBuilder_.setMessage(index, value); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder setMutateOperations( int index, com.google.ads.googleads.v3.services.MutateOperation.Builder builderForValue) { if (mutateOperationsBuilder_ == null) { ensureMutateOperationsIsMutable(); mutateOperations_.set(index, builderForValue.build()); onChanged(); } else { mutateOperationsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addMutateOperations(com.google.ads.googleads.v3.services.MutateOperation value) { if (mutateOperationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMutateOperationsIsMutable(); mutateOperations_.add(value); onChanged(); } else { mutateOperationsBuilder_.addMessage(value); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addMutateOperations( int index, com.google.ads.googleads.v3.services.MutateOperation value) { if (mutateOperationsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMutateOperationsIsMutable(); mutateOperations_.add(index, value); onChanged(); } else { mutateOperationsBuilder_.addMessage(index, value); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addMutateOperations( com.google.ads.googleads.v3.services.MutateOperation.Builder builderForValue) { if (mutateOperationsBuilder_ == null) { ensureMutateOperationsIsMutable(); mutateOperations_.add(builderForValue.build()); onChanged(); } else { mutateOperationsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addMutateOperations( int index, com.google.ads.googleads.v3.services.MutateOperation.Builder builderForValue) { if (mutateOperationsBuilder_ == null) { ensureMutateOperationsIsMutable(); mutateOperations_.add(index, builderForValue.build()); onChanged(); } else { mutateOperationsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder addAllMutateOperations( java.lang.Iterable<? extends com.google.ads.googleads.v3.services.MutateOperation> values) { if (mutateOperationsBuilder_ == null) { ensureMutateOperationsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, mutateOperations_); onChanged(); } else { mutateOperationsBuilder_.addAllMessages(values); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder clearMutateOperations() { if (mutateOperationsBuilder_ == null) { mutateOperations_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { mutateOperationsBuilder_.clear(); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public Builder removeMutateOperations(int index) { if (mutateOperationsBuilder_ == null) { ensureMutateOperationsIsMutable(); mutateOperations_.remove(index); onChanged(); } else { mutateOperationsBuilder_.remove(index); } return this; } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v3.services.MutateOperation.Builder getMutateOperationsBuilder( int index) { return getMutateOperationsFieldBuilder().getBuilder(index); } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v3.services.MutateOperationOrBuilder getMutateOperationsOrBuilder( int index) { if (mutateOperationsBuilder_ == null) { return mutateOperations_.get(index); } else { return mutateOperationsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<? extends com.google.ads.googleads.v3.services.MutateOperationOrBuilder> getMutateOperationsOrBuilderList() { if (mutateOperationsBuilder_ != null) { return mutateOperationsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(mutateOperations_); } } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v3.services.MutateOperation.Builder addMutateOperationsBuilder() { return getMutateOperationsFieldBuilder().addBuilder( com.google.ads.googleads.v3.services.MutateOperation.getDefaultInstance()); } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public com.google.ads.googleads.v3.services.MutateOperation.Builder addMutateOperationsBuilder( int index) { return getMutateOperationsFieldBuilder().addBuilder( index, com.google.ads.googleads.v3.services.MutateOperation.getDefaultInstance()); } /** * <pre> * Required. The list of mutates being added. * Operations can use negative integers as temp ids to signify dependencies * between entities created in this MutateJob. For example, a customer with * id = 1234 can create a campaign and an ad group in that same campaign by * creating a campaign in the first operation with the resource name * explicitly set to "customers/1234/campaigns/-1", and creating an ad group * in the second operation with the campaign field also set to * "customers/1234/campaigns/-1". * </pre> * * <code>repeated .google.ads.googleads.v3.services.MutateOperation mutate_operations = 3 [(.google.api.field_behavior) = REQUIRED];</code> */ public java.util.List<com.google.ads.googleads.v3.services.MutateOperation.Builder> getMutateOperationsBuilderList() { return getMutateOperationsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v3.services.MutateOperation, com.google.ads.googleads.v3.services.MutateOperation.Builder, com.google.ads.googleads.v3.services.MutateOperationOrBuilder> getMutateOperationsFieldBuilder() { if (mutateOperationsBuilder_ == null) { mutateOperationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v3.services.MutateOperation, com.google.ads.googleads.v3.services.MutateOperation.Builder, com.google.ads.googleads.v3.services.MutateOperationOrBuilder>( mutateOperations_, ((bitField0_ & 0x00000004) != 0), getParentForChildren(), isClean()); mutateOperations_ = null; } return mutateOperationsBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v3.services.AddMutateJobOperationsRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v3.services.AddMutateJobOperationsRequest) private static final com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest(); } public static com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AddMutateJobOperationsRequest> PARSER = new com.google.protobuf.AbstractParser<AddMutateJobOperationsRequest>() { @java.lang.Override public AddMutateJobOperationsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AddMutateJobOperationsRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AddMutateJobOperationsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AddMutateJobOperationsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v3.services.AddMutateJobOperationsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * 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. */ @Version("2.3.0") package org.apache.sling.api.scripting; import aQute.bnd.annotation.Version;
/* * Copyright 2015-2020 Emmanuel Keller / QWAZR * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qwazr.search.index; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.qwazr.utils.FileUtils; import com.qwazr.utils.LoggerUtils; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.index.IndexCommit; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.LiveIndexWriterConfig; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.TieredMergePolicy; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.LRUQueryCache; import org.apache.lucene.search.QueryCache; import org.apache.lucene.store.Directory; import org.apache.lucene.store.NRTCachingDirectory; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonAutoDetect(setterVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public class IndexStatus { private final static Logger LOGGER = LoggerUtils.getLogger(IndexStatus.class); @JsonProperty("num_docs") final public Long numDocs; @JsonProperty("num_deleted_docs") final public Long numDeletedDocs; @JsonProperty("has_pending_merges") final public Boolean hasPendingMerges; @JsonProperty("has_uncommitted_changes") final public Boolean hasUncommittedChanges; @JsonProperty("has_deletions") final public Boolean hasDeletions; @JsonProperty("ram_buffer_size_mb") final public Double ramBufferSizeMb; @JsonProperty("index_uuid") final public String indexUuid; @JsonProperty("master_uuid") final public String masterUuid; final public Long version; final public Set<String> analyzers; final public Set<String> fields; final public IndexSettingsDefinition settings; @JsonProperty("field_infos") final public SortedMap<String, Set<FieldInfoStatus>> fieldInfos; @JsonProperty("segment_count") final public Integer segmentCount; @JsonProperty("segments_bytes_size") final public Long segmentsBytesSize; @JsonProperty("segments_size") final public String segmentsSize; @JsonProperty("commit_filenames") final public Collection<String> commitFilenames; @JsonProperty("commit_generation") final public Long commitGeneration; @JsonProperty("merge_policy") final public MergePolicyStatus mergePolicy; @JsonProperty("query_cache") final public QueryCacheStats queryCache; @JsonProperty("commit_user_data") final public Map<String, String> commitUserData; @JsonProperty("directory_class") final public String directoryClass; @JsonProperty("directory_cached_files") final public String[] directoryCachedFiles; @JsonProperty("directory_cached_ram_used") final public String directoryCachedRamUsed; @JsonProperty("active_analyzers") final public Integer activeAnalyzers; @JsonProperty("index_sort_fields") final public Set<String> indexSortFields; @JsonCreator IndexStatus(@JsonProperty("num_docs") Long numDocs, @JsonProperty("num_deleted_docs") Long numDeletedDocs, @JsonProperty("has_pending_merges") Boolean hasPendingMerges, @JsonProperty("has_uncommitted_changes") Boolean hasUncommittedChanges, @JsonProperty("has_deletions") Boolean hasDeletions, @JsonProperty("ram_buffer_size_mb") Double ramBufferSizeMb, @JsonProperty("index_uuid") String indexUuid, @JsonProperty("master_uuid") String masterUuid, @JsonProperty("version") Long version, @JsonProperty("analyzers") Set<String> analyzers, @JsonProperty("fields") Set<String> fields, @JsonProperty("settings") IndexSettingsDefinition settings, @JsonProperty("field_infos") SortedMap<String, Set<FieldInfoStatus>> fieldInfos, @JsonProperty("segment_count") Integer segmentCount, @JsonProperty("segments_bytes_size") Long segmentsBytesSize, @JsonProperty("segments_size") String segmentsSize, @JsonProperty("commit_filenames") Collection<String> commitFilenames, @JsonProperty("commit_generation") Long commitGeneration, @JsonProperty("merge_policy") MergePolicyStatus mergePolicy, @JsonProperty("query_cache") QueryCacheStats queryCache, @JsonProperty("commit_user_data") Map<String, String> commitUserData, @JsonProperty("directory_class") String directoryClass, @JsonProperty("directory_cached_files") String[] directoryCachedFiles, @JsonProperty("directory_cached_ram_used") String directoryCachedRamUsed, @JsonProperty("active_analyzers") Integer activeAnalyzers, @JsonProperty("index_sort_fields") Set<String> indexSortFields) { this.numDocs = numDocs; this.numDeletedDocs = numDeletedDocs; this.mergePolicy = mergePolicy; this.hasPendingMerges = hasPendingMerges; this.hasUncommittedChanges = hasUncommittedChanges; this.ramBufferSizeMb = ramBufferSizeMb; this.hasDeletions = hasDeletions; this.indexUuid = indexUuid; this.masterUuid = masterUuid; this.version = version; this.analyzers = analyzers; this.fields = fields; this.settings = settings; this.fieldInfos = fieldInfos; this.segmentCount = segmentCount; this.segmentsBytesSize = segmentsBytesSize; this.segmentsSize = segmentsSize; this.commitFilenames = commitFilenames; this.commitGeneration = commitGeneration; this.queryCache = queryCache; this.commitUserData = commitUserData; this.directoryClass = directoryClass; this.directoryCachedFiles = directoryCachedFiles; this.directoryCachedRamUsed = directoryCachedRamUsed; this.activeAnalyzers = activeAnalyzers; this.indexSortFields = indexSortFields; } public IndexStatus(final UUID indexUuid, final UUID masterUuid, final Directory directory, final IndexSearcher indexSearcher, final IndexWriter indexWriter, final IndexSettingsDefinition settings, final Set<String> analyzers, final Set<String> fields, final int activeAnalyzers) throws IOException { final IndexReader indexReader = indexSearcher.getIndexReader(); this.numDocs = (long) indexReader.numDocs(); this.numDeletedDocs = (long) indexReader.numDeletedDocs(); final TreeMap<String, Set<FieldInfoStatus>> m = new TreeMap<>(); fillFieldInfos(m, indexReader.leaves()); this.fieldInfos = Collections.unmodifiableSortedMap(m); if (indexWriter == null) { this.mergePolicy = null; this.hasPendingMerges = null; this.hasUncommittedChanges = null; this.hasDeletions = null; this.ramBufferSizeMb = null; this.indexSortFields = null; } else { final LiveIndexWriterConfig config = indexWriter.getConfig(); final MergePolicy mergePolicy = config.getMergePolicy(); this.mergePolicy = mergePolicy == null ? null : new MergePolicyStatus(mergePolicy); this.hasPendingMerges = indexWriter.hasPendingMerges(); this.hasUncommittedChanges = indexWriter.hasUncommittedChanges(); this.hasDeletions = indexWriter.hasDeletions(); this.ramBufferSizeMb = config.getRAMBufferSizeMB(); this.indexSortFields = config.getIndexSortFields(); } final DirectoryReader directoryReader = indexReader instanceof DirectoryReader ? (DirectoryReader) indexReader : null; final IndexCommit indexCommit; if (directoryReader != null) { indexCommit = directoryReader.getIndexCommit(); version = directoryReader.getVersion(); } else { indexCommit = null; version = null; } if (indexCommit != null) { this.commitUserData = indexCommit.getUserData(); this.segmentCount = indexCommit.getSegmentCount(); this.commitFilenames = indexCommit.getFileNames(); this.commitGeneration = indexCommit.getGeneration(); if (directory != null) { long size = 0; for (String filename : this.commitFilenames) { try { size += directory.fileLength(filename); } catch (IOException e) { LOGGER.log(Level.FINE, e, e::getMessage); } } this.segmentsBytesSize = size; this.segmentsSize = FileUtils.byteCountToDisplaySize(size); } else { this.segmentsBytesSize = null; this.segmentsSize = null; } } else { this.commitUserData = null; this.segmentCount = null; this.segmentsBytesSize = null; this.segmentsSize = null; this.commitFilenames = null; this.commitGeneration = null; } this.indexUuid = indexUuid == null ? null : indexUuid.toString(); this.masterUuid = masterUuid == null ? null : masterUuid.toString(); this.settings = settings; this.analyzers = analyzers; this.activeAnalyzers = activeAnalyzers; this.fields = fields; final QueryCache queryCache = indexSearcher.getQueryCache(); this.queryCache = queryCache instanceof LRUQueryCache ? new QueryCacheStats((LRUQueryCache) queryCache) : null; if (directory != null) { if (directory instanceof NRTCachingDirectory) { final NRTCachingDirectory nrtCachingDirectory = (NRTCachingDirectory) directory; this.directoryClass = nrtCachingDirectory.getDelegate().getClass().getName(); this.directoryCachedFiles = nrtCachingDirectory.listCachedFiles(); this.directoryCachedRamUsed = FileUtils.byteCountToDisplaySize(nrtCachingDirectory.ramBytesUsed()); } else { this.directoryClass = directory.getClass().getName(); this.directoryCachedFiles = null; this.directoryCachedRamUsed = null; } } else { this.directoryClass = null; this.directoryCachedFiles = null; this.directoryCachedRamUsed = null; } } private void fillFieldInfos(final Map<String, Set<FieldInfoStatus>> field_infos, final List<LeafReaderContext> leaves) { if (field_infos == null || leaves == null || leaves.isEmpty()) return; leaves.forEach(leafReaderContext -> { final FieldInfos fieldInfos = leafReaderContext.reader().getFieldInfos(); if (fieldInfos == null) return; fieldInfos.forEach(fieldInfo -> { final Set<FieldInfoStatus> set = field_infos.computeIfAbsent(fieldInfo.name, s -> new LinkedHashSet<>()); set.add(new FieldInfoStatus(fieldInfo)); }); }); } @Override public int hashCode() { return Objects.hash(indexUuid, numDocs); } @Override final public boolean equals(final Object o) { if (!(o instanceof IndexStatus)) return false; final IndexStatus s = (IndexStatus) o; if (!Objects.equals(numDocs, s.numDocs)) return false; if (!Objects.equals(numDeletedDocs, s.numDeletedDocs)) return false; if (!Objects.equals(indexUuid, s.indexUuid)) return false; if (!Objects.equals(masterUuid, s.masterUuid)) return false; if (!Objects.equals(version, s.version)) return false; if (!Objects.equals(settings, s.settings)) return false; if (!Objects.deepEquals(analyzers, s.analyzers)) return false; if (!Objects.deepEquals(fields, s.fields)) return false; if (!Objects.equals(activeAnalyzers, s.activeAnalyzers)) return false; if (!Objects.equals(indexSortFields, s.indexSortFields)) return false; return true; } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonAutoDetect(setterVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class MergePolicyStatus { final public String type; @JsonProperty("max_cfs_segment_size_mb") final public Double maxCfsSegmentSizeMb; @JsonProperty("no_cfs_ratio") final public Double noCfsRatio; //TieredMergePolicy @JsonProperty("max_merge_at_once") final public Integer maxMergeAtOnce; @JsonProperty("max_merged_segment_mb") final public Double maxMergedSegmentMb; @JsonProperty("segments_per_tier") final public Double segmentsPerTier; @JsonCreator MergePolicyStatus(@JsonProperty("type") String type, @JsonProperty("max_cfs_segment_size_mb") Double max_cfs_segment_size_mb, @JsonProperty("no_cfs_ratio") Double no_cfs_ratio, @JsonProperty("max_merge_at_once") Integer max_merge_at_once, @JsonProperty("max_merged_segment_mb") Double max_merged_segment_mb, @JsonProperty("segments_per_tier") Double segments_per_tier) { this.type = type; this.maxCfsSegmentSizeMb = max_cfs_segment_size_mb; this.noCfsRatio = no_cfs_ratio; this.maxMergeAtOnce = max_merge_at_once; this.maxMergedSegmentMb = max_merged_segment_mb; this.segmentsPerTier = segments_per_tier; } MergePolicyStatus(final MergePolicy mergePolicy) { type = mergePolicy.getClass().getTypeName(); maxCfsSegmentSizeMb = mergePolicy.getMaxCFSSegmentSizeMB(); noCfsRatio = mergePolicy.getNoCFSRatio(); if (mergePolicy instanceof TieredMergePolicy) { TieredMergePolicy tmp = (TieredMergePolicy) mergePolicy; maxMergeAtOnce = tmp.getMaxMergeAtOnce(); maxMergedSegmentMb = tmp.getMaxMergedSegmentMB(); segmentsPerTier = tmp.getSegmentsPerTier(); } else { maxMergeAtOnce = null; maxMergedSegmentMb = null; segmentsPerTier = null; } } } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonAutoDetect(setterVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class FieldInfoStatus { public final Integer number; @JsonProperty("omit_norms") public final Boolean omitNorms; @JsonProperty("has_norms") public final Boolean hasNorms; @JsonProperty("has_payloads") public final Boolean hasPayloads; @JsonProperty("has_vectors") public final Boolean hasVectors; @JsonProperty("doc_values_gen") public final Long docValuesGen; @JsonProperty("doc_values_type") public final DocValuesType docValuesType; @JsonProperty("index_options") public final IndexOptions indexOptions; @JsonProperty("point_dimension_count") public final Integer pointDimensionCount; @JsonProperty("point_index_dimension_count") public final Integer pointIndexDimensionCount; @JsonProperty("point_num_bytes") public final Integer pointNumBytes; @JsonIgnore private final int hashCode; @JsonCreator FieldInfoStatus(@JsonProperty("number") Integer number, @JsonProperty("omit_norms") Boolean omitNorms, @JsonProperty("has_norms") Boolean hasNorms, @JsonProperty("has_payloads") Boolean hasPayloads, @JsonProperty("has_vectors") Boolean hasVectors, @JsonProperty("doc_values_gen") Long docValuesGen, @JsonProperty("doc_values_type") DocValuesType docValuesType, @JsonProperty("index_options") IndexOptions indexOptions, @JsonProperty("point_dimension_count") Integer pointDimensionCount, @JsonProperty("point_index_dimension_count") Integer pointIndexDimensionCount, @JsonProperty("point_num_bytes") Integer pointNumBytes) { this.number = number; this.omitNorms = omitNorms; this.hasNorms = hasNorms; this.hasPayloads = hasPayloads; this.hasVectors = hasVectors; this.docValuesGen = docValuesGen; this.docValuesType = docValuesType; this.indexOptions = indexOptions; this.pointDimensionCount = pointDimensionCount; this.pointIndexDimensionCount = pointIndexDimensionCount; this.pointNumBytes = pointNumBytes; hashCode = buildHashCode(); } private FieldInfoStatus(final FieldInfo info) { this(info.number, info.omitsNorms(), info.hasNorms(), info.hasPayloads(), info.hasVectors(), info.getDocValuesGen(), info.getDocValuesType(), info.getIndexOptions(), info.getPointDimensionCount(), info.getPointIndexDimensionCount(), info.getPointNumBytes()); } private int buildHashCode() { return Objects.hash(number, omitNorms, hasNorms, hasPayloads, hasVectors, docValuesGen, docValuesType, indexOptions, pointDimensionCount, pointIndexDimensionCount, pointNumBytes); } @Override public int hashCode() { return hashCode; } @Override public boolean equals(final Object o) { if (!(o instanceof FieldInfoStatus)) return false; final FieldInfoStatus info = (FieldInfoStatus) o; if (!Objects.equals(number, info.number)) return false; if (!Objects.equals(omitNorms, info.omitNorms)) return false; if (!Objects.equals(hasNorms, info.hasNorms)) return false; if (!Objects.equals(hasPayloads, info.hasPayloads)) return false; if (!Objects.equals(hasVectors, info.hasVectors)) return false; if (!Objects.equals(docValuesGen, info.docValuesGen)) return false; if (!Objects.equals(docValuesType, info.docValuesType)) return false; if (!Objects.equals(indexOptions, info.indexOptions)) return false; if (!Objects.equals(pointDimensionCount, info.pointDimensionCount)) return false; if (!Objects.equals(pointIndexDimensionCount, info.pointIndexDimensionCount)) return false; if (!Objects.equals(pointNumBytes, info.pointNumBytes)) return false; return true; } } @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonAutoDetect(setterVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY) public static class QueryCacheStats { @JsonProperty("cache_count") public final Long cacheCount; @JsonProperty("cache_size") public final Long cacheSize; @JsonProperty("eviction_count") public final Long evictionCount; @JsonProperty("hit_count") public final Long hitCount; @JsonProperty("miss_count") public final Long missCount; @JsonProperty("total_count") public final Long totalCount; @JsonProperty("hit_rate") public final Float hitRate; @JsonProperty("miss_rate") public final Float missRate; private final int hashCode; @JsonCreator QueryCacheStats(@JsonProperty("cache_count") Long cacheCount, @JsonProperty("cache_size") Long cacheSize, @JsonProperty("eviction_count") Long evictionCount, @JsonProperty("hit_count") Long hitCount, @JsonProperty("miss_count") Long missCount, @JsonProperty("total_count") Long totalCount, @JsonProperty("hit_rate") Float hitRate, @JsonProperty("miss_rate") Float missRate) { this.cacheCount = cacheCount; this.cacheSize = cacheSize; this.evictionCount = evictionCount; this.hitCount = hitCount; this.missCount = missCount; this.totalCount = totalCount; this.hitRate = hitRate; this.missRate = missRate; this.hashCode = Objects.hash(cacheCount, cacheSize, evictionCount, hitCount, missCount, totalCount, hitRate, missRate); } private QueryCacheStats(final LRUQueryCache queryCache) { this(queryCache.getCacheCount(), queryCache.getCacheSize(), queryCache.getEvictionCount(), queryCache.getHitCount(), queryCache.getMissCount(), queryCache.getTotalCount(), (float) (queryCache.getHitCount() * 100) / queryCache.getTotalCount(), (float) (queryCache.getMissCount() * 100) / queryCache.getTotalCount()); } @Override public int hashCode() { return hashCode; } @Override public boolean equals(final Object o) { if (!(o instanceof QueryCacheStats)) return false; final QueryCacheStats cache = (QueryCacheStats) o; if (!Objects.equals(cacheCount, cache.cacheCount)) return false; if (!Objects.equals(cacheSize, cache.cacheSize)) return false; if (!Objects.equals(evictionCount, cache.evictionCount)) return false; if (!Objects.equals(hitCount, cache.hitCount)) return false; if (!Objects.equals(missCount, cache.missCount)) return false; if (!Objects.equals(totalCount, cache.totalCount)) return false; if (!Objects.equals(hitRate, cache.hitRate)) return false; if (!Objects.equals(missRate, cache.missRate)) return false; return true; } } }
package GUI; import java.awt.BorderLayout; import java.awt.GridLayout; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import AccuStat.Battery; import AccuStat.Main; /** * to be used to modify a battery * * @author Joschka Köster * */ public class GUI_ModifyBattery { /** * the main dialog window in this class */ private JDialog dialog; /** * the main panel, containing the forms */ private JPanel panel = new JPanel ( new GridLayout(4, 2, 10, 10)); /** * the lower panel, containing the close button */ private JPanel downPanel = new JPanel(); private JPanel northPanel = new JPanel(); /** * labels for each form field, i.e. each line */ private JLabel labelBrand = new JLabel("Select Brand: "); private JLabel labelType = new JLabel ("Select Type: "); private JLabel labelBattery = new JLabel ("Select Battery: "); private JLabel labelBrandItem = new JLabel(); private JLabel labelTypeItem = new JLabel(); /** * buttons for modifying the batteries */ private JButton save = new JButton("New Battery"); private JButton remove = new JButton("Remove"); private JButton cancel = new JButton("Close"); private JButton refresh = new JButton("Refresh"); /** * contains all the batteries */ private JComboBox<Battery> batteries = new JComboBox<Battery>(); /** * enter a battery name here ... or not? */ private JTextField textfield = new JTextField(15); /** * new dialog windows opened from here to actually add a battery. removing works from this dialog. */ private GUI_AddBattery guiAddBattery = new GUI_AddBattery(this.dialog, this); /** * GUI Class */ @SuppressWarnings("unused") private GUI_Main GUI; /** * the main constructor, taking a JFrame to be locked. does not work, yet, though. * * @param pFrame the JFrame to be locked while this dialog remains open */ public GUI_ModifyBattery(JFrame pFrame, GUI_Main pGUI) { this.GUI = pGUI; this.dialog = new JDialog(pFrame); this.panel.setBorder(new EmptyBorder(10,10,10,10)); this.save.addActionListener(e -> this.openAddBattery()); this.remove.addActionListener(e -> remove()); this.refresh.addActionListener(e -> this.refresh()); this.cancel.addActionListener(e -> this.closeMe()); dialog.setSize(320, 250); this.textfield.setSize(300, 100); this.panel.add(this.labelBattery); this.panel.add(this.batteries); this.panel.add(this.labelBrand); this.panel.add(this.labelBrandItem); this.panel.add(this.labelType); this.panel.add(this.labelTypeItem); this.panel.add(this.save); this.panel.add(this.remove); this.downPanel.add(cancel); this.northPanel.add(new JLabel("Modify Batteries")); this.northPanel.add(this.refresh); this.dialog.getContentPane().add(BorderLayout.NORTH, this.northPanel); this.dialog.getContentPane().add(BorderLayout.CENTER, this.panel); this.dialog.getContentPane().add(BorderLayout.SOUTH, this.downPanel); } private void openAddBattery() { this.closeMe(); this.guiAddBattery.openMe(); } /** * set this dialog visible */ public void openMe() { this.dialog.setVisible(true); Main.populateComboBoxes(); } /** * set this dialog invisible */ public void closeMe() { Main.populateComboBoxes(); this.dialog.setVisible(false); } /** * remove a battery from the list */ public void remove() { Main.removeBattery((Battery) this.batteries.getSelectedItem()); Main.populateComboBoxes(); } /** * populate the combobox with items from the arraylist in the main class and method */ public void populate() { this.batteries.removeAllItems(); this.labelBrandItem.setText(""); this.labelTypeItem.setText(""); ArrayList<Battery> battList = Main.get_Batteries(); for ( Battery b : battList ) this.batteries.addItem(b); this.guiAddBattery.populate(); } public void populate(Battery pBattery, GUI_ModifyBattery pGUI) { this.labelBrandItem.setText(pBattery.getBrand().toString()); this.labelTypeItem.setText(pBattery.getType().toString()); } public void refresh() { Battery bat = (Battery) this.batteries.getSelectedItem(); if ( bat == null ) return; this.labelBrandItem.setText(bat.getBrand().toString()); this.labelTypeItem.setText(bat.getType().toString()); } }
package mage.cards.m; import java.util.UUID; import mage.abilities.Mode; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.effects.common.GainLifeEffect; import mage.abilities.effects.common.TapTargetEffect; import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; import mage.abilities.keyword.FirstStrikeAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.target.common.TargetCreaturePermanent; /** * * @author LoneFox */ public final class MidnightCharm extends CardImpl { public MidnightCharm(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{B}"); // Choose one - Midnight Charm deals 1 damage to target creature and you gain 1 life; or target creature gains first strike until end of turn; or tap target creature. this.getSpellAbility().addEffect(new DamageTargetEffect(1)); this.getSpellAbility().addEffect(new GainLifeEffect(1).setText("and you gain 1 life")); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); Mode mode = new Mode(); mode.getEffects().add(new GainAbilityTargetEffect(FirstStrikeAbility.getInstance(), Duration.EndOfTurn)); mode.getTargets().add(new TargetCreaturePermanent()); this.getSpellAbility().addMode(mode); mode = new Mode(); mode.getEffects().add(new TapTargetEffect()); mode.getTargets().add(new TargetCreaturePermanent()); this.getSpellAbility().addMode(mode); } public MidnightCharm(final MidnightCharm card) { super(card); } @Override public MidnightCharm copy() { return new MidnightCharm(this); } }
package com.karim.examples.rabbitmq.connector.exceptions; /** * <p>This class used as a <i>wrapper</i> for {@link Throwable} thrown during * parsing of the object to <i>JSON</i> and vice-versa. </p> * * <p>It's store a meaningful message and the true cause of the {@link Throwable}. * See {@link #JSONCustomException(String, Throwable)} for more information.</p> * * @author Karim Abd ElKareem * @since 1.0 */ public class JSONCustomException extends Exception { private static final long serialVersionUID = 1L; /** * @param message meaningful message. * @param cause the true cause of the problem. */ public JSONCustomException(String message, Throwable cause){ super(message, cause); } }
/* * 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.aliyuncs.ccc.model.v20200701; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.ccc.transform.v20200701.GetInstanceTrendingReportResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class GetInstanceTrendingReportResponse extends AcsResponse { private String code; private Integer httpStatusCode; private String message; private String requestId; private Data data; public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public Integer getHttpStatusCode() { return this.httpStatusCode; } public void setHttpStatusCode(Integer httpStatusCode) { this.httpStatusCode = httpStatusCode; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Data getData() { return this.data; } public void setData(Data data) { this.data = data; } public static class Data { private List<InboundItem> inbound; private List<OutboundItem> outbound; public List<InboundItem> getInbound() { return this.inbound; } public void setInbound(List<InboundItem> inbound) { this.inbound = inbound; } public List<OutboundItem> getOutbound() { return this.outbound; } public void setOutbound(List<OutboundItem> outbound) { this.outbound = outbound; } public static class InboundItem { private Long statsTime; private Long callsQueued; private Long callsAbandonedInRing; private Long callsHandled; private Long totalCalls; private Long callsAbandonedInIVR; private Long callsAbandonedInQueue; public Long getStatsTime() { return this.statsTime; } public void setStatsTime(Long statsTime) { this.statsTime = statsTime; } public Long getCallsQueued() { return this.callsQueued; } public void setCallsQueued(Long callsQueued) { this.callsQueued = callsQueued; } public Long getCallsAbandonedInRing() { return this.callsAbandonedInRing; } public void setCallsAbandonedInRing(Long callsAbandonedInRing) { this.callsAbandonedInRing = callsAbandonedInRing; } public Long getCallsHandled() { return this.callsHandled; } public void setCallsHandled(Long callsHandled) { this.callsHandled = callsHandled; } public Long getTotalCalls() { return this.totalCalls; } public void setTotalCalls(Long totalCalls) { this.totalCalls = totalCalls; } public Long getCallsAbandonedInIVR() { return this.callsAbandonedInIVR; } public void setCallsAbandonedInIVR(Long callsAbandonedInIVR) { this.callsAbandonedInIVR = callsAbandonedInIVR; } public Long getCallsAbandonedInQueue() { return this.callsAbandonedInQueue; } public void setCallsAbandonedInQueue(Long callsAbandonedInQueue) { this.callsAbandonedInQueue = callsAbandonedInQueue; } } public static class OutboundItem { private Long statsTime; private Long callsAnswered; private Long totalCalls; public Long getStatsTime() { return this.statsTime; } public void setStatsTime(Long statsTime) { this.statsTime = statsTime; } public Long getCallsAnswered() { return this.callsAnswered; } public void setCallsAnswered(Long callsAnswered) { this.callsAnswered = callsAnswered; } public Long getTotalCalls() { return this.totalCalls; } public void setTotalCalls(Long totalCalls) { this.totalCalls = totalCalls; } } } @Override public GetInstanceTrendingReportResponse getInstance(UnmarshallerContext context) { return GetInstanceTrendingReportResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
package net.readonly.utils.tracker.ringbuffer; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nonnegative; public class LongRingBuffer implements RingBuffer { protected final AtomicInteger index = new AtomicInteger(); protected final int size; protected final long[] array; public LongRingBuffer(@Nonnegative int size) { this.size = size; this.array = new long[size]; } @Override public int size() { return size; } @Override public void put(@Nonnegative long value) { array[index.getAndIncrement() % size] = value; } @Override public long sum() { return sumLast(size); } @Override public long sumLast(int amount) { int nextIdx = index.get(); int lastIdx = (nextIdx - 1) % size; long sum = 0; for(int i = 0, amt = Math.min(amount, size); i < amt; i++) { int idx = lastIdx - i; if(idx < 0) { idx += size; } sum += array[idx]; } return sum; } }
package g1801_1900.s1882_process_tasks_using_servers; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.Test; class SolutionTest { @Test void assignTasks() { assertThat( new Solution().assignTasks(new int[] {3, 3, 2}, new int[] {1, 2, 3, 2, 1, 2}), equalTo(new int[] {2, 2, 0, 2, 1, 2})); } @Test void assignTasks2() { assertThat( new Solution() .assignTasks(new int[] {5, 1, 4, 3, 2}, new int[] {2, 1, 2, 4, 5, 2, 1}), equalTo(new int[] {1, 4, 1, 4, 1, 3, 2})); } }
package org.hl7.fhir.r4.model.codesystems; /*- * #%L * org.hl7.fhir.r4 * %% * Copyright (C) 2014 - 2019 Health Level 7 * %% * 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% */ /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 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 HL7 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. */ // Generated on Wed, Jan 30, 2019 16:19-0500 for FHIR v4.0.0 import org.hl7.fhir.exceptions.FHIRException; public enum ContractDefinitionType { /** * To be completed */ TEMP, /** * added to help the parsers */ NULL; public static ContractDefinitionType fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("temp".equals(codeString)) return TEMP; throw new FHIRException("Unknown ContractDefinitionType code '"+codeString+"'"); } public String toCode() { switch (this) { case TEMP: return "temp"; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/contract-definition-type"; } public String getDefinition() { switch (this) { case TEMP: return "To be completed"; default: return "?"; } } public String getDisplay() { switch (this) { case TEMP: return "Temporary Value"; default: return "?"; } } }
package com.kong.alex.sharkfeed.api.info; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class PhotoInfo { @SerializedName("id") @Expose private String id; @SerializedName("secret") @Expose private String secret; @SerializedName("server") @Expose private String server; @SerializedName("farm") @Expose private Integer farm; @SerializedName("dateuploaded") @Expose private String dateuploaded; @SerializedName("isfavorite") @Expose private Integer isfavorite; @SerializedName("license") @Expose private String license; @SerializedName("safety_level") @Expose private String safetyLevel; @SerializedName("rotation") @Expose private Integer rotation; @SerializedName("owner") @Expose private Owner owner; @SerializedName("title") @Expose private Title title; @SerializedName("description") @Expose private Description description; @SerializedName("visibility") @Expose private Visibility visibility; @SerializedName("dates") @Expose private Dates dates; @SerializedName("views") @Expose private String views; @SerializedName("editability") @Expose private Editability editability; @SerializedName("publiceditability") @Expose private Publiceditability publiceditability; @SerializedName("usage") @Expose private Usage usage; @SerializedName("comments") @Expose private Comments comments; @SerializedName("notes") @Expose private Notes notes; @SerializedName("people") @Expose private People people; @SerializedName("tags") @Expose private Tags tags; @SerializedName("urls") @Expose private Urls urls; @SerializedName("media") @Expose private String media; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public Integer getFarm() { return farm; } public void setFarm(Integer farm) { this.farm = farm; } public String getDateuploaded() { return dateuploaded; } public void setDateuploaded(String dateuploaded) { this.dateuploaded = dateuploaded; } public Integer getIsfavorite() { return isfavorite; } public void setIsfavorite(Integer isfavorite) { this.isfavorite = isfavorite; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public String getSafetyLevel() { return safetyLevel; } public void setSafetyLevel(String safetyLevel) { this.safetyLevel = safetyLevel; } public Integer getRotation() { return rotation; } public void setRotation(Integer rotation) { this.rotation = rotation; } public Owner getOwner() { return owner; } public void setOwner(Owner owner) { this.owner = owner; } public Title getTitle() { return title; } public void setTitle(Title title) { this.title = title; } public Description getDescription() { return description; } public void setDescription(Description description) { this.description = description; } public Visibility getVisibility() { return visibility; } public void setVisibility(Visibility visibility) { this.visibility = visibility; } public Dates getDates() { return dates; } public void setDates(Dates dates) { this.dates = dates; } public String getViews() { return views; } public void setViews(String views) { this.views = views; } public Editability getEditability() { return editability; } public void setEditability(Editability editability) { this.editability = editability; } public Publiceditability getPubliceditability() { return publiceditability; } public void setPubliceditability(Publiceditability publiceditability) { this.publiceditability = publiceditability; } public Usage getUsage() { return usage; } public void setUsage(Usage usage) { this.usage = usage; } public Comments getComments() { return comments; } public void setComments(Comments comments) { this.comments = comments; } public Notes getNotes() { return notes; } public void setNotes(Notes notes) { this.notes = notes; } public People getPeople() { return people; } public void setPeople(People people) { this.people = people; } public Tags getTags() { return tags; } public void setTags(Tags tags) { this.tags = tags; } public Urls getUrls() { return urls; } public void setUrls(Urls urls) { this.urls = urls; } public String getMedia() { return media; } public void setMedia(String media) { this.media = media; } }
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.vitro.webapp.controller.edit; import static edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames.TBOX_ASSERTIONS; import java.util.HashMap; import java.util.Iterator; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jena.datatypes.RDFDatatype; import org.apache.jena.datatypes.TypeMapper; import org.apache.jena.ontology.OntClass; import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModelSpec; import org.apache.jena.ontology.OntProperty; import org.apache.jena.ontology.Restriction; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Resource; import org.apache.jena.shared.Lock; import edu.cornell.mannlib.vedit.beans.EditProcessObject; import edu.cornell.mannlib.vedit.controller.BaseEditController; import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent; import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess; @WebServlet(name = "RestrictionOperationController", urlPatterns = {"/addRestriction"} ) public class RestrictionOperationController extends BaseEditController { private static final Log log = LogFactory.getLog(RestrictionOperationController.class.getName()); public void doPost(HttpServletRequest req, HttpServletResponse response) { if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) { return; } VitroRequest request = new VitroRequest(req); String defaultLandingPage = getDefaultLandingPage(request); try { OntModel ontModel = ModelAccess.on(getServletContext()) .getOntModel(TBOX_ASSERTIONS); HashMap epoHash = null; EditProcessObject epo = null; try { epoHash = (HashMap) request.getSession().getAttribute("epoHash"); epo = (EditProcessObject) epoHash.get(request.getParameter("_epoKey")); } catch (NullPointerException e) { //session or edit process expired response.sendRedirect(defaultLandingPage); return; } if (epo == null) { response.sendRedirect(defaultLandingPage); return; } if ( (request.getParameter("_cancel") == null ) ) { processRestriction(request, epo, ontModel); } //if no page forwarder was set, just go back to referring page: String referer = epo.getReferer(); if (referer == null) { response.sendRedirect(defaultLandingPage); } else { response.sendRedirect(referer); } } catch (Exception e) { log.error(e, e); try { response.sendRedirect(defaultLandingPage); } catch (Exception f) { log.error(f, f); throw new RuntimeException(f); } } } private void processRestriction(VitroRequest request, EditProcessObject epo, OntModel ontModel) { ontModel.enterCriticalSection(Lock.WRITE); try { ontModel.getBaseModel().notifyEvent(new EditEvent(request.getUnfilteredWebappDaoFactory().getUserURI(),true)); if ("delete".equals(request.getParameter("_action"))) { processDelete(request, ontModel); } else { processCreate(request, epo, ontModel); } } finally { ontModel.getBaseModel().notifyEvent(new EditEvent(request.getUnfilteredWebappDaoFactory().getUserURI(),false)); ontModel.leaveCriticalSection(); } } private void processDelete(VitroRequest request, OntModel ontModel) { String restId = request.getParameter("restrictionId"); if (restId != null) { OntClass restrictedClass = ontModel.getOntClass( request.getParameter( "classUri" ) ); OntClass rest = null; for ( Iterator i = restrictedClass.listEquivalentClasses(); i.hasNext(); ) { OntClass equivClass = (OntClass) i.next(); if (equivClass.isAnon() && equivClass.getId().toString().equals(restId)) { rest = equivClass; } } if ( rest == null ) { for ( Iterator i = restrictedClass.listSuperClasses(); i.hasNext(); ) { OntClass superClass = (OntClass) i.next(); if (superClass.isAnon() && superClass.getId().toString().equals(restId)) { rest = superClass; } } } /** * removing by graph subtraction so that statements with blank nodes * stick together and are processed appropriately by the bulk update * handler */ if ( rest != null ) { Model temp = ModelFactory.createDefaultModel(); temp.add(rest.listProperties()); ontModel.getBaseModel().remove(temp); } } } private void processCreate(VitroRequest request, EditProcessObject epo, OntModel origModel) { Model temp = ModelFactory.createDefaultModel(); Model dynamicUnion = ModelFactory.createUnion(temp, origModel); OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, dynamicUnion); OntProperty onProperty = ontModel.getOntProperty( (String) request.getParameter("onProperty") ); String conditionTypeStr = request.getParameter("conditionType"); String restrictionTypeStr = (String) epo.getAttribute("restrictionType"); Restriction rest = null; OntClass ontClass = ontModel.getOntClass( (String) epo.getAttribute("VClassURI") ); String roleFillerURIStr = request.getParameter("ValueClass"); Resource roleFiller = null; if (roleFillerURIStr != null) { roleFiller = ontModel.getResource(roleFillerURIStr); } int cardinality = -1; String cardinalityStr = request.getParameter("cardinality"); if (cardinalityStr != null) { cardinality = Integer.decode(cardinalityStr); } switch (restrictionTypeStr) { case "allValuesFrom": rest = ontModel.createAllValuesFromRestriction(null, onProperty, roleFiller); break; case "someValuesFrom": rest = ontModel.createSomeValuesFromRestriction(null, onProperty, roleFiller); break; case "hasValue": String valueURI = request.getParameter("ValueIndividual"); if (valueURI != null) { Resource valueRes = ontModel.getResource(valueURI); if (valueRes != null) { rest = ontModel.createHasValueRestriction(null, onProperty, valueRes); } } else { String valueLexicalForm = request.getParameter("ValueLexicalForm"); if (valueLexicalForm != null) { String valueDatatype = request.getParameter("ValueDatatype"); Literal value = null; if (valueDatatype != null && valueDatatype.length() > 0) { RDFDatatype dtype = null; try { dtype = TypeMapper.getInstance().getSafeTypeByName(valueDatatype); } catch (Exception e) { log.warn("Unable to get safe type " + valueDatatype + " using TypeMapper"); } if (dtype != null) { value = ontModel.createTypedLiteral(valueLexicalForm, dtype); } else { value = ontModel.createLiteral(valueLexicalForm); } } else { value = ontModel.createLiteral(valueLexicalForm); } rest = ontModel.createHasValueRestriction(null, onProperty, value); } } break; case "minCardinality": rest = ontModel.createMinCardinalityRestriction(null, onProperty, cardinality); break; case "maxCardinality": rest = ontModel.createMaxCardinalityRestriction(null, onProperty, cardinality); break; case "cardinality": rest = ontModel.createCardinalityRestriction(null, onProperty, cardinality); break; } if (conditionTypeStr.equals("necessary")) { ontClass.addSuperClass(rest); } else if (conditionTypeStr.equals("necessaryAndSufficient")) { ontClass.addEquivalentClass(rest); } origModel.add(temp); } }
package org.kin.kinrpc.rpc.exception; /** * @author huangjianqin * @date 2020/11/18 */ public class RpcCallTimeOutException extends RuntimeException { private static final long serialVersionUID = 490253965471277042L; public RpcCallTimeOutException(String errorMsg) { super(errorMsg); } public RpcCallTimeOutException(String message, Throwable cause) { super(message, cause); } }
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2014 - 2018 ImageJ developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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 HOLDERS 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. * #L% */ package net.imagej.ops.stats; import net.imagej.ops.AbstractNamespace; import net.imagej.ops.Namespace; import net.imagej.ops.OpMethod; import net.imglib2.IterableInterval; import net.imglib2.algorithm.neighborhood.RectangleNeighborhood; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.real.DoubleType; import net.imglib2.util.Pair; import org.scijava.plugin.Plugin; /** * The stats namespace contains operations related to numerical statistics. * * @author Curtis Rueden * @author Daniel Seebacher (University of Konstanz) * @author Christian Dietz (University of Konstanz) */ @SuppressWarnings("unchecked") @Plugin(type = Namespace.class) public class StatsNamespace extends AbstractNamespace { @OpMethod(ops = { net.imagej.ops.stats.IterableGeometricMean.class, net.imagej.ops.stats.DefaultGeometricMean.class }) public <T extends RealType<T>, O extends RealType<O>> O geometricMean( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.GeometricMean.class, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.IterableGeometricMean.class, net.imagej.ops.stats.DefaultGeometricMean.class }) public <T extends RealType<T>, O extends RealType<O>> O geometricMean( final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.GeometricMean.class, out, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.IterableHarmonicMean.class, net.imagej.ops.stats.DefaultHarmonicMean.class }) public <T extends RealType<T>, O extends RealType<O>> O harmonicMean( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.HarmonicMean.class, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.IterableHarmonicMean.class, net.imagej.ops.stats.DefaultHarmonicMean.class }) public <T extends RealType<T>, O extends RealType<O>> O harmonicMean( final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.HarmonicMean.class, out, in); return result; } @SuppressWarnings("rawtypes") @OpMethod(op = net.imagej.ops.stats.IntegralMean.class) public DoubleType integralMean(final DoubleType out, final RectangleNeighborhood in) { final DoubleType result = (DoubleType) ops().run( net.imagej.ops.stats.IntegralMean.class, out, in); return result; } @SuppressWarnings("rawtypes") @OpMethod(op = net.imagej.ops.stats.IntegralSum.class) public DoubleType integralSum(final RectangleNeighborhood in) { final DoubleType result = (DoubleType) ops().run( net.imagej.ops.stats.IntegralSum.class, in); return result; } @SuppressWarnings("rawtypes") @OpMethod(op = net.imagej.ops.stats.IntegralSum.class) public DoubleType integralSum(final DoubleType out, final RectangleNeighborhood in) { final DoubleType result = (DoubleType) ops().run( net.imagej.ops.stats.IntegralSum.class, out, in); return result; } @SuppressWarnings("rawtypes") @OpMethod(op = net.imagej.ops.stats.IntegralVariance.class) public DoubleType integralVariance(final DoubleType out, final RectangleNeighborhood in) { final DoubleType result = (DoubleType) ops().run( net.imagej.ops.stats.IntegralVariance.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultKurtosis.class) public <T extends RealType<T>, O extends RealType<O>> O kurtosis( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Kurtosis.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultKurtosis.class) public <T extends RealType<T>, O extends RealType<O>> O kurtosis(final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Kurtosis.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.IterableMax.class) public <T extends RealType<T>> T max(final Iterable<T> in) { final T result = (T) ops().run(net.imagej.ops.Ops.Stats.Max.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.IterableMax.class) public <T extends RealType<T>> T max(final T out, final Iterable<T> in) { final T result = (T) ops().run(net.imagej.ops.Ops.Stats.Max.class, out, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.IterableMean.class, net.imagej.ops.stats.DefaultMean.class }) public <T extends RealType<T>, O extends RealType<O>> O mean( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Mean.class, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.IterableMean.class, net.imagej.ops.stats.DefaultMean.class }) public <T extends RealType<T>, O extends RealType<O>> O mean(final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Mean.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMedian.class) public <T extends RealType<T>, O extends RealType<O>> O median( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Median.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMedian.class) public <T extends RealType<T>, O extends RealType<O>> O median(final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Median.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.IterableMin.class) public <T extends RealType<T>> T min(final Iterable<T> in) { final T result = (T) ops().run(net.imagej.ops.Ops.Stats.Min.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.IterableMin.class) public <T extends RealType<T>> T min(final T out, final Iterable<T> in) { final T result = (T) ops().run(net.imagej.ops.Ops.Stats.Min.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMinMax.class) public <T extends RealType<T>> Pair<T,T> minMax(final Iterable<T> in) { final Pair<T,T> result = (Pair<T,T>) ops().run(net.imagej.ops.Ops.Stats.MinMax.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMoment1AboutMean.class) public <T extends RealType<T>, O extends RealType<O>> O moment1AboutMean( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Moment1AboutMean.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMoment1AboutMean.class) public <T extends RealType<T>, O extends RealType<O>> O moment1AboutMean( final O out, final Iterable<T> in) { final O result = (O) ops() .run(net.imagej.ops.Ops.Stats.Moment1AboutMean.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMoment2AboutMean.class) public <T extends RealType<T>, O extends RealType<O>> O moment2AboutMean( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Moment2AboutMean.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMoment2AboutMean.class) public <T extends RealType<T>, O extends RealType<O>> O moment2AboutMean( final O out, final Iterable<T> in) { final O result = (O) ops() .run(net.imagej.ops.Ops.Stats.Moment2AboutMean.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMoment3AboutMean.class) public <T extends RealType<T>, O extends RealType<O>> O moment3AboutMean( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Moment3AboutMean.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMoment3AboutMean.class) public <T extends RealType<T>, O extends RealType<O>> O moment3AboutMean( final O out, final Iterable<T> in) { final O result = (O) ops() .run(net.imagej.ops.Ops.Stats.Moment3AboutMean.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMoment4AboutMean.class) public <T extends RealType<T>, O extends RealType<O>> O moment4AboutMean( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Moment4AboutMean.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultMoment4AboutMean.class) public <T extends RealType<T>, O extends RealType<O>> O moment4AboutMean( final O out, final Iterable<T> in) { final O result = (O) ops() .run(net.imagej.ops.Ops.Stats.Moment4AboutMean.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultPercentile.class) public <T extends RealType<T>, O extends RealType<O>> O percentile( final Iterable<T> in, final double percent) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Percentile.class, in, percent); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultPercentile.class) public <T extends RealType<T>, O extends RealType<O>> O percentile(final O out, final Iterable<T> in, final double percent) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Percentile.class, out, in, percent); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultQuantile.class) public <T extends RealType<T>, O extends RealType<O>> O quantile(final Iterable<T> in, final double quantile) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Quantile.class, in, quantile); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultQuantile.class) public <T extends RealType<T>, O extends RealType<O>> O quantile(final O out, final Iterable<T> in, final double quantile) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Quantile.class, out, in, quantile); return result; } @OpMethod(op = net.imagej.ops.stats.IISize.class) public <T extends RealType<T>, O extends RealType<O>> O size( final IterableInterval<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Size.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.IISize.class) public <T extends RealType<T>, O extends RealType<O>> O size(final O out, final IterableInterval<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Size.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSize.class) public <T extends RealType<T>, O extends RealType<O>> O size( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Size.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSize.class) public <T extends RealType<T>, O extends RealType<O>> O size(final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Size.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSkewness.class) public <T extends RealType<T>, O extends RealType<O>> O skewness( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Skewness.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSkewness.class) public <T extends RealType<T>, O extends RealType<O>> O skewness(final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Skewness.class, out, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.IterableStandardDeviation.class, net.imagej.ops.stats.DefaultStandardDeviation.class }) public <T extends RealType<T>, O extends RealType<O>> O stdDev( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.StdDev.class, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.IterableStandardDeviation.class, net.imagej.ops.stats.DefaultStandardDeviation.class }) public <T extends RealType<T>, O extends RealType<O>> O stdDev(final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.StdDev.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSum.class) public <T extends RealType<T>, O extends RealType<O>> O sum( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Sum.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSum.class) public <T extends RealType<T>, O extends RealType<O>> O sum(final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Sum.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSumOfInverses.class) public <T extends RealType<T>, O extends RealType<O>> O sumOfInverses( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.SumOfInverses.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSumOfInverses.class) public <T extends RealType<T>, O extends RealType<O>> O sumOfInverses( final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.SumOfInverses.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSumOfLogs.class) public <T extends RealType<T>, O extends RealType<O>> O sumOfLogs( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.SumOfLogs.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSumOfLogs.class) public <T extends RealType<T>, O extends RealType<O>> O sumOfLogs( final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.SumOfLogs.class, out, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSumOfSquares.class) public <T extends RealType<T>, O extends RealType<O>> O sumOfSquares( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.SumOfSquares.class, in); return result; } @OpMethod(op = net.imagej.ops.stats.DefaultSumOfSquares.class) public <T extends RealType<T>, O extends RealType<O>> O sumOfSquares( final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.SumOfSquares.class, out, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.DefaultVariance.class, net.imagej.ops.stats.IterableVariance.class }) public <T extends RealType<T>, O extends RealType<O>> O variance( final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Variance.class, in); return result; } @OpMethod(ops = { net.imagej.ops.stats.DefaultVariance.class, net.imagej.ops.stats.IterableVariance.class }) public <T extends RealType<T>, O extends RealType<O>> O variance(final O out, final Iterable<T> in) { final O result = (O) ops().run(net.imagej.ops.Ops.Stats.Variance.class, out, in); return result; } // -- Named methods -- @Override public String getName() { return "stats"; } }
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.car.app.model; import static java.util.Objects.requireNonNull; import android.annotation.SuppressLint; import android.os.Looper; import android.os.RemoteException; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.car.app.IOnCheckedChangeListener; import androidx.car.app.IOnDoneCallback; import androidx.car.app.OnCheckedChangeListenerWrapper; import androidx.car.app.OnDoneCallback; import androidx.car.app.WrappedRuntimeException; import androidx.car.app.utils.RemoteUtils; /** Represents a toggle that can have either a checked or unchecked state. */ public class Toggle { /** A listener for handling checked state change events. */ public interface OnCheckedChangeListener { /** Notifies that the checked state has changed. */ void onCheckedChange(boolean isChecked); } @Keep @Nullable private final OnCheckedChangeListenerWrapper mOnCheckedChangeListener; @Keep private final boolean mIsChecked; /** * Constructs a new builder of {@link Toggle} with the given {@link OnCheckedChangeListener}. * * <p>Note that the listener relates to UI events and will be executed on the main thread * using {@link Looper#getMainLooper()}.z * * @throws NullPointerException if {@code onCheckedChangeListener} is {@code null}. */ @NonNull @SuppressLint("ExecutorRegistration") public static Builder builder(@NonNull OnCheckedChangeListener onCheckedChangeListener) { return new Builder(requireNonNull(onCheckedChangeListener)); } /** * Returns {@code true} if the toggle is checked. */ public boolean isChecked() { return mIsChecked; } /** * Returns the {@link OnCheckedChangeListenerWrapper} that is called when the checked state of * the {@link Toggle} is changed. */ @NonNull public OnCheckedChangeListenerWrapper getOnCheckedChangeListener() { return requireNonNull(mOnCheckedChangeListener); } @Override @NonNull public String toString() { return "[ isChecked: " + mIsChecked + "]"; } @Override public int hashCode() { return Boolean.valueOf(mIsChecked).hashCode(); } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (!(other instanceof Toggle)) { return false; } Toggle otherToggle = (Toggle) other; // Don't compare listener. return mIsChecked == otherToggle.mIsChecked; } private Toggle(Builder builder) { mIsChecked = builder.mIsChecked; mOnCheckedChangeListener = builder.mOnCheckedChangeListener; } /** Constructs an empty instance, used by serialization code. */ private Toggle() { mOnCheckedChangeListener = null; mIsChecked = false; } /** A builder of {@link Toggle}. */ public static final class Builder { private OnCheckedChangeListenerWrapper mOnCheckedChangeListener; private boolean mIsChecked; /** * Sets the initial checked state for {@link Toggle}. * * <p>The default state of a {@link Toggle} is unchecked. */ @NonNull public Builder setChecked(boolean checked) { this.mIsChecked = checked; return this; } /** * Sets the {@link OnCheckedChangeListener} to call when the checked state of the * {@link Toggle} is changed. * * <p>Note that the listener relates to UI events and will be executed on the main thread * using {@link Looper#getMainLooper()}. * * @throws NullPointerException if {@code onCheckedChangeListener} is {@code null}. */ @NonNull @SuppressLint({"ExecutorRegistration"}) public Builder setOnCheckedChangeListener( @NonNull OnCheckedChangeListener onCheckedChangeListener) { this.mOnCheckedChangeListener = createOnCheckedChangeListener(onCheckedChangeListener); return this; } private Builder(@NonNull OnCheckedChangeListener onCheckedChangeListener) { this.mOnCheckedChangeListener = createOnCheckedChangeListener(onCheckedChangeListener); } /** Constructs the {@link Toggle} defined by this builder. */ @NonNull public Toggle build() { return new Toggle(this); } } private static OnCheckedChangeListenerWrapper createOnCheckedChangeListener( @NonNull OnCheckedChangeListener listener) { return new OnCheckedChangeListenerWrapper() { private final IOnCheckedChangeListener mOnCheckedChangeListener = new OnCheckedChangeListenerStub(listener); @Override public void onCheckedChange(boolean isChecked, @NonNull OnDoneCallback callback) { try { mOnCheckedChangeListener.onCheckedChange(isChecked, RemoteUtils.createOnDoneCallbackStub(callback)); } catch (RemoteException e) { throw new WrappedRuntimeException(e); } } }; } @Keep // We need to keep these stub for Bundler serialization logic. private static class OnCheckedChangeListenerStub extends IOnCheckedChangeListener.Stub { private final OnCheckedChangeListener mOnCheckedChangeListener; private OnCheckedChangeListenerStub(OnCheckedChangeListener onCheckedChangeListener) { this.mOnCheckedChangeListener = onCheckedChangeListener; } @Override public void onCheckedChange(boolean isChecked, IOnDoneCallback callback) { RemoteUtils.dispatchHostCall( () -> mOnCheckedChangeListener.onCheckedChange(isChecked), callback, "onCheckedChange"); } } }
/* * Copyright 2002-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 sample; import org.junit.AfterClass; import org.junit.BeforeClass; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.images.builder.ImageFromDockerfile; import java.util.Arrays; import java.util.Base64; import java.util.Map; /** * @author Josh Cummings */ public abstract class AbstractKeycloakITests { private static GenericContainer container = new GenericContainer( new ImageFromDockerfile() .withFileFromClasspath("import-realm.json", "import-realm.json") .withFileFromClasspath("Dockerfile", "realm-importing.docker")); private RestTemplate rest = new RestTemplate(); @Value("${spring.security.oauth2.resourceserver.provider.keycloak.token-uri}") String tokenEndpoint; @BeforeClass public static void setUpClass() { container.setPortBindings(Arrays.asList("8080:8080")); container.start(); } @AfterClass public static void tearDownClass() { container.stop(); } protected String getTokenByResourceOwnerGrant( String clientId, String resourceId, String resourcePassword) { String authorization = Base64.getEncoder().encodeToString((clientId + ":").getBytes()); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + authorization); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("grant_type", "password"); map.add("username", resourceId); map.add("password", resourcePassword); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<Map> response = this.rest.postForEntity( this.tokenEndpoint, request, Map.class ); return (String) response.getBody().get("access_token"); } }
package com.mw.portfolio.auth.service; import com.mw.portfolio.security.model.FirebaseAuthentication; import com.mw.portfolio.user.entity.User; import com.mw.portfolio.user.service.UserService; import lombok.AllArgsConstructor; import lombok.val; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class UserAuthService { private final UserService userService; public User getAuthenticatedUser() { val authenticatedUser = (FirebaseAuthentication) SecurityContextHolder.getContext().getAuthentication(); return userService.getAuthorizedUser(authenticatedUser.getDetails().getUid()); } }
/* * 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.batch; import javax.annotation.Generated; import com.amazonaws.*; import com.amazonaws.regions.*; import com.amazonaws.services.batch.model.*; /** * Interface for accessing AWS Batch. * <p> * <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from * {@link com.amazonaws.services.batch.AbstractAWSBatch} instead. * </p> * <p> * <fullname>Batch</fullname> * <p> * Using Batch, you can run batch computing workloads on the Cloud. Batch computing is a common means for developers, * scientists, and engineers to access large amounts of compute resources. Batch uses the advantages of this computing * workload to remove the undifferentiated heavy lifting of configuring and managing required infrastructure. At the * same time, it also adopts a familiar batch computing software approach. Given these advantages, Batch can help you to * efficiently provision resources in response to jobs submitted, thus effectively helping you to eliminate capacity * constraints, reduce compute costs, and deliver your results more quickly. * </p> * <p> * As a fully managed service, Batch can run batch computing workloads of any scale. Batch automatically provisions * compute resources and optimizes workload distribution based on the quantity and scale of your specific workloads. * With Batch, there's no need to install or manage batch computing software. This means that you can focus your time * and energy on analyzing results and solving your specific problems. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public interface AWSBatch { /** * The region metadata service name for computing region endpoints. You can use this value to retrieve metadata * (such as supported regions) of the service. * * @see RegionUtils#getRegionsForService(String) */ String ENDPOINT_PREFIX = "batch"; /** * Overrides the default endpoint for this client ("batch.us-east-1.amazonaws.com"). Callers can use this method to * control which AWS region they want to work with. * <p> * Callers can pass in just the endpoint (ex: "batch.us-east-1.amazonaws.com") or a full URL, including the protocol * (ex: "batch.us-east-1.amazonaws.com"). If the protocol is not specified here, the default protocol from this * client's {@link ClientConfiguration} will be used, which by default is HTTPS. * <p> * For more information on using AWS regions with the AWS SDK for Java, and a complete list of all available * endpoints for all AWS services, see: <a href= * "https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#region-selection-choose-endpoint" * > https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#region-selection- * choose-endpoint</a> * <p> * <b>This method is not threadsafe. An endpoint should be configured when the client is created and before any * service requests are made. Changing it afterwards creates inevitable race conditions for any service requests in * transit or retrying.</b> * * @param endpoint * The endpoint (ex: "batch.us-east-1.amazonaws.com") or a full URL, including the protocol (ex: * "batch.us-east-1.amazonaws.com") of the region specific AWS endpoint this client will communicate with. * @deprecated use {@link AwsClientBuilder#setEndpointConfiguration(AwsClientBuilder.EndpointConfiguration)} for * example: * {@code builder.setEndpointConfiguration(new EndpointConfiguration(endpoint, signingRegion));} */ @Deprecated void setEndpoint(String endpoint); /** * An alternative to {@link AWSBatch#setEndpoint(String)}, sets the regional endpoint for this client's service * calls. Callers can use this method to control which AWS region they want to work with. * <p> * By default, all service endpoints in all regions use the https protocol. To use http instead, specify it in the * {@link ClientConfiguration} supplied at construction. * <p> * <b>This method is not threadsafe. A region should be configured when the client is created and before any service * requests are made. Changing it afterwards creates inevitable race conditions for any service requests in transit * or retrying.</b> * * @param region * The region this client will communicate with. See {@link Region#getRegion(com.amazonaws.regions.Regions)} * for accessing a given region. Must not be null and must be a region where the service is available. * * @see Region#getRegion(com.amazonaws.regions.Regions) * @see Region#createClient(Class, com.amazonaws.auth.AWSCredentialsProvider, ClientConfiguration) * @see Region#isServiceSupported(String) * @deprecated use {@link AwsClientBuilder#setRegion(String)} */ @Deprecated void setRegion(Region region); /** * <p> * Cancels a job in an Batch job queue. Jobs that are in the <code>SUBMITTED</code>, <code>PENDING</code>, or * <code>RUNNABLE</code> state are canceled. Jobs that have progressed to <code>STARTING</code> or * <code>RUNNING</code> aren't canceled, but the API operation still succeeds, even if no job is canceled. These * jobs must be terminated with the <a>TerminateJob</a> operation. * </p> * * @param cancelJobRequest * Contains the parameters for <code>CancelJob</code>. * @return Result of the CancelJob operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.CancelJob * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CancelJob" target="_top">AWS API * Documentation</a> */ CancelJobResult cancelJob(CancelJobRequest cancelJobRequest); /** * <p> * Creates an Batch compute environment. You can create <code>MANAGED</code> or <code>UNMANAGED</code> compute * environments. <code>MANAGED</code> compute environments can use Amazon EC2 or Fargate resources. * <code>UNMANAGED</code> compute environments can only use EC2 resources. * </p> * <p> * In a managed compute environment, Batch manages the capacity and instance types of the compute resources within * the environment. This is based on the compute resource specification that you define or the <a * href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html">launch template</a> that you * specify when you create the compute environment. Either, you can choose to use EC2 On-Demand Instances and EC2 * Spot Instances. Or, you can use Fargate and Fargate Spot capacity in your managed compute environment. You can * optionally set a maximum price so that Spot Instances only launch when the Spot Instance price is less than a * specified percentage of the On-Demand price. * </p> * <note> * <p> * Multi-node parallel jobs aren't supported on Spot Instances. * </p> * </note> * <p> * In an unmanaged compute environment, you can manage your own EC2 compute resources and have a lot of flexibility * with how you configure your compute resources. For example, you can use custom AMIs. However, you must verify * that each of your AMIs meet the Amazon ECS container instance AMI specification. For more information, see <a * href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/container_instance_AMIs.html">container * instance AMIs</a> in the <i>Amazon Elastic Container Service Developer Guide</i>. After you created your * unmanaged compute environment, you can use the <a>DescribeComputeEnvironments</a> operation to find the Amazon * ECS cluster that's associated with it. Then, launch your container instances into that Amazon ECS cluster. For * more information, see <a * href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_container_instance.html">Launching an * Amazon ECS container instance</a> in the <i>Amazon Elastic Container Service Developer Guide</i>. * </p> * <note> * <p> * Batch doesn't upgrade the AMIs in a compute environment after the environment is created. For example, it doesn't * update the AMIs when a newer version of the Amazon ECS optimized AMI is available. Therefore, you're responsible * for managing the guest operating system (including its updates and security patches) and any additional * application software or utilities that you install on the compute resources. To use a new AMI for your Batch * jobs, complete these steps: * </p> * <ol> * <li> * <p> * Create a new compute environment with the new AMI. * </p> * </li> * <li> * <p> * Add the compute environment to an existing job queue. * </p> * </li> * <li> * <p> * Remove the earlier compute environment from your job queue. * </p> * </li> * <li> * <p> * Delete the earlier compute environment. * </p> * </li> * </ol> * </note> * * @param createComputeEnvironmentRequest * Contains the parameters for <code>CreateComputeEnvironment</code>. * @return Result of the CreateComputeEnvironment operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.CreateComputeEnvironment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CreateComputeEnvironment" target="_top">AWS * API Documentation</a> */ CreateComputeEnvironmentResult createComputeEnvironment(CreateComputeEnvironmentRequest createComputeEnvironmentRequest); /** * <p> * Creates an Batch job queue. When you create a job queue, you associate one or more compute environments to the * queue and assign an order of preference for the compute environments. * </p> * <p> * You also set a priority to the job queue that determines the order that the Batch scheduler places jobs onto its * associated compute environments. For example, if a compute environment is associated with more than one job * queue, the job queue with a higher priority is given preference for scheduling jobs to that compute environment. * </p> * * @param createJobQueueRequest * Contains the parameters for <code>CreateJobQueue</code>. * @return Result of the CreateJobQueue operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.CreateJobQueue * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/CreateJobQueue" target="_top">AWS API * Documentation</a> */ CreateJobQueueResult createJobQueue(CreateJobQueueRequest createJobQueueRequest); /** * <p> * Deletes an Batch compute environment. * </p> * <p> * Before you can delete a compute environment, you must set its state to <code>DISABLED</code> with the * <a>UpdateComputeEnvironment</a> API operation and disassociate it from any job queues with the * <a>UpdateJobQueue</a> API operation. Compute environments that use Fargate resources must terminate all active * jobs on that compute environment before deleting the compute environment. If this isn't done, the compute * environment enters an invalid state. * </p> * * @param deleteComputeEnvironmentRequest * Contains the parameters for <code>DeleteComputeEnvironment</code>. * @return Result of the DeleteComputeEnvironment operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.DeleteComputeEnvironment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeleteComputeEnvironment" target="_top">AWS * API Documentation</a> */ DeleteComputeEnvironmentResult deleteComputeEnvironment(DeleteComputeEnvironmentRequest deleteComputeEnvironmentRequest); /** * <p> * Deletes the specified job queue. You must first disable submissions for a queue with the <a>UpdateJobQueue</a> * operation. All jobs in the queue are eventually terminated when you delete a job queue. The jobs are terminated * at a rate of about 16 jobs each second. * </p> * <p> * It's not necessary to disassociate compute environments from a queue before submitting a * <code>DeleteJobQueue</code> request. * </p> * * @param deleteJobQueueRequest * Contains the parameters for <code>DeleteJobQueue</code>. * @return Result of the DeleteJobQueue operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.DeleteJobQueue * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeleteJobQueue" target="_top">AWS API * Documentation</a> */ DeleteJobQueueResult deleteJobQueue(DeleteJobQueueRequest deleteJobQueueRequest); /** * <p> * Deregisters an Batch job definition. Job definitions are permanently deleted after 180 days. * </p> * * @param deregisterJobDefinitionRequest * @return Result of the DeregisterJobDefinition operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.DeregisterJobDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DeregisterJobDefinition" target="_top">AWS * API Documentation</a> */ DeregisterJobDefinitionResult deregisterJobDefinition(DeregisterJobDefinitionRequest deregisterJobDefinitionRequest); /** * <p> * Describes one or more of your compute environments. * </p> * <p> * If you're using an unmanaged compute environment, you can use the <code>DescribeComputeEnvironment</code> * operation to determine the <code>ecsClusterArn</code> that you should launch your Amazon ECS container instances * into. * </p> * * @param describeComputeEnvironmentsRequest * Contains the parameters for <code>DescribeComputeEnvironments</code>. * @return Result of the DescribeComputeEnvironments operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.DescribeComputeEnvironments * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeComputeEnvironments" * target="_top">AWS API Documentation</a> */ DescribeComputeEnvironmentsResult describeComputeEnvironments(DescribeComputeEnvironmentsRequest describeComputeEnvironmentsRequest); /** * <p> * Describes a list of job definitions. You can specify a <code>status</code> (such as <code>ACTIVE</code>) to only * return job definitions that match that status. * </p> * * @param describeJobDefinitionsRequest * Contains the parameters for <code>DescribeJobDefinitions</code>. * @return Result of the DescribeJobDefinitions operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.DescribeJobDefinitions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobDefinitions" target="_top">AWS * API Documentation</a> */ DescribeJobDefinitionsResult describeJobDefinitions(DescribeJobDefinitionsRequest describeJobDefinitionsRequest); /** * <p> * Describes one or more of your job queues. * </p> * * @param describeJobQueuesRequest * Contains the parameters for <code>DescribeJobQueues</code>. * @return Result of the DescribeJobQueues operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.DescribeJobQueues * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobQueues" target="_top">AWS API * Documentation</a> */ DescribeJobQueuesResult describeJobQueues(DescribeJobQueuesRequest describeJobQueuesRequest); /** * <p> * Describes a list of Batch jobs. * </p> * * @param describeJobsRequest * Contains the parameters for <code>DescribeJobs</code>. * @return Result of the DescribeJobs operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.DescribeJobs * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/DescribeJobs" target="_top">AWS API * Documentation</a> */ DescribeJobsResult describeJobs(DescribeJobsRequest describeJobsRequest); /** * <p> * Returns a list of Batch jobs. * </p> * <p> * You must specify only one of the following items: * </p> * <ul> * <li> * <p> * A job queue ID to return a list of jobs in that job queue * </p> * </li> * <li> * <p> * A multi-node parallel job ID to return a list of nodes for that job * </p> * </li> * <li> * <p> * An array job ID to return a list of the children for that job * </p> * </li> * </ul> * <p> * You can filter the results by job status with the <code>jobStatus</code> parameter. If you don't specify a * status, only <code>RUNNING</code> jobs are returned. * </p> * * @param listJobsRequest * Contains the parameters for <code>ListJobs</code>. * @return Result of the ListJobs operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.ListJobs * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/ListJobs" target="_top">AWS API * Documentation</a> */ ListJobsResult listJobs(ListJobsRequest listJobsRequest); /** * <p> * Lists the tags for an Batch resource. Batch resources that support tags are compute environments, jobs, job * definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) jobs are not supported. * </p> * * @param listTagsForResourceRequest * @return Result of the ListTagsForResource operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.ListTagsForResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/ListTagsForResource" target="_top">AWS API * Documentation</a> */ ListTagsForResourceResult listTagsForResource(ListTagsForResourceRequest listTagsForResourceRequest); /** * <p> * Registers an Batch job definition. * </p> * * @param registerJobDefinitionRequest * Contains the parameters for <code>RegisterJobDefinition</code>. * @return Result of the RegisterJobDefinition operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.RegisterJobDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/RegisterJobDefinition" target="_top">AWS * API Documentation</a> */ RegisterJobDefinitionResult registerJobDefinition(RegisterJobDefinitionRequest registerJobDefinitionRequest); /** * <p> * Submits an Batch job from a job definition. Parameters that are specified during <a>SubmitJob</a> override * parameters defined in the job definition. vCPU and memory requirements that are specified in the * <code>ResourceRequirements</code> objects in the job definition are the exception. They can't be overridden this * way using the <code>memory</code> and <code>vcpus</code> parameters. Rather, you must specify updates to job * definition parameters in a <code>ResourceRequirements</code> object that's included in the * <code>containerOverrides</code> parameter. * </p> * <important> * <p> * Jobs that run on Fargate resources can't be guaranteed to run for more than 14 days. This is because, after 14 * days, Fargate resources might become unavailable and job might be terminated. * </p> * </important> * * @param submitJobRequest * Contains the parameters for <code>SubmitJob</code>. * @return Result of the SubmitJob operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.SubmitJob * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/SubmitJob" target="_top">AWS API * Documentation</a> */ SubmitJobResult submitJob(SubmitJobRequest submitJobRequest); /** * <p> * Associates the specified tags to a resource with the specified <code>resourceArn</code>. If existing tags on a * resource aren't specified in the request parameters, they aren't changed. When a resource is deleted, the tags * that are associated with that resource are deleted as well. Batch resources that support tags are compute * environments, jobs, job definitions, and job queues. ARNs for child jobs of array and multi-node parallel (MNP) * jobs are not supported. * </p> * * @param tagResourceRequest * @return Result of the TagResource operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.TagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/TagResource" target="_top">AWS API * Documentation</a> */ TagResourceResult tagResource(TagResourceRequest tagResourceRequest); /** * <p> * Terminates a job in a job queue. Jobs that are in the <code>STARTING</code> or <code>RUNNING</code> state are * terminated, which causes them to transition to <code>FAILED</code>. Jobs that have not progressed to the * <code>STARTING</code> state are cancelled. * </p> * * @param terminateJobRequest * Contains the parameters for <code>TerminateJob</code>. * @return Result of the TerminateJob operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.TerminateJob * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/TerminateJob" target="_top">AWS API * Documentation</a> */ TerminateJobResult terminateJob(TerminateJobRequest terminateJobRequest); /** * <p> * Deletes specified tags from an Batch resource. * </p> * * @param untagResourceRequest * @return Result of the UntagResource operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.UntagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/UntagResource" target="_top">AWS API * Documentation</a> */ UntagResourceResult untagResource(UntagResourceRequest untagResourceRequest); /** * <p> * Updates an Batch compute environment. * </p> * * @param updateComputeEnvironmentRequest * Contains the parameters for <code>UpdateComputeEnvironment</code>. * @return Result of the UpdateComputeEnvironment operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.UpdateComputeEnvironment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/UpdateComputeEnvironment" target="_top">AWS * API Documentation</a> */ UpdateComputeEnvironmentResult updateComputeEnvironment(UpdateComputeEnvironmentRequest updateComputeEnvironmentRequest); /** * <p> * Updates a job queue. * </p> * * @param updateJobQueueRequest * Contains the parameters for <code>UpdateJobQueue</code>. * @return Result of the UpdateJobQueue operation returned by the service. * @throws ClientException * These errors are usually caused by a client action, such as using an action or resource on behalf of a * user that doesn't have permissions to use the action or resource, or specifying an identifier that's not * valid. * @throws ServerException * These errors are usually caused by a server issue. * @sample AWSBatch.UpdateJobQueue * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/batch-2016-08-10/UpdateJobQueue" target="_top">AWS API * Documentation</a> */ UpdateJobQueueResult updateJobQueue(UpdateJobQueueRequest updateJobQueueRequest); /** * Shuts down this client object, releasing any resources that might be held open. This is an optional method, and * callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client * has been shutdown, it should not be used to make any more requests. */ void shutdown(); /** * Returns additional metadata for a previously executed successful request, typically used for debugging issues * where a service isn't acting as expected. This data isn't considered part of the result data returned by an * operation, so it's available through this separate, diagnostic interface. * <p> * Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic * information for an executed request, you should use this method to retrieve it as soon as possible after * executing a request. * * @param request * The originally executed request. * * @return The response metadata for the specified request, or null if none is available. */ ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request); }
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.core.sql.operator.math; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition; import com.orientechnologies.orient.core.sql.operator.OIndexReuseType; import com.orientechnologies.orient.core.sql.operator.OQueryOperator; import java.math.BigDecimal; import java.util.Date; /** * PLUS "+" operator. * * @author Luca Garulli * */ public class OQueryOperatorPlus extends OQueryOperator { public OQueryOperatorPlus() { super("+", 9, false); } @Override public Object evaluateRecord(final OIdentifiable iRecord, ODocument iCurrentResult, final OSQLFilterCondition iCondition, Object iLeft, Object iRight, OCommandContext iContext) { if (iRight == null) return iLeft; if (iLeft == null) return iRight; if (iLeft instanceof Date) iLeft = ((Date) iLeft).getTime(); if (iRight instanceof Date) iRight = ((Date) iRight).getTime(); if (iLeft instanceof String) return (String) iLeft + iRight.toString(); else if (iRight instanceof String) return iLeft.toString() + (String) iRight; else if (iLeft instanceof Number && iRight instanceof Number) { final Number l = (Number) iLeft; final Number r = (Number) iRight; Class maxPrecisionClass = OQueryOperatorMultiply.getMaxPrecisionClass(l, r); if (Integer.class.equals(maxPrecisionClass)) return OQueryOperatorMultiply.tryDownscaleToInt(l.longValue() + r.longValue()); else if (Long.class.equals(maxPrecisionClass)) return l.longValue() + r.longValue(); else if (Short.class.equals(maxPrecisionClass)) return l.shortValue() + r.shortValue(); else if (Float.class.equals(maxPrecisionClass)) return l.floatValue() + r.floatValue(); else if (Double.class.equals(maxPrecisionClass)) return l.doubleValue() + r.doubleValue(); else if (BigDecimal.class.equals(maxPrecisionClass)) { return (OQueryOperatorMultiply.toBigDecimal(l)).add(OQueryOperatorMultiply.toBigDecimal(r)); } } return null; } @Override public OIndexReuseType getIndexReuseType(Object iLeft, Object iRight) { return OIndexReuseType.NO_INDEX; } @Override public ORID getBeginRidRange(Object iLeft, Object iRight) { return null; } @Override public ORID getEndRidRange(Object iLeft, Object iRight) { return null; } }
package com.mapswithme.maps.maplayer.traffic.widget; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.view.View; import android.widget.ImageButton; import android.widget.RelativeLayout; import com.mapswithme.maps.R; import com.mapswithme.util.ThemeUtils; import com.mapswithme.util.UiUtils; import com.mapswithme.util.Utils; public class TrafficButton { @NonNull private final AnimationDrawable mLoadingAnim; @NonNull private final ImageButton mButton; public TrafficButton(@NonNull ImageButton trafficBtn) { mButton = trafficBtn; mLoadingAnim = getLoadingAnim(trafficBtn); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) trafficBtn.getLayoutParams(); params.setMargins(0, UiUtils.getStatusBarHeight(trafficBtn.getContext()), 0, 0); } @NonNull private static AnimationDrawable getLoadingAnim(@NonNull ImageButton trafficBtn) { Context context = trafficBtn.getContext(); Resources res = context.getResources(); final int animResId = ThemeUtils.getResource(context, R.attr.trafficLoadingAnimation); return Utils.isLollipopOrLater() ? (AnimationDrawable) res.getDrawable(animResId, context.getTheme()) : (AnimationDrawable) res.getDrawable(animResId); } void turnOff() { stopWaitingAnimation(); mButton.setImageResource(ThemeUtils.isNightTheme() ? R.drawable.bg_subway_night_default : R.drawable.bg_subway_light_default); } void turnOn() { stopWaitingAnimation(); mButton.setImageResource(ThemeUtils.isNightTheme() ? R.drawable.ic_traffic_on_night : R.drawable.ic_traffic_on); } void markAsOutdated() { stopWaitingAnimation(); mButton.setImageResource(ThemeUtils.isNightTheme() ? R.drawable.ic_traffic_outdated_night : R.drawable.ic_traffic_outdated); } void startWaitingAnimation() { mButton.setImageDrawable(mLoadingAnim); AnimationDrawable anim = (AnimationDrawable) mButton.getDrawable(); anim.start(); } private void stopWaitingAnimation() { Drawable drawable = mButton.getDrawable(); if (drawable instanceof AnimationDrawable) { AnimationDrawable animation = (AnimationDrawable) drawable; animation.stop(); mButton.setImageDrawable(null); } } public void setOffset(int offsetX, int offsetY) { RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mButton.getLayoutParams(); params.setMargins(offsetX, offsetY, 0, 0); mButton.requestLayout(); } public void show() { UiUtils.show(mButton); } public void hide() { UiUtils.hide(mButton); } public void hideImmediately() { mButton.setVisibility(View.GONE); } public void showImmediately() { mButton.setVisibility(View.VISIBLE); } public void setOnclickListener(View.OnClickListener onclickListener) { mButton.setOnClickListener(onclickListener); } }
/* * 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.tomcat.util.http.mapper; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import javax.naming.NamingException; import javax.naming.directory.DirContext; import org.apache.tomcat.util.buf.Ascii; import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.res.StringManager; /** * Mapper, which implements the servlet API mapping rules (which are derived * from the HTTP rules). * * Servlet映射器,它属于Context内部的路由映射器,只负责该Context容器的路由导航 * * @author Remy Maucherat */ public final class Mapper { private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(Mapper.class); static final StringManager sm = StringManager.getManager(Mapper.class.getPackage().getName()); // ----------------------------------------------------- Instance Variables /** * Array containing the virtual hosts definitions. */ Host[] hosts = new Host[0]; /** * Default host name. */ String defaultHostName = null; /** * ContextVersion associated with this Mapper, used for wrapper mapping. * * <p> * It is used only by Mapper in a Context. Is not used by Mapper in a Connector. * * @see #setContext(String, String[], javax.naming.Context) */ ContextVersion context = new ContextVersion(); // --------------------------------------------------------- Public Methods /** * Set default host. * * @param defaultHostName Default host name */ public void setDefaultHostName(String defaultHostName) { this.defaultHostName = defaultHostName; } /** * Add a new host to the mapper. * * @param name Virtual host name * @param aliases Alias names for the virtual host * @param host Host object */ public synchronized void addHost(String name, String[] aliases, Object host) { Host[] newHosts = new Host[hosts.length + 1]; Host newHost = new Host(name, host); if (insertMap(hosts, newHosts, newHost)) { hosts = newHosts; if (log.isDebugEnabled()) { log.debug(sm.getString("mapper.addHost.success", name)); } } else { Host duplicate = hosts[find(hosts, name)]; if (duplicate.object == host) { // The host is already registered in the mapper. // E.g. it might have been added by addContextVersion() if (log.isDebugEnabled()) { log.debug(sm.getString("mapper.addHost.sameHost", name)); } newHost = duplicate; } else { log.error(sm.getString("mapper.duplicateHost", name, duplicate.getRealHostName())); // Do not add aliases, as removeHost(hostName) won't be able to // remove them return; } } List<Host> newAliases = new ArrayList<Host>(aliases.length); for (String alias : aliases) { Host newAlias = new Host(alias, newHost); if (addHostAliasImpl(newAlias)) { newAliases.add(newAlias); } } newHost.addAliases(newAliases); } /** * Remove a host from the mapper. * * @param name Virtual host name */ public synchronized void removeHost(String name) { // Find and remove the old host Host host = exactFind(hosts, name); if (host == null || host.isAlias()) { return; } Host[] newHosts = hosts.clone(); // Remove real host and all its aliases int j = 0; for (int i = 0; i < newHosts.length; i++) { if (newHosts[i].getRealHost() != host) { newHosts[j++] = newHosts[i]; } } hosts = Arrays.copyOf(newHosts, j); } /** * Add an alias to an existing host. * * @param name The name of the host * @param alias The alias to add */ public synchronized void addHostAlias(String name, String alias) { Host realHost = exactFind(hosts, name); if (realHost == null) { // Should not be adding an alias for a host that doesn't exist but // just in case... return; } Host newAlias = new Host(alias, realHost); if (addHostAliasImpl(newAlias)) { realHost.addAlias(newAlias); } } private boolean addHostAliasImpl(Host newAlias) { Host[] newHosts = new Host[hosts.length + 1]; if (insertMap(hosts, newHosts, newAlias)) { hosts = newHosts; if (log.isDebugEnabled()) { log.debug(sm.getString("mapper.addHostAlias.success", newAlias.name, newAlias.getRealHostName())); } return true; } else { Host duplicate = hosts[find(hosts, newAlias.name)]; if (duplicate.getRealHost() == newAlias.getRealHost()) { // A duplicate Alias for the same Host. // A harmless redundancy. E.g. // <Host name="localhost"><Alias>localhost</Alias></Host> if (log.isDebugEnabled()) { log.debug(sm.getString("mapper.addHostAlias.sameHost", newAlias.name, newAlias.getRealHostName())); } return false; } log.error(sm.getString("mapper.duplicateHostAlias", newAlias.name, newAlias.getRealHostName(), duplicate.getRealHostName())); return false; } } /** * Remove a host alias * * @param alias The alias to remove */ public synchronized void removeHostAlias(String alias) { // Find and remove the alias Host host = exactFind(hosts, alias); if (host == null || !host.isAlias()) { return; } Host[] newHosts = new Host[hosts.length - 1]; if (removeMap(hosts, newHosts, alias)) { hosts = newHosts; host.getRealHost().removeAlias(host); } } /** * Replace {@link Host#contextList} field in <code>realHost</code> and all its * aliases with a new value. */ private void updateContextList(Host realHost, ContextList newContextList) { realHost.contextList = newContextList; for (Host alias : realHost.getAliases()) { alias.contextList = newContextList; } } /** * Set context, used for wrapper mapping (request dispatcher). * * @param welcomeResources Welcome files defined for this context * @param resources Static resources of the context */ public void setContext(String path, String[] welcomeResources, javax.naming.Context resources) { context.path = path; context.welcomeResources = welcomeResources; context.resources = resources; } /** * Add a new Context to an existing Host. * * @param hostName Virtual host name this context belongs to * @param host Host object * @param path Context path * @param version Context version * @param context Context object * @param welcomeResources Welcome files defined for this context * @param resources Static resources of the context * @deprecated Use * {@link #addContextVersion(String, Object, String, String, Object, String[], javax.naming.Context, Collection, boolean, boolean)} */ @Deprecated public void addContextVersion(String hostName, Object host, String path, String version, Object context, String[] welcomeResources, javax.naming.Context resources) { addContextVersion(hostName, host, path, version, context, welcomeResources, resources, null); } /** * Add a new Context to an existing Host. * * @param hostName Virtual host name this context belongs to * @param host Host object * @param path Context path * @param version Context version * @param context Context object * @param welcomeResources Welcome files defined for this context * @param resources Static resources of the context * @param wrappers Information on wrapper mappings * @deprecated Use * {@link #addContextVersion(String, Object, String, String, Object, String[], javax.naming.Context, Collection, boolean, boolean)} */ @Deprecated public void addContextVersion(String hostName, Object host, String path, String version, Object context, String[] welcomeResources, javax.naming.Context resources, Collection<WrapperMappingInfo> wrappers) { addContextVersion(hostName, host, path, version, context, welcomeResources, resources, wrappers, false, false); } /** * Add a new Context to an existing Host. * * @param hostName Virtual host name this context * belongs to * @param host Host object * @param path Context path * @param version Context version * @param context Context object * @param welcomeResources Welcome files defined for this * context * @param resources Static resources of the context * @param wrappers Information on wrapper mappings * @param mapperContextRootRedirectEnabled Mapper does context root redirects * @param mapperDirectoryRedirectEnabled Mapper does directory redirects */ public void addContextVersion(String hostName, Object host, String path, String version, Object context, String[] welcomeResources, javax.naming.Context resources, Collection<WrapperMappingInfo> wrappers, boolean mapperContextRootRedirectEnabled, boolean mapperDirectoryRedirectEnabled) { Host mappedHost = exactFind(hosts, hostName); if (mappedHost == null) { addHost(hostName, new String[0], host); mappedHost = exactFind(hosts, hostName); if (mappedHost == null) { log.error("No host found: " + hostName); return; } } if (mappedHost.isAlias()) { log.error("No host found: " + hostName); return; } int slashCount = slashCount(path); synchronized (mappedHost) { ContextVersion newContextVersion = new ContextVersion(version, context); newContextVersion.path = path; newContextVersion.slashCount = slashCount; newContextVersion.welcomeResources = welcomeResources; newContextVersion.resources = resources; newContextVersion.mapperContextRootRedirectEnabled = mapperContextRootRedirectEnabled; newContextVersion.mapperDirectoryRedirectEnabled = mapperDirectoryRedirectEnabled; if (wrappers != null) { addWrappers(newContextVersion, wrappers); } ContextList contextList = mappedHost.contextList; Context mappedContext = exactFind(contextList.contexts, path); if (mappedContext == null) { mappedContext = new Context(path, newContextVersion); ContextList newContextList = contextList.addContext(mappedContext, slashCount); if (newContextList != null) { updateContextList(mappedHost, newContextList); } } else { ContextVersion[] contextVersions = mappedContext.versions; ContextVersion[] newContextVersions = new ContextVersion[contextVersions.length + 1]; if (insertMap(contextVersions, newContextVersions, newContextVersion)) { mappedContext.versions = newContextVersions; } else { // Re-registration after Context.reload() // Replace ContextVersion with the new one int pos = find(contextVersions, version); if (pos >= 0 && contextVersions[pos].name.equals(version)) { contextVersions[pos] = newContextVersion; } } } } } /** * Remove a context from an existing host. * * @param hostName Virtual host name this context belongs to * @param path Context path * @param version Context version */ public void removeContextVersion(String hostName, String path, String version) { Host host = exactFind(hosts, hostName); if (host == null || host.isAlias()) { return; } synchronized (host) { ContextList contextList = host.contextList; Context context = exactFind(contextList.contexts, path); if (context == null) { return; } ContextVersion[] contextVersions = context.versions; ContextVersion[] newContextVersions = new ContextVersion[contextVersions.length - 1]; if (removeMap(contextVersions, newContextVersions, version)) { if (newContextVersions.length == 0) { // Remove the context ContextList newContextList = contextList.removeContext(path); if (newContextList != null) { updateContextList(host, newContextList); } } else { context.versions = newContextVersions; } } } } /** * Mark a context as being reloaded. Reversion of this state is performed by * calling <code>addContextVersion(...)</code> when context starts up. * * @param ctxt The actual context * @param hostName Virtual host name this context belongs to * @param contextPath Context path * @param version Context version */ public void pauseContextVersion(Object ctxt, String hostName, String contextPath, String version) { ContextVersion contextVersion = findContextVersion(hostName, contextPath, version, true); if (contextVersion == null || !ctxt.equals(contextVersion.object)) { return; } contextVersion.markPaused(); } private ContextVersion findContextVersion(String hostName, String contextPath, String version, boolean silent) { Host host = exactFind(hosts, hostName); if (host == null || host.isAlias()) { if (!silent) { log.error("No host found: " + hostName); } return null; } Context context = exactFind(host.contextList.contexts, contextPath); if (context == null) { if (!silent) { log.error("No context found: " + contextPath); } return null; } ContextVersion contextVersion = exactFind(context.versions, version); if (contextVersion == null) { if (!silent) { log.error("No context version found: " + contextPath + " " + version); } return null; } return contextVersion; } public void addWrapper(String hostName, String contextPath, String version, String path, Object wrapper, boolean jspWildCard, boolean resourceOnly) { ContextVersion contextVersion = findContextVersion(hostName, contextPath, version, false); if (contextVersion == null) { return; } addWrapper(contextVersion, path, wrapper, jspWildCard, resourceOnly); } public void addWrapper(String path, Object wrapper, boolean jspWildCard, boolean resourceOnly) { addWrapper(context, path, wrapper, jspWildCard, resourceOnly); } public void addWrappers(String hostName, String contextPath, String version, Collection<WrapperMappingInfo> wrappers) { ContextVersion contextVersion = findContextVersion(hostName, contextPath, version, false); if (contextVersion == null) { return; } addWrappers(contextVersion, wrappers); } /** * Adds wrappers to the given context. * * @param contextVersion The context to which to add the wrappers * @param wrappers Information on wrapper mappings */ private void addWrappers(ContextVersion contextVersion, Collection<WrapperMappingInfo> wrappers) { for (WrapperMappingInfo wrapper : wrappers) { addWrapper(contextVersion, wrapper.getMapping(), wrapper.getWrapper(), wrapper.isJspWildCard(), wrapper.isResourceOnly()); } } /** * Adds a wrapper to the given context. * * @param context The context to which to add the wrapper * @param path Wrapper mapping * @param wrapper The Wrapper object * @param jspWildCard true if the wrapper corresponds to the JspServlet and the * mapping path contains a wildcard; false otherwise * @param resourceOnly true if this wrapper always expects a physical resource * to be present (such as a JSP) */ protected void addWrapper(ContextVersion context, String path, Object wrapper, boolean jspWildCard, boolean resourceOnly) { synchronized (context) { if (path.endsWith("/*")) { // Wildcard wrapper String name = path.substring(0, path.length() - 2); Wrapper newWrapper = new Wrapper(name, wrapper, jspWildCard, resourceOnly); Wrapper[] oldWrappers = context.wildcardWrappers; Wrapper[] newWrappers = new Wrapper[oldWrappers.length + 1]; if (insertMap(oldWrappers, newWrappers, newWrapper)) { context.wildcardWrappers = newWrappers; int slashCount = slashCount(newWrapper.name); if (slashCount > context.nesting) { context.nesting = slashCount; } } } else if (path.startsWith("*.")) { // Extension wrapper String name = path.substring(2); Wrapper newWrapper = new Wrapper(name, wrapper, jspWildCard, resourceOnly); Wrapper[] oldWrappers = context.extensionWrappers; Wrapper[] newWrappers = new Wrapper[oldWrappers.length + 1]; if (insertMap(oldWrappers, newWrappers, newWrapper)) { context.extensionWrappers = newWrappers; } } else if (path.equals("/")) { // Default wrapper Wrapper newWrapper = new Wrapper("", wrapper, jspWildCard, resourceOnly); context.defaultWrapper = newWrapper; } else { // Exact wrapper final String name; if (path.length() == 0) { // Special case for the Context Root mapping which is // treated as an exact match name = "/"; } else { name = path; } Wrapper newWrapper = new Wrapper(name, wrapper, jspWildCard, resourceOnly); Wrapper[] oldWrappers = context.exactWrappers; Wrapper[] newWrappers = new Wrapper[oldWrappers.length + 1]; if (insertMap(oldWrappers, newWrappers, newWrapper)) { context.exactWrappers = newWrappers; } } } } /** * Remove a wrapper from the context associated with this wrapper. * * @param path Wrapper mapping */ public void removeWrapper(String path) { removeWrapper(context, path); } /** * Remove a wrapper from an existing context. * * @param hostName Virtual host name this wrapper belongs to * @param contextPath Context path this wrapper belongs to * @param path Wrapper mapping */ public void removeWrapper(String hostName, String contextPath, String version, String path) { ContextVersion contextVersion = findContextVersion(hostName, contextPath, version, true); if (contextVersion == null || contextVersion.isPaused()) { return; } removeWrapper(contextVersion, path); } protected void removeWrapper(ContextVersion context, String path) { if (log.isDebugEnabled()) { log.debug(sm.getString("mapper.removeWrapper", context.name, path)); } synchronized (context) { if (path.endsWith("/*")) { // Wildcard wrapper String name = path.substring(0, path.length() - 2); Wrapper[] oldWrappers = context.wildcardWrappers; if (oldWrappers.length == 0) { return; } Wrapper[] newWrappers = new Wrapper[oldWrappers.length - 1]; if (removeMap(oldWrappers, newWrappers, name)) { // Recalculate nesting context.nesting = 0; for (int i = 0; i < newWrappers.length; i++) { int slashCount = slashCount(newWrappers[i].name); if (slashCount > context.nesting) { context.nesting = slashCount; } } context.wildcardWrappers = newWrappers; } } else if (path.startsWith("*.")) { // Extension wrapper String name = path.substring(2); Wrapper[] oldWrappers = context.extensionWrappers; if (oldWrappers.length == 0) { return; } Wrapper[] newWrappers = new Wrapper[oldWrappers.length - 1]; if (removeMap(oldWrappers, newWrappers, name)) { context.extensionWrappers = newWrappers; } } else if (path.equals("/")) { // Default wrapper context.defaultWrapper = null; } else { // Exact wrapper String name; if (path.length() == 0) { // Special case for the Context Root mapping which is // treated as an exact match name = "/"; } else { name = path; } Wrapper[] oldWrappers = context.exactWrappers; if (oldWrappers.length == 0) { return; } Wrapper[] newWrappers = new Wrapper[oldWrappers.length - 1]; if (removeMap(oldWrappers, newWrappers, name)) { context.exactWrappers = newWrappers; } } } } /** * Add a welcome file to the given context. * * @param hostName * @param contextPath * @param welcomeFile */ public void addWelcomeFile(String hostName, String contextPath, String version, String welcomeFile) { ContextVersion contextVersion = findContextVersion(hostName, contextPath, version, false); if (contextVersion == null) { return; } int len = contextVersion.welcomeResources.length + 1; String[] newWelcomeResources = new String[len]; System.arraycopy(contextVersion.welcomeResources, 0, newWelcomeResources, 0, len - 1); newWelcomeResources[len - 1] = welcomeFile; contextVersion.welcomeResources = newWelcomeResources; } /** * Remove a welcome file from the given context. * * @param hostName * @param contextPath * @param welcomeFile */ public void removeWelcomeFile(String hostName, String contextPath, String version, String welcomeFile) { ContextVersion contextVersion = findContextVersion(hostName, contextPath, version, false); if (contextVersion == null || contextVersion.isPaused()) { return; } int match = -1; for (int i = 0; i < contextVersion.welcomeResources.length; i++) { if (welcomeFile.equals(contextVersion.welcomeResources[i])) { match = i; break; } } if (match > -1) { int len = contextVersion.welcomeResources.length - 1; String[] newWelcomeResources = new String[len]; System.arraycopy(contextVersion.welcomeResources, 0, newWelcomeResources, 0, match); if (match < len) { System.arraycopy(contextVersion.welcomeResources, match + 1, newWelcomeResources, match, len - match); } contextVersion.welcomeResources = newWelcomeResources; } } /** * Clear the welcome files for the given context. * * @param hostName * @param contextPath */ public void clearWelcomeFiles(String hostName, String contextPath, String version) { ContextVersion contextVersion = findContextVersion(hostName, contextPath, version, false); if (contextVersion == null) { return; } contextVersion.welcomeResources = new String[0]; } /** * Map the specified host name and URI, mutating the given mapping data. * * @param host Virtual host name * @param uri URI * @param mappingData This structure will contain the result of the mapping * operation */ public void map(MessageBytes host, MessageBytes uri, String version, MappingData mappingData) throws Exception { if (host.isNull()) { host.getCharChunk().append(defaultHostName); } host.toChars(); uri.toChars(); internalMap(host.getCharChunk(), uri.getCharChunk(), version, mappingData); } /** * Map the specified URI relative to the context, mutating the given mapping * data. * * @param uri URI * @param mappingData This structure will contain the result of the mapping * operation */ public void map(MessageBytes uri, MappingData mappingData) throws Exception { uri.toChars(); CharChunk uricc = uri.getCharChunk(); uricc.setLimit(-1); internalMapWrapper(context, uricc, mappingData); } // -------------------------------------------------------- Private Methods /** * Map the specified URI. */ private final void internalMap(CharChunk host, CharChunk uri, String version, MappingData mappingData) throws Exception { if (mappingData.host != null) { // The legacy code (dating down at least to Tomcat 4.1) just // skipped all mapping work in this case. That behaviour has a risk // of returning an inconsistent result. // I do not see a valid use case for it. throw new AssertionError(); } uri.setLimit(-1); // Virtual host mapping Host[] hosts = this.hosts; Host mappedHost = exactFindIgnoreCase(hosts, host); if (mappedHost == null) { if (defaultHostName == null) { return; } mappedHost = exactFind(hosts, defaultHostName); if (mappedHost == null) { return; } } mappingData.host = mappedHost.object; // Context mapping ContextList contextList = mappedHost.contextList; Context[] contexts = contextList.contexts; int nesting = contextList.nesting; int pos = find(contexts, uri); if (pos == -1) { return; } int lastSlash = -1; int uriEnd = uri.getEnd(); int length = -1; boolean found = false; Context context = null; while (pos >= 0) { context = contexts[pos]; if (uri.startsWith(context.name)) { length = context.name.length(); if (uri.getLength() == length) { found = true; break; } else if (uri.startsWithIgnoreCase("/", length)) { found = true; break; } } if (lastSlash == -1) { lastSlash = nthSlash(uri, nesting + 1); } else { lastSlash = lastSlash(uri); } uri.setEnd(lastSlash); pos = find(contexts, uri); } uri.setEnd(uriEnd); if (!found) { if (contexts[0].name.equals("")) { context = contexts[0]; } else { context = null; } } if (context == null) { return; } mappingData.contextPath.setString(context.name); ContextVersion contextVersion = null; ContextVersion[] contextVersions = context.versions; final int versionCount = contextVersions.length; if (versionCount > 1) { Object[] contextObjects = new Object[contextVersions.length]; for (int i = 0; i < contextObjects.length; i++) { contextObjects[i] = contextVersions[i].object; } mappingData.contexts = contextObjects; if (version != null) { contextVersion = exactFind(contextVersions, version); } } if (contextVersion == null) { // Return the latest version // The versions array is known to contain at least one element contextVersion = contextVersions[versionCount - 1]; } mappingData.context = contextVersion.object; mappingData.contextSlashCount = contextVersion.slashCount; // Wrapper mapping if (!contextVersion.isPaused()) { internalMapWrapper(contextVersion, uri, mappingData); } } /** * Wrapper mapping. */ private final void internalMapWrapper(ContextVersion contextVersion, CharChunk path, MappingData mappingData) throws Exception { int pathOffset = path.getOffset(); int pathEnd = path.getEnd(); boolean noServletPath = false; int length = contextVersion.path.length(); if (length == (pathEnd - pathOffset)) { noServletPath = true; } int servletPath = pathOffset + length; path.setOffset(servletPath); // Rule 1 -- Exact Match Wrapper[] exactWrappers = contextVersion.exactWrappers; internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 2 -- Prefix Match boolean checkJspWelcomeFiles = false; Wrapper[] wildcardWrappers = contextVersion.wildcardWrappers; if (mappingData.wrapper == null) { internalMapWildcardWrapper(wildcardWrappers, contextVersion.nesting, path, mappingData); if (mappingData.wrapper != null && mappingData.jspWildCard) { char[] buf = path.getBuffer(); if (buf[pathEnd - 1] == '/') { /* * Path ending in '/' was mapped to JSP servlet based on wildcard match (e.g., * as specified in url-pattern of a jsp-property-group. Force the context's * welcome files, which are interpreted as JSP files (since they match the * url-pattern), to be considered. See Bugzilla 27664. */ mappingData.wrapper = null; checkJspWelcomeFiles = true; } else { // See Bugzilla 27704 mappingData.wrapperPath.setChars(buf, path.getStart(), path.getLength()); mappingData.pathInfo.recycle(); } } } if (mappingData.wrapper == null && noServletPath && contextVersion.mapperContextRootRedirectEnabled) { // The path is empty, redirect to "/" path.append('/'); pathEnd = path.getEnd(); mappingData.redirectPath.setChars(path.getBuffer(), pathOffset, pathEnd - pathOffset); path.setEnd(pathEnd - 1); return; } // Rule 3 -- Extension Match Wrapper[] extensionWrappers = contextVersion.extensionWrappers; if (mappingData.wrapper == null && !checkJspWelcomeFiles) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); } // Rule 4 -- Welcome resources processing for servlets if (mappingData.wrapper == null) { boolean checkWelcomeFiles = checkJspWelcomeFiles; if (!checkWelcomeFiles) { char[] buf = path.getBuffer(); checkWelcomeFiles = (buf[pathEnd - 1] == '/'); } if (checkWelcomeFiles) { for (int i = 0; (i < contextVersion.welcomeResources.length) && (mappingData.wrapper == null); i++) { path.setOffset(pathOffset); path.setEnd(pathEnd); path.append(contextVersion.welcomeResources[i], 0, contextVersion.welcomeResources[i].length()); path.setOffset(servletPath); // Rule 4a -- Welcome resources processing for exact macth internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 4b -- Welcome resources processing for prefix match if (mappingData.wrapper == null) { internalMapWildcardWrapper(wildcardWrappers, contextVersion.nesting, path, mappingData); } // Rule 4c -- Welcome resources processing // for physical folder if (mappingData.wrapper == null && contextVersion.resources != null) { Object file = null; String pathStr = path.toString(); try { file = contextVersion.resources.lookup(pathStr); } catch (NamingException nex) { // Swallow not found, since this is normal } if (file != null && !(file instanceof DirContext)) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); if (mappingData.wrapper == null && contextVersion.defaultWrapper != null) { mappingData.wrapper = contextVersion.defaultWrapper.object; mappingData.requestPath.setChars(path.getBuffer(), path.getStart(), path.getLength()); mappingData.wrapperPath.setChars(path.getBuffer(), path.getStart(), path.getLength()); mappingData.requestPath.setString(pathStr); mappingData.wrapperPath.setString(pathStr); } } } } path.setOffset(servletPath); path.setEnd(pathEnd); } } /* * welcome file processing - take 2 Now that we have looked for welcome files * with a physical backing, now look for an extension mapping listed but may not * have a physical backing to it. This is for the case of index.jsf, index.do, * etc. A watered down version of rule 4 */ if (mappingData.wrapper == null) { boolean checkWelcomeFiles = checkJspWelcomeFiles; if (!checkWelcomeFiles) { char[] buf = path.getBuffer(); checkWelcomeFiles = (buf[pathEnd - 1] == '/'); } if (checkWelcomeFiles) { for (int i = 0; (i < contextVersion.welcomeResources.length) && (mappingData.wrapper == null); i++) { path.setOffset(pathOffset); path.setEnd(pathEnd); path.append(contextVersion.welcomeResources[i], 0, contextVersion.welcomeResources[i].length()); path.setOffset(servletPath); internalMapExtensionWrapper(extensionWrappers, path, mappingData, false); } path.setOffset(servletPath); path.setEnd(pathEnd); } } // Rule 7 -- Default servlet if (mappingData.wrapper == null && !checkJspWelcomeFiles) { if (contextVersion.defaultWrapper != null) { mappingData.wrapper = contextVersion.defaultWrapper.object; mappingData.requestPath.setChars(path.getBuffer(), path.getStart(), path.getLength()); mappingData.wrapperPath.setChars(path.getBuffer(), path.getStart(), path.getLength()); } // Redirection to a folder char[] buf = path.getBuffer(); if (contextVersion.resources != null && buf[pathEnd - 1] != '/') { Object file = null; String pathStr = path.toString(); try { if (pathStr.length() == 0) { file = contextVersion.resources.lookup("/"); } else { file = contextVersion.resources.lookup(pathStr); } } catch (NamingException nex) { // Swallow, since someone else handles the 404 } if (file != null && file instanceof DirContext && contextVersion.mapperDirectoryRedirectEnabled) { // Note: this mutates the path: do not do any processing // after this (since we set the redirectPath, there // shouldn't be any) path.setOffset(pathOffset); path.append('/'); mappingData.redirectPath.setChars(path.getBuffer(), path.getStart(), path.getLength()); } else { mappingData.requestPath.setString(pathStr); mappingData.wrapperPath.setString(pathStr); } } } path.setOffset(pathOffset); path.setEnd(pathEnd); } /** * Exact mapping. */ private final void internalMapExactWrapper(Wrapper[] wrappers, CharChunk path, MappingData mappingData) { Wrapper wrapper = exactFind(wrappers, path); if (wrapper != null) { mappingData.requestPath.setString(wrapper.name); mappingData.wrapper = wrapper.object; if (path.equals("/")) { // Special handling for Context Root mapped servlet mappingData.pathInfo.setString("/"); mappingData.wrapperPath.setString(""); // This seems wrong but it is what the spec says... mappingData.contextPath.setString(""); } else { mappingData.wrapperPath.setString(wrapper.name); } } } /** * Wildcard mapping. */ private final void internalMapWildcardWrapper(Wrapper[] wrappers, int nesting, CharChunk path, MappingData mappingData) { int pathEnd = path.getEnd(); int lastSlash = -1; int length = -1; int pos = find(wrappers, path); if (pos != -1) { boolean found = false; while (pos >= 0) { if (path.startsWith(wrappers[pos].name)) { length = wrappers[pos].name.length(); if (path.getLength() == length) { found = true; break; } else if (path.startsWithIgnoreCase("/", length)) { found = true; break; } } if (lastSlash == -1) { lastSlash = nthSlash(path, nesting + 1); } else { lastSlash = lastSlash(path); } path.setEnd(lastSlash); pos = find(wrappers, path); } path.setEnd(pathEnd); if (found) { mappingData.wrapperPath.setString(wrappers[pos].name); if (path.getLength() > length) { mappingData.pathInfo.setChars(path.getBuffer(), path.getOffset() + length, path.getLength() - length); } mappingData.requestPath.setChars(path.getBuffer(), path.getOffset(), path.getLength()); mappingData.wrapper = wrappers[pos].object; mappingData.jspWildCard = wrappers[pos].jspWildCard; } } } /** * Extension mappings. * * @param wrappers Set of wrappers to check for matches * @param path Path to map * @param mappingData Mapping data for result * @param resourceExpected Is this mapping expecting to find a resource */ private final void internalMapExtensionWrapper(Wrapper[] wrappers, CharChunk path, MappingData mappingData, boolean resourceExpected) { char[] buf = path.getBuffer(); int pathEnd = path.getEnd(); int servletPath = path.getOffset(); int slash = -1; for (int i = pathEnd - 1; i >= servletPath; i--) { if (buf[i] == '/') { slash = i; break; } } if (slash >= 0) { int period = -1; for (int i = pathEnd - 1; i > slash; i--) { if (buf[i] == '.') { period = i; break; } } if (period >= 0) { path.setOffset(period + 1); path.setEnd(pathEnd); Wrapper wrapper = exactFind(wrappers, path); if (wrapper != null && (resourceExpected || !wrapper.resourceOnly)) { mappingData.wrapperPath.setChars(buf, servletPath, pathEnd - servletPath); mappingData.requestPath.setChars(buf, servletPath, pathEnd - servletPath); mappingData.wrapper = wrapper.object; } path.setOffset(servletPath); path.setEnd(pathEnd); } } } /** * Find a map element given its name in a sorted array of map elements. This * will return the index for the closest inferior or equal item in the given * array. */ private static final int find(MapElement[] map, CharChunk name) { return find(map, name, name.getStart(), name.getEnd()); } /** * Find a map element given its name in a sorted array of map elements. This * will return the index for the closest inferior or equal item in the given * array. */ private static final int find(MapElement[] map, CharChunk name, int start, int end) { int a = 0; int b = map.length - 1; // Special cases: -1 and 0 if (b == -1) { return -1; } if (compare(name, start, end, map[0].name) < 0) { return -1; } if (b == 0) { return 0; } int i = 0; while (true) { i = (b + a) / 2; int result = compare(name, start, end, map[i].name); if (result == 1) { a = i; } else if (result == 0) { return i; } else { b = i; } if ((b - a) == 1) { int result2 = compare(name, start, end, map[b].name); if (result2 < 0) { return a; } else { return b; } } } } /** * Find a map element given its name in a sorted array of map elements. This * will return the index for the closest inferior or equal item in the given * array. */ private static final int findIgnoreCase(MapElement[] map, CharChunk name) { return findIgnoreCase(map, name, name.getStart(), name.getEnd()); } /** * Find a map element given its name in a sorted array of map elements. This * will return the index for the closest inferior or equal item in the given * array. */ private static final int findIgnoreCase(MapElement[] map, CharChunk name, int start, int end) { int a = 0; int b = map.length - 1; // Special cases: -1 and 0 if (b == -1) { return -1; } if (compareIgnoreCase(name, start, end, map[0].name) < 0) { return -1; } if (b == 0) { return 0; } int i = 0; while (true) { i = (b + a) / 2; int result = compareIgnoreCase(name, start, end, map[i].name); if (result == 1) { a = i; } else if (result == 0) { return i; } else { b = i; } if ((b - a) == 1) { int result2 = compareIgnoreCase(name, start, end, map[b].name); if (result2 < 0) { return a; } else { return b; } } } } /** * Find a map element given its name in a sorted array of map elements. This * will return the index for the closest inferior or equal item in the given * array. * * @see #exactFind(MapElement[], String) */ private static final int find(MapElement[] map, String name) { int a = 0; int b = map.length - 1; // Special cases: -1 and 0 if (b == -1) { return -1; } if (name.compareTo(map[0].name) < 0) { return -1; } if (b == 0) { return 0; } int i = 0; while (true) { i = (b + a) / 2; int result = name.compareTo(map[i].name); if (result > 0) { a = i; } else if (result == 0) { return i; } else { b = i; } if ((b - a) == 1) { int result2 = name.compareTo(map[b].name); if (result2 < 0) { return a; } else { return b; } } } } /** * Find a map element given its name in a sorted array of map elements. This * will return the element that you were searching for. Otherwise it will return * <code>null</code>. * * @see #find(MapElement[], String) */ private static final <E extends MapElement> E exactFind(E[] map, String name) { int pos = find(map, name); if (pos >= 0) { E result = map[pos]; if (name.equals(result.name)) { return result; } } return null; } /** * Find a map element given its name in a sorted array of map elements. This * will return the element that you were searching for. Otherwise it will return * <code>null</code>. */ private static final <E extends MapElement> E exactFind(E[] map, CharChunk name) { int pos = find(map, name); if (pos >= 0) { E result = map[pos]; if (name.equals(result.name)) { return result; } } return null; } /** * Find a map element given its name in a sorted array of map elements. This * will return the element that you were searching for. Otherwise it will return * <code>null</code>. * * @see #findIgnoreCase(MapElement[], CharChunk) */ private static final <E extends MapElement> E exactFindIgnoreCase(E[] map, CharChunk name) { int pos = findIgnoreCase(map, name); if (pos >= 0) { E result = map[pos]; if (name.equalsIgnoreCase(result.name)) { return result; } } return null; } /** * Compare given char chunk with String. Return -1, 0 or +1 if inferior, equal, * or superior to the String. */ private static final int compare(CharChunk name, int start, int end, String compareTo) { int result = 0; char[] c = name.getBuffer(); int len = compareTo.length(); if ((end - start) < len) { len = end - start; } for (int i = 0; (i < len) && (result == 0); i++) { if (c[i + start] > compareTo.charAt(i)) { result = 1; } else if (c[i + start] < compareTo.charAt(i)) { result = -1; } } if (result == 0) { if (compareTo.length() > (end - start)) { result = -1; } else if (compareTo.length() < (end - start)) { result = 1; } } return result; } /** * Compare given char chunk with String ignoring case. Return -1, 0 or +1 if * inferior, equal, or superior to the String. */ private static final int compareIgnoreCase(CharChunk name, int start, int end, String compareTo) { int result = 0; char[] c = name.getBuffer(); int len = compareTo.length(); if ((end - start) < len) { len = end - start; } for (int i = 0; (i < len) && (result == 0); i++) { if (Ascii.toLower(c[i + start]) > Ascii.toLower(compareTo.charAt(i))) { result = 1; } else if (Ascii.toLower(c[i + start]) < Ascii.toLower(compareTo.charAt(i))) { result = -1; } } if (result == 0) { if (compareTo.length() > (end - start)) { result = -1; } else if (compareTo.length() < (end - start)) { result = 1; } } return result; } /** * Find the position of the last slash in the given char chunk. */ private static final int lastSlash(CharChunk name) { char[] c = name.getBuffer(); int end = name.getEnd(); int start = name.getStart(); int pos = end; while (pos > start) { if (c[--pos] == '/') { break; } } return (pos); } /** * Find the position of the nth slash, in the given char chunk. */ private static final int nthSlash(CharChunk name, int n) { char[] c = name.getBuffer(); int end = name.getEnd(); int start = name.getStart(); int pos = start; int count = 0; while (pos < end) { if ((c[pos++] == '/') && ((++count) == n)) { pos--; break; } } return (pos); } /** * Return the slash count in a given string. */ private static final int slashCount(String name) { int pos = -1; int count = 0; while ((pos = name.indexOf('/', pos + 1)) != -1) { count++; } return count; } /** * Insert into the right place in a sorted MapElement array, and prevent * duplicates. */ private static final boolean insertMap(MapElement[] oldMap, MapElement[] newMap, MapElement newElement) { int pos = find(oldMap, newElement.name); if ((pos != -1) && (newElement.name.equals(oldMap[pos].name))) { return false; } System.arraycopy(oldMap, 0, newMap, 0, pos + 1); newMap[pos + 1] = newElement; System.arraycopy(oldMap, pos + 1, newMap, pos + 2, oldMap.length - pos - 1); return true; } /** * Insert into the right place in a sorted MapElement array. */ private static final boolean removeMap(MapElement[] oldMap, MapElement[] newMap, String name) { int pos = find(oldMap, name); if ((pos != -1) && (name.equals(oldMap[pos].name))) { System.arraycopy(oldMap, 0, newMap, 0, pos); System.arraycopy(oldMap, pos + 1, newMap, pos, oldMap.length - pos - 1); return true; } return false; } // ------------------------------------------------- MapElement Inner Class protected abstract static class MapElement { public final String name; public final Object object; public MapElement(String name, Object object) { this.name = name; this.object = object; } } // ------------------------------------------------------- Host Inner Class protected static final class Host extends MapElement { public volatile ContextList contextList; /** * Link to the "real" Host, shared by all aliases. */ private final Host realHost; /** * Links to all registered aliases, for easy enumeration. This field is * available only in the "real" Host. In an alias this field is * <code>null</code>. */ private final List<Host> aliases; /** * Creates an object for primary Host */ public Host(String name, Object host) { super(name, host); this.realHost = this; this.contextList = new ContextList(); this.aliases = new CopyOnWriteArrayList<Host>(); } /** * Creates an object for an Alias */ public Host(String alias, Host realHost) { super(alias, realHost.object); this.realHost = realHost; this.contextList = realHost.contextList; this.aliases = null; } public boolean isAlias() { return realHost != this; } public Host getRealHost() { return realHost; } public String getRealHostName() { return realHost.name; } public Collection<Host> getAliases() { return aliases; } public void addAlias(Host alias) { aliases.add(alias); } public void addAliases(Collection<? extends Host> c) { aliases.addAll(c); } public void removeAlias(Host alias) { aliases.remove(alias); } } // ------------------------------------------------ ContextList Inner Class protected static final class ContextList { public final Context[] contexts; public final int nesting; public ContextList() { this(new Context[0], 0); } private ContextList(Context[] contexts, int nesting) { this.contexts = contexts; this.nesting = nesting; } public ContextList addContext(Context mappedContext, int slashCount) { Context[] newContexts = new Context[contexts.length + 1]; if (insertMap(contexts, newContexts, mappedContext)) { return new ContextList(newContexts, Math.max(nesting, slashCount)); } return null; } public ContextList removeContext(String path) { Context[] newContexts = new Context[contexts.length - 1]; if (removeMap(contexts, newContexts, path)) { int newNesting = 0; for (Context context : newContexts) { newNesting = Math.max(newNesting, slashCount(context.name)); } return new ContextList(newContexts, newNesting); } return null; } } // ---------------------------------------------------- Context Inner Class protected static final class Context extends MapElement { public volatile ContextVersion[] versions; public Context(String name, ContextVersion firstVersion) { super(name, null); versions = new ContextVersion[] { firstVersion }; } } protected static final class ContextVersion extends MapElement { public String path = null; public int slashCount; public String[] welcomeResources = new String[0]; public javax.naming.Context resources = null; public Wrapper defaultWrapper = null; public Wrapper[] exactWrappers = new Wrapper[0]; public Wrapper[] wildcardWrappers = new Wrapper[0]; public Wrapper[] extensionWrappers = new Wrapper[0]; public int nesting = 0; public boolean mapperContextRootRedirectEnabled = false; public boolean mapperDirectoryRedirectEnabled = false; private volatile boolean paused; public ContextVersion() { super(null, null); } public ContextVersion(String version, Object context) { super(version, context); } public boolean isPaused() { return paused; } public void markPaused() { paused = true; } } // ---------------------------------------------------- Wrapper Inner Class protected static class Wrapper extends MapElement { public final boolean jspWildCard; public final boolean resourceOnly; public Wrapper(String name, /* Wrapper */Object wrapper, boolean jspWildCard, boolean resourceOnly) { super(name, wrapper); this.jspWildCard = jspWildCard; this.resourceOnly = resourceOnly; } } }
package savvy.core.fact.events; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import savvy.core.fact.Fact; /** fired upon creation of fact in the DB */ public final class FactCreated { public final Fact fact; private final Logger log = LoggerFactory.getLogger(this.getClass().getSimpleName()); public FactCreated(Fact fact) { log.info("fact: {}", fact); this.fact = fact; } }
/** * JProdNextTariff.java 2010/06/08 */ package com.ycsoft.beans.core.job; import java.io.Serializable; import java.util.Date; import com.ycsoft.beans.base.BusiBase; import com.ycsoft.daos.config.POJO; /** * JProdNextTariff -> J_PROD_NEXT_TARIFF mapping */ @POJO(tn = "J_PROD_NEXT_TARIFF", sn = "", pk = "job_id") public class JProdNextTariff extends BusiBase implements Serializable { // JProdNextTariff all properties /** * */ private static final long serialVersionUID = 1979816489288004293L; private Integer job_id; private String prod_sn; private String tariff_id; private String old_tariff_id; private Date eff_date; /** * default empty constructor */ public JProdNextTariff() { } // job_id getter and setter public int getJob_id() { return job_id; } public void setJob_id(int job_id) { this.job_id = job_id; } public String getProd_sn() { return prod_sn; } public void setProd_sn(String prod_sn) { this.prod_sn = prod_sn; } // tariff_id getter and setter public String getTariff_id() { return tariff_id; } public void setTariff_id(String tariff_id) { this.tariff_id = tariff_id; } // eff_date getter and setter public Date getEff_date() { return eff_date; } public void setEff_date(Date eff_date) { this.eff_date = eff_date; } public String getOld_tariff_id() { return old_tariff_id; } public void setOld_tariff_id(String old_tariff_id) { this.old_tariff_id = old_tariff_id; } }
package com.github.simy4.xpath.effects; import com.github.simy4.xpath.XmlBuilderException; import com.github.simy4.xpath.expr.Expr; import com.github.simy4.xpath.navigator.Navigator; import com.github.simy4.xpath.navigator.Node; import com.github.simy4.xpath.spi.Effect; import com.github.simy4.xpath.view.AbstractViewVisitor; import com.github.simy4.xpath.view.IterableNodeView; import com.github.simy4.xpath.view.NodeView; import com.github.simy4.xpath.view.View; import java.io.Serializable; public class PutValueEffect implements Effect, Serializable { private static final long serialVersionUID = 1L; private final Expr expr; private final String value; public PutValueEffect(Expr expr, Object value) { this.expr = expr; this.value = String.valueOf(value); } @Override public <N extends Node> void perform(Navigator<N> navigator, N xml) throws XmlBuilderException { expr.resolve(navigator, new NodeView<>(xml), true).visit(new PutValueVisitor<>(navigator, value)); } private static final class PutValueVisitor<N extends Node> extends AbstractViewVisitor<N, Void> { private final Navigator<N> navigator; private final String value; private PutValueVisitor(Navigator<N> navigator, String value) { this.navigator = navigator; this.value = value; } @Override public Void visit(IterableNodeView<N> nodeSet) throws XmlBuilderException { for (var node : nodeSet) { navigator.setText(node.getNode(), value); } return null; } @Override protected Void returnDefault(View<N> view) throws XmlBuilderException { throw new XmlBuilderException("Failed to put value into XML. Read-only view was resolved: " + view); } } }
/* * ModeShape (http://www.modeshape.org) * * 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.modeshape.web.jcr; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Servlet context listener that is responsible for {@link RepositoryManager#initialize(javax.servlet.ServletContext) * initializing} the {@link RepositoryManager repository factory}. * <p> * This class is not thread safe, but in practice this does not matter as the servlet container must ensure that only a single * instance of this exists per web context and that it is only called in a single-threaded manner. * </p> * <p> * This class is not thread-safe. * </p> * * @see RepositoryManager */ public class ModeShapeJcrDeployer implements ServletContextListener { /** * Alerts the repository factory that the web application is shutting down * * @param event the servlet context event * @see RepositoryManager#shutdown() */ @Override public void contextDestroyed( ServletContextEvent event ) { RepositoryManager.shutdown(); } /** * Initializes the repository factory * * @param event the servlet context event * @see RepositoryManager#initialize(javax.servlet.ServletContext) */ @Override public void contextInitialized( ServletContextEvent event ) { RepositoryManager.initialize(event.getServletContext()); } }
package com.rokuality.server.driver.device.hdmi; import java.io.File; import com.rokuality.server.constants.DependencyConstants; import com.rokuality.server.core.CommandExecutor; import com.rokuality.server.utils.OSUtils; import org.eclipse.jetty.util.log.Log; public class HDMIKeyPresser { private static final int DEFAULT_TIMEOUT = 30; private String homeHubDeviceIP = null; private String deviceName = null; public HDMIKeyPresser(String homeHubDeviceIP, String deviceName) { this.homeHubDeviceIP = homeHubDeviceIP; this.deviceName = deviceName; } public boolean pressButton(String button) { File node = new File(OSUtils.getBinaryPath("node")); if (!node.exists()) { Log.getRootLogger().warn("Node was not found in user's path. Please install!"); return false; } String command = node.getAbsolutePath() + " " + DependencyConstants.HARMONY_BIN.getAbsolutePath() + " -l " + homeHubDeviceIP + " -d " + "\"" + deviceName + "\"" + " -c " + button; Log.getRootLogger().info(String.format("Sending %s command to harmony.", command)); String output = new CommandExecutor().execCommand(command, DEFAULT_TIMEOUT); Log.getRootLogger().info("Result of harmony command: " + output); return output != null && output.toLowerCase().contains("success"); } public String getButtons() { File node = new File(OSUtils.getBinaryPath("node")); if (!node.exists()) { Log.getRootLogger().warn("Node was not found in user's path. Please install!"); return null; } String command = node.getAbsolutePath() + " " + DependencyConstants.HARMONY_BIN.getAbsolutePath() + " -l " + homeHubDeviceIP + " -d " + "\"" + deviceName + "\"" + " -r commands"; Log.getRootLogger().info(String.format("Sending %s command to harmony.", command)); String output = new CommandExecutor().execCommand(command, DEFAULT_TIMEOUT); return output; } }
/* * The MIT License (MIT) * * Copyright (c) 2019-2021 TheRandomLabs * * 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.therandomlabs.changeloggenerator; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import java.util.stream.Collectors; import com.google.common.collect.Lists; import com.therandomlabs.curseapi.CurseException; import com.therandomlabs.curseapi.file.BasicCurseFile; import com.therandomlabs.curseapi.file.CurseFile; import com.therandomlabs.curseapi.file.CurseFileChange; import com.therandomlabs.curseapi.file.CurseFiles; import com.therandomlabs.curseapi.minecraft.modpack.CurseModpack; import com.therandomlabs.curseapi.project.CurseProject; import com.therandomlabs.curseapi.util.JsoupUtils; /** * A variant of {@link BasicChangelogGenerator} that generates a Markdown changelog. */ public class MarkdownChangelogGenerator extends BasicChangelogGenerator { private static final Pattern image = Pattern.compile(".*!\\[.*]\\(.*\\).*"); /** * Constructs a {@link MarkdownChangelogGenerator}. */ public MarkdownChangelogGenerator() { this(new ChangelogGeneratorOptions()); } /** * Constructs a {@link MarkdownChangelogGenerator}. * * @param options ChangelogGenerator options. */ public MarkdownChangelogGenerator(ChangelogGeneratorOptions options) { super(options); } /** * {@inheritDoc} */ @Override protected void appendTitle(StringBuilder builder, String title) { builder.append("## ").append(title).append(System.lineSeparator()); } /** * {@inheritDoc} */ @Override protected void appendModpackVersions( StringBuilder builder, CurseModpack oldModpack, CurseModpack newModpack ) throws CurseException { builder.append("# ").append(oldModpack.name()).append(' ').append(oldModpack.version()). append('⟶').append(newModpack.name()).append(' ').append(newModpack.version()); } /** * {@inheritDoc} */ @Override protected void appendFiles( StringBuilder builder, String title, CurseFiles<BasicCurseFile> files ) throws CurseException { appendTitle(builder, title); final Set<String> projectNames = files.parallelMap( file -> Optional.ofNullable(file.project()). map(project -> "[" + project.name() + "](" + project.url() + ")"). orElse("Deleted project"), Collectors.toCollection(TreeSet::new) ); for (String projectName : projectNames) { builder.append(System.lineSeparator()).append("* ").append(projectName); } } /** * {@inheritDoc} */ @SuppressWarnings("Duplicates") @Override protected void appendChangelogEntries( StringBuilder builder, String projectName, ChangelogEntries changelogEntries ) throws CurseException { final CurseFileChange<BasicCurseFile> fileChange = changelogEntries.fileChange(); final CurseFile oldFile = fileChange.oldCurseFile(); final String oldDisplayName; if (oldFile == null) { oldDisplayName = "Archived file"; } else { oldDisplayName = "[" + oldFile.displayName() + "](" + oldFile.url() + ")"; } final CurseFile newFile = fileChange.newCurseFile(); final String newDisplayName; if (newFile == null) { newDisplayName = "Archived file"; } else { newDisplayName = "[" + newFile.displayName() + "](" + newFile.url() + ")"; } builder.append("### ").append( Optional.ofNullable(fileChange.project()). map(project -> "[" + project.name() + "](" + project.url() + ")"). orElse("Deleted project") ).append(" (").append(oldDisplayName).append('⟶').append(newDisplayName).append(')'). append(System.lineSeparator()); List<ChangelogEntry> entries = new ArrayList<>(changelogEntries.entries()); if (entries.isEmpty()) { return; } final int maxEntries = getOptions().maxEntryCount; final int extraEntries = maxEntries == 0 ? 0 : entries.size() - maxEntries; if (extraEntries > 0) { entries = entries.subList(0, maxEntries); } for (ChangelogEntry entry : entries) { builder.append(System.lineSeparator()).append("#### [").append(entry.title()). append("](").append(entry.url()).append(')').append(System.lineSeparator()); List<String> entryLines; if (JsoupUtils.isEmpty(entry.entry())) { entryLines = Lists.newArrayList("No changelog available."); } else { entryLines = Lists.newArrayList( lineSeparatorSplitter.split(JsoupUtils.getPlainText(entry.entry())) ); } //Remove all lines with images. entryLines = entryLines.stream(). filter(line -> !image.matcher(line).matches()). collect(Collectors.toCollection(ArrayList::new)); final int maxLines = getOptions().maxEntryLineCount; if (maxLines != 0 && entryLines.size() > maxLines) { final int extra = entryLines.size() - maxLines; entryLines.set( maxLines, "[(" + extra + " more line" + (extra == 1 ? ")](" : "s)](") + entry.url() + ')' ); entryLines = entryLines.subList(0, maxLines + 1); } boolean wasListItem = false; for (int i = 0; i < entryLines.size(); i++) { final String line = entryLines.get(i); builder.append(System.lineSeparator()); if (!line.isEmpty()) { //For consistency, we change "- " and "+ " to "* " at line beginnings. if ((line.startsWith("- ") || line.startsWith("+ ") || line.startsWith("* ")) && line.length() > 2) { builder.append("* ").append(line.substring(2).trim()); wasListItem = true; } else { if (wasListItem) { builder.append(System.lineSeparator()); wasListItem = false; } builder.append(line); if (i != entryLines.size() - 1) { builder.append(System.lineSeparator()); } } } } builder.append(System.lineSeparator()); } if (extraEntries > 0) { //This is guaranteed to be non-null, but we have to appease the static code analysis //tools. final CurseProject project = fileChange.project(); if (project == null) { builder.append(System.lineSeparator()).append("#### ").append(extraEntries). append(" more entr").append(extraEntries == 1 ? "y" : "ies"); return; } builder.append(System.lineSeparator()).append("#### [").append(extraEntries). append(" more entr").append(extraEntries == 1 ? "y](" : "ies]("). append(project.url()).append("/files/all)"). append(System.lineSeparator()); } } /** * {@inheritDoc} */ @Override protected void appendTail(StringBuilder builder) { builder.append("Generated using [ChangelogGenerator ").append(VERSION). append("](https://github.com/TheRandomLabs/ChangelogGenerator)."); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.openwire.codec.universal; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.activemq.openwire.codec.*; import org.apache.activemq.openwire.commands.*; /** * Marshalling code for Open Wire for SubscriptionInfo * * NOTE!: This file is auto generated - do not modify! * */ public class SubscriptionInfoMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure handled by this Marshaler * * @return short representation of the type data structure */ public byte getDataStructureType() { return SubscriptionInfo.DATA_STRUCTURE_TYPE; } /** * @return a new instance of the managed type. */ public DataStructure createObject() { return new SubscriptionInfo(); } /** * Un-marshal an object instance from the data input stream * * @param wireFormat the OpenWireFormat instance to use * @param target the object to un-marshal * @param dataIn the data input stream to build the object from * @param bs the boolean stream where the type's booleans were marshaled * * @throws IOException if an error occurs while reading the data */ public void tightUnmarshal(OpenWireFormat wireFormat, Object target, DataInput dataIn, BooleanStream bs) throws IOException { super.tightUnmarshal(wireFormat, target, dataIn, bs); SubscriptionInfo info = (SubscriptionInfo) target; int version = wireFormat.getVersion(); info.setClientId(tightUnmarshalString(dataIn, bs)); info.setDestination((OpenWireDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); info.setSelector(tightUnmarshalString(dataIn, bs)); info.setSubscriptionName(tightUnmarshalString(dataIn, bs)); if (version >= 3) { info.setSubscribedDestination((OpenWireDestination) tightUnmarsalNestedObject(wireFormat, dataIn, bs)); } if (version >= 11) { info.setNoLocal(bs.readBoolean()); } } /** * Write the booleans that this object uses to a BooleanStream * * @param wireFormat the OpenWireFormat instance to use * @param source the object to marshal * @param bs the boolean stream where the type's booleans are written * * @throws IOException if an error occurs while writing the data */ public int tightMarshal1(OpenWireFormat wireFormat, Object source, BooleanStream bs) throws IOException { SubscriptionInfo info = (SubscriptionInfo) source; int version = wireFormat.getVersion(); int rc = super.tightMarshal1(wireFormat, source, bs); rc += tightMarshalString1(info.getClientId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); rc += tightMarshalString1(info.getSelector(), bs); rc += tightMarshalString1(info.getSubscriptionName(), bs); if (version >= 3) { rc += tightMarshalNestedObject1(wireFormat, (DataStructure)info.getSubscribedDestination(), bs); } if (version >= 11) { bs.writeBoolean(info.isNoLocal()); } return rc + 0; } /** * Write a object instance to data output stream * * @param wireFormat the OpenWireFormat instance to use * @param source the object to marshal * @param dataOut the DataOut where the properties are written * @param bs the boolean stream where the type's booleans are written * * @throws IOException if an error occurs while writing the data */ public void tightMarshal2(OpenWireFormat wireFormat, Object source, DataOutput dataOut, BooleanStream bs) throws IOException { super.tightMarshal2(wireFormat, source, dataOut, bs); SubscriptionInfo info = (SubscriptionInfo) source; int version = wireFormat.getVersion(); tightMarshalString2(info.getClientId(), dataOut, bs); tightMarshalCachedObject2(wireFormat, (DataStructure)info.getDestination(), dataOut, bs); tightMarshalString2(info.getSelector(), dataOut, bs); tightMarshalString2(info.getSubscriptionName(), dataOut, bs); if (version >= 3) { tightMarshalNestedObject2(wireFormat, (DataStructure)info.getSubscribedDestination(), dataOut, bs); } if (version >= 11) { bs.readBoolean(); } } /** * Write the object to the output using loose marshaling. * * @throws IOException if an error occurs while writing the data */ public void looseMarshal(OpenWireFormat wireFormat, Object source, DataOutput dataOut) throws IOException { SubscriptionInfo info = (SubscriptionInfo) source; int version = wireFormat.getVersion(); super.looseMarshal(wireFormat, source, dataOut); looseMarshalString(info.getClientId(), dataOut); looseMarshalCachedObject(wireFormat, (DataStructure)info.getDestination(), dataOut); looseMarshalString(info.getSelector(), dataOut); looseMarshalString(info.getSubscriptionName(), dataOut); if (version >= 3) { looseMarshalNestedObject(wireFormat, (DataStructure)info.getSubscribedDestination(), dataOut); } if (version >= 11) { dataOut.writeBoolean(info.isNoLocal()); } } /** * Un-marshal an object instance from the data input stream * * @param target the object to un-marshal * @param dataIn the data input stream to build the object from * * @throws IOException if an error occurs while writing the data */ public void looseUnmarshal(OpenWireFormat wireFormat, Object target, DataInput dataIn) throws IOException { super.looseUnmarshal(wireFormat, target, dataIn); SubscriptionInfo info = (SubscriptionInfo) target; int version = wireFormat.getVersion(); info.setClientId(looseUnmarshalString(dataIn)); info.setDestination((OpenWireDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); info.setSelector(looseUnmarshalString(dataIn)); info.setSubscriptionName(looseUnmarshalString(dataIn)); if (version >= 3) { info.setSubscribedDestination((OpenWireDestination) looseUnmarsalNestedObject(wireFormat, dataIn)); } if (version >= 11) { info.setNoLocal(dataIn.readBoolean()); } } }
package cub3d.file.reader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipReader extends Reader { private boolean hasLoaded; private Map<ZipEntry, ByteArrayOutputStream> entrys = new HashMap<ZipEntry, ByteArrayOutputStream>(); private ZipInputStream input = null; public ZipReader(Reader r) { super(r.getStream()); this.input = new ZipInputStream(getStream()); } private void load() throws IOException { if(!hasLoaded) { hasLoaded = true; ZipEntry ze = null; while((ze = input.getNextEntry()) != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); while(input.available() > 0) baos.write(input.read()); entrys.put(ze, baos); } } } public Reader getReaderFor(String filename) throws IOException { load(); for(ZipEntry ze : entrys.keySet()) if(ze.getName().equals(filename)) { ByteArrayOutputStream baos = entrys.get(ze); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); return new Reader(bais); } return null; } public Map<ZipEntry, ByteArrayOutputStream> getEntrys() throws IOException { load(); return entrys; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.api.types; /** * RangeInterval type. */ public class IntervalRangeType extends AtomicType { public static final IntervalRangeType INSTANCE = new IntervalRangeType(); private IntervalRangeType() { } }
package de.codecentric.reedelk.mail.internal.smtp.attachment; import de.codecentric.reedelk.mail.component.smtp.AttachmentDefinition; import de.codecentric.reedelk.mail.internal.commons.ContentType; import de.codecentric.reedelk.mail.internal.exception.MailAttachmentException; import de.codecentric.reedelk.runtime.api.commons.StreamUtils; import de.codecentric.reedelk.runtime.api.flow.FlowContext; import de.codecentric.reedelk.runtime.api.message.Message; import de.codecentric.reedelk.runtime.api.resource.ResourceBinary; import de.codecentric.reedelk.runtime.api.script.ScriptEngineService; import de.codecentric.reedelk.runtime.api.script.dynamicvalue.DynamicString; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.MultiPartEmail; import javax.mail.util.ByteArrayDataSource; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import static de.codecentric.reedelk.mail.internal.commons.Messages.MailSendComponent.ATTACHMENT_RESOURCE_MUST_NOT_BE_EMPTY; public class ResourceType extends AbstractAttachment { @Override public void build(ScriptEngineService scriptEngine, AttachmentDefinition definition, MultiPartEmail email, FlowContext context, Message message) { String name = definition.getName(); String charset = definition.getCharset(); String contentType = definition.getContentType(); DynamicString userDefinedFileName = definition.getFileName(); ResourceBinary resourceFile = Optional.ofNullable(definition.getResourceFile()) .orElseThrow(() -> new MailAttachmentException(ATTACHMENT_RESOURCE_MUST_NOT_BE_EMPTY.format())); Path theResourceFilePath = Paths.get(resourceFile.path()); String finalFileName = attachmentFileNameFrom(scriptEngine, context, message, userDefinedFileName, theResourceFilePath); try { byte[] data = StreamUtils.FromByteArray.consume(resourceFile.data()); String attachmentContentType = ContentType.from(contentType, charset); ByteArrayDataSource dataSource = new ByteArrayDataSource(data, attachmentContentType); email.attach(dataSource, finalFileName, name); } catch (EmailException exception) { throw new MailAttachmentException(exception.getMessage(), exception); } } }