hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
ca9e5eefd410a51f681f5fcc95a7ade967a729f5
373
package com.GB.ChinaMobileMS.services.interfaces; import java.util.List; import com.GB.ChinaMobileMS.entity.CompanyEntity; public interface CompanyService { public CompanyEntity getCompanyManager(int companyID); public List<CompanyEntity> queryCompany(); public List<CompanyEntity> getCompanyByName(String companyName); public List<CompanyEntity> listcompany(); }
26.642857
65
0.820375
33682f788f206c5f830cf2adc317671e116b7242
1,091
/******************************************************************************* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.dataflow.IFDS; import com.ibm.wala.dataflow.IFDS.TabulationSolver.Result; import com.ibm.wala.util.CancelException; /** * A {@link CancelException} thrown during tabulation; holds a pointer to a partial {@link Result}. Use with care, this can hold on * to a lot of memory. */ public class TabulationCancelException extends CancelException { private final Result result; protected TabulationCancelException(Exception cause, Result r) { super(cause); this.result = r; } public Result getResult() { return result; } }
32.088235
131
0.633364
6197685eefb8e4ea4670cdff09f5c0edf0ef91f8
49,244
/*- * #%L * athena-jdbc * %% * Copyright (C) 2019 Amazon Web Services * %% * 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 com.amazonaws.connectors.athena.jdbc.kdb; import static java.util.stream.Collectors.joining; import com.amazonaws.athena.connector.lambda.domain.Split; import com.amazonaws.athena.connector.lambda.domain.predicate.Constraints; import com.amazonaws.athena.connector.lambda.domain.predicate.Marker.Bound; import com.amazonaws.athena.connector.lambda.domain.predicate.Range; import com.amazonaws.athena.connector.lambda.domain.predicate.SortedRangeSet; import com.amazonaws.athena.connector.lambda.domain.predicate.ValueSet; import com.amazonaws.connectors.athena.jdbc.TimeManagerRealtime; import com.amazonaws.connectors.athena.jdbc.manager.JdbcSplitQueryBuilder; import com.amazonaws.connectors.athena.jdbc.manager.JdbcRecordHandler.SkipQueryException; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.arrow.vector.types.Types; import org.apache.arrow.vector.types.Types.MinorType; import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Days; import org.joda.time.LocalDateTime; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collectors; /** * Extends {@link JdbcSplitQueryBuilder} and implements Kdb specific SQL clauses for split. * * Kdb provides named partitions which can be used in a FROM clause. */ public class KdbQueryStringBuilder extends JdbcSplitQueryBuilder { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(KdbQueryStringBuilder.class); private static final org.joda.time.LocalDateTime EPOCH = new org.joda.time.LocalDateTime(1970, 1, 1, 0, 0); private static final org.joda.time.LocalDate EPOCH_DATE = new org.joda.time.LocalDate(1970, 1, 1); //@Nonnull private final TimeManager timemgr; public KdbQueryStringBuilder(final String quoteCharacters) { this(quoteCharacters, new TimeManagerRealtime()); } KdbQueryStringBuilder(final String quoteCharacters, TimeManager timemgr) { super(quoteCharacters); Preconditions.checkArgument(timemgr != null, "timemgr is null"); this.timemgr = timemgr; } /** * Common logic to build Split SQL including constraints translated in where clause. * * @param jdbcConnection JDBC connection. See {@link Connection}. * @param catalog Athena provided catalog name. * @param schema table schema name. * @param table table name. * @param tableSchema table schema (column and type information). * @param constraints constraints passed by Athena to push down. * @param split table split. * @return prepated statement with SQL. See {@link PreparedStatement}. * @throws SQLException JDBC database exception. */ @Override public PreparedStatement buildSql( final Connection jdbcConnection, final String catalog, final String schema, final String table, final Schema tableSchema, final Constraints constraints, final Split split) throws SQLException { final String sql = buildSqlString(catalog, schema, table, tableSchema, constraints, split); PreparedStatement statement = jdbcConnection.prepareStatement(sql); return statement; } /** * Common logic to build Split SQL including constraints translated in where clause. * * @param catalog Athena provided catalog name. * @param schema table schema name. * @param table table name. * @param tableSchema table schema (column and type information). * @param constraints constraints passed by Athena to push down. * @param split table split. * @return prepated statement with SQL. See {@link PreparedStatement}. * @throws SQLException JDBC database exception. */ @VisibleForTesting String buildSqlString( final String catalog, final String schema, final String table, final Schema tableSchema, Constraints constraints, final Split split) throws SQLException { LOGGER.info("buildSqlString catalog={} schema={}, table={}, tableSchema={} constraints={}, split={}" , catalog , schema , table , tableSchema , constraints , split ); final String partition_name = split.getProperties().get(KdbMetadataHandler.PARTITION_COLUMN_NAME); LOGGER.info("partition_name={}", partition_name); int total_partitions = 1; int partition_idx = 0; if(partition_name.contains("/")) { String[] a = partition_name.split("/", 2); partition_idx = Integer.parseInt(a[0]) - 1; total_partitions = Integer.parseInt(a[1]); } Map<String, String> props = new HashMap<>(); props.putAll(KdbMetadataHandler.getProperties(Objects.toString(System.getenv("connector_properties"), ""))); LOGGER.info("connector_properties:{}", props); props.putAll(KdbMetadataHandler.getProperties(schema)); LOGGER.info("overwritten props:{}", props); String datefield = Objects.toString(props.get(KdbMetadataHandler.SCHEMA_DATEFIELD_KEY), ""); if(datefield.isEmpty()) datefield = "date"; final boolean wherepushdown = "true".equals(props.get(KdbMetadataHandler.SCHEMA_WHEREPUSHDOWN_KEY)); StringBuilder sql = new StringBuilder(); String columnNames = tableSchema.getFields().stream() .map(Field::getName) .filter(c -> !split.getProperties().containsKey(c)) .map(this::quote) .collect(Collectors.joining(", ")); sql.append("q) "); sql.append("select "); sql.append(columnNames); if (columnNames.isEmpty()) { sql.append("null"); } //explicit upperdate final String upperdateStr = props.get(KdbMetadataHandler.SCHEMA_UPPERDATE_KEY); LOGGER.info("upperdate={}", upperdateStr); String timezone = props.get("timezone"); if(timezone == null) timezone = "Asia/Tokyo"; LocalDateTime upperdate = timemgr.newLocalDateTime(DateTimeZone.forID(timezone)); if(upperdateStr != null && ! upperdateStr.trim().isEmpty()) { try { upperdate = DateTimeFormat.forPattern("yyyyMMdd").parseLocalDateTime(upperdateStr.trim()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("error occurs during parsing upperdate(expected format is yyyyMMdd):" + upperdateStr, e); } } //getDateRange //push down parition clauses final ValueSet date_valueset = (constraints.getSummary() != null && !constraints.getSummary().isEmpty()) ? constraints.getSummary().get(datefield) : null; DateCriteria daterange = getDateRange(date_valueset, upperdate); if(daterange == null) { //try to find time field then String timestampfield = props.get(KdbMetadataHandler.SCHEMA_TIMESTAMPFIELD_KEY); if(timestampfield == null) timestampfield = "time"; final ValueSet timestamp_valueset = (constraints.getSummary() != null && !constraints.getSummary().isEmpty()) ? constraints.getSummary().get(timestampfield) : null; daterange = getDateRangeForTimestamp(timestamp_valueset, upperdate); } //date range adjustment if(daterange != null) { final String lowerdateadjustStr = props.get(KdbMetadataHandler.SCHEMA_LOWERDATEADJUST_KEY); int lowerdateadjust = 0; if(lowerdateadjustStr != null) { try { lowerdateadjust = Integer.parseInt(lowerdateadjustStr); } catch (NumberFormatException ignored) { throw new IllegalArgumentException(KdbMetadataHandler.SCHEMA_LOWERDATEADJUST_KEY + " should be integer format but was " + lowerdateadjustStr); } } final String upperdateadjustStr = props.get(KdbMetadataHandler.SCHEMA_UPPERDATEADJUST_KEY); int upperdateadjust = 0; if(upperdateadjustStr != null) { try { upperdateadjust = Integer.parseInt(upperdateadjustStr); } catch (NumberFormatException ignored) { throw new IllegalArgumentException(KdbMetadataHandler.SCHEMA_UPPERDATEADJUST_KEY + " should be integer format but was " + upperdateadjustStr); } } daterange = new DateCriteria(daterange.from_day + lowerdateadjust, daterange.to_day + upperdateadjust); } //parallel query if(daterange == null) { if(partition_idx != 0) throw new SkipQueryException("no date range criteria. skipping query as partition_idx=" + partition_idx); } else { LOGGER.info("pushdownable date range criteria is found. " + daterange); daterange = getDateRangeParallelQuery(daterange, total_partitions, partition_idx); LOGGER.info("In the result of parallel query splitting, now date range criteria is " + daterange); } String kdbTableName = KdbMetadataHandler.athenaTableNameToKdbTableName(table); //push down date criteria if (daterange != null) { final String datepushdown = Objects.toString(props.get(KdbMetadataHandler.SCHEMA_DATEPUSHDOWN_KEY), "").toLowerCase(); LOGGER.info("datepushdown={}", datepushdown); if("true".equals(datepushdown)) { LOGGER.info("datepushdown is enabled."); final String nowhereondatepushdownStr = Objects.toString(props.get(KdbMetadataHandler.SCHEMA_NOWHEREONDATEPUSHDOWN_KEY), "").toLowerCase(); LOGGER.info("nowhereondatepushdown={}", nowhereondatepushdownStr); final boolean nowhereondatepushdown = "true".equals(nowhereondatepushdownStr); // prepare where clause push down String whereclause = null; if (wherepushdown) { LOGGER.info("wherepushdown is enabled."); whereclause = toWhereClause(tableSchema.getFields(), constraints.getSummary(), split.getProperties(), nowhereondatepushdown, datefield); LOGGER.info("whereclause=" + String.valueOf(whereclause)); } final String orgKdbTableName = kdbTableName; kdbTableName = pushDownDateCriteriaIntoFuncArgs(kdbTableName, daterange, whereclause); if(! kdbTableName.equals(orgKdbTableName)) { if(nowhereondatepushdown) { LOGGER.info("ignore where clause of date."); daterange = null; //we don't use daterange information in where clause Map<String, ValueSet> summary = Maps.newHashMap(constraints.getSummary()); summary.remove(datefield); constraints = new Constraints(summary); } } } } sql.append(" from " + quote(kdbTableName) + " "); List<TypeAndValue> accumulator = new ArrayList<>(); List<String> clauses = new ArrayList<>(); //use daterange if(daterange != null) { clauses.add("(" + datefield + " within (" + KdbQueryStringBuilder.toLiteral(daterange.from_day, MinorType.DATEDAY, null) + ";" + KdbQueryStringBuilder.toLiteral(daterange.to_day, MinorType.DATEDAY, null) + "))"); } //normal where clauses clauses.addAll(toConjuncts(tableSchema.getFields(), constraints, accumulator, split.getProperties())); if (!clauses.isEmpty()) { sql.append(" where ") .append(Joiner.on(" , ").join(clauses)); } LOGGER.info("Generated SQL : {}", sql.toString()); return sql.toString(); } public static class DateCriteria { public final int from_day; public final int to_day; public DateCriteria(int from_day, int to_day) { this.from_day = from_day; this.to_day = to_day; } public String getFromDate() { return KdbQueryStringBuilder.toLiteral(from_day, MinorType.DATEDAY, null); } public String getToDate() { return KdbQueryStringBuilder.toLiteral(to_day, MinorType.DATEDAY, null); } @Override public String toString() { return from_day + "(" + getFromDate() + ")-" + to_day + "(" + getToDate() + ")"; } @Override public int hashCode() { return from_day + to_day; } @Override public boolean equals(Object other) { if(other == null) return false; if(other.getClass() != getClass()) return false; DateCriteria d = (DateCriteria)other; return from_day == d.from_day && to_day == d.to_day; } } static public DateCriteria getDateRange(ValueSet valueSet, /*NotNull*/ LocalDateTime upperdate) { LOGGER.info("getDateRange valueset={}, upperdate={}", valueSet, upperdate); if(valueSet == null) return null; //no date range criteria if(valueSet.isNullAllowed()) return null; //no date range criteria if (! (valueSet instanceof SortedRangeSet)) return null; //no date range criteria Range rangeSpan = ((SortedRangeSet) valueSet).getSpan(); LOGGER.info("span={}", rangeSpan); if (rangeSpan.getLow().isLowerUnbounded() && rangeSpan.getHigh().isUpperUnbounded()) return null; List<Range> ranges = valueSet.getRanges().getOrderedRanges(); LOGGER.info("ranges={}", ranges); if(ranges.size() != 1) return null; //multiple range is not supported Range range = ranges.get(0); if (range.isSingleValue()) { return new DateCriteria((Integer)range.getLow().getValue(), (Integer)range.getLow().getValue()); } else if (!range.getLow().isLowerUnbounded() && range.getLow().getBound() == Bound.EXACTLY && !range.getHigh().isUpperUnbounded() && range.getHigh().getBound() == Bound.EXACTLY) { return new DateCriteria((Integer)range.getLow().getValue(), (Integer)range.getHigh().getValue()); } else if (!range.getLow().isLowerUnbounded() && range.getLow().getBound() == Bound.EXACTLY && range.getHigh().isUpperUnbounded()) { //assume upper bound is today int days_today = getDaysOf(upperdate); return new DateCriteria((Integer)range.getLow().getValue(), days_today); } else { return null; } } static public DateCriteria getDateRangeForTimestamp(ValueSet valueSet, LocalDateTime upperdate) { LOGGER.info("getDateRangeForTimestamp valueset={}, upperdate={}", valueSet, upperdate); if(valueSet == null) return null; //no date range criteria if(valueSet.isNullAllowed()) return null; //no date range criteria if (! (valueSet instanceof SortedRangeSet)) return null; //no date range criteria Range rangeSpan = ((SortedRangeSet) valueSet).getSpan(); LOGGER.info("span={}", rangeSpan); if (rangeSpan.getLow().isLowerUnbounded() && rangeSpan.getHigh().isUpperUnbounded()) return null; List<Range> ranges = valueSet.getRanges().getOrderedRanges(); LOGGER.info("ranges={}", ranges); if(ranges.size() != 1) return null; //multiple range is not supported Range range = ranges.get(0); if (range.isSingleValue()) { return new DateCriteria(timestampToDateValue(range.getLow().getValue()), timestampToDateValue(range.getLow().getValue())); } else if (!range.getLow().isLowerUnbounded() && range.getLow().getBound() == Bound.EXACTLY && !range.getHigh().isUpperUnbounded() && range.getHigh().getBound() == Bound.EXACTLY) { return new DateCriteria(timestampToDateValue(range.getLow().getValue()), timestampToDateValue(range.getHigh().getValue())); } else if (!range.getLow().isLowerUnbounded() && range.getLow().getBound() == Bound.EXACTLY && range.getHigh().isUpperUnbounded()) { //assume upper bound is today int days_today = getDaysOf(upperdate); return new DateCriteria(timestampToDateValue(range.getLow().getValue()), days_today); } else { return null; } } static public int timestampToDateValue(final Object vectorKdbTimestampLiteral) throws IllegalArgumentException { Preconditions.checkNotNull(vectorKdbTimestampLiteral, "vectorKdbTimestampLiteral is null"); //regardless org.apache.arrow.vector.util.Text instance or not, toString() should be enough to get String. //new String(((org.apache.arrow.vector.util.Text)vectorKdbTimestampLiteral).getBytes(), StandardCharsets.UTF_8) is not required. String kdbTimestampLiteral = vectorKdbTimestampLiteral.toString(); if(kdbTimestampLiteral.length() < 10) throw new IllegalArgumentException("Cannot extract date from kdbTimestampLiteral. kdbTimestampLiteral=" + kdbTimestampLiteral); // yyyy.MM.ddD.... try { LocalDateTime ldt = DateTimeFormat.forPattern("yyyy.MM.dd").parseLocalDateTime(kdbTimestampLiteral.substring(0, 10)); return getDaysOf(ldt); } catch(IllegalArgumentException ex) { throw new IllegalArgumentException("Cannot extract date from kdbTimestampLiteral. kdbTimestampLiteral=" + kdbTimestampLiteral, ex); } } static public int getDaysOf(final LocalDateTime now) { final int days_today = Days.daysBetween(EPOCH, now).getDays(); LOGGER.info("current LocalDateTime is " + now + " today days=" + days_today); return days_today; } static public DateCriteria getDateRangeParallelQuery(DateCriteria daterange, int total_partitions, int partition_idx) { int days = daterange.to_day - daterange.from_day + 1; int[] a = getDateRangeParallelQuery(days, total_partitions); LOGGER.info("days assignment {}", Arrays.toString(a)); int fromday = daterange.from_day; for(int i = 0; i < total_partitions; i++) { if(i == partition_idx) { if(a[i] == 0) throw new SkipQueryException("skip query as no assigned query at partition_idx=" + partition_idx); return new DateCriteria(fromday, fromday + a[i] - 1); } else fromday += a[i]; } //we shouldn't come here. throw new RuntimeException("something wrong."); } static public int[] getDateRangeParallelQuery(int days, int total_partitions) { if(days < 1) throw new IllegalArgumentException("days should be positive but was " + days); if(total_partitions < 1) throw new IllegalArgumentException("total_partitions should be positive but was " + total_partitions); final int num_days_per_part = days / total_partitions; int[] a = new int[total_partitions]; int n = 0; for(int i = 0; i < total_partitions; i++) { if(i == total_partitions - 1) a[i] = days - n; else { a[i] = num_days_per_part; n += num_days_per_part; } } return a; } static public String pushDownDateCriteriaIntoFuncArgs(String kdbTableName, DateCriteria daterange, String whereclause) { String from = KdbQueryStringBuilder.toLiteral(daterange.from_day, MinorType.DATEDAY, null); String to = KdbQueryStringBuilder.toLiteral(daterange.to_day , MinorType.DATEDAY, null); //First two arguments of function look date type and date_from and date_to are given. final String orgkdbTableName = kdbTableName; if(whereclause != null) { kdbTableName = kdbTableName.replaceFirst( "\\[ *[0-9][0-9][0-9][0-9]\\.[0-9][0-9]\\.[0-9][0-9] *; *[0-9][0-9][0-9][0-9]\\.[0-9][0-9]\\.[0-9][0-9] *;` *(?=(;|\\]))" , "[" + from + ";" + to + ";" + whereclause); if(! kdbTableName.equals(orgkdbTableName)) { return kdbTableName; //pushdown successfully } else { //tested by buildSql_datepushdown_wherepushdown_fallback_between } } kdbTableName = kdbTableName.replaceFirst( "\\[ *[0-9][0-9][0-9][0-9]\\.[0-9][0-9]\\.[0-9][0-9] *; *[0-9][0-9][0-9][0-9]\\.[0-9][0-9]\\.[0-9][0-9] *" , "[" + from + ";" + to); return kdbTableName; } @Override protected String getFromClauseWithSplit(String catalog, String schema, String athenaTableName, Split split) { throw new RuntimeException("getFromClauseWithSplit is not used in kdb+"); } @Override protected List<String> getPartitionWhereClauses(final Split split) { return Collections.emptyList(); } private static final ThreadLocal<DateTimeFormatter> DATE_FORMAT = new ThreadLocal<DateTimeFormatter>() { @Override protected DateTimeFormatter initialValue() { return DateTimeFormat.forPattern("yyyy.MM.dd"); } }; private static final ThreadLocal<DateTimeFormatter> TIME_FORMAT = new ThreadLocal<DateTimeFormatter>() { @Override protected DateTimeFormatter initialValue() { return DateTimeFormat.forPattern("HH:mm:ss.SSS000000"); } }; private static final ThreadLocal<Function<Timestamp, String>> TIMESTAMP_FORMAT = new ThreadLocal<Function<Timestamp, String>>() { final SimpleDateFormat datetime_format = new SimpleDateFormat("yyyy.MM.dd'D'HH:mm:ss"); final DecimalFormat nano_format = new DecimalFormat("000000000"); @Override protected Function<Timestamp, String> initialValue() { return new Function<Timestamp, String>() { @Override public String apply(Timestamp value) { return datetime_format.format(value) + "." + nano_format.format(value.getNanos()); } }; } }; static String toLiteral(Object value, ArrowType type, String columnName, Field column) { if(LOGGER.isDebugEnabled()) LOGGER.debug("column:" + String.valueOf(columnName) + " value:" + String.valueOf(value)); String literal = toLiteral(value, Types.getMinorTypeForArrowType(type), KdbTypes.valueOf(column.getMetadata().get(KdbMetadataHandler.KDBTYPE_KEY))); return literal; } @VisibleForTesting static String toLiteral(Object value, Types.MinorType minorTypeForArrowType, KdbTypes kdbtype) { if(LOGGER.isDebugEnabled()) LOGGER.debug("kdbtype:" + String.valueOf(kdbtype) + " minorTypeForArrowType:" + String.valueOf(minorTypeForArrowType) + " value:" + String.valueOf(value) + (value == null ? "null" : value.getClass().getName())); final String literal = _toLiteral(value, minorTypeForArrowType, kdbtype); if(LOGGER.isDebugEnabled()) LOGGER.debug("literal:" + String.valueOf(literal)); return literal; } static private String _toLiteral(Object value, Types.MinorType minorTypeForArrowType, KdbTypes kdbtype) { if(LOGGER.isDebugEnabled()) LOGGER.debug("minortype:" + String.valueOf(minorTypeForArrowType) + " kdbtype:" + String.valueOf(kdbtype) + " value:" + String.valueOf(value) + " valuetype:" + (value == null ? "null" : value.getClass().getName())); switch (minorTypeForArrowType) { case BIGINT: if (value == null) { return "0Nj"; } else { return String.valueOf(value); } case INT: if (value == null) { return "0Ni"; } else { return ((Number) value).intValue() + "i"; } case SMALLINT: if (value == null) { return "0Nh"; } else { return ((Number) value).shortValue() + "i"; } case TINYINT: //byte if (value == null) { return "0x00"; } else { return ((Number) value).byteValue() + "i"; } case FLOAT8: if (kdbtype == KdbTypes.real_type) { if (value == null) { return "0Ne"; } else { return String.valueOf(((Number) value).doubleValue()) + "e"; } } else { if (value == null) { return "0n"; } else { return String.valueOf(((Number) value).doubleValue()); } } case FLOAT4: //real if (value == null) { return "0Ne"; } else { return String.valueOf(((Number) value).floatValue()); } case BIT: //boolean if (value == null) { return "0b"; } else { return ((boolean) value) ? "1b" : "0b"; } case DATEDAY: if (value == null) { return "0Nd"; } else { if (value instanceof Number) { final int days = ((Number) value).intValue(); final org.joda.time.LocalDateTime dateTime = EPOCH.minusDays(-days); return DATE_FORMAT.get().print(dateTime); } else { final org.joda.time.LocalDateTime dateTime = ((org.joda.time.LocalDateTime) value); return DATE_FORMAT.get().print(dateTime); } } case DATEMILLI: if (value == null) { return "0Np"; } else { org.joda.time.LocalDateTime timestamp = ((org.joda.time.LocalDateTime) value); return DATE_FORMAT.get().print(timestamp) + "D" + TIME_FORMAT.get().print(timestamp); } case VARCHAR: switch(kdbtype) { case guid_type: if (value == null) { return "0Ng"; } else { return "\"G\"$\"" + value + "\""; } case char_type: if (value == null) { return "\" \""; } else { return "\"" + value.toString() + "\""; } case time_type: if (value == null) { return "0Nt"; } else { return value.toString(); } case timespan_type: if (value == null) { return "0Nn"; } else { return value.toString(); } case timestamp_type: if (value == null) { return "0Np"; } else { if (value instanceof Timestamp) { final Timestamp timestamp = (Timestamp) value; if(LOGGER.isDebugEnabled()) LOGGER.debug(String.format("timestamp#getTime:%s, getNanos:%s", timestamp.getTime(), timestamp.getNanos())); return TIMESTAMP_FORMAT.get().apply(timestamp); } else { return value.toString(); } } case list_of_char_type: throw new UnsupportedOperationException("list of char type cannot be pushed down to where statement"); default: //symbol if (value == null) { return "` "; } else { return "`" + String.valueOf(value); } } // case VARBINARY: // return String.valueOf((byte[]) typeAndValue.getValue()); //or throw exception // case DECIMAL: // ArrowType.Decimal decimalType = (ArrowType.Decimal) type; // BigDecimal decimal = BigDecimal.valueOf((Long) value, decimalType.getScale()); // return decimal.toPlainString(); default: throw new UnsupportedOperationException(String.format("Can't handle type: %s", minorTypeForArrowType)); } } @Override protected List<String> toConjuncts(List<Field> columns, Constraints constraints, List<TypeAndValue> accumulator, Map<String, String> partitionSplit) { List<String> conjuncts = new ArrayList<>(); for (Field column : columns) { if (partitionSplit.containsKey(column.getName())) { continue; // Ignore constraints on partition name as RDBMS does not contain these as columns. Presto will filter these values. } final char kdbtype = KdbMetadataHandler.getKdbTypeChar(column); switch(kdbtype) { case 'C': //list of char case 'P': //list of timestamp case 'S': //list of symbol case 'X': //list of byte case 'H': //list of short case 'I': //list of int case 'J': //list of long case 'E': //list of real case 'F': //list of float case 'B': //list of bit case 'G': //list of guid case 'D': //list of date LOGGER.info("list column is excluded from where caluse. columnName=" + column.getName()); continue; default: //no default logic } ArrowType type = column.getType(); if (constraints.getSummary() != null && !constraints.getSummary().isEmpty()) { ValueSet valueSet = constraints.getSummary().get(column.getName()); if (valueSet != null) { conjuncts.add(toPredicate(column.getName(), column, valueSet, type, accumulator)); } } } return conjuncts; } protected String toWhereClause(List<Field> columns, Map<String, ValueSet> constraintsSummary, Map<String, String> partitionSplit, boolean nowhereondatepushdown, String datefield) { List<String> conjuncts = Lists.newArrayList(); for (Field column : columns) { if (partitionSplit.containsKey(column.getName())) { continue; // Ignore constraints on partition name as RDBMS does not contain these as columns. Presto will filter these values. } if (nowhereondatepushdown && datefield.equals(column.getName())) { LOGGER.info("toWhereClause skips field " + datefield); continue; } final char kdbtype = KdbMetadataHandler.getKdbTypeChar(column); switch(kdbtype) { case 'C': //list of char case 'P': //list of timestamp case 'S': //list of symbol case 'X': //list of byte case 'H': //list of short case 'I': //list of int case 'J': //list of long case 'E': //list of real case 'F': //list of float case 'B': //list of bit case 'G': //list of guid case 'D': //list of date LOGGER.info("list column is excluded from where caluse. columnName=" + column.getName()); continue; default: //no default logic } ArrowType type = column.getType(); if (constraintsSummary != null && ! constraintsSummary.isEmpty()) { ValueSet valueSet = constraintsSummary.get(column.getName()); if (valueSet != null) { String cond = toWhereClause(column.getName(), column, valueSet, type); if(cond != null) conjuncts.add(cond); } } } if(conjuncts.isEmpty()) return "`"; else if(conjuncts.size() == 1) return "enlist " + Iterables.getOnlyElement(conjuncts); else return "(" + Joiner.on("; ").join(conjuncts) + ")"; } protected String toPredicate(String columnName, Field column, ValueSet valueSet, ArrowType type, List<TypeAndValue> accumulator) { List<String> disjuncts = new ArrayList<>(); List<Object> singleValues = new ArrayList<>(); // TODO Add isNone and isAll checks once we have data on nullability. if (valueSet instanceof SortedRangeSet) { if (valueSet.isNone() && valueSet.isNullAllowed()) { return toPredicateNull(columnName, column, type, accumulator); } // we don't need to add disjunction(OR (colname IS NULL)) because if (valueSet.isNullAllowed()) { disjuncts.add(toPredicateNull(columnName, column, type, accumulator)); } Range rangeSpan = ((SortedRangeSet) valueSet).getSpan(); if (!valueSet.isNullAllowed() && rangeSpan.getLow().isLowerUnbounded() && rangeSpan.getHigh().isUpperUnbounded()) { //probably this is typo and meant "valueSet.isNullAllowed() && rangeSpan.getLow().isLowerUnbounded() && rangeSpan.getHigh().isUpperUnbounded()" ? return toPredicateNull(columnName, column, type, accumulator); } for (Range range : valueSet.getRanges().getOrderedRanges()) { if (range.isSingleValue()) { singleValues.add(range.getLow().getValue()); } else { List<String> rangeConjuncts = new ArrayList<>(); if (!range.getLow().isLowerUnbounded() && range.getLow().getBound() == Bound.EXACTLY && !range.getHigh().isUpperUnbounded() && range.getHigh().getBound() == Bound.EXACTLY) { //between = within rangeConjuncts.add(quote(columnName) + " within (" + toLiteral(range.getLow().getValue(), type, columnName, column) + ";" + toLiteral(range.getHigh().getValue(), type, columnName, column) + ")"); } else { if (!range.getLow().isLowerUnbounded()) { switch (range.getLow().getBound()) { case ABOVE: rangeConjuncts.add(toPredicate(columnName, column, ">", range.getLow().getValue(), type, accumulator)); break; case EXACTLY: rangeConjuncts.add(toPredicate(columnName, column, ">=", range.getLow().getValue(), type, accumulator)); break; case BELOW: throw new IllegalArgumentException("Low marker should never use BELOW bound"); default: throw new AssertionError("Unhandled bound: " + range.getLow().getBound()); } } if (!range.getHigh().isUpperUnbounded()) { switch (range.getHigh().getBound()) { case ABOVE: throw new IllegalArgumentException("High marker should never use ABOVE bound"); case EXACTLY: rangeConjuncts.add(toPredicate(columnName, column, "<=", range.getHigh().getValue(), type, accumulator)); break; case BELOW: rangeConjuncts.add(toPredicate(columnName, column, "<", range.getHigh().getValue(), type, accumulator)); break; default: throw new AssertionError("Unhandled bound: " + range.getHigh().getBound()); } } } // If rangeConjuncts is null, then the range was ALL, which should already have been checked for Preconditions.checkState(!rangeConjuncts.isEmpty()); StringBuilder rngsql = new StringBuilder(); for (int i = 0; i < rangeConjuncts.size(); i++) { if (i > 0) rngsql.append(" and "); if (rangeConjuncts.size() > 0) rngsql.append("("); rngsql.append(rangeConjuncts.get(i)); if (rangeConjuncts.size() > 0) rngsql.append(")"); } disjuncts.add(rngsql.toString()); } } // Add back all of the possible single values either as an equality or an IN predicate if (singleValues.size() == 1) { disjuncts.add(toPredicate(columnName, column, "=", Iterables.getOnlyElement(singleValues), type, accumulator)); } else if (singleValues.size() > 1) { final StringBuilder insql = new StringBuilder(); insql.append(quote(columnName)); insql.append(" in ("); int count = 0; for (Object val : singleValues) { if (count > 0) insql.append(", "); insql.append(toLiteral(val, type, columnName, column)); count++; } insql.append(")"); disjuncts.add(insql.toString()); } } return "(" + Joiner.on(" or ").join(disjuncts) + ")"; } protected String toWhereClause(String columnName, Field column, ValueSet valueSet, ArrowType type) { if(valueSet == null) return null; LOGGER.info("toWhereClause columnName={}, type={}, valueSet={}", columnName, type, valueSet); if (! (valueSet instanceof SortedRangeSet)) { //don't know this type valueSet LOGGER.info("toWhereClause don't know this type valueSet. columnName={}, type={}, valueSet={}", columnName, type, valueSet); return null; } List<String> disjuncts = new ArrayList<>(); List<Object> singleValues = new ArrayList<>(); if(valueSet.isAll()) return null; //no condition if (valueSet.isNone()) { if (valueSet.isNullAllowed()) return toWhereClauseNull(columnName); else throw new IllegalArgumentException("not supported isNone && ! isNullAllowed combination. columnName=" + columnName + "; valueSet=" + valueSet); } Range rangeSpan = ((SortedRangeSet) valueSet).getSpan(); if (valueSet.isNullAllowed()) { disjuncts.add(toWhereClauseNull(columnName)); } if (rangeSpan.getLow().isLowerUnbounded() && rangeSpan.getHigh().isUpperUnbounded()) { //no boundary condition } else { for (Range range : valueSet.getRanges().getOrderedRanges()) { if (range.isSingleValue()) { singleValues.add(range.getLow().getValue()); } else { final List<String> rangeConjuncts = new ArrayList<>(); if (!range.getLow().isLowerUnbounded() && range.getLow().getBound() == Bound.EXACTLY && !range.getHigh().isUpperUnbounded() && range.getHigh().getBound() == Bound.EXACTLY) { //between = within final List<Object> atoms = Lists.newArrayList(range.getLow().getValue(), range.getHigh().getValue()); rangeConjuncts.add(toWhereClause(columnName, column, "within", atoms, type)); } else { if (!range.getLow().isLowerUnbounded()) { switch (range.getLow().getBound()) { case ABOVE: rangeConjuncts.add(toWhereClause(columnName, column, ">", range.getLow().getValue(), type)); break; case EXACTLY: rangeConjuncts.add(toWhereClause(columnName, column, ">=", range.getLow().getValue(), type)); break; case BELOW: throw new IllegalArgumentException("Low marker should never use BELOW bound"); default: throw new AssertionError("Unhandled bound: " + range.getLow().getBound()); } } if (!range.getHigh().isUpperUnbounded()) { switch (range.getHigh().getBound()) { case ABOVE: throw new IllegalArgumentException("High marker should never use ABOVE bound"); case EXACTLY: rangeConjuncts.add(toWhereClause(columnName, column, "<=", range.getHigh().getValue(), type)); break; case BELOW: rangeConjuncts.add(toWhereClause(columnName, column, "<", range.getHigh().getValue(), type)); break; default: throw new AssertionError("Unhandled bound: " + range.getHigh().getBound()); } } } // If rangeConjuncts is null, then the range was ALL, which should already have been checked for Preconditions.checkState(!rangeConjuncts.isEmpty()); if(rangeConjuncts.size() > 1) { disjuncts.add("(and; " + Joiner.on("; ").join(rangeConjuncts) + ")"); } else { disjuncts.add(rangeConjuncts.get(0)); } } } } // Add back all of the possible single values either as an equality or an IN predicate if (singleValues.size() == 1) { disjuncts.add(toWhereClause(columnName, column, "=", Iterables.getOnlyElement(singleValues), type)); } else if (singleValues.size() > 1) { disjuncts.add(toWhereClause(columnName, column, "in", singleValues, type)); } if(disjuncts.isEmpty()) return null; //no criteria else if(disjuncts.size() == 1) return Iterables.getOnlyElement(disjuncts); else return "(or; " + Joiner.on("; ").join(disjuncts) + ")"; } protected String toPredicateNull(String columnName, Field column, ArrowType type, List<TypeAndValue> accumulator) { // accumulator.add(new TypeAndValue(type, value)); return "(" + quote(columnName) + " = " + toLiteral(null, type, columnName, column) + ")"; } protected String toPredicate(String columnName, Field column, String operator, Object value, ArrowType type, List<TypeAndValue> accumulator) { // accumulator.add(new TypeAndValue(type, value)); return quote(columnName) + " " + operator + " " + toLiteral(value, type, columnName, column); } @Override protected String quote(String name) { return name; } protected static String backquote(String s) { return "`" + s; } static String toWhereClause(String columnName, Field column, String operator, Object value, ArrowType type) { String valuestr; if(operator == "=") { final List<Object> list = Lists.newLinkedList(); list.add(value); value = list; //to ensure list } if(value instanceof List) { final List<Object> list = (List<Object>)value; if(list.isEmpty()) { throw new IllegalStateException("toWhereClause not expect empty list. columnName=" + columnName + " operator=" + operator + " type=" + type); } else if(list.size() == 1) { valuestr = "enlist " + toLiteral(Iterables.getOnlyElement(list), type, columnName, column); } else { valuestr = "(" + list.stream().map(e->toLiteral(e, type, columnName, column)).collect(joining("; ")) + ")"; } } else { valuestr = toLiteral(value, type, columnName, column); } return "(" + operator + "; " + backquote(columnName) + "; " + valuestr + ")"; } static String toWhereClauseNull(String columnName) { return "(null; `" + columnName + ")"; } }
43.967857
251
0.550097
251b731438b77c201f46de4ecaf7b97e0dcdee73
759
package com.cjmalloy.torrentfs.server.remote.rest; import java.net.URI; import javax.ws.rs.*; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import com.cjmalloy.torrentfs.extension.HtmlExtension; import com.cjmalloy.torrentfs.server.TfsClientSingleton; @Path("/ext/html/") public class HtmlExtensionApi { @GET @Path("/index/{info_hash}") public Response getIndex(@PathParam("info_hash") String infoHash) { HtmlExtension ext = (HtmlExtension) TfsClientSingleton.get().getTorrent(infoHash).tfsData.extensions.get("html"); if (ext == null) throw new WebApplicationException(400); URI uri = UriBuilder.fromUri("/ext/html/static/" + infoHash + "/" + ext.index).build(); return Response.seeOther(uri).build(); } }
33
117
0.741765
853b3f8c86271aaf1829f0d3f1fbc02519853a4d
4,456
/* * Kodkod -- Copyright (c) 2005-present, Emina Torlak * * 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 kodkod.engine.bool; import java.util.Iterator; import java.util.NoSuchElementException; import kodkod.util.ints.Ints; /** * A logic NOT gate. * * @invariant this.op = Operator.NOT * @invariant #inputs = 1 * @invariant this.label = -inputs.label * @invariant label in (-Integer.MAX_VALUE..-1] * @author Emina Torlak */ public final class NotGate extends BooleanFormula { private final int hashcode; /** * Constructs a new NotGate with the given formula as its input. * * @requires input != null && input !in NotGate * @ensures this.inputs' = 0->input && this.output'.label = -input.label */ NotGate(BooleanFormula input) { super(input); this.hashcode = Ints.superFastHash(-input.label()); } /** * Returns a hash of this inverter's label. * * @return Ints.superFastHash(this.label) */ @Override public int hash(Operator op) { return hashcode; } /** * Returns an iterator that returns this gate's single input. * * @return an iterator over this.inputs. */ @Override public Iterator<BooleanFormula> iterator() { return new Iterator<BooleanFormula>() { boolean hasNext = true; @Override public boolean hasNext() { return hasNext; } @Override public BooleanFormula next() { if (!hasNext) throw new NoSuchElementException(); hasNext = false; return negation(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * Returns the label for this value. * * @return this.label */ @Override public final int label() { return -negation().label(); } /** * Returns 1. * * @return 1. */ @Override public int size() { return 1; } /** * Passes this value and the given argument value to the visitor, and returns * the resulting value. * * @return the value produced by the visitor when visiting this node with the * given argument. */ @Override public <T, A> T accept(BooleanVisitor<T,A> visitor, A arg) { return visitor.visit(this, arg); } /** * Returns a string representation of this inverter. * * @return a string representation of this inverter. */ @Override public String toString() { return "!" + negation().toString(); } /** * Returns Operator.NOT. * * @return Operator.NOT */ @Override public kodkod.engine.bool.Operator op() { return kodkod.engine.bool.Operator.NOT; } /** * Returns this.input[i]. * * @return this.input[i] * @throws IndexOutOfBoundsException i != 0 */ @Override public BooleanFormula input(int i) { if (i != 0) throw new IndexOutOfBoundsException(); return negation(); } /** * Returns a hashcode for this inverter. * * @return a hashcode for this inverter. */ @Override public int hashCode() { return hashcode; } }
26.211765
81
0.607271
90fcf71bbfd8883f4e9040e10762530b69ddd45c
1,946
package de.endrullis.idea.postfixtemplatesgenerator; import java.util.Comparator; import lombok.*; import static cn.hutool.core.util.ClassUtil.*; import static com.google.common.collect.ImmutableSortedSet.*; import static java.lang.System.*; import static java.lang.reflect.Modifier.isPublic; import static java.lang.reflect.Modifier.isStatic; import static java.util.Comparator.*; import static java.util.stream.Collectors.*; import static java.util.stream.Stream.*; public class Main { public static void main(String[] args) { scan("cn.hutool","com.google.common"); } private static void scan(String... packages) { for (String pack : packages) { val classes = scanPackage(pack, Main::filter); Comparator<Class<?>> comparator1 = comparing(v -> v.getTypeName().contains(".util.")); Comparator<Class<?>> comparator2 = comparing(v -> v.getTypeName().contains("Util")); Comparator<Class<?>> comparator3 = comparing(Class::getTypeName); val result = copyOf(comparator1.thenComparing(comparator2).thenComparing(comparator3).reversed(), classes); result.forEach(Main::println); out.println(); } } private static boolean filter(Class<?> clazz) { if (clazz.isEnum() || clazz.isAnnotation() || clazz.isAnnotationPresent(Deprecated.class) || !isPublic(clazz.getModifiers()) || isStatic(clazz.getModifiers())) return false; val publicMethods = getPublicMethods(clazz, method -> isStatic(method.getModifiers())); return !publicMethods.isEmpty(); } private static void println(Class<?> clazz) { val length = clazz.getTypeParameters().length; if (length == 0) { out.println("classOf[" + clazz.getTypeName() + "],"); } else { val generic = generate(() -> "_").limit(length).collect(joining(",", "[", "]")); out.println("classOf[" + clazz.getTypeName() + generic + "],"); } } }
38.156863
133
0.668551
07d7b3429b4e78b449669666c6c0453bb2a9468a
13,919
package com.company; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.time.format.DateTimeFormatter; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; public class Tournament { final static UI ui = new UI(); static final DateTimeFormatter myDateTimeFormat = DateTimeFormatter.ofPattern("dd-MM-yy HH:mm"); static final DateTimeFormatter myDateFormat = DateTimeFormatter.ofPattern("dd-MM-yy"); static private int idCounter; private int id; private String name; private String sport; private String tournamentMode; private LocalDateTime signUpDeadline; private ArrayList<LocalDate> gameDates = new ArrayList<LocalDate>(); private ArrayList<Team> teams = new ArrayList<Team>(); private ArrayList<Match> matches = new ArrayList<Match>(); // For tournaments created by user public Tournament(String name, String sport, String tournamentMode, String signUpDeadline) { this.id = idCounter; this.name = name; this.sport = sport; this.tournamentMode = tournamentMode; this.signUpDeadline = LocalDateTime.parse(signUpDeadline, myDateTimeFormat); idCounter++; } // For tournaments created from data public Tournament(int id, String name, String sport, String tournamentMode, String signUpDeadline) { this.id = id; this.name = name; this.sport = sport; this.tournamentMode = tournamentMode; this.signUpDeadline = LocalDateTime.parse(signUpDeadline, myDateTimeFormat); } // ******************** Getter and Setter-ish ******************* public static int getIdCounter(){ return idCounter; } public static void setIdCounter(int idCounterFromData){ idCounter = idCounterFromData; } public int getId(){ return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSport() { return sport; } public void setSport(String sport) { this.sport = sport; } public String getTournamentMode() { return tournamentMode; } public void setTournamentMode(String tournamentMode) { this.tournamentMode = tournamentMode; } public LocalDateTime getSignUpDeadline() { return signUpDeadline; } public void setSignUpDeadline(LocalDateTime signUpDeadline) { this.signUpDeadline = signUpDeadline; } public ArrayList<LocalDate> getGameDates(){ return gameDates; } public void addGameDates(String dateToAdd){ gameDates.add(LocalDate.parse(dateToAdd, myDateFormat)); } public ArrayList<Team> getTeams() { return teams; } public void addTeam(Team team){ teams.add(team); } // ***************** Getter and Setter-ish END ******************* // *********************** Other methods ************************* public void displayTeamRankings(){ ArrayList<Team> rankings = new ArrayList<Team>(); for(Team team : teams){ rankings.add(team); } // Team teamWithHighestPoint = rankings.get(0); // // for(int i = 0; i < rankings.size(); i++){ // for(int j = 1; j < (rankings.size() - i); j++){ // if(rankings.get(j-1).getPoint() > rankings.get(j).getPoint()){ // //swap elements // teamWithHighestPoint = rankings.get(j-1); // rankings.add(j-1, rankings.get(j)); // rankings.add(j, teamWithHighestPoint); // } // // } // } int rankCounter = 1; for(Team team : rankings){ System.out.println(rankCounter + ") " + team.getName() + ": " + team.getPoint() + " points"); rankCounter++; } } // ********************* Other methods END *********************** // ********************** Static methods ************************* public static void readTournamentData(String filePath){ try{ File tournamentsDir = new File(filePath); String tournamentsDirContent[] = tournamentsDir.list(); for(int i = 0; i<tournamentsDirContent.length; i++) { File tournamentData = new File(filePath + "/" + tournamentsDirContent[i] + "/tournamentData.txt"); Scanner scanner = new Scanner(tournamentData); String[] tournamentLine; while(scanner.hasNextLine()) { String line = scanner.nextLine(); tournamentLine = line.split(","); int id = Integer.parseInt(tournamentLine[1]); String name = tournamentLine[3]; String sport = tournamentLine[5]; String tournamentMode = tournamentLine[7]; String signUpDeadline = tournamentLine[9]; Main.tournaments.add(new Tournament(id, name, sport, tournamentMode, signUpDeadline)); // Adds dateAndTimes data to the corresponding tournament readTournamentGameDateData(filePath, Main.tournaments.get(i)); readTournamentTeamData(filePath, Main.tournaments.get(i)); } scanner.close(); } }catch(IOException e){ System.out.println(e); } } public static void readTournamentGameDateData(String filePath, Tournament tournament){ try{ File tournamentsDir = new File(filePath); File gameDateData = new File(filePath + "/" + tournament.getName() + "/gameDateData.txt"); Scanner scanner = new Scanner(gameDateData); String[] gameDateLines; while(scanner.hasNextLine()) { String line = scanner.nextLine(); gameDateLines = line.split(","); for(String gameDateLine : gameDateLines){ tournament.addGameDates(gameDateLine); } } scanner.close(); }catch(IOException e){ System.out.println(e); } } public static void readTournamentTeamData(String filePath, Tournament tournament){ try{ File tournamentsDir = new File(filePath); File teamData = new File(filePath + "/" + tournament.getName() + "/teamData.txt"); Scanner scanner = new Scanner(teamData); String[] teamLines; while(scanner.hasNextLine()) { String line = scanner.nextLine(); teamLines = line.split(","); int id = Integer.parseInt(teamLines[1]); String name = teamLines[3]; boolean stillInTournament = Boolean.parseBoolean(teamLines[5]); int point = Integer.parseInt(teamLines[7]); int goalsMade = Integer.parseInt(teamLines[9]); int opposingTeamsGoals = Integer.parseInt(teamLines[11]); tournament.teams.add(new Team(id, name, stillInTournament, point, goalsMade, opposingTeamsGoals)); } scanner.close(); }catch(IOException e){ System.out.println(e); } } public static void saveTournamentData(String filePath, String fileName, String data){ String fileData = data; try{ Main.createNewDir(filePath, fileName); File file = new File(filePath + "/" + fileName + "/tournamentData.txt"); FileWriter fileWriter = new FileWriter(file, false); fileWriter.write(data); fileWriter.close(); }catch (IOException e){ System.out.println(e.getCause()); } } public static void registerNewTournament(){ ui.displayMsg("\n(REGISTER NEW TOURNAMENT)"); String name = ui.getUserInput("\nTournament name:"); String sport = ui.getUserInput("Sport:"); String mode = ui.getUserInput("Tournament mode (knock-out or group):"); String signUpDeadline = ui.getUserInput("Signup deadline (dd-MM-yy HH:mm):"); Tournament tournament = new Tournament(name, sport, mode, signUpDeadline); Main.tournaments.add(tournament); ui.displayMsg("\nNew tournament has been registered!"); Main.saveIdCounterData("src/data/idCounters/idCounter_Tournament.txt", "ID:" + Tournament.getIdCounter()); saveTournamentData("src/data/tournaments", name, tournament.toString()); Main.saveData("src/data/tournaments/" + name + "/gameDateData.txt", ""); Main.saveData("src/data/tournaments/" + name + "/teamData.txt", ""); String willAddDateAndTimesNow = ui.getUserInput("\nWould you like to add game dates now? (y/n):").toLowerCase(); if(willAddDateAndTimesNow.equals("y")){ ui.displayMsg("\n(ADD GAME DATE)"); ui.displayMsg("\nWrite the game date you would like to add to the tournament"); ui.displayMsg("Type -1 to end\n"); boolean stillAdding = true; while(stillAdding){ String date = ui.getUserInput("Date (dd-MM-yy): "); if(date.equals("-1")){ ui.displayMsg("\nAll game dates has now been saved"); stillAdding = false; return; }else{ tournament.addGameDates(date); Main.saveData("src/data/tournaments/" + name + "/gameDateData.txt", date + "\n"); } } } } public static void displayAllTournaments(){ for(Tournament tournament : Main.tournaments){ System.out.println("- " + tournament.getName() + " (ID: " + tournament.getId() + ")"); } } public static Tournament findTournament(int id){ Tournament tournamentMatch = null; for(Tournament tournament : Main.tournaments){ if(tournament.getId() == id){ tournamentMatch = tournament; break; } } return tournamentMatch; } public static void displayTeamRankings(Tournament tournament){ ArrayList<Team> rankings = new ArrayList<Team>(); for(Team team : tournament.getTeams()){ rankings.add(team); } int n = rankings.size(); for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (rankings.get(j).getPoint() < rankings.get(j+1).getPoint()) { // swap arr[j+1] and arr[j] Team temp = rankings.get(j); rankings.set(j, rankings.get(j+1)); rankings.set(j+1, temp); } int rankCounter = 1; for(Team team : rankings){ System.out.println(rankCounter + ") " + team.getName() + ": " + team.getPoint() + " points"); rankCounter++; } } public static ArrayList<LocalDate> showGameDates(Tournament tournament){ ArrayList<LocalDate> gameDates = tournament.gameDates; return gameDates; } public static void deleteTournament(){ ui.displayMsg("\n(DELETE TOURNAMENT)"); ui.displayMsg("\nTournaments currently in the system: "); if(Main.tournaments.size() != 0){ displayAllTournaments(); String userInput = ui.getUserInput("\nType the ID of the tournament you " + "would like to delete\nType -1 to cancel: "); if(!userInput.equals("-1")){ int tournamentId = Integer.parseInt(userInput); Tournament tournamentToBeDeleted = findTournament(tournamentId); if(tournamentToBeDeleted != null){ File fileToBeDeleted = new File("src/data/tournaments/" + tournamentToBeDeleted.getName()); Main.deleteFolder(fileToBeDeleted); Main.tournaments.remove(findTournament(tournamentId)); ui.displayMsg("\nThe tournament was successfully deleted!"); }else{ ui.displayMsg("\nNo tournament matching the provided id could be found in the system..."); } } }else{ ui.displayMsg("There are currently no tournaments registered in the system..."); } } // ******************** Static methods END *********************** public void randomTeamsToMatch(){ int amountOfTeams = teams.size(); ArrayList<Integer> randDone = new ArrayList<>(); if(amountOfTeams < 2) { System.out.println("You need at least 2 teams to start a match"); }else if(amountOfTeams % 2 != 0){ System.out.println("You have an uneven number of teams"); }else if(amountOfTeams == 2){ Team[] matchTeams = {teams.get(0), teams.get(1)}; Match m = new Match(matchTeams); saveMatchesToFile(m); }else{ Random rand = new Random(); while(randDone.size() < amountOfTeams){ int r1 = rand.nextInt(amountOfTeams - 0) + 0; int r2 = rand.nextInt(amountOfTeams - 0) + 0; boolean result = randDone.contains(r1); boolean result2 = randDone.contains(r2); if(result == false && result2 == false && r2 != r1){ randDone.add(r1); randDone.add(r2); Team[] matchTeams = {teams.get(r1), teams.get(r2)}; Match m = new Match(matchTeams); saveMatchesToFile(m); } } } } public void saveMatchesToFile(Match data){ try{ File file = new File("src/data/matches/matchesBetween.txt"); FileWriter fr = new FileWriter(file, true); String myData = data.toString() + "\n"; fr.write(myData); fr.close(); Main.printTournamentData(file); }catch (IOException e){ System.out.println(e.getCause()); } } @Override public String toString(){ return "ID," + this.id + "," + "Name," + this.name + "," + "Sport," + this.sport + "," + "Tournament mode," + this.tournamentMode + "," + "SignUp deadline," + this.signUpDeadline.format(myDateTimeFormat); } }
32.905437
118
0.591063
3352f71aa85c150ec63024664f683bb10825e7e3
1,177
package com.haulmont.sample.petclinic.service; import com.haulmont.sample.petclinic.entity.visit.VisitType; import java.io.Serializable; import java.time.LocalDateTime; public class VisitCreation implements Serializable { private final LocalDateTime visitStart; private final LocalDateTime visitEnd; private final String petIdentificationNumber; private final VisitType type; private final String description; public VisitCreation(LocalDateTime visitStart, LocalDateTime visitEnd, String petIdentificationNumber, VisitType type, String description) { this.visitStart = visitStart; this.visitEnd = visitEnd; this.petIdentificationNumber = petIdentificationNumber; this.type = type; this.description = description; } public LocalDateTime getVisitStart() { return visitStart; } public LocalDateTime getVisitEnd() { return visitEnd; } public String getPetIdentificationNumber() { return petIdentificationNumber; } public VisitType getType() { return type; } public String getDescription() { return description; } }
26.155556
77
0.713679
e3486721853e3a40f056023ea22a655d337a0ca2
3,049
/* * Copyright 2002-2021 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.security.saml2.provider.service.web.authentication.logout; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link OpenSaml3LogoutRequestResolver} */ public class OpenSaml3LogoutRequestResolverTests { RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); @Test public void resolveWhenCustomParametersConsumerThenUses() { OpenSaml3LogoutRequestResolver logoutRequestResolver = new OpenSaml3LogoutRequestResolver( this.relyingPartyRegistrationResolver); logoutRequestResolver.setParametersConsumer((parameters) -> parameters.getLogoutRequest().setID("myid")); HttpServletRequest request = new MockHttpServletRequest(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutRequest logoutRequest = logoutRequestResolver.resolve(request, authentication); assertThat(logoutRequest.getId()).isEqualTo("myid"); } @Test public void setParametersConsumerWhenNullThenIllegalArgument() { OpenSaml3LogoutRequestResolver logoutRequestResolver = new OpenSaml3LogoutRequestResolver( this.relyingPartyRegistrationResolver); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> logoutRequestResolver.setParametersConsumer(null)); } }
46.19697
114
0.827156
53df3a98bf4e9b8adba75bc38b6125a49fdc1a32
360
package tf.ssf.sfort.lessclutter.mixin.access; import net.minecraft.client.gui.widget.TexturedButtonWidget; import net.minecraft.util.Identifier; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; @Mixin(TexturedButtonWidget.class) public interface TextButton { @Accessor("texture") Identifier getTexture(); }
27.692308
60
0.805556
8368cb8ff6a3f3fc1821fefbb53fd218faeab870
19,210
package vn.zalopay.benchmark; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.google.protobuf.Descriptors; import kg.apc.jmeter.JMeterPluginsUtils; import kg.apc.jmeter.gui.BrowseAction; import kg.apc.jmeter.gui.GuiBuilderHelper; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.gui.util.HorizontalPanel; import org.apache.jmeter.gui.util.JSyntaxTextArea; import org.apache.jmeter.gui.util.JTextScrollPane; import org.apache.jmeter.gui.util.VerticalPanel; import org.apache.jmeter.samplers.gui.AbstractSamplerGui; import org.apache.jmeter.testelement.TestElement; import org.apache.jorphan.gui.JLabeledTextField; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import vn.zalopay.benchmark.core.ClientList; import vn.zalopay.benchmark.core.protobuf.ProtoMethodName; import vn.zalopay.benchmark.core.protobuf.ServiceResolver; import vn.zalopay.benchmark.util.JMeterVariableUtils; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.List; import java.util.UUID; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; public class GRPCSamplerGui extends AbstractSamplerGui { private static final Logger log = LoggerFactory.getLogger(GRPCSamplerGui.class); private static final long serialVersionUID = 240L; private static final String WIKI_PAGE = "https://github.com/zalopay-oss/jmeter-grpc-request"; private GRPCSampler grpcSampler; private String[] protoMethods; private JTextField protoFolderField; private JButton protoBrowseButton; private JTextField libFolderField; private JButton libBrowseButton; private JComboBox<String> fullMethodField; private JButton fullMethodButton; private JTextField metadataField; private JLabeledTextField hostField; private JLabeledTextField portField; private JLabeledTextField deadlineField; private JLabeledTextField protocVersionField; private JCheckBox isTLSCheckBox; private JCheckBox isTLSDisableVerificationCheckBox; private JSyntaxTextArea requestJsonArea; public GRPCSamplerGui() { super(); initGui(); initGuiValues(); } @Override public String getLabelResource() { return "grpc_sampler_title"; // $NON-NLS-1$ } @Override public String getStaticLabel() { return "GRPC Request"; } @Override public TestElement createTestElement() { grpcSampler = new GRPCSampler(); modifyTestElement(grpcSampler); return grpcSampler; } @Override public void modifyTestElement(TestElement element) { configureTestElement(element); if (!(element instanceof GRPCSampler)) { return; } grpcSampler = (GRPCSampler) element; grpcSampler.setProtoFolder(this.protoFolderField.getText()); grpcSampler.setLibFolder(this.libFolderField.getText()); grpcSampler.setMetadata(this.metadataField.getText()); grpcSampler.setHost(this.hostField.getText()); grpcSampler.setPort(this.portField.getText()); grpcSampler.setFullMethod(this.fullMethodField.getSelectedItem().toString()); grpcSampler.setDeadline(this.deadlineField.getText()); grpcSampler.setProtocVersion(this.protocVersionField.getText()); grpcSampler.setTls(this.isTLSCheckBox.isSelected()); grpcSampler.setTlsDisableVerification(this.isTLSDisableVerificationCheckBox.isSelected()); grpcSampler.setRequestJson(this.requestJsonArea.getText()); } @Override public void configure(TestElement element) { super.configure(element); if (!(element instanceof GRPCSampler)) { return; } grpcSampler = (GRPCSampler) element; protoFolderField.setText(grpcSampler.getProtoFolder()); libFolderField.setText(grpcSampler.getLibFolder()); metadataField.setText(grpcSampler.getMetadata()); protocVersionField.setText(grpcSampler.getProtocVersion()); hostField.setText(grpcSampler.getHost()); portField.setText(grpcSampler.getPort()); fullMethodField.setSelectedItem(grpcSampler.getFullMethod()); deadlineField.setText(grpcSampler.getDeadline()); isTLSCheckBox.setSelected(grpcSampler.isTls()); isTLSDisableVerificationCheckBox.setSelected(grpcSampler.isTlsDisableVerification()); requestJsonArea.setText(grpcSampler.getRequestJson()); } @Override public void clearGui() { super.clearGui(); initGuiValues(); } private void initGuiValues() { protoFolderField.setText(""); libFolderField.setText(""); metadataField.setText(""); protocVersionField.setText(""); hostField.setText(""); portField.setText(""); fullMethodField.setSelectedItem(""); deadlineField.setText("1000"); isTLSCheckBox.setSelected(false); isTLSDisableVerificationCheckBox.setSelected(false); requestJsonArea.setText(""); } private void initGui() { setLayout(new BorderLayout(0, 5)); setBorder(makeBorder()); // TOP panel Container topPanel = makeTitlePanel(); add(JMeterPluginsUtils.addHelpLinkToPanel(topPanel, WIKI_PAGE), BorderLayout.NORTH); add(topPanel, BorderLayout.NORTH); // MAIN panel JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); mainPanel.add(getWebServerPanel()); mainPanel.add(getGRPCRequestPanel()); mainPanel.add(getOptionConfigPanel()); mainPanel.add(getRequestJSONPanel()); add(mainPanel, BorderLayout.CENTER); } /** * Helper function */ private void addToPanel(JPanel panel, GridBagConstraints constraints, int col, int row, JComponent component) { constraints.gridx = col; constraints.gridy = row; panel.add(component, constraints); } private JPanel getWebServerPanel() { portField = new JLabeledTextField("Port Number:", 3); // $NON-NLS-1$ hostField = new JLabeledTextField("Server Name or IP:", 11); // $NON-NLS-1$ isTLSCheckBox = new JCheckBox("SSL/TLS"); isTLSDisableVerificationCheckBox = new JCheckBox("Disable SSL/TLS Cert Verification"); JPanel webServerPanel = new VerticalPanel(); webServerPanel.setBorder(BorderFactory.createTitledBorder("Web Server")); // $NON-NLS-1$ JPanel webserverHostPanel = new HorizontalPanel(); webserverHostPanel.add(hostField); webserverHostPanel.add(portField); JPanel webserverOtherPanel = new HorizontalPanel(); webserverOtherPanel.add(isTLSCheckBox); webserverOtherPanel.add(isTLSDisableVerificationCheckBox); webServerPanel.add(webserverHostPanel); webServerPanel.add(webserverOtherPanel); return webServerPanel; } private JPanel getRequestJSONPanel() { requestJsonArea = JSyntaxTextArea.getInstance(30, 50); requestJsonArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JSON); requestJsonArea.setBracketMatchingEnabled(true); requestJsonArea.setPaintMatchedBracketPair(true); requestJsonArea.setAutoIndentEnabled(true); requestJsonArea.setMarkOccurrences(true); requestJsonArea.setPaintMarkOccurrencesBorder(true); requestJsonArea.setPaintTabLines(true); requestJsonArea.setShowMatchedBracketPopup(true); JPanel webServerPanel = new JPanel(new BorderLayout()); webServerPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(9, 0, 0, 0), BorderFactory.createTitledBorder("Send JSON Format With the Request") )); JTextScrollPane syntaxPanel = JTextScrollPane.getInstance(requestJsonArea); webServerPanel.add(syntaxPanel); return webServerPanel; } private JPanel getOptionConfigPanel() { JLabel metadataLabel = new JLabel("Metadata:"); metadataField = new JTextField("Metadata", 32); // $NON-NLS-1$ deadlineField = new JLabeledTextField("Deadline:", 7); // $NON-NLS-1$ protocVersionField = new JLabeledTextField("Protoc Version:", 4); JPanel webServerPanel = new HorizontalPanel(); webServerPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(9, 0, 0, 0), BorderFactory.createTitledBorder("Optional Configuration") )); webServerPanel.add(metadataLabel); webServerPanel.add(metadataField); webServerPanel.add(deadlineField); webServerPanel.add(protocVersionField); return webServerPanel; } private JPanel getGRPCRequestPanel() { JPanel requestPanel = new JPanel(new GridBagLayout()); GridBagConstraints labelConstraints = new GridBagConstraints(); labelConstraints.anchor = GridBagConstraints.FIRST_LINE_END; GridBagConstraints editConstraints = new GridBagConstraints(); editConstraints.anchor = GridBagConstraints.FIRST_LINE_START; editConstraints.weightx = 1.0; editConstraints.fill = GridBagConstraints.HORIZONTAL; // Proto folder int row = 0; addToPanel(requestPanel, labelConstraints, 0, row, new JLabel("Proto Root Directory: ", JLabel.RIGHT)); addToPanel(requestPanel, editConstraints, 1, row, protoFolderField = new JTextField(20)); addToPanel(requestPanel, labelConstraints, 2, row, protoBrowseButton = new JButton("Browse...")); row++; GuiBuilderHelper.strechItemToComponent(protoFolderField, protoBrowseButton); editConstraints.insets = new java.awt.Insets(2, 0, 0, 0); labelConstraints.insets = new java.awt.Insets(2, 0, 0, 0); protoBrowseButton.addActionListener(new BrowseAction(protoFolderField, true)); // Lib folder addToPanel(requestPanel, labelConstraints, 0, row, new JLabel("Library Directory (Optional): ", JLabel.RIGHT)); addToPanel(requestPanel, editConstraints, 1, row, libFolderField = new JTextField(20)); addToPanel(requestPanel, labelConstraints, 2, row, libBrowseButton = new JButton("Browse...")); row++; GuiBuilderHelper.strechItemToComponent(libFolderField, libBrowseButton); editConstraints.insets = new java.awt.Insets(2, 0, 0, 0); labelConstraints.insets = new java.awt.Insets(2, 0, 0, 0); libBrowseButton.addActionListener(new BrowseAction(libFolderField, true)); // Full method addToPanel(requestPanel, labelConstraints, 0, row, new JLabel("Full Method: ", JLabel.RIGHT)); addToPanel(requestPanel, editConstraints, 1, row, fullMethodField = new JComboBox<>()); fullMethodField.setEditable(true); fullMethodField.setMaximumRowCount(12); addToPanel(requestPanel, labelConstraints, 2, row, fullMethodButton = new JButton("Listing...")); fullMethodButton.addActionListener(new ActionListener() { // fullMethodButton click listener @Override public void actionPerformed(ActionEvent e) { reloadProtoMethods(); } }); fullMethodField.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } // fullMethod list checked listener @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { // Request Mock Auto Create requestMock(); } @Override public void popupMenuCanceled(PopupMenuEvent e) { } }); fullMethodField.addActionListener(new ActionListener() { // fullMethod edit enter listener @Override public void actionPerformed(ActionEvent e) { if ("comboBoxEdited".equals(e.getActionCommand())) { // fullMethodField Drop - down box edit auto-complement String fullMethod = fullMethodField.getSelectedItem().toString(); if (StringUtils.isBlank(fullMethod)) { return; } String[] protoMethods = getProtoMethods(false); try { for (String protoMethod : protoMethods) { boolean startsWith = protoMethod.startsWith(fullMethod); if (startsWith == true) { fullMethodField.setSelectedItem(protoMethod); if (protoMethod.equals(fullMethod) == false) { fullMethodField.showPopup(); } break; } } } catch (Exception ex) { ex.printStackTrace(); } // Request Mock Auto Create requestMock(); } } }); // Container JPanel container = new JPanel(new BorderLayout()); container.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(9, 0, 0, 0), BorderFactory.createTitledBorder("GRPC Request") )); container.add(requestPanel, BorderLayout.NORTH); return container; } private void reloadProtoMethods() { Object selectedItem = fullMethodField.getSelectedItem(); getProtoMethods(true); try { if (selectedItem != null && StringUtils.isBlank(selectedItem.toString())) { selectedItem = fullMethodField.getSelectedItem(); } fullMethodField.setSelectedItem(selectedItem); } catch (Exception e) { fullMethodField.setSelectedIndex(0); } finally { fullMethodField.showPopup(); } } private String[] getProtoMethods(boolean reload) { if (StringUtils.isNotBlank(grpcSampler.getProtoFolder()) && (ArrayUtils.isEmpty(protoMethods) || reload == true)) { JMeterVariableUtils.undoVariableReplacement(grpcSampler); ServiceResolver serviceResolver = ClientList.getServiceResolver(grpcSampler.getProtoFolder(), grpcSampler.getLibFolder(), reload, grpcSampler.getProtocVersion()); List<String> methodList = ClientList.listServices(serviceResolver); protoMethods = new String[methodList.size()]; methodList.toArray(protoMethods); Arrays.sort(protoMethods); fullMethodField.setModel(new DefaultComboBoxModel<>(protoMethods)); log.info("Full Methods Length: {}", protoMethods.length); } return protoMethods; } private void requestMock() { try { if (StringUtils.isNotBlank(requestJsonArea.getText())) { return; } String fullMethod = fullMethodField.getSelectedItem().toString(); ProtoMethodName grpcMethodName = ProtoMethodName.parseFullGrpcMethodName(fullMethod); JMeterVariableUtils.undoVariableReplacement(grpcSampler); ServiceResolver serviceResolver = ClientList.getServiceResolver(grpcSampler.getProtoFolder(), grpcSampler.getLibFolder(), grpcSampler.getProtocVersion()); Descriptors.MethodDescriptor methodDescriptor = serviceResolver.resolveServiceMethod(grpcMethodName); if (methodDescriptor != null) { Descriptors.Descriptor inputType = methodDescriptor.getInputType(); List<Descriptors.FieldDescriptor> fields = inputType.getFields(); JSONObject requestBody = new JSONObject(true); for (Descriptors.FieldDescriptor field : fields) { String name = field.getName(); Object defaultValue = getMockValue(field); requestBody.put(name, defaultValue); } String text = requestBody.toString( SerializerFeature.PrettyFormat, // Formatting Json String SerializerFeature.WriteMapNullValue, // Outputs Null values SerializerFeature.WriteNullListAsEmpty // Null List output is [] ); requestJsonArea.setText(text); } } catch (Exception ex) { log.error("request mock error", ex); } } private Object getMockValue(Descriptors.FieldDescriptor field) { String name = field.getName(); String type = field.getType().name().toLowerCase(); if ("message".equals(type)) { List<Descriptors.FieldDescriptor> fields = field.getMessageType().getFields(); JSONObject repeatedField = new JSONObject(true); for (Descriptors.FieldDescriptor repeatedFieldDescriptor : fields) { repeatedField.put(repeatedFieldDescriptor.getName(), this.getMockValue(repeatedFieldDescriptor)); } return repeatedField; } else { return getMockDefaultValue(name, type); } } private Object getMockDefaultValue(String name, String type) { switch (type) { case "string": return fieldNameGenerateMock(name); case "bool": return true; case "number": case "int32": return 10; case "int64": return 20; case "uint32": case "uint64": case "sint32": return 100; case "sint64": return 1200; case "fixed32": return 1400; case "fixed64": return 1500; case "sfixed32": return 1600; case "sfixed64": return 1700; case "float": return 1.1; case "double": return 1.4; case "bytes": return "Hello"; default: return null; } } /** * Mock generation from fieldName. * * <p>Default: Hello</p> */ private String fieldNameGenerateMock(String fieldName) { String fieldNameLower = fieldName.toLowerCase(); if (fieldNameLower.startsWith("id") || fieldNameLower.endsWith("id")) { return UUID.randomUUID().toString(); } return "Hello"; } }
39.93763
174
0.643259
18ba401bb9ec4965198be067fbd63c8f0d89393b
6,354
/** * Copyright (C) 2012 - 2016 Alessandro Vurro. * * 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.googlecode.jmapper.enums; /** * Enumeration that containts all conversion between primitive types. * @author Alessandro Vurro * */ public enum ConversionType { // ... TO STRING FromByteToString, FrombyteToString, FromShortToString, FromshortToString, FromintToString, FromIntegerToString, FromlongToString, FromLongToString, FromfloatToString, FromFloatToString, FromdoubleToString, FromDoubleToString, FromcharToString, FromCharacterToString, FrombooleanToString, FromBooleanToString, // FROM STRING TO OTHERS... FromStringTobyte, FromStringToByte, FromStringToshort, FromStringToShort, FromStringToint, FromStringToInteger, FromStringTolong, FromStringToLong, FromStringTofloat, FromStringToFloat, FromStringTodouble, FromStringToDouble, FromStringTochar, FromStringToCharacter, FromStringToboolean, FromStringToBoolean, // FROM BYTE TO OTHERS... FromByteToshort, FromByteToShort, FromByteToint, FromByteToInteger, FromByteTolong, FromByteToLong, FromByteTofloat, FromByteToFloat, FromByteTodouble, FromByteToDouble, FromByteTochar, FromByteToCharacter, FromByteToboolean, FromByteToBoolean, FrombyteToshort, FrombyteToShort, FrombyteToint, FrombyteToInteger, FrombyteTolong, FrombyteToLong, FrombyteTofloat, FrombyteToFloat, FrombyteTodouble, FrombyteToDouble, FrombyteTochar, FrombyteToCharacter, FrombyteToboolean, FrombyteToBoolean, // FROM SHORT TO OTHERS... FromShortTobyte, FromShortToByte, FromShortToint, FromShortToInteger, FromShortTolong, FromShortToLong, FromShortTofloat, FromShortToFloat, FromShortTodouble, FromShortToDouble, FromShortTochar, FromShortToCharacter, FromShortToboolean, FromShortToBoolean, FromshortTobyte, FromshortToByte, FromshortToint, FromshortToInteger, FromshortTolong, FromshortToLong, FromshortTofloat, FromshortToFloat, FromshortTodouble, FromshortToDouble, FromshortTochar, FromshortToCharacter, FromshortToboolean, FromshortToBoolean, // FROM INTEGER/INT TO OTHERS... FromIntegerTobyte, FromIntegerToByte, FromIntegerToshort, FromIntegerToShort, FromIntegerTolong, FromIntegerToLong, FromIntegerTofloat, FromIntegerToFloat, FromIntegerTodouble, FromIntegerToDouble, FromIntegerTochar, FromIntegerToCharacter, FromIntegerToboolean, FromIntegerToBoolean, FromintTobyte, FromintToByte, FromintToshort, FromintToShort, FromintTolong, FromintToLong, FromintTofloat, FromintToFloat, FromintTodouble, FromintToDouble, FromintTochar, FromintToCharacter, FromintToboolean, FromintToBoolean, // FROM LONG TO OTHERS... FromLongTobyte, FromLongToByte, FromLongToshort, FromLongToShort, FromLongToint, FromLongToInteger, FromLongTofloat, FromLongToFloat, FromLongTodouble, FromLongToDouble, FromLongTochar, FromLongToCharacter, FromLongToboolean, FromLongToBoolean, FromlongTobyte, FromlongToByte, FromlongToshort, FromlongToShort, FromlongToint, FromlongToInteger, FromlongTofloat, FromlongToFloat, FromlongTodouble, FromlongToDouble, FromlongTochar, FromlongToCharacter, FromlongToboolean, FromlongToBoolean, // FROM FLOAT TO OTHERS... FromFloatTobyte, FromFloatToByte, FromFloatToshort, FromFloatToShort, FromFloatToint, FromFloatToInteger, FromFloatTolong, FromFloatToLong, FromFloatTodouble, FromFloatToDouble, FromFloatTochar, FromFloatToCharacter, FromFloatToboolean, FromFloatToBoolean, FromfloatTobyte, FromfloatToByte, FromfloatToshort, FromfloatToShort, FromfloatToint, FromfloatToInteger, FromfloatTolong, FromfloatToLong, FromfloatTodouble, FromfloatToDouble, FromfloatTochar, FromfloatToCharacter, FromfloatToboolean, FromfloatToBoolean, // FROM DOUBLE TO OTHERS... FromDoubleTobyte, FromDoubleToByte, FromDoubleToshort, FromDoubleToShort, FromDoubleToint, FromDoubleToInteger, FromDoubleTolong, FromDoubleToLong, FromDoubleTofloat, FromDoubleToFloat, FromDoubleTochar, FromDoubleToCharacter, FromDoubleToboolean, FromDoubleToBoolean, FromdoubleTobyte, FromdoubleToByte, FromdoubleToshort, FromdoubleToShort, FromdoubleToint, FromdoubleToInteger, FromdoubleTolong, FromdoubleToLong, FromdoubleTofloat, FromdoubleToFloat, FromdoubleTochar, FromdoubleToCharacter, FromdoubleToboolean, FromdoubleToBoolean, // FROM CHARACTER/CHAR TO OTHERS... FromCharacterTobyte, FromCharacterToByte, FromCharacterToshort, FromCharacterToShort, FromCharacterToint, FromCharacterToInteger, FromCharacterTolong, FromCharacterToLong, FromCharacterTofloat, FromCharacterToFloat, FromCharacterTodouble, FromCharacterToDouble, FromCharacterToboolean, FromCharacterToBoolean, FromcharTobyte, FromcharToByte, FromcharToshort, FromcharToShort, FromcharToint, FromcharToInteger, FromcharTolong, FromcharToLong, FromcharTofloat, FromcharToFloat, FromcharTodouble, FromcharToDouble, FromcharToboolean, FromcharToBoolean, // FROM BOOLEAN TO OTHERS... FromBooleanTobyte, FromBooleanToByte, FromBooleanToshort, FromBooleanToShort, FromBooleanToint, FromBooleanToInteger, FromBooleanTolong, FromBooleanToLong, FromBooleanTofloat, FromBooleanToFloat, FromBooleanTodouble, FromBooleanToDouble, FromBooleanTochar, FromBooleanToCharacter, FrombooleanTobyte, FrombooleanToByte, FrombooleanToshort, FrombooleanToShort, FrombooleanToint, FrombooleanToInteger, FrombooleanTolong, FrombooleanToLong, FrombooleanTofloat, FrombooleanToFloat, FrombooleanTodouble, FrombooleanToDouble, FrombooleanTochar, FrombooleanToCharacter, DEFINED, UNDEFINED, ABSENT; public boolean isDefined(){return this == DEFINED;} public boolean isUndefined(){return this == UNDEFINED;} public boolean isAbsent(){return this == ABSENT;} }
19.981132
75
0.815077
2fe10768e39ce6b10997f1c7e00928ede9e88888
294
package com.example.application.util.css; public enum WhiteSpace { NORMAL("normal"), NOWRAP("nowrap"), PRE("pre"), PRE_WRAP( "pre-wrap"), PRE_LINE("pre-line"); private String value; WhiteSpace(String value) { this.value = value; } public String getValue() { return value; } }
16.333333
58
0.676871
3b2a5cbad27fc3a08a3de14aa334a1ed7b34bd70
4,770
/* * Copyright 2017-2018 original 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 io.micronaut.configuration.elasticsearch.health; import io.micronaut.context.annotation.Requires; import io.micronaut.health.HealthStatus; import io.micronaut.management.endpoint.health.HealthEndpoint; import io.micronaut.management.health.indicator.HealthIndicator; import io.micronaut.management.health.indicator.HealthResult; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.reactivestreams.Publisher; import javax.inject.Singleton; import java.io.IOException; import static io.micronaut.health.HealthStatus.DOWN; import static io.micronaut.health.HealthStatus.UP; import static java.util.Collections.emptyMap; import static org.elasticsearch.cluster.health.ClusterHealthStatus.GREEN; import static org.elasticsearch.cluster.health.ClusterHealthStatus.YELLOW; /** * A {@link HealthIndicator} for Elasticsearch that uses an automatically-configured high-level REST client, injected as a dependency, to communicate * with Elasticsearch. * * @author Puneet Behl * @author Robyn Dalgleish * @since 1.0.0 */ @Requires(beans = HealthEndpoint.class) @Requires(property = HealthEndpoint.PREFIX + ".elasticsearch.rest.high.level.enabled", notEquals = "false") @Singleton public class ElasticsearchHealthIndicator implements HealthIndicator { private static final String NAME = "elasticsearch"; private final RestHighLevelClient esClient; /** * Constructor. * * @param esClient The Elasticsearch high level REST client. */ public ElasticsearchHealthIndicator(RestHighLevelClient esClient) { this.esClient = esClient; } /** * Tries to call the cluster info API on Elasticsearch to obtain information about the cluster. If the call succeeds, the Elasticsearch cluster * health status (GREEN / YELLOW / RED) will be included in the health indicator details. * * @return A positive health result UP if the cluster can be communicated with and is in either GREEN or YELLOW status. A negative health result * DOWN if the cluster cannot be communicated with or is in RED status. */ @Override public Publisher<HealthResult> getResult() { return (subscriber -> esClient.cluster().healthAsync(new ClusterHealthRequest(), RequestOptions.DEFAULT, new ActionListener<ClusterHealthResponse>() { private final HealthResult.Builder resultBuilder = HealthResult.builder(NAME); @Override public void onResponse(ClusterHealthResponse response) { HealthResult result; try { result = resultBuilder .status(healthResultStatus(response)) .details(healthResultDetails(response)) .build(); } catch (IOException e) { result = resultBuilder.status(DOWN).exception(e).build(); } subscriber.onNext(result); subscriber.onComplete(); } @Override public void onFailure(Exception e) { subscriber.onNext(resultBuilder.status(DOWN).exception(e).build()); subscriber.onComplete(); } })); } private String healthResultDetails(ClusterHealthResponse response) throws IOException { XContentBuilder xContentBuilder = XContentFactory.jsonBuilder(); response.toXContent(xContentBuilder, new ToXContent.MapParams(emptyMap())); return Strings.toString(xContentBuilder); } private HealthStatus healthResultStatus(ClusterHealthResponse response) { return response.getStatus() == GREEN || response.getStatus() == YELLOW ? UP : DOWN; } }
39.75
158
0.722432
4fb8064abef406b40b858d5f8dc80df22584ce48
1,849
package com.incloud.hcp.jco.controlLogistico.dto; import java.util.HashMap; import java.util.List; public class ConsultaHorometroExports { private String mensaje; private List<HashMap<String, Object>> str_emb; private List<HashMap<String, Object>> str_evn; private List<HashMap<String, Object>> str_lho; private List<HashMap<String, Object>> t_mensaje; private List<HorometroExportDto> listaHorometro; private List<HorometroStrDto> listaHoroStr; public List<HorometroStrDto> getListaHoroStr() { return listaHoroStr; } public void setListaHoroStr(List<HorometroStrDto> listaHoroStr) { this.listaHoroStr = listaHoroStr; } public List<HorometroExportDto> getListaHorometro() { return listaHorometro; } public void setListaHorometro(List<HorometroExportDto> listaHorometro) { this.listaHorometro = listaHorometro; } public String getMensaje() { return mensaje; } public void setMensaje(String mensaje) { this.mensaje = mensaje; } public List<HashMap<String, Object>> getStr_emb() { return str_emb; } public void setStr_emb(List<HashMap<String, Object>> str_emb) { this.str_emb = str_emb; } public List<HashMap<String, Object>> getStr_evn() { return str_evn; } public void setStr_evn(List<HashMap<String, Object>> str_evn) { this.str_evn = str_evn; } public List<HashMap<String, Object>> getStr_lho() { return str_lho; } public void setStr_lho(List<HashMap<String, Object>> str_lho) { this.str_lho = str_lho; } public List<HashMap<String, Object>> getT_mensaje() { return t_mensaje; } public void setT_mensaje(List<HashMap<String, Object>> t_mensaje) { this.t_mensaje = t_mensaje; } }
25.680556
76
0.674419
526ce00a311027b17e09ad5fd9927a01334bc2f8
2,468
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.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 boofcv.alg.feature.associate; import boofcv.struct.feature.AssociatedIndex; import org.ddogleg.struct.DogArray; import org.ddogleg.struct.FastAccess; import org.ddogleg.struct.FastArray; /** * Removes any ambiguous associations. If multiple features from the 'src' match the same feature * in the 'dst' then only the association with the lowest 'fitScore' is saved. * * @author Peter Abeles */ public class EnsureUniqueAssociation { // An element for each 'dst' feature. Only the best association with the lowest score is saved here. AssociatedIndex[] bestScores = new AssociatedIndex[1]; // The final output list with the best associations FastArray<AssociatedIndex> unambiguous = new FastArray<>(AssociatedIndex.class); /** * Removes ambiguous associations. Call {@link #getMatches()} to get the list of unambiguous * matches. * * @param matches List of candidate associations * @param sizeDst Number of 'dst' features */ public void process( DogArray<AssociatedIndex> matches, int sizeDst ) { // initialize data structures if (bestScores.length < sizeDst) bestScores = new AssociatedIndex[sizeDst]; for (int i = 0; i < matches.size; i++) { AssociatedIndex match = matches.data[i]; if (bestScores[match.dst] == null || match.fitScore < bestScores[match.dst].fitScore) { bestScores[match.dst] = match; } } // add the best unambiguous pairs back unambiguous.reset(); for (int i = 0; i < sizeDst; i++) { if (bestScores[i] != null) { unambiguous.add(bestScores[i]); // clean up so that you don't have a dangling reference bestScores[i] = null; } } } /** * List of unambiguous matches. * * @return list of matches */ public FastAccess<AssociatedIndex> getMatches() { return unambiguous; } }
31.240506
101
0.715154
6e99fe0735543d6c1a855c0a8c366c8575f238d1
1,548
package frc.robot.auto; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.api.motor.RunMotor; import frc.robot.subsystems.Elevator; import frc.robot.subsystems.Intake; import frc.robot.subsystems.Shooter; import frc.robot.subsystems.drivetrain.DriveStraightTimed; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.subsystems.drivetrain.TurnDegrees; import frc.robot.subsystems.intakepivot.IntakePivot; import frc.robot.subsystems.intakepivot.PivotIntakeDown; public class ThreeBallAuto extends ParallelCommandGroup { public ThreeBallAuto(Shooter shooter, Elevator elevator, Drivetrain drive, IntakePivot intakePivot, Intake intake) { addCommands( new RunMotor(intake), new RunMotor(elevator), new SequentialCommandGroup( new PivotIntakeDown(intakePivot), new DriveStraightTimed(drive, -1, 1000), new WaitCommand(0.5), new DriveStraightTimed(drive, 1, 1350), new RunMotor(shooter, 1000), new DriveStraightTimed(drive, -1, 400), new WaitCommand(0.5), new TurnDegrees(drive, -0.65, 55, true), new DriveStraightTimed(drive, -1, 1450), new WaitCommand(0.5), new DriveStraightTimed(drive, 1, 1250), new WaitCommand(0.5), new TurnDegrees(drive, 0.65, 40, true), new DriveStraightTimed(drive, 1, 400), new RunMotor(shooter, 1000) ) ); } }
36.857143
118
0.72739
7ee3c0052f4b0ed839a0a4d021e44fdfa8999c10
328
class Tester { static { System.out.println("正在初始化Tester实例"); } } public class ClassLoaderTest { public static void main(String[] args) throws ClassNotFoundException { ClassLoader cl = ClassLoader.getSystemClassLoader(); cl.loadClass("Tester"); System.out.println("loadClass方法执行完成"); Class.forName("Tester"); } }
21.866667
71
0.731707
059d348caff6f822a5f0cc9800b82228beb7db21
1,994
package com.smart.app.weighing.auth.config; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; @Component public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { HttpSession session = request.getSession(); /* Set some session variables */ User authUser = (User) SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); session.setAttribute("uname", authUser.getUsername()); session.setAttribute("authorities", authentication.getAuthorities()); /* Set target URL to redirect */ String targetUrl = determineTargetUrl(authentication); redirectStrategy.sendRedirect(request, response, targetUrl); } private String determineTargetUrl(Authentication authentication) { if(authentication.isAuthenticated()) { return "/home/"; } return "/login?error"; } /** * @return the redirectStrategy */ public RedirectStrategy getRedirectStrategy() { return redirectStrategy; } /** * @param redirectStrategy the redirectStrategy to set */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } }
31.15625
84
0.804915
5bf43c4644a195305ff4172aed5a22bd7526ce78
4,650
package uk.ac.ebi.quickgo.index.geneproduct; import uk.ac.ebi.quickgo.geneproduct.common.GeneProductType; import uk.ac.ebi.quickgo.index.common.DocumentReaderException; import com.google.common.base.Preconditions; import java.util.Map; import org.springframework.batch.item.validator.ValidationException; import org.springframework.batch.item.validator.Validator; import static uk.ac.ebi.quickgo.index.common.datafile.GOADataFileParsingHelper.convertLinePropertiesToMap; import static uk.ac.ebi.quickgo.index.common.datafile.GOADataFileParsingHelper.splitValue; import static uk.ac.ebi.quickgo.index.geneproduct.Columns.*; import static uk.ac.ebi.quickgo.index.geneproduct.GeneProductParsingHelper.*; /** * Checks if the {@link GeneProduct} object has been populated properly. * * @author Ricardo Antunes */ public class GeneProductValidator implements Validator<GeneProduct> { private final String interValueDelimiter; private final String intraValueDelimiter; public GeneProductValidator(String interValueDelimiter, String intraValueDelimiter) { Preconditions.checkArgument(interValueDelimiter != null && interValueDelimiter.length() > 0, "Inter value delimiter can not be null or empty"); Preconditions.checkArgument(intraValueDelimiter != null && intraValueDelimiter.length() > 0, "Intra " + "value delimiter can not be null or empty"); this.interValueDelimiter = interValueDelimiter; this.intraValueDelimiter = intraValueDelimiter; } @Override public void validate(GeneProduct geneProduct) throws ValidationException { if(geneProduct == null) { throw new DocumentReaderException("Gene product can not be null"); } try { checkIsNullOrEmpty(geneProduct.database, COLUMN_DB.getName()); checkIsNullOrEmpty(geneProduct.id, COLUMN_ID.getName()); checkIsNullOrEmpty(geneProduct.symbol, COLUMN_SYMBOL.getName()); checkTaxonId(geneProduct.taxonId); checkType(geneProduct.type, COLUMN_TYPE.getName()); checkHasAtMostOneParentId(geneProduct.parentId); Map<String, String> properties = convertLinePropertiesToMap(geneProduct.properties, interValueDelimiter, intraValueDelimiter); } catch (ValidationException e) { throw new ValidationException("Error occurred in database: " + geneProduct.database + ", for entry: " + geneProduct.id, e); } } /** * Checks to see if the expression is verified, if so it will throw a {@link ValidationException}. * * @param expression the expression to check * @param message the message that will be appended to the exception */ private void checkAttribute(boolean expression, String message) { if (expression) { throw new ValidationException(message); } } private void checkIsNull(String value, String field) { checkAttribute(value == null, "Found null value in field: " + field); } private void checkIsEmpty(String value, String field) { checkAttribute(value.isEmpty(), "Found empty value in field: " + field); } private void checkIsNullOrEmpty(String value, String field) { checkIsNull(value, field); checkIsEmpty(value, field); } private void checkHasAtMostOneParentId(String parentId) { if (parentId != null) { String[] parentIds = splitValue(parentId, interValueDelimiter); checkAttribute(parentIds.length > 1, "Found more than one id in field: " + COLUMN_PARENT_ID.getName()); } } private void checkBooleanValue(String value, String field) { if (value != null) { if (!value.equalsIgnoreCase(TRUE_STRING) && !value.equalsIgnoreCase(FALSE_STRING)) { throw new ValidationException("Found invalid value for field: " + field + ": " + value); } } } private void checkType(String value, String field) { checkIsNullOrEmpty(value, field); try { GeneProductType.typeOf(value); } catch (IllegalArgumentException e) { throw new ValidationException("Error in field: " + field + " - [" + e.getMessage() + "]"); } } private void checkTaxonId(String taxonId) { checkIsNullOrEmpty(taxonId, COLUMN_TAXON_ID.getName()); if(!GeneProductParsingHelper.taxonIdMatchesRegex(taxonId)) { throw new ValidationException("Taxon id column does not conform to regex: " +taxonId); } } }
39.40678
115
0.679785
7b51f876b233a89b541888b076e121dc91b42380
495
package pl.KarolCzechowicz.converter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.converter.Converter; import pl.KarolCzechowicz.model.Fuel; import pl.KarolCzechowicz.repository.FuelRepository; public class FuelConverter implements Converter<String, Fuel> { @Autowired private FuelRepository fuelRepository; @Override public Fuel convert(String s) { return fuelRepository.findOne(Long.parseLong(s)); } }
27.5
63
0.787879
b5bfd5c969a316b1eb8cb94a23d25cc6ce94b626
25,160
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.util; import java.net.MalformedURLException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit tests for the <code>org.apache.catalina.util.URL</code> class. * * @author Craig R. McClanahan * @version $Id: URLTestCase.java 939532 2010-04-30 00:55:18Z kkolinko $ */ public class URLTestCase extends TestCase { // ----------------------------------------------------- Instance Variables // ----------------------------------------------------------- Constructors /** * Construct a new instance of this test case. * * @param name Name of the test case */ public URLTestCase(String name) { super(name); } // --------------------------------------------------- Overall Test Methods /** * Set up instance variables required by this test case. */ public void setUp() { ; // No action required } /** * Return the tests included in this test suite. */ public static Test suite() { return (new TestSuite(URLTestCase.class)); } /** * Tear down instance variables required by this test case. */ public void tearDown() { ; // No action required } // ------------------------------------------------ Individual Test Methods /** * Negative tests for absolute URL strings in various patterns. Each of * these should throw <code>MalformedURLException</code>. */ public void testNegativeAbsolute() { negative("index.html"); negative("index.html#ref"); negative("index.html?name=value"); negative("index.html?name=value#ref"); negative("/index.html"); negative("/index.html#ref"); negative("/index.html?name=value"); negative("/index.html?name=value#ref"); } /** * Negative tests for <code>normalize()</code>. Attempts to normalize * these legal URLs should throw <code>MalformedURLException</code>. */ public void testNegativeNormalize() { normalize("http://localhost/.."); normalize("http://localhost/..#ref"); normalize("http://localhost/..?name=value"); normalize("http://localhost/..?name=value#ref"); normalize("http://localhost:8080/.."); normalize("http://localhost:8080/..#ref"); normalize("http://localhost:8080/..?name=value"); normalize("http://localhost:8080/..?name=value#ref"); normalize("http://localhost/../"); normalize("http://localhost/../#ref"); normalize("http://localhost/../?name=value"); normalize("http://localhost/../?name=value#ref"); normalize("http://localhost:8080/../"); normalize("http://localhost:8080/../#ref"); normalize("http://localhost:8080/../?name=value"); normalize("http://localhost:8080/../?name=value#ref"); normalize("http://localhost/index.html/../../foo.html"); normalize("http://localhost/index.html/../../foo.html#ref"); normalize("http://localhost/index.html/../../foo.html?name=value"); normalize("http://localhost/index.html/../../foo.html?name=value#ref"); normalize("http://localhost:8080/index.html/../../foo.html"); normalize("http://localhost:8080/index.html/../../foo.html#ref"); normalize("http://localhost:8080/index.html/../../foo.html?name=value"); normalize("http://localhost:8080/index.html/../../foo.html?name=value#ref"); } /** * Negative tests for relative URL strings in various patterns. Each of * these should throw <code>MalformedURLException</code>. */ public void testNegativeRelative() { // Commented out because java.net.URL ignores extraneous "../" // negative("http://a/b/c/d;p?q", "../../../g"); // negative("http://a/b/c/d;p?q", "/../g"); } /** * Positive tests for absolute URL strings in various patterns. */ public void testPositiveAbsolute() { positive("http://a/b/c/d;p?q"); positive("http://localhost/index.html"); positive("http://localhost/index.html#ref"); positive("http://localhost/index.html?name=value"); positive("http://localhost/index.html?name=value#ref"); positive("http://localhost:8080/index.html"); positive("http://localhost:8080/index.html#ref"); positive("http://localhost:8080/index.html?name=value"); positive("http://localhost:8080/index.html?name=value#ref"); positive("http://localhost/index.html/."); positive("http://localhost/index.html/.#ref"); positive("http://localhost/index.html/.?name=value"); positive("http://localhost/index.html/.?name=value#ref"); positive("http://localhost:8080/index.html/."); positive("http://localhost:8080/index.html/.#ref"); positive("http://localhost:8080/index.html/.?name=value"); positive("http://localhost:8080/index.html/.?name=value#ref"); positive("http://localhost/index.html/foo/.."); positive("http://localhost/index.html/foo/..#ref"); positive("http://localhost/index.html/foo/..?name=value"); positive("http://localhost/index.html/foo/..?name=value#ref"); positive("http://localhost:8080/index.html/foo/.."); positive("http://localhost:8080/index.html/foo/..#ref"); positive("http://localhost:8080/index.html/foo/..?name=value"); positive("http://localhost:8080/index.html/foo/..?name=value#ref"); positive("http://localhost/index.html/../foo.html"); positive("http://localhost/index.html/../foo.html#ref"); positive("http://localhost/index.html/../foo.html?name=value"); positive("http://localhost/index.html/../foo.html?name=value#ref"); positive("http://localhost:8080/index.html/../foo.html"); positive("http://localhost:8080/index.html/../foo.html#ref"); positive("http://localhost:8080/index.html/../foo.html?name=value"); positive("http://localhost:8080/index.html/../foo.html?name=value#ref"); positive("http://localhost"); positive("http://localhost#ref"); positive("http://localhost?name=value"); positive("http://localhost?name=value#ref"); positive("http://localhost:8080"); positive("http://localhost:8080#ref"); positive("http://localhost:8080?name=value"); positive("http://localhost:8080?name=value#ref"); positive("http://localhost/"); positive("http://localhost/#ref"); positive("http://localhost/?name=value"); positive("http://localhost/?name=value#ref"); positive("http://localhost:8080/"); positive("http://localhost:8080/#ref"); positive("http://localhost:8080/?name=value"); positive("http://localhost:8080/?name=value#ref"); } /** * Positive tests for normalizing absolute URL strings in various patterns. */ public void testPositiveNormalize() { normalize("http://a/b/c/d;p?q", "http://a/b/c/d;p?q"); normalize("http://localhost/index.html", "http://localhost/index.html"); normalize("http://localhost/index.html#ref", "http://localhost/index.html#ref"); normalize("http://localhost/index.html?name=value", "http://localhost/index.html?name=value"); normalize("http://localhost/index.html?name=value#ref", "http://localhost/index.html?name=value#ref"); normalize("http://localhost:8080/index.html", "http://localhost:8080/index.html"); normalize("http://localhost:8080/index.html#ref", "http://localhost:8080/index.html#ref"); normalize("http://localhost:8080/index.html?name=value", "http://localhost:8080/index.html?name=value"); normalize("http://localhost:8080/index.html?name=value#ref", "http://localhost:8080/index.html?name=value#ref"); normalize("http://localhost/./index.html", "http://localhost/index.html"); normalize("http://localhost/./index.html#ref", "http://localhost/index.html#ref"); normalize("http://localhost/./index.html?name=value", "http://localhost/index.html?name=value"); normalize("http://localhost/./index.html?name=value#ref", "http://localhost/index.html?name=value#ref"); normalize("http://localhost:8080/./index.html", "http://localhost:8080/index.html"); normalize("http://localhost:8080/./index.html#ref", "http://localhost:8080/index.html#ref"); normalize("http://localhost:8080/./index.html?name=value", "http://localhost:8080/index.html?name=value"); normalize("http://localhost:8080/./index.html?name=value#ref", "http://localhost:8080/index.html?name=value#ref"); normalize("http://localhost/index.html/.", "http://localhost/index.html/"); normalize("http://localhost/index.html/.#ref", "http://localhost/index.html/#ref"); normalize("http://localhost/index.html/.?name=value", "http://localhost/index.html/?name=value"); normalize("http://localhost/index.html/.?name=value#ref", "http://localhost/index.html/?name=value#ref"); normalize("http://localhost:8080/index.html/.", "http://localhost:8080/index.html/"); normalize("http://localhost:8080/index.html/.#ref", "http://localhost:8080/index.html/#ref"); normalize("http://localhost:8080/index.html/.?name=value", "http://localhost:8080/index.html/?name=value"); normalize("http://localhost:8080/index.html/.?name=value#ref", "http://localhost:8080/index.html/?name=value#ref"); normalize("http://localhost/index.html/./", "http://localhost/index.html/"); normalize("http://localhost/index.html/./#ref", "http://localhost/index.html/#ref"); normalize("http://localhost/index.html/./?name=value", "http://localhost/index.html/?name=value"); normalize("http://localhost/index.html/./?name=value#ref", "http://localhost/index.html/?name=value#ref"); normalize("http://localhost:8080/index.html/./", "http://localhost:8080/index.html/"); normalize("http://localhost:8080/index.html/./#ref", "http://localhost:8080/index.html/#ref"); normalize("http://localhost:8080/index.html/./?name=value", "http://localhost:8080/index.html/?name=value"); normalize("http://localhost:8080/index.html/./?name=value#ref", "http://localhost:8080/index.html/?name=value#ref"); normalize("http://localhost/foo.html/../index.html", "http://localhost/index.html"); normalize("http://localhost/foo.html/../index.html#ref", "http://localhost/index.html#ref"); normalize("http://localhost/foo.html/../index.html?name=value", "http://localhost/index.html?name=value"); normalize("http://localhost/foo.html/../index.html?name=value#ref", "http://localhost/index.html?name=value#ref"); normalize("http://localhost:8080/foo.html/../index.html", "http://localhost:8080/index.html"); normalize("http://localhost:8080/foo.html/../index.html#ref", "http://localhost:8080/index.html#ref"); normalize("http://localhost:8080/foo.html/../index.html?name=value", "http://localhost:8080/index.html?name=value"); normalize("http://localhost:8080/foo.html/../index.html?name=value#ref", "http://localhost:8080/index.html?name=value#ref"); normalize("http://localhost/index.html/foo.html/..", "http://localhost/index.html/"); normalize("http://localhost/index.html/foo.html/..#ref", "http://localhost/index.html/#ref"); normalize("http://localhost/index.html/foo.html/..?name=value", "http://localhost/index.html/?name=value"); normalize("http://localhost/index.html/foo.html/..?name=value#ref", "http://localhost/index.html/?name=value#ref"); normalize("http://localhost:8080/index.html/foo.html/..", "http://localhost:8080/index.html/"); normalize("http://localhost:8080/index.html/foo.html/..#ref", "http://localhost:8080/index.html/#ref"); normalize("http://localhost:8080/index.html/foo.html/..?name=value", "http://localhost:8080/index.html/?name=value"); normalize("http://localhost:8080/index.html/foo.html/..?name=value#ref", "http://localhost:8080/index.html/?name=value#ref"); normalize("http://localhost/index.html/foo.html/../", "http://localhost/index.html/"); normalize("http://localhost/index.html/foo.html/../#ref", "http://localhost/index.html/#ref"); normalize("http://localhost/index.html/foo.html/../?name=value", "http://localhost/index.html/?name=value"); normalize("http://localhost/index.html/foo.html/../?name=value#ref", "http://localhost/index.html/?name=value#ref"); normalize("http://localhost:8080/index.html/foo.html/../", "http://localhost:8080/index.html/"); normalize("http://localhost:8080/index.html/foo.html/../#ref", "http://localhost:8080/index.html/#ref"); normalize("http://localhost:8080/index.html/foo.html/../?name=value", "http://localhost:8080/index.html/?name=value"); normalize("http://localhost:8080/index.html/foo.html/../?name=value#ref", "http://localhost:8080/index.html/?name=value#ref"); } /** * Positive tests for relative URL strings in various patterns. */ public void testPositiveRelative() { // Test cases based on RFC 2396, Appendix C positive("http://a/b/c/d;p?q", "http:h"); positive("http://a/b/c/d;p?q", "g"); positive("http://a/b/c/d;p?q", "./g"); positive("http://a/b/c/d;p?q", "g/"); positive("http://a/b/c/d;p?q", "/g"); // positive("http://a/b/c/d;p?q", "//g"); positive("http://a/b/c/d;p?q", "?y"); positive("http://a/b/c/d;p?q", "g?y"); // positive("http://a/b/c/d;p?q", "#s"); positive("http://a/b/c/d;p?q", "g#s"); positive("http://a/b/c/d;p?q", "g?y#s"); positive("http://a/b/c/d;p?q", ";x"); positive("http://a/b/c/d;p?q", "g;x"); positive("http://a/b/c/d;p?q", "g;x?y#s"); positive("http://a/b/c/d;p?q", "."); positive("http://a/b/c/d;p?q", "./"); positive("http://a/b/c/d;p?q", ".."); positive("http://a/b/c/d;p?q", "../"); positive("http://a/b/c/d;p?q", "../g"); positive("http://a/b/c/d;p?q", "../.."); positive("http://a/b/c/d;p?q", "../../"); positive("http://a/b/c/d;p?q", "../../g"); // Commented because java.net.URL doesn't normalize out the "/./"???? // positive("http://a/b/c/d;p?q", "/./g"); positive("http://a/b/c/d;p?q", "g."); positive("http://a/b/c/d;p?q", ".g"); positive("http://a/b/c/d;p?q", "g.."); positive("http://a/b/c/d;p?q", "..g"); positive("http://a/b/c/d;p?q", "./../g"); positive("http://a/b/c/d;p?q", "./g/."); positive("http://a/b/c/d;p?q", "g/./h"); positive("http://a/b/c/d;p?q", "g/../h"); positive("http://a/b/c/d;p?q", "g;x=1/./y"); positive("http://a/b/c/d;p?q", "g;x=1/../y"); positive("http://a/b/c/d;p?q", "g?y/./x"); positive("http://a/b/c/d;p?q", "g?y/../x"); positive("http://a/b/c/d;p?q", "g#s/./x"); positive("http://a/b/c/d;p?q", "g#s/../x"); positive("http://a/b", "c"); positive("http://a/b/", "c"); } // -------------------------------------------------------- Private Methods /** * Check that both our URL class and <code>java.net.URL</code> throw * <code>MalformedURLException</code> on an absolute URL specification. * * @param spec Absolute URL specification to be checked */ private void negative(String spec) { try { java.net.URL url = new java.net.URL(spec); fail(spec + " should have failed on java.net.URL " + "but returned " + url.toExternalForm()); } catch (MalformedURLException e) { ; // Expected response } try { URL url = new URL(spec); fail(spec + " should have failed on tested URL " + "but returned " + url.toExternalForm()); } catch (MalformedURLException e) { ; // Expected response } } /** * Check that both our URL class and <code>java.net.URL</code> throw * <code>MalformedURLException</code> on an absolute URL specification * plus the corresponding relative URL specification. * * @param abs Absolute URL specification to be checked * @param rel Relative URL specification to be checked */ private void negative(String abs, String rel) { java.net.URL baseNet = null; URL baseUrl = null; try { baseNet = new java.net.URL(abs); } catch (MalformedURLException e) { fail(abs + " net URL threw " + e); } try { baseUrl = new URL(abs); } catch (MalformedURLException e) { fail(abs + " url URL threw " + e); } try { java.net.URL url = new java.net.URL(baseNet, rel); fail(rel + " should have failed on java.net.URL " + "but returned " + url.toExternalForm()); } catch (MalformedURLException e) { ; // Expected response } try { URL url = new URL(baseUrl, rel); fail(rel + " should have failed on tested URL " + "but returned " + url.toExternalForm()); } catch (MalformedURLException e) { ; // Expected response } } /** * Attempts to normalize the specified URL should throw * MalformedURLException. * * @param spec Unnormalized version of the URL specification */ private void normalize(String spec) { URL url = null; try { url = new URL(spec); } catch (Throwable t) { fail(spec + " should not have thrown " + t); } try { url.normalize(); fail(spec + ".normalize() should have thrown MUE"); } catch (MalformedURLException e) { ; // Expected result } } /** * It should be possible to normalize the specified URL into the * specified normalized form. * * @param spec Unnormalized version of the URL specification * @param norm Normalized version of the URL specification */ private void normalize(String spec, String norm) { try { URL url = new URL(spec); url.normalize(); assertEquals(spec + ".normalize()", norm, url.toExternalForm()); } catch (Throwable t) { fail(spec + ".normalize() threw " + t); } } /** * Check the details of our URL class against <code>java.net.URL</code> * for an absolute URL specification. * * @param spec Absolute URL specification to be checked */ private void positive(String spec) { // Compare results with what java.net.URL returns try { URL url = new URL(spec); java.net.URL net = new java.net.URL(spec); assertEquals(spec + " toExternalForm()", net.toExternalForm(), url.toExternalForm()); assertEquals(spec + ".getAuthority()", net.getAuthority(), url.getAuthority()); assertEquals(spec + ".getFile()", net.getFile(), url.getFile()); assertEquals(spec + ".getHost()", net.getHost(), url.getHost()); assertEquals(spec + ".getPath()", net.getPath(), url.getPath()); assertEquals(spec + ".getPort()", net.getPort(), url.getPort()); assertEquals(spec + ".getProtocol()", net.getProtocol(), url.getProtocol()); assertEquals(spec + ".getQuery()", net.getQuery(), url.getQuery()); assertEquals(spec + ".getRef()", net.getRef(), url.getRef()); assertEquals(spec + ".getUserInfo()", net.getUserInfo(), url.getUserInfo()); } catch (Throwable t) { fail(spec + " positive test threw " + t); } } /** * Check the details of our URL class against <code>java.net.URL</code> * for a relative URL specification. * * @param abs Absolute URL specification for base reference * @param rel Relative URL specification to resolve */ private void positive(String abs, String rel) { // Compare results with what java.net.URL returns try { URL urlBase = new URL(abs); java.net.URL netBase = new java.net.URL(abs); URL url = new URL(urlBase, rel); java.net.URL net = new java.net.URL(netBase, rel); assertEquals(rel + " toExternalForm()", net.toExternalForm(), url.toExternalForm()); assertEquals(rel + ".getAuthority()", net.getAuthority(), url.getAuthority()); assertEquals(rel + ".getFile()", net.getFile(), url.getFile()); assertEquals(rel + ".getHost()", net.getHost(), url.getHost()); assertEquals(rel + ".getPath()", net.getPath(), url.getPath()); assertEquals(rel + ".getPort()", net.getPort(), url.getPort()); assertEquals(rel + ".getProtocol()", net.getProtocol(), url.getProtocol()); assertEquals(rel + ".getQuery()", net.getQuery(), url.getQuery()); assertEquals(rel + ".getRef()", net.getRef(), url.getRef()); assertEquals(rel + ".getUserInfo()", net.getUserInfo(), url.getUserInfo()); } catch (Throwable t) { fail(rel + " positive test threw " + t); } } }
39.25117
85
0.526073
75871c59974e696cb94e44ec76a3b18de5437674
1,693
/* * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import javax.swing.JApplet; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** * @test * @bug 4222153 * @author Konstantin Eremin * @run applet/manual=yesno bug4222153.html */ public class bug4222153 extends JApplet { public void init() { SwingUtilities.invokeLater(() -> { try { UIManager.setLookAndFeel( "javax.swing.plaf.metal.MetalLookAndFeel"); } catch (Exception e) { throw new RuntimeException(e); } getContentPane().add(new JTable(2, 2)); }); } }
34.55102
79
0.687537
5ffb13a45d808d644c3eb2e7637c0e9f9cafa283
32,365
/* * 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.netbeans.modules.terminal.nb; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; import javax.swing.JPanel; import javax.swing.SpinnerNumberModel; import javax.swing.UIManager; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.netbeans.lib.terminalemulator.LineDiscipline; import org.netbeans.lib.terminalemulator.Term; import org.netbeans.lib.terminalemulator.support.TermOptions; import static org.netbeans.modules.terminal.nb.Bundle.*; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.util.NbBundle.Messages; /** * A copy of org.netbeans.lib.terminalemulator.support.TermOptionsPanel that * uses NB's ColorComboBoxes */ public final class TermOptionsPanel extends JPanel { private final Term term; private final PropertyChangeListener propertyListener; private boolean inApplyingModel; private TermOptions termOptions; /** * Creates new form TermOptionPanel */ @Messages({ "MSG_Hello=Hello from Term", "FontChooser.title=Font Chooser", "FontChooser.defaultFont.label=Default Font" }) public TermOptionsPanel() { propertyListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { refreshView(); } }; initComponents(); initCustomComponents(); term = new Term(); final String line1String = MSG_Hello() + "\r\n"; // NOI18N final char line1[] = line1String.toCharArray(); term.putChars(line1, 0, line1.length); term.pushStream(new LineDiscipline()); term.setRowsColumns(7, 60); term.setClickToType(true); previewPanel.add(term, BorderLayout.CENTER); } private boolean changingSelectByWordText = false; private void initCustomComponents() { selectByWordTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { textChangeActionPerformed(); } @Override public void removeUpdate(DocumentEvent e) { textChangeActionPerformed(); } @Override public void changedUpdate(DocumentEvent e) { // ignore } private void textChangeActionPerformed() { if (inApplyingModel) { return; } changingSelectByWordText = true; String delimiters = selectByWordTextField.getText(); termOptions.setSelectByWordDelimiters(delimiters); changingSelectByWordText = false; } }); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { descriptionLabel = new javax.swing.JLabel(); restoreButton = new javax.swing.JButton(); fontLabel = new javax.swing.JLabel(); fontText = new javax.swing.JTextField(); fontButton = new javax.swing.JButton(); fontSizeLabel = new javax.swing.JLabel(); fontSizeSpinner = new javax.swing.JSpinner(); foregroundLabel = new javax.swing.JLabel(); foregroundComboBox = new org.openide.awt.ColorComboBox(); backgroundLabel = new javax.swing.JLabel(); backgroundComboBox = new org.openide.awt.ColorComboBox(); selectionLabel = new javax.swing.JLabel(); selectionComboBox = new org.openide.awt.ColorComboBox(); historySizeLabel = new javax.swing.JLabel(); historySizeSpinner = new javax.swing.JSpinner(); tabSizeLabel = new javax.swing.JLabel(); tabSizeSpinner = new javax.swing.JSpinner(); selectByWordLabel = new javax.swing.JLabel(); selectByWordTextField = new javax.swing.JTextField(); clickToTypeCheckBox = new javax.swing.JCheckBox(); ignoreKeymapCheckBox = new javax.swing.JCheckBox(); lineWrapCheckBox = new javax.swing.JCheckBox(); scrollOnInputCheckBox = new javax.swing.JCheckBox(); scrollOnOutputCheckBox = new javax.swing.JCheckBox(); previewLabel = new javax.swing.JLabel(); previewPanel = new javax.swing.JPanel(); altSendsEscapeCheckBox = new javax.swing.JCheckBox(); org.openide.awt.Mnemonics.setLocalizedText(descriptionLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.descriptionLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(restoreButton, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.restoreButton.text")); // NOI18N restoreButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { restoreButtonActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(fontLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.fontLabel.text")); // NOI18N fontText.setEditable(false); fontText.setText(org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.fontText.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(fontButton, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.fontButton.text")); // NOI18N fontButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fontButtonActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(fontSizeLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.fontSizeLabel.text")); // NOI18N fontSizeSpinner.setModel(new SpinnerNumberModel(12, TermOptions.MIN_FONT_SIZE, TermOptions.MAX_FONT_SIZE, 1)); fontSizeSpinner.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { fontSizeSpinnerStateChanged(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(foregroundLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.foregroundLabel.text")); // NOI18N foregroundComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { foregroundComboBoxActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(backgroundLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.backgroundLabel.text")); // NOI18N backgroundComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backgroundComboBoxActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(selectionLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.selectionLabel.text")); // NOI18N selectionComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selectionComboBoxActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(historySizeLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.historySizeLabel.text")); // NOI18N historySizeSpinner.setModel(new SpinnerNumberModel(5000, TermOptions.MIN_HISTORY_SIZE, TermOptions.MAX_HISTORY_SIZE, 1)); historySizeSpinner.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { historySizeSpinnerStateChanged(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(tabSizeLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.tabSizeLabel.text")); // NOI18N tabSizeSpinner.setModel(new SpinnerNumberModel(8, TermOptions.MIN_TAB_SIZE, TermOptions.MAX_TAB_SIZE, 1)); tabSizeSpinner.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { tabSizeSpinnerStateChanged(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(selectByWordLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.selectByWordLabel.text")); // NOI18N selectByWordTextField.setText(org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.selectByWordTextField.text")); // NOI18N clickToTypeCheckBox.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(clickToTypeCheckBox, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.clickToTypeCheckBox.text")); // NOI18N clickToTypeCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clickToTypeCheckBoxActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(ignoreKeymapCheckBox, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.ignoreKeymapCheckBox.text")); // NOI18N ignoreKeymapCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ignoreKeymapCheckBoxActionPerformed(evt); } }); lineWrapCheckBox.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(lineWrapCheckBox, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.lineWrapCheckBox.text")); // NOI18N lineWrapCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lineWrapCheckBoxActionPerformed(evt); } }); scrollOnInputCheckBox.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(scrollOnInputCheckBox, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.scrollOnInputCheckBox.text")); // NOI18N scrollOnInputCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { scrollOnInputCheckBoxActionPerformed(evt); } }); scrollOnOutputCheckBox.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(scrollOnOutputCheckBox, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.scrollOnOutputCheckBox.text")); // NOI18N scrollOnOutputCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { scrollOnOutputCheckBoxActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(previewLabel, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.previewLabel.text")); // NOI18N previewPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); previewPanel.setLayout(new java.awt.BorderLayout()); org.openide.awt.Mnemonics.setLocalizedText(altSendsEscapeCheckBox, org.openide.util.NbBundle.getMessage(TermOptionsPanel.class, "TermOptionsPanel.altSendsEscapeCheckBox.text")); // NOI18N altSendsEscapeCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { altSendsEscapeCheckBoxActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(previewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(fontLabel) .addComponent(fontSizeLabel) .addComponent(foregroundLabel) .addComponent(backgroundLabel) .addComponent(selectionLabel) .addComponent(historySizeLabel) .addComponent(descriptionLabel)) .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(foregroundComboBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE) .addComponent(backgroundComboBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(selectionComboBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(selectByWordTextField, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(fontText, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(fontSizeSpinner, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(historySizeSpinner, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tabSizeSpinner, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(restoreButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(fontButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tabSizeLabel) .addComponent(previewLabel) .addComponent(selectByWordLabel) .addGroup(layout.createSequentialGroup() .addComponent(ignoreKeymapCheckBox) .addGap(86, 86, 86) .addComponent(altSendsEscapeCheckBox)) .addGroup(layout.createSequentialGroup() .addComponent(scrollOnInputCheckBox) .addGap(18, 18, 18) .addComponent(scrollOnOutputCheckBox)) .addGroup(layout.createSequentialGroup() .addComponent(clickToTypeCheckBox) .addGap(31, 31, 31) .addComponent(lineWrapCheckBox))) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(descriptionLabel) .addComponent(restoreButton)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(fontLabel) .addComponent(fontButton) .addComponent(fontText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(fontSizeLabel) .addComponent(fontSizeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(foregroundLabel) .addComponent(foregroundComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(backgroundLabel) .addComponent(backgroundComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(selectionLabel) .addComponent(selectionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(historySizeLabel) .addComponent(historySizeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tabSizeLabel) .addComponent(tabSizeSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(selectByWordLabel) .addComponent(selectByWordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ignoreKeymapCheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(altSendsEscapeCheckBox)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(clickToTypeCheckBox) .addComponent(lineWrapCheckBox)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(scrollOnInputCheckBox) .addComponent(scrollOnOutputCheckBox)) .addGap(18, 18, 18) .addComponent(previewLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(previewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void fontSizeSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_fontSizeSpinnerStateChanged if (inApplyingModel) { return; } Object fontSizeObj = fontSizeSpinner.getValue(); if (fontSizeObj instanceof Integer) { int fontSize = ((Integer) fontSizeObj).intValue(); termOptions.setFontSize(fontSize); } }//GEN-LAST:event_fontSizeSpinnerStateChanged private void historySizeSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_historySizeSpinnerStateChanged if (inApplyingModel) { return; } Object historySizeObj = historySizeSpinner.getValue(); if (historySizeObj instanceof Integer) { int historySize = ((Integer) historySizeObj).intValue(); termOptions.setHistorySize(historySize); } }//GEN-LAST:event_historySizeSpinnerStateChanged private void tabSizeSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_tabSizeSpinnerStateChanged if (inApplyingModel) { return; } Object tabSizeObj = tabSizeSpinner.getValue(); if (tabSizeObj instanceof Integer) { int tabSize = ((Integer) tabSizeObj).intValue(); termOptions.setTabSize(tabSize); } }//GEN-LAST:event_tabSizeSpinnerStateChanged private void fontButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fontButtonActionPerformed PropertyEditor pe = PropertyEditorManager.findEditor(Font.class); if (pe != null) { pe.setValue(termOptions.getFont()); DialogDescriptor dd = new DialogDescriptor(pe.getCustomEditor(), FontChooser_title()); String defaultFontString = FontChooser_defaultFont_label(); dd.setOptions(new Object[]{DialogDescriptor.OK_OPTION, defaultFontString, DialogDescriptor.CANCEL_OPTION}); //NOI18N DialogDisplayer.getDefault().createDialog(dd).setVisible(true); if (dd.getValue() == DialogDescriptor.OK_OPTION) { Font f = (Font) pe.getValue(); termOptions.setFont(f); applyTermOptions(); } else if (dd.getValue() == defaultFontString) { Font controlFont = UIManager.getFont("controlFont"); //NOI18N int fontSize = (controlFont == null) ? 12 : controlFont.getSize(); termOptions.setFont(new Font("monospaced", Font.PLAIN, fontSize)); //NOI18N } } }//GEN-LAST:event_fontButtonActionPerformed private void restoreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restoreButtonActionPerformed termOptions.resetToDefault(); }//GEN-LAST:event_restoreButtonActionPerformed private void clickToTypeCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clickToTypeCheckBoxActionPerformed if (inApplyingModel) { return; } termOptions.setClickToType(clickToTypeCheckBox.isSelected()); }//GEN-LAST:event_clickToTypeCheckBoxActionPerformed private void scrollOnInputCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scrollOnInputCheckBoxActionPerformed if (inApplyingModel) { return; } termOptions.setScrollOnInput(scrollOnInputCheckBox.isSelected()); }//GEN-LAST:event_scrollOnInputCheckBoxActionPerformed private void scrollOnOutputCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scrollOnOutputCheckBoxActionPerformed if (inApplyingModel) { return; } termOptions.setScrollOnOutput(scrollOnOutputCheckBox.isSelected()); }//GEN-LAST:event_scrollOnOutputCheckBoxActionPerformed private void lineWrapCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lineWrapCheckBoxActionPerformed if (inApplyingModel) { return; } termOptions.setLineWrap(lineWrapCheckBox.isSelected()); }//GEN-LAST:event_lineWrapCheckBoxActionPerformed private void ignoreKeymapCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ignoreKeymapCheckBoxActionPerformed if (inApplyingModel) { return; } termOptions.setIgnoreKeymap(ignoreKeymapCheckBox.isSelected()); }//GEN-LAST:event_ignoreKeymapCheckBoxActionPerformed private void foregroundComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_foregroundComboBoxActionPerformed if (inApplyingModel) { return; } Color c = foregroundComboBox.getSelectedColor(); if (c != null) { termOptions.setForeground(c); } }//GEN-LAST:event_foregroundComboBoxActionPerformed private void backgroundComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backgroundComboBoxActionPerformed if (inApplyingModel) { return; } Color c = backgroundComboBox.getSelectedColor(); if (c != null) { termOptions.setBackground(c); } }//GEN-LAST:event_backgroundComboBoxActionPerformed private void selectionComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectionComboBoxActionPerformed if (inApplyingModel) { return; } Color c = selectionComboBox.getSelectedColor(); if (c != null) { termOptions.setSelectionBackground(c); } }//GEN-LAST:event_selectionComboBoxActionPerformed private void altSendsEscapeCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_altSendsEscapeCheckBoxActionPerformed if (inApplyingModel) { return; } termOptions.setAltSendsEscape(altSendsEscapeCheckBox.isSelected()); }//GEN-LAST:event_altSendsEscapeCheckBoxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox altSendsEscapeCheckBox; private org.openide.awt.ColorComboBox backgroundComboBox; private javax.swing.JLabel backgroundLabel; private javax.swing.JCheckBox clickToTypeCheckBox; private javax.swing.JLabel descriptionLabel; private javax.swing.JButton fontButton; private javax.swing.JLabel fontLabel; private javax.swing.JLabel fontSizeLabel; private javax.swing.JSpinner fontSizeSpinner; private javax.swing.JTextField fontText; private org.openide.awt.ColorComboBox foregroundComboBox; private javax.swing.JLabel foregroundLabel; private javax.swing.JLabel historySizeLabel; private javax.swing.JSpinner historySizeSpinner; private javax.swing.JCheckBox ignoreKeymapCheckBox; private javax.swing.JCheckBox lineWrapCheckBox; private javax.swing.JLabel previewLabel; private javax.swing.JPanel previewPanel; private javax.swing.JButton restoreButton; private javax.swing.JCheckBox scrollOnInputCheckBox; private javax.swing.JCheckBox scrollOnOutputCheckBox; private javax.swing.JLabel selectByWordLabel; private javax.swing.JTextField selectByWordTextField; private org.openide.awt.ColorComboBox selectionComboBox; private javax.swing.JLabel selectionLabel; private javax.swing.JLabel tabSizeLabel; private javax.swing.JSpinner tabSizeSpinner; // End of variables declaration//GEN-END:variables /** * Set the model for this view. Changes in the panel are directly reflected * in this model which may be {@link TermOptions#assign}ed later. * * @param termOptions */ public void setTermOptions(TermOptions termOptions) { if (this.termOptions != null) { this.termOptions.removePropertyChangeListener(propertyListener); } this.termOptions = termOptions; if (this.termOptions != null) { this.termOptions.addPropertyChangeListener(propertyListener); } refreshView(); } private void applyTermOptions() { inApplyingModel = true; try { fontSizeSpinner.setValue(termOptions.getFontSize()); fontText.setText(termOptions.getFont().getFamily() + " " + // NOI18N termOptions.getFont().getSize()); foregroundComboBox.setSelectedColor(termOptions.getForeground()); backgroundComboBox.setSelectedColor(termOptions.getBackground()); selectionComboBox.setSelectedColor(termOptions.getSelectionBackground()); historySizeSpinner.setValue(termOptions.getHistorySize()); tabSizeSpinner.setValue(termOptions.getTabSize()); // Without this check we will get an // IllegalStateException: Attempt to mutate in notification if (!changingSelectByWordText) { selectByWordTextField.setText(termOptions.getSelectByWordDelimiters()); } clickToTypeCheckBox.setSelected(termOptions.getClickToType()); scrollOnInputCheckBox.setSelected(termOptions.getScrollOnInput()); scrollOnOutputCheckBox.setSelected(termOptions.getScrollOnOutput()); lineWrapCheckBox.setSelected(termOptions.getLineWrap()); ignoreKeymapCheckBox.setSelected(termOptions.getIgnoreKeymap()); altSendsEscapeCheckBox.setSelected(termOptions.getAltSendsEscape()); } finally { inApplyingModel = false; } } private void refreshView() { if (termOptions != null) { termOptions.removePropertyChangeListener(propertyListener); } try { applyTermOptions(); } finally { if (termOptions != null) { termOptions.addPropertyChangeListener(propertyListener); } } previewTermOptions(); } /** * Apply current models values to the preview area Term. */ private void previewTermOptions() { if (term == null) { return; } term.setFixedFont(true); term.setFont(termOptions.getFont()); term.setBackground(termOptions.getBackground()); term.setForeground(termOptions.getForeground()); term.setHighlightColor(termOptions.getSelectionBackground()); term.setHistorySize(termOptions.getHistorySize()); term.setTabSize(termOptions.getTabSize()); term.setSelectByWordDelimiters(termOptions.getSelectByWordDelimiters()); term.setClickToType(termOptions.getClickToType()); term.setScrollOnInput(termOptions.getScrollOnInput()); term.setScrollOnOutput(termOptions.getScrollOnOutput()); term.setHorizontallyScrollable(!termOptions.getLineWrap()); term.setAltSendsEscape(termOptions.getAltSendsEscape()); term.setRowsColumns(7, 60); patchSizes(); } /** * Adjust dialog size and layout. * If the chosen font size is >= 14 the * term preview area grows too large for the dialog (I think). The result is * that the term preview area, button sizes and the font name textarea all * shrink to a point. * * This is an attempt to force the dialog to resize itself but it doesn't * work. */ private void patchSizes() { term.invalidate(); previewPanel.validate(); previewPanel.invalidate(); this.validate(); this.invalidate(); } }
49.18693
195
0.722416
3b14cdc13993b063a9ddc9600cefd2efab285589
627
package com.larsschwegmann.labyrinth.scenes; public interface Renderer { /** * Called by GameStateManager * Use this method to update positions and recalculate things */ public void update(); /** * Called by GameStateManager after update() * Use this method to draw on the screen */ public void render(); /** * Called by GameStateManager when you're the new activeRenderer */ public void willBecomeActiveRenderer(); /** * Called by GameStateManager when you'll be removed as the activeRenderer */ public void willResignActiveRenderer(); }
22.392857
78
0.661882
15eaa3200d1c8ce73c791a1427d622448b6c3869
233
package com.microsoft.cognitive.speakerrecognition; public interface BaseUrls { /** * Base Address of the MS APIs */ String COGNITIVE_SERVICES_BASE_URL = "https://westus.api.cognitive.microsoft.com/spid/v1.0/"; }
23.3
97
0.712446
030fcdcfab9c8e2c12aa3d11b0a6e9d65f65bca2
602
/** * */ package org.ednovo.gooru.client.mvp.shelf.collection.folders.events; import java.util.HashMap; import org.ednovo.gooru.application.shared.model.content.CollectionDo; import org.ednovo.gooru.application.shared.model.folder.FolderDo; import org.ednovo.gooru.client.mvp.folders.event.RefreshFolderType; import com.google.gwt.event.shared.EventHandler; /** * @author Search Team * */ public interface RefreshFolderItemHandler extends EventHandler { void refreshFolderItem(FolderDo folderDo, RefreshFolderType refreshFolderType, HashMap<String,String> params, CollectionDo collDo); }
26.173913
132
0.802326
dcc4a403ab17aa337a05cb8a9d0638380b68aa33
11,546
package discover.components; import shared.connectivity.thor.response.Table; import shared.database.model.SQLTable; import shared.database.model.SQLTuple; import discover.DiscoverApplication; import discover.model.TableTupleSets; import discover.model.TupleSet; import shared.util.Timer; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; // Input: Basic tuple sets and a set of keywords {k1, ..., km} // Output: TupleSets Ri^K containing tuples with keywords in all // the subsets Ksub of K={k1, ..., km} and no other keywords // except from K - Ksub for a relation i. public class TupleSetPostProcessor { private List<String> keywords; // All keywords of the query. private List<TupleSet> basicTupleSets; // All basic tuple sets of the single keywords. private List<TableTupleSets> tableBasicTupleSets; // All basic tuple sets sorted by the table they belong to. // Statistics private double timeGeneratingTupleSets; // The output of the TupleSetPostProcessor as described above. // Contains the TupleSets Ri^K of the keyword subsets K. List<TupleSet> tupleSetCombinations; public TupleSetPostProcessor(List<String> keywords, List<TupleSet> basicTupleSets) { this.keywords = keywords; this.basicTupleSets = basicTupleSets; this.tableBasicTupleSets = new ArrayList<TableTupleSets>(); this.tupleSetCombinations = new ArrayList<TupleSet>(); } // Getters and Setters. public List<TupleSet> getKeywordSubsetTupleSets() { return this.tupleSetCombinations; } // The main function of the TupleSetPostProcessor component. // Generates a tuple set for every subset of the keywords. public List<TupleSet> generateKeywordSubsetsTupleSets() { // Start the timer. Timer timer = new Timer(); timer.start(); // Order the basic tuple sets by the table they belong to. this.orderBasicTupleSetsByTable(); // Create the tuple sets Ri^K as described above. for (TableTupleSets currentTableTupleSets : this.tableBasicTupleSets) { // Get all TupleSets containing keyword subsets contained in current table. List<TupleSet> tableSubsets = this.createTableSubsets(currentTableTupleSets); // Add them to the post processor component's output list. this.tupleSetCombinations.addAll(tableSubsets); } // Stop the timer. this.timeGeneratingTupleSets = timer.stop(); return this.tupleSetCombinations; } // Given the basic tuple sets of a table, this function creates all possible subsets // of keywords from the list of keywords contained in the table's basic tuple sets. // Then, for every subset of keywords it creates the tuple set from the given table // that contains all keywords of the subset. public List<TupleSet> createTableSubsets(TableTupleSets tableBasicTupleSets) { // List of tuple sets for every subset of keywords. List<TupleSet> subsetsTupleSets = new ArrayList<TupleSet>(); // Get all the keywords contained in the current table's basic tuple sets. List<String> tableKeywords = new ArrayList<>(tableBasicTupleSets.getKeywords()); int keywordsNumber = tableKeywords.size(); int numOfSubsets = 1 << keywordsNumber; // Generate all possible subsets of the keywords and save their corresponding tuple sets. for (int subsetNum = 1; subsetNum < numOfSubsets; subsetNum++) { // The tuple sets of the single keywords that make up a set of keywords. List<TupleSet> tupleSetsCombination = new ArrayList<TupleSet>(); // If not create it with basic tuple sets of single keywords. for (int pos = 0; pos < keywordsNumber; pos++) { if ((subsetNum & (1 << pos)) > 0) { TupleSet keywordTupleSet = tableBasicTupleSets.getBasicTupleSetOfKeyword( tableKeywords.get(pos) ); if (keywordTupleSet != null) { tupleSetsCombination.add(keywordTupleSet); } } } // Create the tuple set of the current subset of keywords. TupleSet subset = this.createSubset(tupleSetsCombination, this.keywords); if (!subset.isEmpty()) { subsetsTupleSets.add(subset); } } return subsetsTupleSets; } // Given a list of basic tuple sets create a new tuple set that contains all keywords // of the given tuple sets, but no other keyword from the allKeywords list. // // Specifically, for a subset K of {k1, ..., km} create a tuple set where every tuple // in the set contains all keywords of K, but no keyword of {k1, ..., km} - K. public TupleSet createSubset(List<TupleSet> tupleSetsCombination, List<String> allKeywords) { // Get the first tuple set. TupleSet intersectedSet = new TupleSet(tupleSetsCombination.get(0)); // Intersect it with the remaining tuple sets recursively. for (int i = 1; i < tupleSetsCombination.size(); i++) { intersectedSet = TupleSet.intersect(intersectedSet, tupleSetsCombination.get(i)); } // Create a list with all keywords that should not be contained in the tuple set. // This list is the set {k1, ..., km} - K. List<String> unwantedKeywords = new ArrayList<String>(); for (String keyword : allKeywords) if (!intersectedSet.getKeywords().contains(keyword)) unwantedKeywords.add(keyword); // Remove all tuples with unwanted keywords. intersectedSet.removeTuplesContainingUnwantedKeywords(unwantedKeywords); return intersectedSet; } // Returns the index of a table in the tableBasicTupleSets list. // Returns -1 if it was not found. public int getIndexOfTable(SQLTable table) { for (int index = 0; index < this.tableBasicTupleSets.size(); index++) { if (this.tableBasicTupleSets.get(index).getTable().equals(table)) { return index; } } return -1; } // Orders the basic tuple sets by the table they belong to. // A table may have multiple basic tuple sets depending on the keywords that its tuples contain. // Stores the result in the tableBasicTupleSets list. public void orderBasicTupleSetsByTable() { if (!this.tableBasicTupleSets.isEmpty()) { return; } // Add every basic tuple set to the tuple set list of the table they belong to. for (TupleSet tupleSet : this.basicTupleSets) { int index = getIndexOfTable(tupleSet.getTable()); if (index != -1) { this.tableBasicTupleSets.get(index).addTupleSet(tupleSet); } else { this.tableBasicTupleSets.add(new TableTupleSets(tupleSet)); } } } // Print the statistics public void printStats() { System.out.println("TUPLE SETS PRE PROCESSOR STATS :"); System.out.println("\tTime to generate TupleSets Combos: " + this.timeGeneratingTupleSets); } // Fill the Statistics we want to display on Thor public Table getStatistics() { List<Table.Row> rows = new ArrayList<>(); // The table rows. rows.add(new Table.Row( Arrays.asList( "Num of Basic TupleSets", Integer.toString(this.basicTupleSets.size()) ))); rows.add(new Table.Row( Arrays.asList( "Num of Combinations (using the above TupleSets)", Integer.toString(this.tupleSetCombinations.size()) ))); // Return the table containing the Components Info. return new Table(rows); } } // +==========================+ // | TupleSet HashTable Class | // +==========================+ class TupleSetsHashTable { // A list of HashMaps ordered in the cardinality of the sets they include. // The BitSet represents what keywords each tupleSet contains (with 1) and not contain (with 0). List<Map<BitSet,TupleSet>> listOfMaps; // Public Constructor TupleSetsHashTable (int maxSetCardinality) { this.listOfMaps = new ArrayList<Map<BitSet,TupleSet>>(maxSetCardinality); for (int index=0; index < maxSetCardinality; index++) { this.listOfMaps.add(new HashMap<BitSet,TupleSet>()); } } public static BitSet convert(int value) { BitSet bits = new BitSet(); int index = 0; while (value != 0L) { if (value % 2L != 0) { bits.set(index); } index++; value = value >>> 1; } return bits; } // Add a new tuple set void add(BitSet bitset, TupleSet tupleSet) { // Determine the Hash Map that this tuple set will // be added to depending on his bitset sum of 1. // Which means on the number of tupleSets contained // in the TupleSet. int index = bitset.cardinality() - 1; this.listOfMaps.get(index).put(bitset, tupleSet); } // Get the TupleSet mapped to bitset TupleSet getTupleSetWithBitSet(BitSet bitset){ // The hash map that this biteSet's tuple // is, can be located from the bitSets sum of 1. Map<BitSet,TupleSet> map = this.listOfMaps.get(bitset.cardinality() - 1); return map.get(bitset); } // Get a pair of TupleSets that create the give bitSet of keywords List<TupleSet> getPairCreatingTupleSetWithBitSet(BitSet bitset) { // Dont search for TupleSets containing less than two keywords if (bitset.cardinality() < 2) { return null; } // Find the first occurrence of a bit set to 1 int index = bitset.nextSetBit(0); // Candidate one : // Create a bit set with the same size but with only that bit set to 1 BitSet candidateOne = new BitSet(bitset.length()); candidateOne.set(index); // Candidate two : BitSet candidateTwo = (BitSet) bitset.clone(); candidateTwo.clear(index); // Search for both candidates in the hash map. // They should be there because of the way that Tuple // sets are created from the callee function. TupleSet tupleSetOne = this.getTupleSetWithBitSet(candidateOne); TupleSet tupleSetTwo = this.getTupleSetWithBitSet(candidateTwo); // Return the candidates or null if a candidate was not found. if (tupleSetOne == null || tupleSetTwo == null) { return null; } List<TupleSet> resultList = new ArrayList<TupleSet>(); resultList.add(tupleSetOne); resultList.add(tupleSetTwo); if (DiscoverApplication.DEBUG_PRINTS) { System.out.println("Candidate TupleSets for creating a set"); for (TupleSet set: resultList) { System.out.println(set.toAbbreviation()); for (SQLTuple tup: set.getTuples()) { System.out.println("\t" + tup); } } } return resultList; } }
38.744966
113
0.626018
1a9147930cf65bf87b329a9996fe4d68f346d9a5
3,700
/* Copyright (c) 2015, Boston University * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.cidarlab.sparrow.test; import java.net.URL; import java.util.Set; import org.cidarlab.eugene.dom.Component; import org.cidarlab.sparrow.Sparrow; import org.cidarlab.sparrow.exception.ImportException; import org.cidarlab.sparrow.exception.SparrowException; import org.cidarlab.sparrow.importers.SBOLImporter; /** * * and here's the mapping again: * SBOL DnaComponent (w/o SequenceAnnotations) --> Sparrow Part * SBOL DnaComponent (w/ SequenceAnnotations) --> Sparrow Device * SBOL Collection --> Sparrow java.util.HashSet * * @author Ernst Oberortner */ public class URLImporter { private Sparrow sparrow; private static final String URL_PREFIX = "http://convert.sbols.org/biobrick/"; public URLImporter() throws SparrowException { try { this.sparrow = new Sparrow(); } catch(SparrowException se) { throw new SparrowException(se.getMessage()); } } public void test() throws SparrowException, ImportException { String[] parts = {"BBa_K780001", "BBa_K780002", "BBa_K780003", "BBa_I0500"}; for(String part : parts) { if(!this.importSBOL(part)) { throw new ImportException("import of "+part+" failed."); } } // compare the test results w/ the expected results if(4 != this.sparrow.getFactCount()) { throw new SparrowException("[URLImporter.test] FAILED!"); } } @SuppressWarnings("unchecked") public boolean importSBOL(String part) { try { Object o = SBOLImporter.importSBOL(new URL(URL_PREFIX+part)); if(null != o) { if(o instanceof Component) { // Part or Device this.sparrow.insertFact((Component)o); } else if(o instanceof java.util.HashSet) { // Collection /* * here, we iterate over the collection * inserting each element */ Set<Component> components = (java.util.Set<Component>)o; if(!components.isEmpty()) { for(Component c : components) { this.sparrow.insertFact(c); } } } return true; } } catch(Exception e) { e.printStackTrace(); } return false; } }
33.035714
100
0.707297
c5157e75c9c459a262bdc554f7d71c3b1248f929
759
package net.minecraft.item; import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class ItemCoal extends Item { private static final String __OBFID = "CL_00000002"; public ItemCoal() { this.func_77627_a(true); this.func_77656_e(0); this.func_77637_a(CreativeTabs.field_78035_l); } public String func_77667_c(ItemStack p_77667_1_) { return p_77667_1_.func_77960_j() == 1?"item.charcoal":"item.coal"; } public void func_150895_a(Item p_150895_1_, CreativeTabs p_150895_2_, List p_150895_3_) { p_150895_3_.add(new ItemStack(p_150895_1_, 1, 0)); p_150895_3_.add(new ItemStack(p_150895_1_, 1, 1)); } }
27.107143
92
0.72332
73844b96c5252f5ee2894c84ce0b02cd9b6350b6
2,847
// BiblioCriterion.java // // senger@ebi.ac.uk // April 2001 // /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bibliography; /** * The criteria define how the matching or ordering should be done * during queries. * * @author <A HREF="mailto:senger@ebi.ac.uk">Martin Senger</A> * @version $Id: BiblioCriterion.java 2812 2003-07-16 16:01:11Z mrp $ * @since 1.3 */ public class BiblioCriterion { /** * A query criterion. */ public static final int QUERY_CRITERION = 0; /** * A sort criterion. */ public static final int SORT_CRITERION = 1; /** * <p> * Each Criterion is identified by its name. * A list of criteria names is used in methods for querying and sorting * (see {@link BibRefQuery} interface). * </p> * * <p> * The implementations are advised to use descriptive names. * For example, the names for matching can be: * <pre> * match all words * match any word * case insensitive * case sensitive * partial word match * full word match * </pre> * and the names for ordering can be: * <pre> * ascending * descending * </pre> * Another example of how to use Criteria is to allow regular expressions in queries. * Not every implementation is supposed to have the capability of matching by regular * expressions but those who have can specify (and document), for example, criterion * with name <tt>regular expression</tt>. * </p> */ public String name; /** * The criteria can be used for defining rules for matching * (type {@link #QUERY_CRITERION}), or for ordering (type {@link #SORT_CRITERION}). */ public int type = QUERY_CRITERION; /** * <p> * A list of other criteria names that this criterion is mutually exclusive with. * </p> * * <p> * For example, a sort criterion <tt>ascending</tt> will probably have * <tt>descending</tt> in this list. * </p> */ public String[] mutuallyExclusiveWith; /** * A name of a repository subset which this criterion is valid/used for. * @see BiblioEntryStatus#repositorySubset */ public String forSubset; }
27.114286
89
0.625922
013bda4a25aaf6efec8aee64785f4113f99a07bb
1,780
package demos.components; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; import com.jfoenix.controls.JFXSlider; import com.jfoenix.controls.JFXSlider.IndicatorPosition; public class SliderDemo extends Application { @Override public void start(Stage primaryStage) throws Exception { try { JFXSlider hor_left = new JFXSlider(); hor_left.setMinWidth(500); JFXSlider hor_right = new JFXSlider(); hor_left.setMinWidth(500); hor_left.setIndicatorPosition(IndicatorPosition.RIGHT); JFXSlider ver_left = new JFXSlider(); ver_left.setMinHeight(500); ver_left.setOrientation(Orientation.VERTICAL); JFXSlider ver_right = new JFXSlider(); ver_right.setMinHeight(500); ver_right.setOrientation(Orientation.VERTICAL); ver_right.setIndicatorPosition(IndicatorPosition.RIGHT); HBox hbox = new HBox(); hbox.setSpacing(450); hbox.getChildren().addAll(ver_right, ver_left); VBox vbox = new VBox(); vbox.getChildren().addAll(hor_right, hor_left, hbox); vbox.setSpacing(100); vbox.setPadding(new Insets(100, 50, 50, 150)); Scene scene = new Scene(new Group()); ((Group) scene.getRoot()).getChildren().add(vbox); scene.getStylesheets().add(SliderDemo.class.getResource("/resources/css/jfoenix-components.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.setWidth(900); primaryStage.setHeight(900); primaryStage.show(); primaryStage.setTitle("JFX Slider Demo"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } }
28.253968
118
0.747191
4aa5ee9523c9a2b31db1ecb499f38b9a1c545c3a
343
package net.optifine.render; import net.minecraft.util.math.AxisAlignedBB; public interface ICamera { void setCameraPosition(double var1, double var3, double var5); boolean isBoundingBoxInFrustum(AxisAlignedBB var1); boolean isBoxInFrustumFully(double var1, double var3, double var5, double var7, double var9, double var11); }
26.384615
111
0.784257
b664cb6053e185defa4c9d5f0e1895cd52b6ea5f
360
package edu.bu.met.cs665; import edu.bu.met.cs665.entity.Game; import edu.bu.met.cs665.entity.NewGame; public class Main { /** * A main method to run examples. * @param args not used */ public static void main(String[] args) { //Create a single game object Game game = NewGame.getInstance(); game.startGame(); } }
18
43
0.633333
d995b58c003c278be47a9f597814ffcd488d3e66
921
package se.cbb.jprime.mcmc; /** * Represents a simple fixed tuning parameter. * * @author Joel Sjöstrand. */ public class ConstantTuningParameter implements TuningParameter { /** The value. */ protected double value; /** * Constructor. * @param value the value. */ public ConstantTuningParameter(double value) { this.value = value; } @Override public double getValue() { return this.value; } @Override public double getMinValue() { return this.value; } @Override public double getMaxValue() { return this.value; } @Override public String getPreInfo(String prefix) { StringBuilder sb = new StringBuilder(); sb.append(prefix).append("CONSTANT TUNING PARAMETER\n"); sb.append(prefix).append("Value: ").append(this.value).append('\n'); return sb.toString(); } @Override public String getPostInfo(String prefix) { return (prefix + "CONSTANT TUNING PARAMETER\n"); } }
18.42
70
0.697068
326e662c1345fd0502ec61b6bf14d10f139ec6e4
8,112
/******************************************************************************* * Copyright (C) FlexiCore, Inc - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Avishay Ben Natan And Asaf Ben Natan, October 2015 ******************************************************************************/ package com.flexicore.interceptors; import com.flexicore.annotations.OperationsInside; import com.flexicore.data.jsoncontainers.OperationInfo; import com.flexicore.model.Operation; import com.flexicore.model.Tenant; import com.flexicore.model.User; import com.flexicore.request.RecoverTotpRequest; import com.flexicore.request.TotpAuthenticationRequest; import com.flexicore.rest.TotpRESTService; import com.flexicore.security.SecurityContext; import com.flexicore.service.impl.SecurityService; import io.jsonwebtoken.JwtException; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import javax.websocket.CloseReason; import javax.websocket.Session; import javax.ws.rs.NotAuthorizedException; import java.lang.reflect.Method; import java.util.List; import java.util.stream.Stream; /** * uses Aspect Oriented Programming (through JavaEE support) to enforce security * Access granularity is specified in a separate UML diagram * * @author Avishay Ben Natan */ @Aspect @Component @Order(0) public class SecurityImposer { /** * */ private static final long serialVersionUID = 1L; @Autowired private SecurityService securityService; private static final Logger logger = LoggerFactory.getLogger(SecurityImposer.class); private static Method totpAuthenticationMethod; private static Method totpRecoveryMethod; @Around("execution(@com.flexicore.annotations.Protected * *(..)) || within(@(@com.flexicore.annotations.Protected *) *)|| within(@com.flexicore.annotations.Protected *)") public Object transformReturn(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); Session websocketSession = null; try { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); Object[] parameters = joinPoint.getArgs(); String methodName = method.getName(); logger.info("Method is: " + methodName + " , on Thread " + Thread.currentThread().getName()); String authenticationkey = (String) parameters[0]; websocketSession = getWebsocketSession(parameters); if (authenticationkey != null && !authenticationkey.isEmpty()) { OperationInfo operationInfo = securityService.getIOperation(method); SecurityContext securityContext = securityService.getSecurityContext(authenticationkey, operationInfo.getOperationId()); if (securityContext == null) { return deny(websocketSession); } User user = securityContext.getUser(); List<Tenant> tenants = securityContext.getTenants(); Operation operation = securityContext.getOperation(); OperationsInside operationsInside = method.getDeclaringClass().getAnnotation(OperationsInside.class); if (operationInfo.getiOperation() == null) { logger.error("could not find io operation annotation on method: " + methodName); return deny(websocketSession); } if (user == null) { logger.error("could not determine user"); return deny(websocketSession); } if (tenants == null) { logger.error("could not determine tenants"); return deny(websocketSession); } if (operation == null) { logger.error("could not determine operation for method " + methodName); return deny(websocketSession); } if (!isTotpAuthentication(method)&&user.isTotpEnabled() && !securityContext.isTotpVerified()) { return deny(websocketSession); } if (securityService.checkIfAllowed(user, tenants, operation, operationInfo.getiOperation().access())) { Object procceed = procceed(securityContext, joinPoint, methodName, parameters, start); return procceed; } else { return deny(websocketSession); } } else { return deny(websocketSession); } } catch (JwtException e) { logger.error("security check failed with error", e); return deny(websocketSession); } } private boolean isTotpAuthentication(Method method) { Method totpAuthenticationMethod= getTotpAuthenticationMethod(); Method totpRecoveryMethod= getTotpRecoveryMethod(); return method.equals(totpAuthenticationMethod)||method.equals(totpRecoveryMethod); } private Method getTotpAuthenticationMethod() { if(totpAuthenticationMethod==null){ try { totpAuthenticationMethod = TotpRESTService.class.getMethod("authenticateTotp", String.class, TotpAuthenticationRequest.class, SecurityContext.class); } catch (Exception e){ logger.error("could not find totp authenticationMethod"); } } return totpAuthenticationMethod; } private Method getTotpRecoveryMethod() { if(totpRecoveryMethod==null){ try { totpRecoveryMethod = TotpRESTService.class.getMethod("recoverTotp", String.class, RecoverTotpRequest.class, SecurityContext.class); } catch (Exception e){ logger.error("could not find totp authenticationMethod"); } } return totpRecoveryMethod; } private Session getWebsocketSession(Object[] parameters) { return parameters != null ? Stream.of(parameters).filter(f -> f instanceof Session).map(f -> (Session) f).findAny().orElse(null) : null; } private Object procceed(SecurityContext securityContext, ProceedingJoinPoint proceedingJoinPoint, String methodName, Object[] parameters, long start) throws Throwable { Object param = parameters[parameters.length - 1]; if (param instanceof Session) { Session session = (Session) param; session.getUserProperties().put("securityContext", securityContext); } else { parameters[parameters.length - 1] = securityContext; } Object o = proceedingJoinPoint.proceed(parameters); long timeTaken = System.currentTimeMillis() - start; logger.info("request to " + methodName + " took: " + timeTaken + "ms"); return o; } private Object deny(Session websocketSession) { String reason = "user is not authorized for this resource"; closeWSIfNecessary(websocketSession, reason); throw new NotAuthorizedException(reason); } private void closeWSIfNecessary(Session websocketSession, String reason) { if (websocketSession != null && websocketSession.isOpen()) { try { String id = websocketSession.getId(); websocketSession.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, reason)); logger.warn("Closed WS " + id + " for being unauthorized"); } catch (Exception e) { logger.error("failed closing WS", e); } } } }
40.158416
174
0.641519
76bb43381fc728d0884e180449818b8e3629688d
575
package perococco.aoc.api; import lombok.NonNull; public interface AOCProblem<S> extends Comparable<AOCProblem<?>> { @NonNull AOCProblemId id(); @NonNull S solve(); default boolean isSkipped() { return false; } @NonNull default String problemName() { return id().day()+" "+id().part(); } @Override default int compareTo(@NonNull AOCProblem<?> other) { return this.id().compareTo(other.id()); } default @NonNull AOCProblem<S> skipped() { return new SkippedAOCProblem<>(this); } }
18.548387
66
0.606957
5213978f20efc8f99c5a7e6a3c82dfa5a327a703
9,901
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.io.cassandra; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Table; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import org.apache.beam.sdk.coders.SerializableCoder; import org.apache.beam.sdk.io.BoundedSource; import org.apache.beam.sdk.io.BoundedSource.BoundedReader; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Count; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.MapElements; import org.apache.beam.sdk.transforms.SimpleFunction; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Objects; import org.junit.Rule; import org.junit.Test; /** Tests of {@link CassandraIO}. */ public class CassandraIOTest implements Serializable { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Test public void testEstimatedSizeBytes() { final FakeCassandraService service = new FakeCassandraService(); service.load(); PipelineOptions pipelineOptions = PipelineOptionsFactory.create(); CassandraIO.Read<Scientist> spec = CassandraIO.<Scientist>read().withCassandraService(service); CassandraIO.CassandraSource<Scientist> source = new CassandraIO.CassandraSource<>(spec, null); long estimatedSizeBytes = source.getEstimatedSizeBytes(pipelineOptions); // the size is the sum of the bytes size of the String representation of a scientist in the map assertEquals(113890, estimatedSizeBytes); } @Test public void testRead() { FakeCassandraService service = new FakeCassandraService(); service.load(); PCollection<Scientist> output = pipeline.apply( CassandraIO.<Scientist>read() .withCassandraService(service) .withKeyspace("beam") .withTable("scientist") .withCoder(SerializableCoder.of(Scientist.class)) .withEntity(Scientist.class)); PAssert.thatSingleton(output.apply("Count", Count.globally())).isEqualTo(10000L); PCollection<KV<String, Integer>> mapped = output.apply( MapElements.via( new SimpleFunction<Scientist, KV<String, Integer>>() { @Override public KV<String, Integer> apply(Scientist scientist) { return KV.of(scientist.name, scientist.id); } })); PAssert.that(mapped.apply("Count occurrences per scientist", Count.perKey())) .satisfies( input -> { for (KV<String, Long> element : input) { assertEquals(element.getKey(), 1000, element.getValue().longValue()); } return null; }); pipeline.run(); } @Test public void testWrite() { FakeCassandraService service = new FakeCassandraService(); ArrayList<Scientist> data = new ArrayList<>(); for (int i = 0; i < 1000; i++) { Scientist scientist = new Scientist(); scientist.id = i; scientist.name = "Name " + i; data.add(scientist); } pipeline .apply(Create.of(data)) .apply( CassandraIO.<Scientist>write() .withCassandraService(service) .withKeyspace("beam") .withEntity(Scientist.class)); pipeline.run(); assertEquals(1000, service.getTable().size()); for (Scientist scientist : service.getTable().values()) { assertTrue(scientist.name.matches("Name (\\d*)")); } } @Test public void testDelete() { FakeCassandraService service = new FakeCassandraService(); service.load(); assertEquals(10000, service.getTable().size()); pipeline .apply( CassandraIO.<Scientist>read() .withCassandraService(service) .withKeyspace("beam") .withTable("scientist") .withCoder(SerializableCoder.of(Scientist.class)) .withEntity(Scientist.class)) .apply( CassandraIO.<Scientist>delete() .withCassandraService(service) .withKeyspace("beam") .withEntity(Scientist.class)); pipeline.run(); assertEquals(0, service.getTable().size()); } /** A {@link CassandraService} implementation that stores the entity in memory. */ private static class FakeCassandraService implements CassandraService<Scientist> { private static final Map<Integer, Scientist> table = new ConcurrentHashMap<>(); void load() { table.clear(); String[] scientists = { "Lovelace", "Franklin", "Meitner", "Hopper", "Curie", "Faraday", "Newton", "Bohr", "Galilei", "Maxwell" }; for (int i = 0; i < 10000; i++) { int index = i % scientists.length; Scientist scientist = new Scientist(); scientist.id = i; scientist.name = scientists[index]; table.put(scientist.id, scientist); } } Map<Integer, Scientist> getTable() { return table; } @Override public BoundedReader<Scientist> createReader(CassandraIO.CassandraSource<Scientist> source) { return new FakeCassandraReader(source); } private static class FakeCassandraReader extends BoundedSource.BoundedReader<Scientist> { private final CassandraIO.CassandraSource<Scientist> source; private Iterator<Scientist> iterator; private Scientist current; FakeCassandraReader(CassandraIO.CassandraSource<Scientist> source) { this.source = source; } @Override public boolean start() { iterator = table.values().iterator(); return advance(); } @Override public boolean advance() { if (iterator.hasNext()) { current = iterator.next(); return true; } current = null; return false; } @Override public void close() { iterator = null; current = null; } @Override public Scientist getCurrent() throws NoSuchElementException { if (current == null) { throw new NoSuchElementException(); } return current; } @Override public CassandraIO.CassandraSource<Scientist> getCurrentSource() { return this.source; } } @Override public long getEstimatedSizeBytes(CassandraIO.Read spec) { long size = 0L; for (Scientist scientist : table.values()) { size = size + scientist.toString().getBytes(StandardCharsets.UTF_8).length; } return size; } @Override public List<BoundedSource<Scientist>> split( CassandraIO.Read<Scientist> spec, long desiredBundleSizeBytes) { return Collections.singletonList(new CassandraIO.CassandraSource<>(spec, null)); } private static class FakeCassandraWriter implements Writer<Scientist> { @Override public void write(Scientist scientist) { table.put(scientist.id, scientist); } @Override public void close() { // nothing to do } } @Override public FakeCassandraWriter createWriter(CassandraIO.Mutate<Scientist> spec) { return new FakeCassandraWriter(); } private static class FakeCassandraDeleter implements Deleter<Scientist> { @Override public void delete(Scientist scientist) { table.remove(scientist.id); } @Override public void close() { // nothing to do } } @Override public FakeCassandraDeleter createDeleter(CassandraIO.Mutate<Scientist> spec) { return new FakeCassandraDeleter(); } } /** Simple Cassandra entity used in test. */ @Table(name = "scientist", keyspace = "beam") static class Scientist implements Serializable { @Column(name = "person_name") String name; @Column(name = "person_id") int id; @Override public String toString() { return id + ":" + name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Scientist scientist = (Scientist) o; return id == scientist.id && Objects.equal(name, scientist.name); } @Override public int hashCode() { return Objects.hashCode(name, id); } } }
30.653251
99
0.648722
0e8b98f6d4f5cf8502e904bda0e43b2778203d72
2,227
/* * Copyright 2005-2019 Dozer Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.dozermapper.core.events; import java.util.List; import com.github.dozermapper.core.MappingException; /** * Event manager which simply fires to the corrasponding {@link EventListener} */ public final class DefaultEventManager implements EventManager { private final List<? extends EventListener> eventListeners; /** * Event manager which simply fires to the corrasponding {@link EventListener} * * @param eventListeners event listeners to callback to */ public DefaultEventManager(List<? extends EventListener> eventListeners) { this.eventListeners = eventListeners; } /** * {@inheritDoc} */ @Override public void on(Event event) { if (eventListeners != null) { for (EventListener listener : eventListeners) { switch (event.getType()) { case MAPPING_STARTED: listener.onMappingStarted(event); break; case MAPPING_PRE_WRITING_DEST_VALUE: listener.onPreWritingDestinationValue(event); break; case MAPPING_POST_WRITING_DEST_VALUE: listener.onPostWritingDestinationValue(event); break; case MAPPING_FINISHED: listener.onMappingFinished(event); break; default: throw new MappingException("Unsupported event type: " + event.getType()); } } } } }
34.261538
97
0.614279
42fae73b8ab19743ff5659cf5639d2e62562ba67
13,067
/* * @(#)RandomVariable.java 3.0.0 2016-05-07 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariuszgromada.org@gmail.com * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ package org.mariuszgromada.math.mxparser.parsertokens; /** * Random variables - mXparser tokens definition. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * * @version 3.0.0 */ public final class RandomVariable { /* * BooleanOperator - token type id. */ public static final int TYPE_ID = 10; public static final String TYPE_DESC = "Random Variable"; /* * BooleanOperator - tokens id. */ public static final int UNIFORM_ID = 1; public static final int INT_ID = 2; public static final int INT1_ID = 3; public static final int INT2_ID = 4; public static final int INT3_ID = 5; public static final int INT4_ID = 6; public static final int INT5_ID = 7; public static final int INT6_ID = 8; public static final int INT7_ID = 9; public static final int INT8_ID = 10; public static final int INT9_ID = 11; public static final int NAT0_ID = 12; public static final int NAT0_1_ID = 13; public static final int NAT0_2_ID = 14; public static final int NAT0_3_ID = 15; public static final int NAT0_4_ID = 16; public static final int NAT0_5_ID = 17; public static final int NAT0_6_ID = 18; public static final int NAT0_7_ID = 19; public static final int NAT0_8_ID = 20; public static final int NAT0_9_ID = 21; public static final int NAT1_ID = 22; public static final int NAT1_1_ID = 23; public static final int NAT1_2_ID = 24; public static final int NAT1_3_ID = 25; public static final int NAT1_4_ID = 26; public static final int NAT1_5_ID = 27; public static final int NAT1_6_ID = 28; public static final int NAT1_7_ID = 29; public static final int NAT1_8_ID = 30; public static final int NAT1_9_ID = 31; public static final int NOR_ID = 32; /* * BooleanOperator - tokens key words. */ public static final String UNIFORM_STR = "[Uni]"; public static final String INT_STR = "[Int]"; public static final String INT1_STR = "[Int1]"; public static final String INT2_STR = "[Int2]"; public static final String INT3_STR = "[Int3]"; public static final String INT4_STR = "[Int4]"; public static final String INT5_STR = "[Int5]"; public static final String INT6_STR = "[Int6]"; public static final String INT7_STR = "[Int7]"; public static final String INT8_STR = "[Int8]"; public static final String INT9_STR = "[Int9]"; public static final String NAT0_STR = "[nat]"; public static final String NAT0_1_STR = "[nat1]"; public static final String NAT0_2_STR = "[nat2]"; public static final String NAT0_3_STR = "[nat3]"; public static final String NAT0_4_STR = "[nat4]"; public static final String NAT0_5_STR = "[nat5]"; public static final String NAT0_6_STR = "[nat6]"; public static final String NAT0_7_STR = "[nat7]"; public static final String NAT0_8_STR = "[nat8]"; public static final String NAT0_9_STR = "[nat9]"; public static final String NAT1_STR = "[Nat]"; public static final String NAT1_1_STR = "[Nat1]"; public static final String NAT1_2_STR = "[Nat2]"; public static final String NAT1_3_STR = "[Nat3]"; public static final String NAT1_4_STR = "[Nat4]"; public static final String NAT1_5_STR = "[Nat5]"; public static final String NAT1_6_STR = "[Nat6]"; public static final String NAT1_7_STR = "[Nat7]"; public static final String NAT1_8_STR = "[Nat8]"; public static final String NAT1_9_STR = "[Nat9]"; public static final String NOR_STR = "[Nor]"; /* * BooleanOperator - tokens description. */ public static final String UNIFORM_DESC = "(3.0) Random variable - Uniform continuous distribution U(0,1), usage example: 2*[Uni]"; public static final String INT_DESC = "(3.0) Random variable - random integer - usage example sin( 3*[Int] )"; public static final String INT1_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^1, 10^1} - usage example sin( 3*[Int1] )"; public static final String INT2_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^2, 10^2} - usage example sin( 3*[Int2] )"; public static final String INT3_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^3, 10^3} - usage example sin( 3*[Int3] )"; public static final String INT4_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^4, 10^4} - usage example sin( 3*[Int4] )"; public static final String INT5_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^5, 10^5} - usage example sin( 3*[Int5] )"; public static final String INT6_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^6, 10^6} - usage example sin( 3*[Int6] )"; public static final String INT7_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^7, 10^7} - usage example sin( 3*[Int7] )"; public static final String INT8_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^8, 10^8} - usage example sin( 3*[Int8] )"; public static final String INT9_DESC = "(3.0) Random variable - random integer - Uniform discrete distribution U{-10^9, 10^9} - usage example sin( 3*[Int9] )"; public static final String NAT0_DESC = "(3.0) Random variable - random natural number including 0 - usage example sin( 3*[nat] )"; public static final String NAT0_1_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^1} - usage example sin( 3*[nat1] )"; public static final String NAT0_2_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^2} - usage example sin( 3*[nat2] )"; public static final String NAT0_3_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^3} - usage example sin( 3*[nat3] )"; public static final String NAT0_4_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^4} - usage example sin( 3*[nat4] )"; public static final String NAT0_5_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^5} - usage example sin( 3*[nat5] )"; public static final String NAT0_6_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^6} - usage example sin( 3*[nat6] )"; public static final String NAT0_7_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^7} - usage example sin( 3*[nat7] )"; public static final String NAT0_8_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^8} - usage example sin( 3*[nat8] )"; public static final String NAT0_9_DESC = "(3.0) Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^9} - usage example sin( 3*[nat9] )"; public static final String NAT1_DESC = "(3.0) Random variable - random natural number - usage example sin( 3*[Nat] )"; public static final String NAT1_1_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^1} - usage example sin( 3*[Nat1] )"; public static final String NAT1_2_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^2} - usage example sin( 3*[Nat2] )"; public static final String NAT1_3_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^3} - usage example sin( 3*[Nat3] )"; public static final String NAT1_4_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^4} - usage example sin( 3*[Nat4] )"; public static final String NAT1_5_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^5} - usage example sin( 3*[Nat5] )"; public static final String NAT1_6_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^6} - usage example sin( 3*[Nat6] )"; public static final String NAT1_7_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^7} - usage example sin( 3*[Nat7] )"; public static final String NAT1_8_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^8} - usage example sin( 3*[Nat8] )"; public static final String NAT1_9_DESC = "(3.0) Random variable - random natural number - Uniform discrete distribution U{1, 10^9} - usage example sin( 3*[Nat9] )"; public static final String NOR_DESC = "(3.0) Random variable - Normal distribution N(0,1) - usage example cos( 3*[Nor]+1 )"; }
69.877005
182
0.683477
e7e89390d8bea54e1768f660a67ded13b8a878a7
578
package GameObjects; import Controller.KeyboardController; import Interfaces.Moveable; import java.awt.Color; /** * * @author Brandon Neri */ public abstract class ControlledGameObject extends GameObject implements Moveable { KeyboardController control; public ControlledGameObject(int xPosition, int yPosition, Color color, KeyboardController control) { // Might be MovingGameObject super(xPosition, yPosition, color); // Inherit values from GameObject Class this.control = control; // Define new instance of KeyboardController Class } }
28.9
133
0.757785
d6546ab378d93339ba971c5d93c362f4694b26d6
1,764
package org.python.core; public enum CompareOp { LT(0), LE(1), EQ(2), NE(3), GT(4), GE(5); private int n; private static final CompareOp[] swappedOps = new CompareOp[] { GT, GE, EQ, NE, LT, LE }; private static final String[] stringOps = new String[] { "<", "<=", "==", "!=", ">", ">=" }; private static final String[] methOps = new String[] { "__lt__", "__le__", "__eq__", "__ne__", "__gt__", "__ge__" }; CompareOp(int n) { this.n = n; } public CompareOp reflectedOp() { return swappedOps[n]; } public PyObject bool(int result) { if (result < -1) { // if (this == EQ) { // return Py.False; // } else if (this == NE) { // return Py.True; // } return Py.NotImplemented; } switch(this) { case LT: return Py.newBoolean(result < 0); case LE: return Py.newBoolean(result <= 0); case EQ: return Py.newBoolean(result == 0); case NE: return Py.newBoolean(result != 0); case GT: return Py.newBoolean(result > 0); case GE: return Py.newBoolean(result >= 0); default: return Py.NotImplemented; } } public PyObject neq() { switch (this) { case EQ: return Py.False; case NE: return Py.True; default: return Py.NotImplemented; } } public String toString() { return stringOps[n]; } public String meth() { return methOps[n]; } }
24.84507
67
0.451247
9689259350595f803b32c4c5bc124823b52d7f8f
819
package org.innovateuk.ifs; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.io.IOException; /** * Helper around handling JSON within tests */ public class JsonTestUtil { public static <T> T fromJson(String json, Class<T> clazz) { try { return new ObjectMapper().registerModule(new JavaTimeModule()).readValue(json, clazz); } catch (IOException e) { throw new RuntimeException(e); } } public static String toJson(Object object) { try { return new ObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
27.3
98
0.671551
be72032247df497ce3dee0e3279977c1f2c4978f
584
package com.ducks.goodsduck.commons.model.dto.post; import com.ducks.goodsduck.commons.model.entity.User; import lombok.Data; @Data public class PostDetailResponsePostOwner { private Long userId; private String bcryptId; private String nickName; private String imageUrl; private Integer level; public PostDetailResponsePostOwner(User user) { this.userId = user.getId(); this.bcryptId = user.getBcryptId(); this.nickName = user.getNickName(); this.imageUrl = user.getImageUrl(); this.level = user.getLevel(); } }
25.391304
53
0.696918
6a9b53ea4fe05aa25c48f13d048265046b49498e
2,188
/* * 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.axis2.transport.sms.smpp; import org.jsmpp.bean.SubmitSm; import java.util.ArrayList; /** * Manage the SMSCMessageObservers and notify them when a new SMSC message is came in */ public class SMSCMessageNotifier { private ArrayList<SMSCMessageObserver> observers = new ArrayList<SMSCMessageObserver>(); private static SMSCMessageNotifier smsMessageNotifier = new SMSCMessageNotifier(); private SMSCMessageNotifier() { } public static SMSCMessageNotifier getInstence() { return smsMessageNotifier; } /** * Notify the registered Observer about the incomming shotMessage * @param sm */ public void notifyObservers(SubmitSm sm) { for(SMSCMessageObserver o : observers) { o.messsageIn(sm); } } /** * register the SMSCMessageObserver with the SMSCMessageNotifier so that observer will get notified * when the new shot message came from the SMSC * @param o */ public void addObserver(SMSCMessageObserver o) { if(o != null) { observers.add(o); } } /** * Un register the SMSCMessageObserver so that Observer will not notifed of new Shot Message arrivals after that * @param o */ public void removeObserver(SMSCMessageObserver o) { observers.remove(o); } }
30.816901
116
0.694698
aa6bbce17ec3c2466a1444e1ca2655b55cff9d08
1,508
/* * Copyright (C) 2020 catdrinker. * * 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.drinker.speedy; import java.io.IOException; import javax.annotation.Nonnull; import okhttp3.RequestBody; public final class CatchExceptionRequestBody<T> { @Nonnull private Converter<T, okhttp3.RequestBody> requestBodyConverter; public CatchExceptionRequestBody(Converter<T, okhttp3.RequestBody> requestBodyConverter) { this.requestBodyConverter = requestBodyConverter; } public okhttp3.RequestBody getBody(T value) { try { RequestBody body = requestBodyConverter.transform(value); if (body == null) { throw new NullPointerException("cause of converter " + requestBodyConverter.getClass() + " we converter body is null"); } return body; } catch (IOException e) { throw new IllegalStateException("can't transform with requestBody converter " + value); } } }
32.782609
135
0.699602
7507105acf2b98d752b584201f71a6f330752362
850
package com.example.anipa.myapplication; public class People { private String name; private String genero; private String birthday; public People(String name, String genero, String birthday ) { this.name = name; this.genero=genero; this.birthday=birthday; } public String getName() { return name; } public String getGender() { return genero; } public String getBirthday() { return birthday; } } public Hero(String name, String genero, String birthday ) { this.name = name; this.genero=genero; this.birthday=birthday; } public String getName() { return name; } public String getGenero() { return genero; } public String getBirthday() { return birthday; } }
15.178571
66
0.584706
13eb07fa589fb13ddf39230fce8b8417691b3ac9
4,239
package com.denizenscript.denizen2sponge.events.player; import com.denizenscript.denizen2core.events.ScriptEvent; import com.denizenscript.denizen2core.tags.AbstractTagObject; import com.denizenscript.denizen2core.tags.objects.IntegerTag; import com.denizenscript.denizen2sponge.Denizen2Sponge; import com.denizenscript.denizen2sponge.events.D2SpongeEventHelper; import com.denizenscript.denizen2sponge.tags.objects.LocationTag; import com.denizenscript.denizen2sponge.tags.objects.PlayerTag; import com.denizenscript.denizen2sponge.utilities.Utilities; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.entity.ChangeEntityExperienceEvent; import org.spongepowered.api.event.filter.cause.Root; import java.util.HashMap; public class ExperienceChangesScriptEvent extends ScriptEvent { // <--[event] // @Since 0.3.0 // @Events // experience changes // // @Updated 2017/10/16 // // @Cancellable true // // @Group Player // // @Triggers when a player's experience changes. // // @Warning This event does not trigger in Sponge during last testing. // // @Switch world (WorldTag) checks the world. // @Switch cuboid (CuboidTag) checks the cuboid area. // @Switch weather (TextTag) checks the weather. // // @Context // player (PlayerTag) returns the player that changed experience. // old_xp (IntegerTag) returns the old experience value. // new_xp (IntegerTag) returns the new experience value. // // @Determinations // xp (IntegerTag) sets the new experience value. // --> @Override public String getName() { return "ExperienceChanges"; } @Override public boolean couldMatch(ScriptEventData data) { return data.eventPath.startsWith("experience changes"); } @Override public boolean matches(ScriptEventData data) { return D2SpongeEventHelper.checkWorld(player.getOnline(this::error).getLocation().getExtent(), data, this::error) && D2SpongeEventHelper.checkCuboid((new LocationTag(player.getOnline(this::error) .getLocation())).getInternal(), data, this::error) && D2SpongeEventHelper.checkWeather(Utilities.getIdWithoutDefaultPrefix( player.getOnline(this::error).getLocation().getExtent().getWeather().getId()), data, this::error); } public PlayerTag player; public IntegerTag old_xp; public IntegerTag new_xp; public ChangeEntityExperienceEvent internal; @Override public HashMap<String, AbstractTagObject> getDefinitions(ScriptEventData data) { HashMap<String, AbstractTagObject> defs = super.getDefinitions(data); defs.put("player", player); defs.put("old_xp", old_xp); defs.put("new_xp", new_xp); return defs; } @Override public void enable() { Sponge.getEventManager().registerListeners(Denizen2Sponge.instance, this); } @Override public void disable() { Sponge.getEventManager().unregisterListeners(this); } @Listener public void onExperienceChanges(ChangeEntityExperienceEvent evt, @Root Player player) { ExperienceChangesScriptEvent event = (ExperienceChangesScriptEvent) clone(); event.internal = evt; event.player = new PlayerTag(player); event.old_xp = new IntegerTag(evt.getOriginalExperience()); event.new_xp = new IntegerTag(evt.getExperience()); event.cancelled = evt.isCancelled(); event.run(); evt.setCancelled(event.cancelled); } @Override public void applyDetermination(boolean errors, String determination, AbstractTagObject value) { if (determination.equals("xp")) { IntegerTag it = IntegerTag.getFor(this::error, value); new_xp = it; internal.setExperience((int) it.getInternal()); } else { super.applyDetermination(errors, determination, value); } } }
35.621849
122
0.673744
ed81f39cc085a02d7796e657f76fed03c1af3b56
162
package problem1; public class EmptyPriorityQueueException extends Exception { public EmptyPriorityQueueException(String message) { super(message); } }
18
60
0.783951
5281743a8bec78223ced46c82e57a0f61048bd93
2,554
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.bpmn.definition.property.cm; import javax.validation.Valid; import org.jboss.errai.common.client.api.annotations.MapsTo; import org.jboss.errai.common.client.api.annotations.Portable; import org.jboss.errai.databinding.client.api.Bindable; import org.kie.workbench.common.forms.adf.definitions.annotations.FormDefinition; import org.kie.workbench.common.forms.adf.definitions.annotations.FormField; import org.kie.workbench.common.forms.adf.definitions.settings.FieldPolicy; import org.kie.workbench.common.stunner.bpmn.definition.BPMNPropertySet; import org.kie.workbench.common.stunner.bpmn.forms.model.cm.RolesEditorFieldType; import org.kie.workbench.common.stunner.core.definition.annotation.Property; import org.kie.workbench.common.stunner.core.definition.annotation.PropertySet; import org.kie.workbench.common.stunner.core.util.HashUtil; @Portable @Bindable @PropertySet @FormDefinition( policy = FieldPolicy.ONLY_MARKED, startElement = "caseRoles" ) public class CaseManagementSet implements BPMNPropertySet { @Property @FormField( type = RolesEditorFieldType.class ) @Valid private CaseRoles caseRoles; public CaseManagementSet() { this(new CaseRoles()); } public CaseManagementSet(final @MapsTo("caseRoles") CaseRoles caseRoles) { this.caseRoles = caseRoles; } public CaseRoles getCaseRoles() { return caseRoles; } public void setCaseRoles(CaseRoles caseRoles) { this.caseRoles = caseRoles; } @Override public int hashCode() { return HashUtil.combineHashCodes(caseRoles.hashCode()); } @Override public boolean equals(Object o) { if (o instanceof CaseManagementSet) { CaseManagementSet other = (CaseManagementSet) o; return caseRoles.equals(other.caseRoles); } return false; } }
32.329114
81
0.735709
5bf6081b6d1e1c74ab1803cfb6c4d6c2601f3fb5
1,548
package com.atguigu.gulimall.product.exception; import com.atguigu.common.exception.BizCodeEnum; import com.atguigu.common.utils.R; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; @Slf4j @ResponseBody @ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller") public class GulimallExceptionControllerAdvice { @ExceptionHandler(value = MethodArgumentNotValidException.class) public R handleValidException(MethodArgumentNotValidException e) { log.error("Validation failed, {}, Exception Class: ", e.getMessage(), e.getClass()); BindingResult result=e.getBindingResult(); Map<String, String> map=new HashMap<>(); result.getFieldErrors().forEach((item)->{ String field=item.getField(); String message=item.getDefaultMessage(); map.put(field, message); }); return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data", map); } @ExceptionHandler(value=Throwable.class) public R handleException(Throwable throwable) { return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMessage()); } }
39.692308
121
0.757106
920536cfcaed403923a9e0706f4316fdba7532e6
28,428
package com.mimacom.liferay.portal.setup.core; /* * #%L * Liferay Portal DB Setup core * %% * Copyright (C) 2016 - 2018 mimacom ag * %% * 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. * #L% */ import com.liferay.asset.kernel.model.AssetEntry; import com.liferay.asset.kernel.model.AssetLinkConstants; import com.liferay.asset.kernel.service.AssetEntryLocalServiceUtil; import com.liferay.asset.kernel.service.AssetLinkLocalServiceUtil; import com.liferay.dynamic.data.lists.model.DDLRecordSet; import com.liferay.dynamic.data.lists.service.DDLRecordSetLocalServiceUtil; import com.liferay.dynamic.data.mapping.exception.StructureDuplicateStructureKeyException; import com.liferay.dynamic.data.mapping.exception.TemplateDuplicateTemplateKeyException; import com.liferay.dynamic.data.mapping.model.*; import com.liferay.dynamic.data.mapping.service.DDMStructureLocalServiceUtil; import com.liferay.dynamic.data.mapping.service.DDMTemplateLocalServiceUtil; import com.liferay.dynamic.data.mapping.util.DDMUtil; import com.liferay.journal.model.JournalArticle; import com.liferay.journal.model.JournalArticleConstants; import com.liferay.journal.model.JournalFolder; import com.liferay.journal.service.JournalArticleLocalServiceUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.RoleConstants; import com.liferay.portal.kernel.search.Indexer; import com.liferay.portal.kernel.search.IndexerRegistryUtil; import com.liferay.portal.kernel.security.permission.ActionKeys; import com.liferay.portal.kernel.service.ClassNameLocalServiceUtil; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.util.*; import com.liferay.portal.kernel.workflow.WorkflowConstants; import com.mimacom.liferay.portal.setup.LiferaySetup; import com.mimacom.liferay.portal.setup.core.util.ResolverUtil; import com.mimacom.liferay.portal.setup.core.util.ResourcesUtil; import com.mimacom.liferay.portal.setup.core.util.TaggingUtil; import com.mimacom.liferay.portal.setup.core.util.FieldMapUtil; import com.mimacom.liferay.portal.setup.core.util.WebFolderUtil; import com.mimacom.liferay.portal.setup.domain.*; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * Created by mapa, guno.. */ public final class SetupArticles { private static final Log LOG = LogFactoryUtil.getLog(SetupArticles.class); private static final HashMap<String, List<String>> DEFAULT_PERMISSIONS; private static final HashMap<String, List<String>> DEFAULT_DDM_PERMISSIONS; private static final int ARTICLE_PUBLISH_YEAR = 2008; private static final int MIN_DISPLAY_ROWS = 10; static { DEFAULT_PERMISSIONS = new HashMap<String, List<String>>(); DEFAULT_DDM_PERMISSIONS= new HashMap<String, List<String>>(); List<String> actionsOwner = new ArrayList<String>(); actionsOwner.add(ActionKeys.VIEW); actionsOwner.add(ActionKeys.ADD_DISCUSSION); actionsOwner.add(ActionKeys.DELETE); actionsOwner.add(ActionKeys.DELETE_DISCUSSION); actionsOwner.add(ActionKeys.EXPIRE); actionsOwner.add(ActionKeys.PERMISSIONS); actionsOwner.add(ActionKeys.UPDATE); actionsOwner.add(ActionKeys.UPDATE_DISCUSSION); List<String> ddmActionsOwner = new ArrayList<String>(); ddmActionsOwner.add(ActionKeys.VIEW); ddmActionsOwner.add(ActionKeys.DELETE); ddmActionsOwner.add(ActionKeys.UPDATE); ddmActionsOwner.add(ActionKeys.PERMISSIONS); DEFAULT_PERMISSIONS.put(RoleConstants.OWNER, actionsOwner); DEFAULT_DDM_PERMISSIONS.put(RoleConstants.OWNER, ddmActionsOwner); List<String> actionsUser = new ArrayList<String>(); actionsUser.add(ActionKeys.VIEW); DEFAULT_PERMISSIONS.put(RoleConstants.USER, actionsUser); DEFAULT_DDM_PERMISSIONS.put(RoleConstants.USER, actionsUser); List<String> actionsGuest = new ArrayList<String>(); actionsGuest.add(ActionKeys.VIEW); DEFAULT_PERMISSIONS.put(RoleConstants.GUEST, actionsGuest); DEFAULT_DDM_PERMISSIONS.put(RoleConstants.GUEST, actionsGuest); } private SetupArticles() { } public static void setupSiteStructuresAndTemplates(final Site site, final long groupId, final long companyId) throws PortalException { List<Structure> articleStructures = site.getArticleStructure(); if (articleStructures != null) { long classNameId = ClassNameLocalServiceUtil.getClassNameId(JournalArticle.class); for (Structure structure : articleStructures) { try { addDDMStructure(structure, groupId, classNameId,companyId); } catch (StructureDuplicateStructureKeyException | IOException | URISyntaxException e) { LOG.error(e); } } } List<Structure> ddlStructures = site.getDdlStructure(); if (articleStructures != null) { long classNameId = ClassNameLocalServiceUtil.getClassNameId(DDLRecordSet.class); for (Structure structure : ddlStructures) { LOG.info("Adding DDL structure " + structure.getName()); try { addDDMStructure(structure, groupId, classNameId,companyId); } catch (StructureDuplicateStructureKeyException | IOException | URISyntaxException e) { LOG.error(e); } } } List<ArticleTemplate> articleTemplates = site.getArticleTemplate(); if (articleTemplates != null) { for (ArticleTemplate template : articleTemplates) { try { addDDMTemplate(template, groupId); } catch (TemplateDuplicateTemplateKeyException | IOException | URISyntaxException e) { LOG.error(e); } } } } public static void setupSiteArticles(final Site site, final long groupId, final long companyId) throws PortalException, SystemException { List<Article> articles = site.getArticle(); if (articles != null) { for (Article article : articles) { addJournalArticle(article, groupId, companyId); } } List<Adt> adts = site.getAdt(); if (adts != null) { for (Adt template : adts) { try { addDDMTemplate(template, groupId); } catch (TemplateDuplicateTemplateKeyException | URISyntaxException | IOException e) { LOG.error("Error in adding ADT: " + template.getName(), e); } } } List<DdlRecordset> recordSets = site.getDdlRecordset(); if (recordSets != null) { for (DdlRecordset recordSet : recordSets) { try { addDDLRecordSet(recordSet, groupId); } catch (TemplateDuplicateTemplateKeyException e) { LOG.error("Error in adding DDLRecordSet: " + recordSet.getName(), e); } } } } public static void addDDMStructure(final Structure structure, final long groupId, final long classNameId,final long companyId) throws SystemException, PortalException, IOException, URISyntaxException { LOG.info("Adding Article structure " + structure.getName()); Map<Locale, String> nameMap = new HashMap<>(); Locale siteDefaultLocale = PortalUtil.getSiteDefaultLocale(groupId); String name = getStructureNameOrKey(structure); nameMap.put(siteDefaultLocale, name); Map<Locale, String> descMap = new HashMap<>(); String content = null; DDMForm ddmForm = null; DDMFormLayout ddmFormLayout = null; try { content = ResourcesUtil.getFileContent(structure.getPath()); ddmForm = DDMUtil.getDDMForm(content); if (ddmForm == null) { LOG.error("Can not parse given structure JSON content into Liferay DDMForm."); return; } ddmFormLayout = DDMUtil.getDefaultDDMFormLayout(ddmForm); } catch (IOException e) { LOG.error("Error Reading Structure File content for: " + structure.getName()); return; } catch (PortalException e) { LOG.error("Can not parse given structure JSON content into Liferay DDMForm.", e); return; } catch (Exception e) { LOG.error("Other error while trying to get content of the structure file. Possibly wrong filesystem path (" + structure.getPath() + ")?", e); return; } Locale contentDefaultLocale = ddmForm.getDefaultLocale(); if (!contentDefaultLocale.equals(siteDefaultLocale)) { nameMap.put(contentDefaultLocale, name); } DDMStructure ddmStructure = null; try { ddmStructure = DDMStructureLocalServiceUtil.fetchStructure(groupId, classNameId, structure.getKey()); } catch (SystemException e) { LOG.error("Error while trying to find Structure with key: " + structure.getKey(), e); } if (ddmStructure != null) { LOG.info("Structure already exists and will be overwritten."); if (structure.getParent() != null && !structure.getParent().isEmpty()) { LOG.info("Setting up parent structure: " + structure.getName()); DDMStructure parentStructure = DDMStructureLocalServiceUtil.fetchStructure(groupId, classNameId, structure.getParent(), true); if (parentStructure != null) { ddmStructure.setParentStructureId(parentStructure.getStructureId()); } else { LOG.info("Parent structure not found: " + structure.getName()); } } DDMStructure ddmStructureSaved=DDMStructureLocalServiceUtil.updateStructure(LiferaySetup.getRunAsUserId(), ddmStructure.getStructureId(), ddmStructure.getParentStructureId(), nameMap, descMap, ddmForm, ddmFormLayout, new ServiceContext()); LOG.info("Template successfully updated: " + structure.getName()); SetupPermissions.updatePermission("Structure "+structure.getKey(),groupId ,companyId,ddmStructureSaved.getStructureId(),DDMStructure.class.getName()+"-"+JournalArticle.class.getName(),structure.getRolePermissions(),DEFAULT_DDM_PERMISSIONS); return; } DDMStructure newStructure = DDMStructureLocalServiceUtil.addStructure( LiferaySetup.getRunAsUserId(), groupId, structure.getParent(), classNameId, structure.getKey(), nameMap, descMap, ddmForm, ddmFormLayout, "json", 0, new ServiceContext()); SetupPermissions.updatePermission("Structure "+structure.getKey(),groupId ,companyId,newStructure.getStructureId(),DDMStructure.class.getName()+ "-" + JournalArticle.class.getName(),structure.getRolePermissions(),DEFAULT_DDM_PERMISSIONS); LOG.info("Added Article structure: " + newStructure.getName()); } private static String getStructureNameOrKey(final Structure structure) { if (structure.getName() == null) { return structure.getName(); } return structure.getKey(); } public static void addDDMTemplate(final ArticleTemplate template, final long groupId) throws SystemException, PortalException, IOException, URISyntaxException { LOG.info("Adding Article template " + template.getName()); long classNameId = ClassNameLocalServiceUtil.getClassNameId(DDMStructure.class); long resourceClassnameId = ClassNameLocalServiceUtil.getClassNameId(JournalArticle.class); Map<Locale, String> nameMap = new HashMap<>(); Locale siteDefaultLocale = PortalUtil.getSiteDefaultLocale(groupId); String name = template.getName(); if (name == null) { name = template.getKey(); } nameMap.put(siteDefaultLocale, name); Map<Locale, String> descMap = new HashMap<>(); String script; try { script = ResourcesUtil.getFileContent(template.getPath()); } catch (Exception e) { LOG.error("Error Reading Template File content for: " + template.getName()); return; } long classPK = 0; if (template.getArticleStructureKey() != null) { try { classPK = ResolverUtil.getStructureId(template.getArticleStructureKey(), groupId, JournalArticle.class, false); } catch (Exception e) { LOG.error("Given article structure with ID: "+ template.getArticleStructureKey() + " can not be found. Therefore, article template can not be added/changed.", e); return; } } DDMTemplate ddmTemplate = null; try { ddmTemplate = DDMTemplateLocalServiceUtil.fetchTemplate(groupId, classNameId, template.getKey()); } catch (SystemException e) { LOG.error("Error while trying to find template with key: " + template.getKey(), e); } if (ddmTemplate != null) { LOG.info("Template already exists and will be overwritten."); ddmTemplate.setNameMap(nameMap); ddmTemplate.setLanguage(template.getLanguage()); ddmTemplate.setScript(script); ddmTemplate.setClassPK(classPK); ddmTemplate.setCacheable(template.isCacheable()); DDMTemplateLocalServiceUtil.updateDDMTemplate(ddmTemplate); LOG.info("Template successfully updated: " + ddmTemplate.getName()); return; } DDMTemplate newTemplate = DDMTemplateLocalServiceUtil.addTemplate( LiferaySetup.getRunAsUserId(), groupId, classNameId, classPK, resourceClassnameId, template.getKey(), nameMap, descMap, DDMTemplateConstants.TEMPLATE_TYPE_DISPLAY, null, template.getLanguage(), script, template.isCacheable(), false, null, null, new ServiceContext()); LOG.info("Added Article template: " + newTemplate.getName()); } public static void addDDMTemplate(final Adt template, final long groupId) throws SystemException, PortalException, IOException, URISyntaxException { LOG.info("Adding ADT " + template.getName()); long classNameId = PortalUtil.getClassNameId(template.getClassName()); long resourceClassnameId = Validator.isBlank(template.getResourceClassName()) ? ClassNameLocalServiceUtil.getClassNameId(JournalArticle.class) : ClassNameLocalServiceUtil.getClassNameId(template.getResourceClassName()); Map<Locale, String> nameMap = new HashMap<Locale, String>(); Locale siteDefaultLocale = PortalUtil.getSiteDefaultLocale(groupId); String name = template.getName(); if (name == null) { name = template.getTemplateKey(); } nameMap.put(siteDefaultLocale, name); Map<Locale, String> descriptionMap = new HashMap<Locale, String>(); descriptionMap.put(siteDefaultLocale, template.getDescription()); DDMTemplate ddmTemplate = null; try { ddmTemplate = DDMTemplateLocalServiceUtil.fetchTemplate(groupId, classNameId, template.getTemplateKey()); } catch (SystemException e) { LOG.error("Error while trying to find ADT with key: " + template.getTemplateKey()); } String script = ResourcesUtil.getFileContent(template.getPath()); if (ddmTemplate != null) { LOG.info("Template already exists and will be overwritten."); ddmTemplate.setLanguage(template.getLanguage()); ddmTemplate.setNameMap(nameMap); ddmTemplate.setDescriptionMap(descriptionMap); ddmTemplate.setClassName(template.getClassName()); ddmTemplate.setCacheable(template.isCacheable()); ddmTemplate.setScript(script); DDMTemplateLocalServiceUtil.updateDDMTemplate(ddmTemplate); LOG.info("ADT successfully updated: " + ddmTemplate.getName()); return; } DDMTemplate newTemplate = DDMTemplateLocalServiceUtil.addTemplate( LiferaySetup.getRunAsUserId(), groupId, classNameId, 0, resourceClassnameId, template.getTemplateKey(), nameMap, descriptionMap, DDMTemplateConstants.TEMPLATE_TYPE_DISPLAY, null, template.getLanguage(), script, true, false, null, null, new ServiceContext()); LOG.info("Added ADT: " + newTemplate.getName()); } public static void addJournalArticle(final Article article, final long groupId, final long companyId) { LOG.info("Adding Journal Article " + article.getTitle()); String content = null; long folderId = 0L; if (article.getArticleFolderPath() != null && !article.getArticleFolderPath().equals("")) { JournalFolder jf = WebFolderUtil.findWebFolder(companyId, groupId, LiferaySetup.getRunAsUserId(), article.getArticleFolderPath(), "", true); if (jf == null) { LOG.warn("Specified webfolder " + article.getArticleFolderPath() + " of article " + article.getTitle() + " not found! Will put article into web content root folder!"); } else { folderId = jf.getFolderId(); } } try { content = ResourcesUtil.getFileContent(article.getPath()); content = ResolverUtil.lookupAll(LiferaySetup.getRunAsUserId(), groupId, companyId, content, article.getPath()); } catch (IOException e) { LOG.error( "Error Reading Article File content for article ID: " + article.getArticleId()); } Map<Locale, String> titleMap = FieldMapUtil.getTitleMap(article.getTitleTranslation(), groupId, article.getTitle(), " Article with title " + article.getArticleId()); Locale articleDefaultLocale = LocaleUtil.fromLanguageId( LocalizationUtil.getDefaultLanguageId(content)); if (!titleMap.containsKey(articleDefaultLocale)) { titleMap.put(articleDefaultLocale, article.getTitle()); } Map<Locale,String> descriptionMap=null; if(article.getArticleDescription()!=null && !article.getArticleDescription().isEmpty()) { descriptionMap=FieldMapUtil.getDescriptionMap(article.getDescriptionTranslation(), groupId, article.getArticleDescription(), " Article with description " + article.getArticleId()); if (!descriptionMap.containsKey(articleDefaultLocale)) { descriptionMap.put(articleDefaultLocale, article.getArticleDescription()); } } ServiceContext serviceContext = new ServiceContext(); serviceContext.setScopeGroupId(groupId); JournalArticle journalArticle = null; boolean generatedId = (article.getArticleId().isEmpty()); if (generatedId) { LOG.info("Article " + article.getTitle() + " will have autogenerated ID."); } else { try { journalArticle = JournalArticleLocalServiceUtil.fetchLatestArticle(groupId, article.getArticleId(), WorkflowConstants.STATUS_APPROVED); } catch (SystemException e) { LOG.error("Error while trying to find article with ID: " + article.getArticleId(), e); } } try { if (journalArticle == null) { journalArticle = JournalArticleLocalServiceUtil.addArticle( LiferaySetup.getRunAsUserId(), groupId, folderId, 0, 0, article.getArticleId(), generatedId, JournalArticleConstants.VERSION_DEFAULT, titleMap, descriptionMap, content, article.getArticleStructureKey(), article.getArticleTemplateKey(), StringPool.BLANK, 1, 1, ARTICLE_PUBLISH_YEAR, 0, 0, 0, 0, 0, 0, 0, true, 0, 0, 0, 0, 0, true, true, false, StringPool.BLANK, null, null, StringPool.BLANK, serviceContext); LOG.info("Added JournalArticle " + journalArticle.getTitle() + " with ID: " + journalArticle.getArticleId()); Indexer bi = IndexerRegistryUtil.getIndexer(JournalArticle.class); if (bi != null) { bi.reindex(journalArticle); } } else { LOG.info("Article " + article.getTitle() + " with article ID: " + article.getArticleId() + " already exists. Will be overwritten."); journalArticle.setTitleMap(titleMap); journalArticle.setContent(content); journalArticle.setDescriptionMap(descriptionMap); JournalArticleLocalServiceUtil.updateJournalArticle(journalArticle); // if the folder changed, move it... if (journalArticle.getFolderId() != folderId) { JournalArticleLocalServiceUtil.moveArticle(groupId, journalArticle.getArticleId(), folderId); } LOG.info("Updated JournalArticle: " + journalArticle.getTitle()); } TaggingUtil.associateTagsAndCategories(groupId, article, journalArticle); processRelatedAssets(article, journalArticle, LiferaySetup.getRunAsUserId(), groupId, companyId); SetupPermissions.updatePermission("Article " + journalArticle.getArticleId(), groupId, companyId, journalArticle.getResourcePrimKey(), JournalArticle.class, article.getRolePermissions(), DEFAULT_PERMISSIONS); } catch (PortalException | SystemException e) { LOG.error("Error while trying to add/update Article with Title: " + article.getTitle(), e); } } private static void addDDLRecordSet(final DdlRecordset recordSet, final long groupId) throws SystemException, PortalException { LOG.info("Adding DDLRecordSet " + recordSet.getName()); Map<Locale, String> nameMap = new HashMap<>(); Locale siteDefaultLocale = PortalUtil.getSiteDefaultLocale(groupId); nameMap.put(siteDefaultLocale, recordSet.getName()); Map<Locale, String> descMap = new HashMap<>(); descMap.put(siteDefaultLocale, recordSet.getDescription()); DDLRecordSet ddlRecordSet = null; try { ddlRecordSet = DDLRecordSetLocalServiceUtil.fetchRecordSet(groupId, recordSet.getKey()); } catch (SystemException e) { LOG.error("Error while trying to find DDLRecordSet with key: " + recordSet.getKey(), e); } if (ddlRecordSet != null) { LOG.info("DDLRecordSet already exists and will be overwritten."); ddlRecordSet.setNameMap(nameMap); ddlRecordSet.setDescriptionMap(descMap); ddlRecordSet.setDDMStructureId(ResolverUtil .getStructureId(recordSet.getDdlStructureKey(), groupId, DDLRecordSet.class, false)); DDLRecordSetLocalServiceUtil.updateDDLRecordSet(ddlRecordSet); LOG.info("DDLRecordSet successfully updated: " + recordSet.getName()); return; } DDLRecordSet newDDLRecordSet = DDLRecordSetLocalServiceUtil.addRecordSet( LiferaySetup.getRunAsUserId(), groupId, ResolverUtil.getStructureId(recordSet.getDdlStructureKey(), groupId, DDLRecordSet.class, false), recordSet.getDdlStructureKey(), nameMap, descMap, MIN_DISPLAY_ROWS, 0, new ServiceContext()); LOG.info("Added DDLRecordSet: " + newDDLRecordSet.getName()); } public static void processRelatedAssets(final Article article, final JournalArticle ja, final long runAsUserId, final long groupId, final long companyId) { if (article.getRelatedAssets() != null) { RelatedAssets ras = article.getRelatedAssets(); AssetEntry ae = null; if (ras.isClearAllAssets()) { try { ae = AssetEntryLocalServiceUtil.getEntry(JournalArticle.class.getName(), ja.getResourcePrimKey()); AssetLinkLocalServiceUtil.deleteLinks(ae.getEntryId()); } catch (PortalException | SystemException e) { LOG.error("Problem clearing related assets of article " + ja.getArticleId(), e); } } if (ras.getRelatedAsset() != null && !ras.getRelatedAsset().isEmpty()) { List<RelatedAsset> ra = ras.getRelatedAsset(); for (RelatedAsset r : ra) { String clazz = r.getAssetClass(); String clazzPrimKey = r.getAssetClassPrimaryKey(); String resolverHint = "Related asset for article " + ja.getArticleId() + " " + "clazz " + clazz + ", " + "primary key " + clazzPrimKey; clazzPrimKey = ResolverUtil.lookupAll(runAsUserId, groupId, companyId, clazzPrimKey, resolverHint); long id = 0; try { id = Long.parseLong(clazzPrimKey); } catch (Exception ex) { LOG.error("Class primary key is not parseable as long value.", ex); } try { AssetEntry ae2 = AssetEntryLocalServiceUtil.getEntry(clazz, id); AssetLinkLocalServiceUtil.addLink(runAsUserId, ae.getEntryId(), ae2.getEntryId(), AssetLinkConstants.TYPE_RELATED, 1); } catch (PortalException | SystemException e) { LOG.error( "Problem resolving related asset of article " + ja.getArticleId() + " with clazz " + clazz + " primary key " + clazzPrimKey, e); } } } } } }
48.264856
186
0.630505
f734b481387b4c2c2dd3a6f66a696879a1275db4
530
package it.mrbackslash.discordspigotstatus; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; public class InfoCommand implements CommandExecutor { private String vers; InfoCommand(String version){ vers = version; } public boolean onCommand(CommandSender sender, Command command, String label, String[] args){ sender.sendMessage("§9§l[i] §r§aDiscordSpigotStatus v" + vers + " by mrBackSlash-it"); return true; } }
29.444444
97
0.728302
7c02000ffe3f1bb3723032dcbc08c4f79fb0abc1
2,037
package com.mydeo.seckilldemo.result; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * description 请求结果信息类 * * @author Chris he * @date 2020/9/29 */ @ApiModel(value = "请求结果信息类") @Data public class ResultVo<T> { @ApiModelProperty(value = "请求结果代码") private Integer code; @ApiModelProperty(value = "提示信息") private String msg; @ApiModelProperty(value = "返回的数据") private T data; public ResultVo(ErrorCode codeEnum, String msg) { this.code = codeEnum.getCode(); this.msg = msg; } public ResultVo(ErrorCode codeEnum) { this.code = codeEnum.getCode(); this.msg = codeEnum.getMsg(); } public ResultVo(ErrorCode codeEnum, T data) { this.code = codeEnum.getCode(); this.msg = codeEnum.getMsg(); this.data = data; } public ResultVo(ErrorCode codeEnum, String msg, T data) { this.code = codeEnum.getCode(); this.msg = msg; this.data = data; } public ResultVo(Integer code, String msg) { this.code = code; this.msg = msg; } public static ResultVo success() { return new ResultVo(ErrorCode.SUCCESS); } public static <T> ResultVo<T> success(T t) { return new ResultVo<>(ErrorCode.SUCCESS, t); } public static <T> ResultVo<T> success(String msg, T t) { return new ResultVo<>(ErrorCode.SUCCESS, msg, t); } public static <T> ResultVo<T> success(ErrorCode codeEnum, T t) { return new ResultVo<>(codeEnum, t); } public static <T> ResultVo<T> error(String msg) { return new ResultVo<>(ErrorCode.ERROR, msg); } public static <T> ResultVo<T> error(ErrorCode codeEnum, String msg) { return new ResultVo<>(codeEnum, msg); } public static <T> ResultVo<T> error(ErrorCode codeEnum) { return new ResultVo<>(codeEnum); } public static <T> ResultVo<T> error(String msg, T t) { return new ResultVo<>(ErrorCode.ERROR, msg, t); } public static <T> ResultVo<T> error(Integer code, String msg) { return new ResultVo<>(code, msg); } }
23.413793
71
0.667649
aee7a800092271c58456d3e77959fa17fac065fa
395
package aadl2upaal.aadl; public class UVar extends AVar { private APort applied; public Distribution dist; public String applied_var=""; public UVar(String name, String type) { super(name, type); // TODO Auto-generated constructor stub } public APort getApplied() { return applied; } public void setApplied(APort applied) { this.applied = applied; } }
17.954545
42
0.683544
15af79b2b0cd53f34e046126a2240731f3ef69db
2,889
package com.smartgwt.sample.showcase.client.basics.components; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.sample.showcase.client.PanelFactory; import com.smartgwt.sample.showcase.client.ShowcasePanel; public class ResizeSample extends ShowcasePanel { private static final String DESCRIPTION = "Click the buttons to expand or collapse the text box."; public static class Factory implements PanelFactory { private String id; public ShowcasePanel create() { ResizeSample panel = new ResizeSample(); id = panel.getID(); return panel; } public String getID() { return id; } public String getDescription() { return DESCRIPTION; } } public Canvas getViewPanel() { Canvas canvas = new Canvas(); final HTMLFlow htmlFlow = new HTMLFlow(); htmlFlow.setHeight(45); htmlFlow.setWidth(75); htmlFlow.setTop(50); htmlFlow.setOverflow(Overflow.HIDDEN); htmlFlow.setStyleName("exampleTextBlock"); htmlFlow.setShowEdges(true); String contents = "<span class='exampleDropTitle'>Ajax&nbsp;&nbsp;</span> <b>A</b>synchronous <b>J</b>avaScript " + "<b>A</b>nd <b>X</b>ML (AJAX) is a Web development technique for creating interactive <b>web applications</b>. " + "The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind" + " the scenes, so that the entire Web page does not have to be reloaded each time the user makes a change. " + "This is meant to increase the Web page's <b>interactivity</b>, <b>speed</b>, and <b>usability</b>. " + "(Source: <a href='http://www.wikipedia.org' title='Wikipedia' target='_blank'>Wikipedia</a>)"; htmlFlow.setContents(contents); IButton expandButton = new IButton("Expand"); expandButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { htmlFlow.resizeBy(235, 150); } }); IButton collapseButton = new IButton("Collapse"); collapseButton.setLeft(120); collapseButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { htmlFlow.resizeTo(75, 45); } }); canvas.addChild(expandButton); canvas.addChild(collapseButton); canvas.addChild(htmlFlow); return canvas; } public String getIntro() { return DESCRIPTION; } }
36.1125
131
0.642437
3893ba0efabd6393a619ef1b65efbb7460cd47fe
111
package jeaphunter.antipattern; public class DestructiveWrappingAntiPattern extends ExceptionAntiPattern { }
18.5
74
0.864865
7cfc6da00ca83cfd2ea9ed7c27d5e292d7b2865a
8,353
/* * Copyright (c) 2005-2018 Trident Kirill Grouchnikov. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o 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. * * o Neither the name of Trident Kirill Grouchnikov nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.pushingpixels.demo.trident.swing.tracker; import java.awt.Component; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.util.Map; import java.util.TreeMap; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.pushingpixels.trident.Timeline; import org.pushingpixels.trident.Timeline.RepeatBehavior; import org.pushingpixels.trident.Timeline.TimelineState; import org.pushingpixels.trident.callback.TimelineCallbackAdapter; import org.pushingpixels.trident.ease.Linear; import org.pushingpixels.trident.ease.Sine; import org.pushingpixels.trident.ease.Spline; import org.pushingpixels.trident.ease.TimelineEase; import org.pushingpixels.trident.swing.SwingRepaintTimeline; public class BallTracker extends JFrame { Timeline timelineBallFalling; public BallTracker() { super("Ball tracker"); this.setLayout(new GridLayout(2, 1)); JPanel main = new JPanel(new GridLayout(1, 2)); final TimelineVisualizer visualizer = new TimelineVisualizer(); this.add(main); this.add(visualizer); JPanel controls = new JPanel(new FlowLayout()); main.add(controls); final BallPanel ballPanel = new BallPanel(); main.add(ballPanel); // final JFormattedTextField easeFactor = new JFormattedTextField( // new MaskFormatter("#.#")); // easeFactor.setText("0.8"); // easeFactor.setColumns(5); // controls.add(easeFactor); Map<String, TimelineEase> eases = new TreeMap<String, TimelineEase>(); eases.put("1. Linear", new Linear()); eases.put("2. Sine", new Sine()); eases.put("3. Spline (0.1, 0.0)-(0.9,1.0)", new Spline(0.1f, 0.0f, 0.9f, 1.0f)); eases.put("4. Spline (0.2, 0.0)-(0.8,1.0)", new Spline(0.2f, 0.0f, 0.8f, 1.0f)); eases.put("5. Spline (0.5, 0.0)-(0.5,1.0)", new Spline(0.5f, 0.0f, 0.5f, 1.0f)); eases.put("6. Spline (0.8, 0.0)-(0.2,1.0)", new Spline(0.8f, 0.0f, 0.2f, 1.0f)); eases.put("7. Spline (0.9, 0.0)-(0.1,1.0)", new Spline(0.9f, 0.0f, 0.1f, 1.0f)); eases.put("8. Spline (1.0, 0.0)-(0.9,1.0)", new Spline(1.0f, 0.0f, 0.9f, 1.0f)); ComboBoxModel easeModel = new DefaultComboBoxModel(eases.entrySet().toArray()); final JComboBox easeCombo = new JComboBox(easeModel); easeCombo.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { return super.getListCellRendererComponent(list, ((Map.Entry<String, TimelineEase>) value).getKey(), index, isSelected, cellHasFocus); } }); easeCombo.setSelectedIndex(0); controls.add(easeCombo); final JTextField msToSkip = new JTextField("0", 6); controls.add(new JLabel("to skip")); controls.add(msToSkip); final JTextField msInitialDelay = new JTextField("500", 6); controls.add(new JLabel("initial delay")); controls.add(msInitialDelay); final JTextField msCycleDelay = new JTextField("0", 6); controls.add(new JLabel("cycle delay")); controls.add(msCycleDelay); JButton runTimeline = new JButton("run"); runTimeline.addActionListener((ActionEvent e) -> { if (timelineBallFalling != null) timelineBallFalling.cancel(); timelineBallFalling = new Timeline(ballPanel); timelineBallFalling.addPropertyToInterpolate("ballY", BallPanel.RADIUS, ballPanel.getHeight() - BallPanel.RADIUS); timelineBallFalling.setDuration(2000); timelineBallFalling.setInitialDelay(Integer.parseInt(msInitialDelay.getText())); timelineBallFalling.setCycleDelay(Integer.parseInt(msCycleDelay.getText())); timelineBallFalling.setEase( ((Map.Entry<String, TimelineEase>) easeCombo.getSelectedItem()).getValue()); timelineBallFalling.addCallback(new TimelineCallbackAdapter() { @Override public void onTimelinePulse(float durationFraction, float timelinePosition) { // add a fading dot to visualize the timeline // interpolation behavior visualizer.addDot(durationFraction, timelinePosition); } @Override public void onTimelineStateChanged(TimelineState oldState, TimelineState newState, float durationFraction, float timelinePosition) { System.out .println("State change: " + oldState.name() + " -> " + newState.name()); } }); long toSkip = Long.parseLong(msToSkip.getText()); if (toSkip > 0) { timelineBallFalling.playLoopSkipping(RepeatBehavior.REVERSE, toSkip); } else { timelineBallFalling.playLoop(RepeatBehavior.REVERSE); } }); JButton cancelTimeline = new JButton("cancel"); cancelTimeline.addActionListener((ActionEvent e) -> { if (timelineBallFalling != null) timelineBallFalling.cancelAtCycleBreak(); }); JButton suspendTimeline = new JButton("suspend"); suspendTimeline.addActionListener((ActionEvent e) -> { if (timelineBallFalling != null) timelineBallFalling.suspend(); }); JButton resumeTimeline = new JButton("resume"); resumeTimeline.addActionListener((ActionEvent e) -> { if (timelineBallFalling != null) timelineBallFalling.resume(); }); controls.add(runTimeline); controls.add(cancelTimeline); controls.add(suspendTimeline); controls.add(resumeTimeline); Timeline paintTimeline = new SwingRepaintTimeline(this); paintTimeline.playLoop(RepeatBehavior.LOOP); this.setSize(500, 600); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new BallTracker().setVisible(true)); } }
43.279793
100
0.659643
904e621fca4675ad010a74e394131fca62c4f947
1,204
package cn.lastwhisper.atguigu.search; import cn.lastwhisper.util.ArrayUtil; /** * * @author cn.lastwhisper */ public class InsertValueSearch { private static int count = 0; public static void main(String[] args) { int[] arr = ArrayUtil.generateArrByOrder(100); //int[] arr = {1, 1, 1, 1, 10, 89, 1000, 1234}; System.out.println(insertValueSearch(arr, 0, arr.length - 1, 37)); System.out.println("查找次数:"+count); } /** * 插值查找(递归) * * @param arr * @param left * @param right * @param target * @return int */ public static int insertValueSearch(int[] arr, int left, int right, int target) { count++; // 必要条件 if (left > right || target < arr[0] || target > arr[arr.length - 1]) { return -1; } // 自适应写法 int mid = left + (right - left) * (target - arr[left]) / (arr[right] - arr[left]); if (target > arr[mid]) { return insertValueSearch(arr, mid + 1, right, target); } else if (target < arr[mid]) { return insertValueSearch(arr, left, mid - 1, target); } else { return mid; } } }
27.363636
90
0.535714
29da0ae4ee26e84b81d7c3ba20345429ce8fba3f
318
package <%= appPackage %>.<%= packageName %>.pojo; /** * Generated by generator-android-template * This is the pojo class you got by using <%= dataClass %>Endpoint. * This will be stored in the DB using Realm as a Realm<%= dataClass %> */ public class <%= dataClass %> { public <%= dataClass %>() { } }
22.714286
71
0.628931
5881b9867cae003d7e1b18fd16f836ef42dca56c
7,649
/* * Copyright (C) Lennart Martens * * Contact: lennart.martens AT UGent.be (' AT ' to be replaced with '@') */ /* * Created by IntelliJ IDEA. * User: Lennart * Date: 31-jan-03 * Time: 22:34:59 */ package com.compomics.util.io.file; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.FilterInputStream; /* * CVS information: * * $Revision: 1.3 $ * $Date: 2007/07/06 09:41:53 $ */ /** * This class implements an InputStream that reports on the progress of reading * a file in integer quantities, even though the underlying file may have a binary size that is outside * of integer range. * * @author Lennart Martens */ public class MonitorableFileInputStream extends MonitorableInputStream { // Class specific log4j logger for MonitorableFileInputStream instances. Logger logger = LogManager.getLogger(MonitorableFileInputStream.class); /** * The maximum readable size. */ private long iMaximum = 0; /** * The current amount of bytes read from the file. */ private long iCurrent = 0; /** * The number of actual bytes will be divided by 1024 to the 'iFactor' power * to yield an integer scale. */ private int iFactor = 0; /** * This constructor takes a file to load the FileInputStream from. * * @param aFile File to connect the inputstream to. * @exception IOException when the file could not be raed. */ public MonitorableFileInputStream(File aFile) throws IOException { super(new FileInputStream(aFile)); long length = aFile.length(); int factor = 0; long max = Integer.MAX_VALUE; while(length >= max) { length /= 1024; factor++; } this.iMaximum = aFile.length(); this.iFactor = factor; } /** * This constructor takes a file to load the FileInputStream from. * * @param aFile String with the filename for the file to connect * the inputstream to. * @exception IOException when the file could not be raed. */ public MonitorableFileInputStream(String aFile) throws IOException { this(new File(aFile)); } /** * This method reports on the maximum scale for the monitor. * * @return int with the maximum for the monitor. */ public int getMaximum() { return (int)(this.iMaximum/Math.pow(1024, iFactor)); } /** * This method returns the progress (as measured by taking the value * of iMaximum, minus the current progress as reported by the cache). * * @return int with the progress. */ public int monitorProgress() { int result = (int)((this.iMaximum - (this.iMaximum-this.iCurrent))/Math.pow(1024, iFactor)); return result; } /** * Reads up to <code>byte.length</code> bytes of data from this * input stream into an array of bytes. This method blocks until some * input is available. * <p> * This method simply performs the call * <code>read(b, 0, b.length)</code> and returns * the result. It is important that it does * <i>not</i> do <code>in.read(b)</code> instead; * certain subclasses of <code>FilterInputStream</code> * depend on the implementation strategy actually * used. * * @param b the buffer into which the data is read. * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of * the stream has been reached. * @exception IOException if an I/O error occurs. * @see java.io.FilterInputStream#read(byte[], int, int) */ public int read(byte b[]) throws IOException { int result = super.read(b); iCurrent += result; return result; } /** * Reads the next byte of data from this input stream. The value * byte is returned as an <code>int</code> in the range * <code>0</code> to <code>255</code>. If no byte is available * because the end of the stream has been reached, the value * <code>-1</code> is returned. This method blocks until input data * is available, the end of the stream is detected, or an exception * is thrown. * <p> * This method * simply performs <code>in.read()</code> and returns the result. * * @return the next byte of data, or <code>-1</code> if the end of the * stream is reached. * @exception IOException if an I/O error occurs. * @see java.io.FilterInputStream#in */ public int read() throws IOException { int result = super.read(); iCurrent++; return result; } /** * Reads up to <code>len</code> bytes of data from this input stream * into an array of bytes. This method blocks until some input is * available. * <p> * This method simply performs <code>in.read(b, off, len)</code> * and returns the result. * * @param b the buffer into which the data is read. * @param off the start offset of the data. * @param len the maximum number of bytes read. * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of * the stream has been reached. * @exception IOException if an I/O error occurs. * @see FilterInputStream#in */ public int read(byte b[], int off, int len) throws IOException { int result = super.read(b, off, len);; iCurrent += result; return result; } /** * Skips over and discards <code>n</code> bytes of data from the * input stream. The <code>skip</code> method may, for a variety of * reasons, end up skipping over some smaller number of bytes, * possibly <code>0</code>. The actual number of bytes skipped is * returned. * <p> * This method * simply performs <code>in.skip(n)</code>. * * @param n the number of bytes to be skipped. * @return the actual number of bytes skipped. * @exception IOException if an I/O error occurs. */ public long skip(long n) throws IOException { long result = super.skip(n); iCurrent += n; return result; } /** * Repositions this stream to the position at the time the * <code>mark</code> method was last called on this input stream. * <p> * This method * simply performs <code>in.reset()</code>. * <p> * Stream marks are intended to be used in * situations where you need to read ahead a little to see what's in * the stream. Often this is most easily done by invoking some * general parser. If the stream is of the type handled by the * parse, it just chugs along happily. If the stream is not of * that type, the parser should toss an exception when it fails. * If this happens within readlimit bytes, it allows the outer * code to reset the stream and try another parser. * * @exception IOException if the stream has not been marked or if the * mark has been invalidated. * @see java.io.FilterInputStream#in * @see java.io.FilterInputStream#mark(int) */ public synchronized void reset() throws IOException { super.reset(); iCurrent = 0l; } }
33.995556
103
0.617859
4be2e9912b9f55d64fd5e1d205b6b27832935b38
289
package com.group12.course.entity; /** * @author Y Jiang * 2018/11/28 */ public class CourseNotFoundException extends RuntimeException { private int courseId; public CourseNotFoundException(int courseId){ this.courseId=courseId; } public int getId() { return courseId; } }
24.083333
75
0.733564
ab4e21e0f482cef7d390ce09eda8c653ce8266dc
2,898
package com.practice.game_of_life; import org.hamcrest.Matchers; import org.junit.Test; import java.util.stream.IntStream; import static org.hamcrest.MatcherAssert.assertThat; /** * Checker Tester. */ public class CheckerTest { @Test public void liveLessThanTwoDie() { boolean[][] gird = getTestGrid(1, 0, 0, 0, 1, 0, 0, 0, 0); boolean state = Checker.checkCellNextState(gird, 1, 1); assertThat(state, Matchers.is(false)); } @Test public void liveMoreThanThreeDie() { assertThat( Checker.checkCellNextState( getTestGrid(1, 1, 1, 1, 1, 0, 0, 0, 0), 1, 1), Matchers.is(false)); } @Test public void deadThreeLive() { assertThat( Checker.checkCellNextState( getTestGrid(1, 1, 1, 0, 0, 0, 0, 0, 0), 1, 1), Matchers.is(true)); } @Test public void liveTwoLive() { assertThat( Checker.checkCellNextState( getTestGrid(1, 1, 0, 0, 1, 0, 0, 0, 0), 1, 1), Matchers.is(true)); } @Test public void liveThreeLive() { assertThat( Checker.checkCellNextState( getTestGrid(1, 1, 1, 0, 1, 0, 0, 0, 0), 1, 1), Matchers.is(true)); } @Test public void deadTwoDie() { assertThat( Checker.checkCellNextState( getTestGrid(1, 1, 0, 0, 0, 0, 0, 0, 0), 1, 1), Matchers.is(false)); } @Test public void deadFourDie() { assertThat( Checker.checkCellNextState( getTestGrid(1, 1, 1, 1, 0, 0, 0, 0, 0), 1, 1), Matchers.is(false)); } @Test public void simplyConnectedThree() { boolean[][] grid = getTestGrid(1, 0, 1, 0, 0, 0, 1, 0, 1); assertThat(Checker.checkCellNextState(grid, 0, 0), Matchers.is(true)); assertThat(Checker.checkCellNextState(grid, 0, 2), Matchers.is(true)); assertThat(Checker.checkCellNextState(grid, 2, 0), Matchers.is(true)); assertThat(Checker.checkCellNextState(grid, 2, 2), Matchers.is(true)); } @Test public void simpleConnectedTwo() { boolean[][] grid = getTestGrid(1, 0, 1, 0, 0, 0, 0, 0, 1); assertThat(Checker.checkCellNextState(grid, 0, 0), Matchers.is(true)); assertThat(Checker.checkCellNextState(grid, 0, 2), Matchers.is(true)); assertThat(Checker.checkCellNextState(grid, 2, 2), Matchers.is(true)); } private boolean[][] getTestGrid(int... data) { boolean[][] gird = new boolean[3][3]; IntStream.range(0, 3).forEachOrdered(i -> IntStream.range(0, 3).forEachOrdered(j -> gird[i][j] = data[i * 3 + j] == 1)); return gird; } }
31.16129
78
0.539683
00a350cb88cc29a5cef6929b0dec1d6f78357cec
2,658
package com.skjanyou.server.core; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import com.skjanyou.server.api.constant.StatusCode; import com.skjanyou.server.api.inter.Headers; import com.skjanyou.server.api.inter.Protocol; import com.skjanyou.server.api.inter.Response; import com.skjanyou.util.FileUtil; public class HttpResponse implements Response { private HttpHeaders headers ; private HttpResponseBody responseBody ; private HttpResponseLine responseLine ; public HttpResponse(){ headers = new HttpHeaders(); responseBody = new HttpResponseBody(); responseLine = new HttpResponseLine(); } public static class HttpResponseBody implements ResponseBody { private byte[] bodyContent; @Override public ResponseBody setBodyContent(String bodyContent) { try { this.bodyContent = bodyContent.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return this; } @Override public ResponseBody setBodyContent(byte[] bodyContent) { this.bodyContent = bodyContent; return this; } @Override public ResponseBody setBodyContent(File file) { this.bodyContent = FileUtil.getFileBytes(file); return this; } @Override public byte[] getBodyContent() { return this.bodyContent; } @Override public ResponseBody writeToStream(OutputStream os) { try { os.write(this.bodyContent); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("写数据出错",e); } return this; } } public static class HttpResponseLine implements ResponseLine { private StatusCode statusCode; private Protocol protocol; public void setStatusCode(StatusCode statusCode) { this.statusCode = statusCode; } public void setProtocol(Protocol protocol) { this.protocol = protocol; } @Override public StatusCode statusCode() { return this.statusCode; } @Override public Protocol protocol() { return this.protocol; } } @Override public ResponseBody responseBody() { return this.responseBody; } @Override public ResponseLine responseLine() { return this.responseLine; } @Override public Headers headers() { return this.headers; } /** 设置Http头 **/ public HttpResponse putHeader( String key,String value ) { this.headers.put(key, value); return this; } /** **/ public HttpResponseBody getHttpResponseBody(){ return this.responseBody; } public HttpResponseLine getHttpResponseLine(){ return this.responseLine; } public HttpHeaders getHttpHeaders(){ return this.headers; } }
21.095238
63
0.729872
8a50afa74147e8a32c6d89356b10aaa77db190ae
201
// "@Pointcut with throws clause" package ataspectj.misuse; import org.aspectj.lang.annotation.*; @Aspect public class Test016{ @Pointcut("call(* *.*(..))") void someCall() throws Exception {} }
18.272727
37
0.691542
47f7958a8597a02cc82965efe9d31e0259e3127b
1,468
package com.synopsys.integration.detectable.detectables.nuget.unit; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import com.synopsys.integration.common.util.finder.FileFinder; import com.synopsys.integration.detectable.DetectableEnvironment; import com.synopsys.integration.detectable.detectable.inspector.nuget.NugetInspectorOptions; import com.synopsys.integration.detectable.detectable.inspector.nuget.NugetInspectorResolver; import com.synopsys.integration.detectable.detectables.nuget.NugetInspectorExtractor; import com.synopsys.integration.detectable.detectables.nuget.NugetProjectDetectable; import com.synopsys.integration.detectable.util.MockDetectableEnvironment; import com.synopsys.integration.detectable.util.MockFileFinder; public class NugetProjectDetectableTest { @Test public void testApplicableForRproj() { NugetInspectorOptions nugetInspectorOptions = null; NugetInspectorResolver nugetInspectorResolver = null; NugetInspectorExtractor nugetInspectorExtractor = null; DetectableEnvironment environment = MockDetectableEnvironment.empty(); FileFinder fileFinder = MockFileFinder.withFileNamed("example.rproj"); NugetProjectDetectable detectable = new NugetProjectDetectable(environment, fileFinder, nugetInspectorOptions, nugetInspectorResolver, nugetInspectorExtractor); assertTrue(detectable.applicable().getPassed()); } }
47.354839
168
0.826975
42a0df2d616d58d9dde9e8621b62b47d091013f6
1,182
package org.visallo.web.structuredingest.core.routes; import com.google.inject.Inject; import com.v5analytics.webster.ParameterizedHandler; import com.v5analytics.webster.annotations.Handle; import org.visallo.web.structuredingest.core.model.ClientApiMimeTypes; import org.visallo.web.structuredingest.core.model.StructuredIngestParser; import org.visallo.web.structuredingest.core.util.StructuredIngestParserFactory; import java.util.Collection; public class MimeTypes implements ParameterizedHandler { private final StructuredIngestParserFactory structuredIngestParserFactory; @Inject public MimeTypes( StructuredIngestParserFactory structuredIngestParserFactory ) { this.structuredIngestParserFactory = structuredIngestParserFactory; } @Handle public ClientApiMimeTypes handle() throws Exception { Collection<StructuredIngestParser> parsers = structuredIngestParserFactory.getParsers(); ClientApiMimeTypes response = new ClientApiMimeTypes(); for (StructuredIngestParser parser : parsers) { response.addMimeTypes(parser.getSupportedMimeTypes()); } return response; } }
35.818182
96
0.781726
415d48a30c75c2426b9589cae19cc322725a1711
219
package com.borneo.framework.base.dao; import com.borneo.framework.base.entity.Trole; public interface TroleDAO extends BaseDAO { String BEAN_NAME = "troleDAO"; Trole getRoleByCode(String code); }
19.909091
47
0.726027
bcb5986214abde131347ee6eff2f73e9acf952d6
5,787
package com.asis.joi.model.entities; import com.asis.ui.asis_node.node_functional_expansion.ComponentVisitor; import org.json.JSONArray; import org.json.JSONObject; public class Condition extends JOIComponent { public enum ConditionType { EQUALS, GREATER_THAN, LESS_THAN } private GotoScene gotoSceneTrue; private GotoScene gotoSceneFalse; private String variable; private Object comparingValue; private ConditionType conditionType = ConditionType.EQUALS; public Condition(int componentId) { super(componentId); } public static Condition createEntity(JSONObject jsonObject) { Condition condition = new Condition(0); createEntity(jsonObject, condition); for (String key : jsonObject.keySet()) { switch (key) { case "conditionType": condition.setConditionType(ConditionType.valueOf(jsonObject.getString(key))); break; case "variable": condition.setVariable(jsonObject.getString(key)); break; case "comparingValue": condition.setComparingValue(jsonObject.get(key)); break; case "gotoScene": JSONArray jsonArray = jsonObject.getJSONArray(key); for(int i=0; i<jsonArray.length(); i++) { JSONObject gotoObject = new JSONObject(); if(jsonArray.getJSONObject(i).has("gotoScene")) { gotoObject.put("array", new JSONArray(new int[]{jsonArray.getJSONObject(i).getInt("gotoScene")})); } else if(jsonArray.getJSONObject(i).has("gotoSceneInRange")) { gotoObject.put("array", jsonArray.getJSONObject(i).getJSONArray("gotoSceneInRange")); } if(jsonArray.getJSONObject(i).getBoolean("output")) { condition.setGotoSceneTrue(GotoScene.createEntity(gotoObject)); } else { condition.setGotoSceneFalse(GotoScene.createEntity(gotoObject)); } } break; } } return condition; } @Override public JSONObject toJSON() { JSONObject object = super.toJSON(); object.put("conditionType", getConditionType()); if(getVariable() != null) object.put("variable", getVariable()); if(getComparingValue() != null) object.put("comparingValue", getComparingValue()); object.put("componentType", "Conditional"); JSONArray outputArray = new JSONArray(); if(getGotoSceneFalse() != null) { JSONObject outputObject = new JSONObject(); outputObject.put("output", false); outputObject.put(getGotoSceneFalse().getJsonKeyName(), getGotoSceneFalse().getJsonValue()); outputArray.put(outputObject); } if(getGotoSceneTrue() != null) { JSONObject outputObject = new JSONObject(); outputObject.put("output", true); outputObject.put(getGotoSceneTrue().getJsonKeyName(), getGotoSceneTrue().getJsonValue()); outputArray.put(outputObject); } object.put("gotoScene", outputArray); return object; } @Override public Object clone() throws CloneNotSupportedException { Condition condition = (Condition) super.clone(); condition.setConditionType(getConditionType()); condition.setVariable(getVariable()); condition.setComparingValue(getComparingValue()); return condition; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Condition)) return false; if (!super.equals(o)) return false; Condition condition = (Condition) o; if (getGotoSceneTrue() != null ? !getGotoSceneTrue().equals(condition.getGotoSceneTrue()) : condition.getGotoSceneTrue() != null) return false; if (getGotoSceneFalse() != null ? !getGotoSceneFalse().equals(condition.getGotoSceneFalse()) : condition.getGotoSceneFalse() != null) return false; if (getVariable() != null ? !getVariable().equals(condition.getVariable()) : condition.getVariable() != null) return false; if (getComparingValue() != null ? !getComparingValue().equals(condition.getComparingValue()) : condition.getComparingValue() != null) return false; return getConditionType() == condition.getConditionType(); } @Override public void accept(ComponentVisitor componentVisitor) { componentVisitor.visit(this); } //Getters and Setters public GotoScene getGotoSceneTrue() { return gotoSceneTrue; } public void setGotoSceneTrue(GotoScene gotoSceneTrue) { this.gotoSceneTrue = gotoSceneTrue; } public GotoScene getGotoSceneFalse() { return gotoSceneFalse; } public void setGotoSceneFalse(GotoScene gotoSceneFalse) { this.gotoSceneFalse = gotoSceneFalse; } public String getVariable() { return variable; } public void setVariable(String variable) { this.variable = variable; } public Object getComparingValue() { return comparingValue; } public void setComparingValue(Object comparingValue) { this.comparingValue = comparingValue; } public ConditionType getConditionType() { return conditionType; } public void setConditionType(ConditionType conditionType) { this.conditionType = conditionType; } }
35.503067
141
0.611889
f779a0f68bb91ced10431f927cb2da6c2bb5586d
1,552
package net.moddingplayground.toymaker.impl.mixin; import net.minecraft.server.Main; import net.moddingplayground.toymaker.Toymaker; import net.moddingplayground.toymaker.impl.DataMain; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.io.IOException; import java.util.ArrayList; import java.util.List; @SuppressWarnings("UnusedMixin") @Mixin(Main.class) public class DataGenMixin { @Inject(method = "main", at = @At("HEAD"), cancellable = true, remap = false) private static void onDataMain(String[] strings, CallbackInfo ci) { boolean data = Boolean.parseBoolean(System.getProperty(Toymaker.MOD_ID + ".datagen")); if (data) { String path = System.getProperty(Toymaker.MOD_ID + ".datagen.path"); String[] paths = path == null ? new String[0] : path.split(";"); List<String> args = new ArrayList<>(); args.add("-client"); args.add("-server"); String pathOptName = "-output"; for (String pth : paths) { args.add(pathOptName); args.add(pth); pathOptName = "-extra"; } try { DataMain.main(args.toArray(new String[0])); } catch (IOException e) { e.printStackTrace(); } finally { ci.cancel(); } } } }
33.73913
94
0.615335
4100885a791f9cbcfb8de24c179d9b75b7c54236
5,318
/* * 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.lucene.index; import java.io.IOException; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.TextField; import org.apache.lucene.search.CollectionStatistics; import org.apache.lucene.search.TermStatistics; import org.apache.lucene.search.similarities.ClassicSimilarity; import org.apache.lucene.search.similarities.PerFieldSimilarityWrapper; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.util.LineFileDocs; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.LuceneTestCase.Slow; import org.apache.lucene.util.LuceneTestCase.SuppressCodecs; import org.apache.lucene.util.TestUtil; /** * Test that norms info is preserved during index life - including * separate norms, addDocument, addIndexes, forceMerge. */ @SuppressCodecs({ "Direct", "SimpleText" }) @Slow public class TestNorms extends LuceneTestCase { static final String BYTE_TEST_FIELD = "normsTestByte"; public void testMaxByteNorms() throws IOException { Directory dir = newFSDirectory(createTempDir("TestNorms.testMaxByteNorms")); buildIndex(dir); DirectoryReader open = DirectoryReader.open(dir); NumericDocValues normValues = MultiDocValues.getNormValues(open, BYTE_TEST_FIELD); assertNotNull(normValues); for (int i = 0; i < open.maxDoc(); i++) { Document document = open.document(i); int expected = Integer.parseInt(document.get(BYTE_TEST_FIELD).split(" ")[0]); assertEquals(i, normValues.nextDoc()); assertEquals(expected, normValues.longValue()); } open.close(); dir.close(); } // TODO: create a testNormsNotPresent ourselves by adding/deleting/merging docs public void buildIndex(Directory dir) throws IOException { Random random = random(); MockAnalyzer analyzer = new MockAnalyzer(random()); analyzer.setMaxTokenLength(TestUtil.nextInt(random(), 1, IndexWriter.MAX_TERM_LENGTH)); IndexWriterConfig config = newIndexWriterConfig(analyzer); Similarity provider = new MySimProvider(); config.setSimilarity(provider); RandomIndexWriter writer = new RandomIndexWriter(random, dir, config); final LineFileDocs docs = new LineFileDocs(random); int num = atLeast(100); for (int i = 0; i < num; i++) { Document doc = docs.nextDoc(); int boost = TestUtil.nextInt(random, 1, 255); String value = IntStream.range(0, boost).mapToObj(k -> Integer.toString(boost)).collect(Collectors.joining(" ")); Field f = new TextField(BYTE_TEST_FIELD, value, Field.Store.YES); doc.add(f); writer.addDocument(doc); doc.removeField(BYTE_TEST_FIELD); if (rarely()) { writer.commit(); } } writer.commit(); writer.close(); docs.close(); } public class MySimProvider extends PerFieldSimilarityWrapper { Similarity delegate = new ClassicSimilarity(); @Override public Similarity get(String field) { if (BYTE_TEST_FIELD.equals(field)) { return new ByteEncodingBoostSimilarity(); } else { return delegate; } } } public static class ByteEncodingBoostSimilarity extends Similarity { @Override public long computeNorm(FieldInvertState state) { return state.getLength(); } @Override public SimScorer scorer(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) { throw new UnsupportedOperationException(); } } public void testEmptyValueVsNoValue() throws IOException { Directory dir = newDirectory(); IndexWriterConfig cfg = newIndexWriterConfig().setMergePolicy(newLogMergePolicy()); IndexWriter w = new IndexWriter(dir, cfg); Document doc = new Document(); w.addDocument(doc); doc.add(newTextField("foo", "", Store.NO)); w.addDocument(doc); w.forceMerge(1); IndexReader reader = DirectoryReader.open(w); w.close(); LeafReader leafReader = getOnlyLeafReader(reader); NumericDocValues normValues = leafReader.getNormValues("foo"); assertNotNull(normValues); assertEquals(1, normValues.nextDoc()); // doc 0 does not have norms assertEquals(0, normValues.longValue()); reader.close(); dir.close(); } }
36.930556
119
0.730162
259e91025eeb926a4ff2fed8b7e659e44d7427bd
2,558
package com.rideaustin.rest; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import org.apache.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.rideaustin.RiderEndpoint; import com.rideaustin.assemblers.MobileRiderRideDtoEnricher; import com.rideaustin.assemblers.RiderCardDtoAssembler; import com.rideaustin.assemblers.RiderDtoEnricher; import com.rideaustin.model.enums.AvatarType; import com.rideaustin.rest.exception.RideAustinException; import com.rideaustin.rest.model.CurrentRiderDto; import com.rideaustin.rest.model.MobileRiderRideDto; import com.rideaustin.rest.model.RiderDto; import com.rideaustin.service.RideService; import com.rideaustin.service.RiderCardService; import com.rideaustin.service.farepayment.FarePaymentService; import com.rideaustin.service.user.RiderService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("/rest/riders") @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class Riders { private final RiderService riderService; private final RideService rideService; private final RiderCardService riderCardService; private final FarePaymentService farePaymentService; private final MobileRiderRideDtoEnricher<MobileRiderRideDto> rideDtoEnricher; private final RiderCardDtoAssembler cardAssembler; private final RiderDtoEnricher riderAssembler; @RiderEndpoint @GetMapping("current") @RolesAllowed(AvatarType.ROLE_RIDER) @ApiOperation("Get current rider information") @ApiResponses({ @ApiResponse(code = HttpStatus.SC_OK, message = "OK"), @ApiResponse(code = HttpStatus.SC_FORBIDDEN, message = "Current user is not a rider"), @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = "Error while getting rider cards information from Stripe") }) public CurrentRiderDto current() throws RideAustinException { RiderDto currentRider = riderService.getCurrentRider(); return CurrentRiderDto.builder() .ride(rideDtoEnricher.enrich(rideService.getCurrentRideAsRider())) .rider(riderAssembler.toDto(currentRider)) .cards(cardAssembler.toDto(riderCardService.listRiderCards(currentRider.getId()))) .unpaid(farePaymentService.listPendingPayments(currentRider.getId())) .build(); } }
41.258065
129
0.81939
64af0c284f621be2e6c7c953a7c6b954d96d272b
6,866
package main; public class Bombs { //Variable declaring. All will be used on the methods below private int bombTiming=0; private boolean bombVisible=false; private boolean bombAvailable=false; private int rangeRight; private int rangeLeft; private int rangeUp; private int rangeDown; private String [] spriteBombs;//array of images for the bomb private int bombSpriteCounter=0;////this counter will make possible the change between bomb sprites into the arrays private int bombX; private int bombY; private String [] spriteExplosion; private String [] spriteExplosionRight; private String [] spriteExplosionLeft; private String [] spriteExplosionVertical; private String [] spriteExplosionHorizontal; private String [] spriteExplosionUp; private String [] spriteExplosionDown; private int range=1; //Non-argument constructor public Bombs () { setSpriteBombs(); //initialized the sprite of images for each bomb and the explosion for the 4 directions. setSpriteExplosion(); setSpriteExplosionRight(); setSpriteExplosionLeft(); setSpriteExplosionUp(); setSpriteExplosionDown(); setSpriteExplosionVertical(); setSpriteExplosionHorizontal(); } public int getRangeRight() { return rangeRight; } public void setRangeRight(int rangeRight) { this.rangeRight = rangeRight; } public int getRangeLeft() { return rangeLeft; } public void setRangeLeft(int rangeLeft) { this.rangeLeft = rangeLeft; } public int getRangeUp() { return rangeUp; } public void setRangeUp(int rangeUp) { this.rangeUp = rangeUp; } public int getRangeDown() { return rangeDown; } public void setRangeDown(int rangeDown) { this.rangeDown = rangeDown; } public void setBombTiming(int bombTiming) { this.bombTiming=bombTiming; } public void setBombVisible(boolean bombVisible) { this.bombVisible=bombVisible; } public void setBombAvailable(boolean bombAvailable) { this.bombAvailable=bombAvailable; } public void setBombsSpriteCounter(int bombsCounter) { this.bombSpriteCounter=bombsCounter; } public void setBombX(int bombX) { this.bombX=bombX; } public void setBombY(int bombY){ this.bombY=bombY; } public int getBombTiming() { return this.bombTiming; } public boolean getBombVisible() { return this.bombVisible; } public boolean getBombAvailable() { return this.bombAvailable; } public int getBombsSpriteCounter() { return this.bombSpriteCounter; } public int getBombX() { return bombX; } public int getBombY() { return bombY; } public int getRange() { return this.range; } //Arrays for the explosion animation on the central position and the directions public void setSpriteExplosion() { this.spriteExplosion=new String[6]; this.spriteExplosion[0]="explosion_C3.gif"; this.spriteExplosion[1]="explosion_C3.gif"; this.spriteExplosion[2]="explosion_C1.gif"; this.spriteExplosion[3]="explosion_C1.gif"; this.spriteExplosion[4]="explosion_C2.gif"; this.spriteExplosion[5]="explosion_C2.gif"; } public void setSpriteExplosionRight() { this.spriteExplosionRight=new String[6]; this.spriteExplosionRight[0]="explosion_E3.gif"; this.spriteExplosionRight[1]="explosion_E3.gif"; this.spriteExplosionRight[2]="explosion_E1.gif"; this.spriteExplosionRight[3]="explosion_E1.gif"; this.spriteExplosionRight[4]="explosion_E2.gif"; this.spriteExplosionRight[5]="explosion_E2.gif"; } public void setSpriteExplosionLeft() { this.spriteExplosionLeft=new String[6]; this.spriteExplosionLeft[0]="explosion_W3.gif"; this.spriteExplosionLeft[1]="explosion_W3.gif"; this.spriteExplosionLeft[2]="explosion_W1.gif"; this.spriteExplosionLeft[3]="explosion_W1.gif"; this.spriteExplosionLeft[4]="explosion_W2.gif"; this.spriteExplosionLeft[5]="explosion_W2.gif"; } public void setSpriteExplosionUp() { this.spriteExplosionUp=new String[6]; this.spriteExplosionUp[0]="explosion_N3.gif"; this.spriteExplosionUp[1]="explosion_N3.gif"; this.spriteExplosionUp[2]="explosion_N1.gif"; this.spriteExplosionUp[3]="explosion_N1.gif"; this.spriteExplosionUp[4]="explosion_N2.gif"; this.spriteExplosionUp[5]="explosion_N2.gif"; } public void setSpriteExplosionDown() { this.spriteExplosionDown=new String[6]; this.spriteExplosionDown[0]="explosion_S3.gif"; this.spriteExplosionDown[1]="explosion_S3.gif"; this.spriteExplosionDown[2]="explosion_S1.gif"; this.spriteExplosionDown[3]="explosion_S1.gif"; this.spriteExplosionDown[4]="explosion_S2.gif"; this.spriteExplosionDown[5]="explosion_S2.gif"; } public void setSpriteExplosionVertical() { this.spriteExplosionVertical=new String[6]; this.spriteExplosionVertical[0]="explosion_V3.gif"; this.spriteExplosionVertical[1]="explosion_V3.gif"; this.spriteExplosionVertical[2]="explosion_V1.gif"; this.spriteExplosionVertical[3]="explosion_V1.gif"; this.spriteExplosionVertical[4]="explosion_V2.gif"; this.spriteExplosionVertical[5]="explosion_V2.gif"; } public void setSpriteExplosionHorizontal() { this.spriteExplosionHorizontal=new String[6]; this.spriteExplosionHorizontal[0]="explosion_H3.gif"; this.spriteExplosionHorizontal[1]="explosion_H3.gif"; this.spriteExplosionHorizontal[2]="explosion_H1.gif"; this.spriteExplosionHorizontal[3]="explosion_H1.gif"; this.spriteExplosionHorizontal[4]="explosion_H2.gif"; this.spriteExplosionHorizontal[5]="explosion_H2.gif"; } //Sets the array for the Bombs sprite animation public void setSpriteBombs() { this.spriteBombs=new String[2]; this.spriteBombs[0]="bomb1.gif"; this.spriteBombs[1]="bomb2.gif"; } public void setRange(int range) { if (range<=5) { this.range=range; } else { this.range=5; //the max value of the range } } //getters of the different sprites that will automatically take the position of the array that the counter points. public String getSpriteExplosion() { return this.spriteExplosion[this.bombSpriteCounter]; } public String getSpriteExplosionRight() { return this.spriteExplosionRight[this.bombSpriteCounter]; } public String getSpriteExplosionLeft() { return this.spriteExplosionLeft[this.bombSpriteCounter]; } public String getSpriteExplosionUp() { return this.spriteExplosionUp[this.bombSpriteCounter]; } public String getSpriteExplosionDown() { return this.spriteExplosionDown[this.bombSpriteCounter]; } public String getSpriteExplosionVertical() { return this.spriteExplosionVertical[this.bombSpriteCounter]; } public String getSpriteExplosionHorizontal() { return this.spriteExplosionHorizontal[this.bombSpriteCounter]; } public String getSpriteBombs() { return this.spriteBombs[this.bombSpriteCounter]; } }
33.492683
117
0.744975
e5ae9480b5662bebaa58d42cd703eabea590bf78
627
package de.elbatya.cryptocoins.bittrexclient.api; import de.elbatya.cryptocoins.bittrexclient.api.model.common.TctApiResult; import de.elbatya.cryptocoins.bittrexclient.api.model.publicapi.tct.Summary; import feign.Param; import feign.RequestLine; import java.util.List; /** * @author contact@elbatya.de */ public interface TctPublicApi { @RequestLine("GET /v3/ticker/summary?type=0&sort=1&offset=0&limit={limit}&top=0") // @Headers("user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.30") TctApiResult<Summary> getTickerSummary(@Param("limit") int limit); }
29.857143
120
0.757576
629dc3d3a9872ecd85a13ad153f1ad2805fbbf5c
1,247
package cn.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class smbmsFiltre implements Filter { private String charset; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chian) throws IOException, ServletException { request.setCharacterEncoding(charset); response.setCharacterEncoding(charset); System.out.println("进去有session的过滤器"); HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (null == req.getSession().getAttribute("user")) { resp.sendRedirect(req.getContextPath() + "/index.jsp"); return; } // 放行 chian.doFilter(request, response); System.out.println("响应了有session的过滤器"); } public void init(FilterConfig config) throws ServletException { String Init = config.getInitParameter("Init"); if (Init == null) { charset = "Utf-8"; } else { charset = Init; } } public void destroy() { } }
26.531915
71
0.76263
1c972193567c590e55428fbf8e0705a16651d99d
384
package org.gama.stalactite.sql.result; import org.gama.stalactite.sql.test.MySQLEmbeddableDataSource; import org.junit.jupiter.api.BeforeEach; /** * @author Guillaume Mary */ class ResultSetIteratorMySQLTest extends ResultSetIteratorITTest { @Override @BeforeEach void createDataSource() { super.dataSource = new MySQLEmbeddableDataSource(3406); } }
22.588235
66
0.747396
530a6ee4827a7a412e70d436aa60b4ca0832ae20
515
package com.bookstore.service; import com.bookstore.domain.*; import java.util.List; /** * Created by z00382545 on 12/29/16. */ public interface CartItemService { CartItem addBookToCartItem(Book book, User user, int qty ); List<CartItem> findByShoppingCart(ShoppingCart shoppingCart); List<CartItem> findByOrder(Order order); CartItem updateCartItem(CartItem cartItem); void removeCartItem (CartItem cartItem); CartItem findById(Long id); CartItem save(CartItem cartItem); }
19.807692
65
0.737864
f16c5684771e865c71e075ea51319ff26e52b661
11,686
/* 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 xml.parsing.machine.api; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; /** * This class is a brick you build your parsing model from. * Implements a state machine builder for xml structure. */ public class Handler extends RootHandler { protected int depth = 1; protected boolean active = false; protected boolean attributed = false; private final String token; private Map<String, String> values; protected Consumer<String> textConsumer = null; protected Consumer<Handler> startConsumer = null; protected Consumer<Handler> finallyConsumer = null; private Function<Handler, Boolean> assumption; /** * This method allows to combine tags so you can process different elements. For example, * this is how you can read {@code author} and {@code title} of books: * <pre> * &lt;book&gt; * &lt;author&gt;Charles Michael Palahniuk&lt;/author&gt; * &lt;title&gt;Fight Club&lt;/title&gt; * &lt;/book&gt; * </pre> * you can build this structure: * <pre> * RootHandler root = RootHandler.instance(); * root.then("book") * .or("author", a -&gt; a.text(MyClass::storeAuthor) * .or("title", t -&gt; t.text(MyClass::storeTitle); * </pre> * An alternative can be * <pre> * RootHandler root = RootHandler.instance(); * Handler book = root.then("book"); * book.then("author").text(MyClass::storeAuthor); * book.then("title").text(MyClass::storeAuthor); * </pre> * * @param token element name to wait for * @param consumer function to customize the nested handler * @return {@code this} that allows to continue the pipeline */ public Handler or(String token, Consumer<Handler> consumer) { if (consumer == null) { throw new IllegalArgumentException("Consumer must not be null"); } consumer.accept(then(token)); return this; } /** * Defines how to process text of element. * * <p>This functionality can not be combined with {@link Handler#propagate()}.</p> * * @param consumer function that processes text of element * @return {@code this} that allows to continue the pipeline */ public Handler text(Consumer<String> consumer) { if (consumer == null) { throw new IllegalArgumentException("Consumer must not be null"); } if (textConsumer != null) { throw new IllegalStateException("Duplicate call to text()"); } textConsumer = consumer; return this; } /** * Makes handler to share it's text value with parent handler. * The feature is useful for collecting simple values from sub-elements * so they can be processed in one place. * <p>The values can be accessed through {@link Handler#getProperty(String)} where property name is * the same as corresponding element name:</p> * <pre> * RootHandler.instance("book", book -&gt; book * .or("title", Handler::propagate) * .or("author", Handler::propagate) * .close(book -&gt; { * MyClass::setAuthor(book.getProperty("author")); * MyClass::setTitle(book.getProperty("title")); * } * </pre> * <p>Propagation can be nested:</p> * <pre> * RootHandler.instance("book", book -&gt; book * .close(book -&gt; { * MyClass::setAuthor(book.getProperty("meta/author")); * MyClass::setTitle(book.getProperty("meta/title")); * } * .then("meta") * .or("title", Handler::propagate) * .or("author", Handler::propagate) * .propagate(); * </pre> * <p>The given example wont work correctly if {@code book} element has multiple {@code meta} children. * In this case you will get values of the last {@code meta} item.</p> * * @return {@code this} that allows to continue the pipeline */ public Handler propagate() { if (textConsumer != null) { throw new IllegalStateException("Method propagate() can not be combined with text()"); } if (values == null) { values = new HashMap<>(); } textConsumer = x -> values.put(null, x); return this; } /** * Tells the handler to collect node attributes. * <p> * Attributes then are stored in handler's properties (see {@link Handler#getProperty(String)} but * can be accessed only in {@link Handler#close(Consumer)}. They are not filled at the moment * when {@link Handler#open(Consumer)} is called. * </p> * @return {@code this} that allows to continue the pipeline */ public Handler withAttributes() { attributed = true; if (values == null) { values = new HashMap<>(); } return this; } /** * Defines action to take when the system finds matching element. * Fires before any other actions for the element. Node attributes are not * * @param consumer action * @return {@code this} that allows to continue the pipeline */ public Handler open(Consumer<Handler> consumer) { if (startConsumer != null) { throw new IllegalStateException("Duplicate call of open()"); } if (consumer == null) { throw new IllegalArgumentException("Consumer must not be null"); } startConsumer = consumer; return this; } /** * Defines action to take when the system completes parsing of matching element. * * @param consumer action * @return {@code this} that allows to continue the pipeline */ public Handler close(Consumer<Handler> consumer) { if (finallyConsumer != null) { throw new IllegalStateException("Duplicate call of close()"); } if (consumer == null) { throw new IllegalArgumentException("Consumer must not be null"); } finallyConsumer = consumer; return this; } /** * Allows to filter node on custom criteria. * <p> * The assumption is checked at the start of each child node. If it returns {@code FALSE}, * the child node will be skipped. * </p> * <p> * Useful for checking attributes. For example, this code will print content of only Russian books: * </p> * <p> * WARNING. The argument of the assumption is the active node, not it's child. * </p> * <pre> * StringReader reader = new StringReader("&lt;books&gt;&lt;book language='ru'&gt;&lt;content&gt;text 1&lt;/content&gt;&lt;/book&gt;&lt;book&gt;&lt;content&gt;text 2&lt;/content&gt;&lt;/book&gt;&lt;/books&gt;")) { * StaxParser parser = new StaxParser(xmlFactory.createXMLStreamReader(reader)); * parser.read(RootHandler.instance("books", r -&gt; r * .then("book").withAttributes() * .assume(book -&gt; "ru".equals(book.getProperty("@language"))) * .then("content").text(System.out::println) * )); * </pre> * * @param assumption function that controls processing of child node * @return {@code this} that allows to continue the pipeline */ public Handler assume(Function<Handler, Boolean> assumption) { if (this.assumption == null) { this.assumption = assumption; } else { throw new IllegalStateException("Duplicate call to assume"); } return this; } /** * Get property propagated to the handler by nested handlers. * <p>The method can also return note attributes (prefixed with '@') if {@link Handler#withAttributes()} * was called. Propagated attribute name starts with owner node name: {@code owner/@attributeName}</p> * <p>Please pay attention: attributes are not available in {@link Handler#open(Consumer)}.</p> * * @param name property name. See {@link Handler#propagate()} * @return {@code this} that allows to continue the pipeline */ public String getProperty(String name) { if (values == null) { throw new IllegalStateException("None of the children provided a value. Did you forgot propagate()?"); } else { return values.get(name); } } protected Handler(String token) { if (token == null || token.isEmpty()) { throw new IllegalArgumentException("Token must not be empty"); } this.token = token; } @Override public XmlNodeHandler onStartElement(String name) { if (depth != 1) { return null; } if (active) { if (assumption == null || !Boolean.FALSE.equals(assumption.apply(this))) { return super.onStartElement(name); } } return this; } @Override public void onText(Supplier<String> text) { if (active && textConsumer != null) { textConsumer.accept(text.get()); } } @Override public void onAttributes(Map<String, String> values) { assert attributed; assert this.values != null; if (values == null) { throw new IllegalArgumentException("Argument must not be null"); } values.forEach((key, value) -> this.values.put("@" + key, value)); } @Override public void onEndElement(XmlNodeHandler parent) { if (!active) { throw new IllegalStateException("Can be called for active handlers only"); } active = false; if (finallyConsumer != null) { finallyConsumer.accept(this); } if (values != null && parent instanceof Handler) { Handler h = (Handler) parent; if (h.values == null) { h.values = new HashMap<>(); } values.forEach((k,v) -> { String key; if (k == null) { key = token; } else { key = token + '/' + k; } h.values.put(key, v); }); } if (values != null) { values.clear(); } } @Override public int down() { return ++depth; } @Override public int up() { depth--; if (depth < 0) { throw new IllegalStateException("Depth can not be negative. Something is wrong with parser structure"); } return depth; } @Override public boolean isActive() { return depth == 1; } @Override public boolean needAttributes() { return attributed; } }
35.093093
217
0.592589
243c0117f7ff773a11cd5e2c62cf29e4de9296ab
2,101
package TournamentSystem.Scoring.Elo; /** * This static class holds the calculation logic to determin the players new Elo's after a match. * Instantiate {@link EloPlayerFIDE} or {@link EloPlayerUSCF} to use this class. * <p> * This code uses parts of the following source <a href="https://bitbucket.org/marioosh/java-elo">java-elo</a> * * @author Felix Barsnick, Cologne University of Applied Sciences, 2018 */ public class EloCalculator { public static final float WIN = 1.0f; public static final float DRAW = 0.5f; public static final float LOSS = 0.0f; /** * Calculate and set the new Elo's after a match. * @param playerA first player * @param gameResult game result<p> * +1 = Player A wins<p> * 0 = Tie<p> * -1 = Player B wins * @param playerB second player */ public static void setNewElos(EloPlayer playerA, int gameResult, EloPlayer playerB) { double changeA, changeB; int gameResB; switch(gameResult){ case +1: gameResB = -1; break; case 0: gameResB = 0; break; case -1: gameResB = +1; break; default: gameResB = 0; } changeA = computeChange(playerA, gameResult, playerB); changeB = computeChange(playerB, gameResB, playerA); // player updaten playerA.updateElo(changeA); playerB.updateElo(changeB); } private static double computeChange(EloPlayer playerA, int gameResult, EloPlayer playerB) { double expected = computeExpected(playerA.getEloRating(), playerB.getEloRating()); float scoreTyp; switch(gameResult){ case +1: scoreTyp = WIN; break; case 0: scoreTyp = DRAW; break; case -1: scoreTyp = LOSS; break; default: return 0; } return playerA.getKFactor() * (scoreTyp - expected); } private static double computeExpected(double ratingA, double ratingB) { return 1.0 / (1.0 + Math.pow(10, (ratingB - ratingA) / 400)); } }
35.016667
110
0.610662
d7eef3a49193dfb845ea9b07ce029ab8ad23b1f5
429
package io.github.artemnazarov.sdktestapplication.bidders.yieldmo; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import io.github.artemnazarov.sdktestapplication.R; public class YieldmoActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_yieldmo); } }
26.8125
66
0.79021
8e55e9fc0b37ec56c0a8a67e6651822dc5955f4e
37,895
/** * Copyright 2014-2017 Linagora, Université Joseph Fourier, Floralis * * The present code is developed in the scope of the joint LINAGORA - * Université Joseph Fourier - Floralis research program and is designated * as a "Result" pursuant to the terms and conditions of the LINAGORA * - Université Joseph Fourier - Floralis research program. Each copyright * holder of Results enumerated here above fully & independently holds complete * ownership of the complete Intellectual Property rights applicable to the whole * of said Results, and may freely exploit it in any manner which does not infringe * the moral rights of the other copyright holders. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.roboconf.dm.rest.commons.json; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import net.roboconf.core.model.beans.Application; import net.roboconf.core.model.beans.ApplicationTemplate; import net.roboconf.core.model.beans.Component; import net.roboconf.core.model.beans.Instance; import net.roboconf.core.model.beans.Instance.InstanceStatus; import net.roboconf.core.model.helpers.ComponentHelpers; import net.roboconf.core.model.helpers.InstanceHelpers; import net.roboconf.core.model.helpers.VariableHelpers; import net.roboconf.core.model.runtime.CommandHistoryItem; import net.roboconf.core.model.runtime.Preference; import net.roboconf.core.model.runtime.Preference.PreferenceKeyCategory; import net.roboconf.core.model.runtime.ScheduledJob; import net.roboconf.core.model.runtime.TargetUsageItem; import net.roboconf.core.model.runtime.TargetWrapperDescriptor; import net.roboconf.core.utils.IconUtils; import net.roboconf.core.utils.Utils; import net.roboconf.dm.rest.commons.Diagnostic; import net.roboconf.dm.rest.commons.Diagnostic.DependencyInformation; import net.roboconf.dm.rest.commons.beans.ApplicationBindings; import net.roboconf.dm.rest.commons.beans.ApplicationBindings.ApplicationBindingItem; import net.roboconf.dm.rest.commons.beans.TargetAssociation; import net.roboconf.dm.rest.commons.beans.WebSocketMessage; /** * A set of utilities to bind Roboconf's runtime model to JSon. * @author Vincent Zurczak - Linagora */ public final class JSonBindingUtils { // Annotations set by the deserializers public static final String AT_INSTANCE_PATH = "@instance_path"; // We use global maps to verify some little things in tests. static final Map<Class<?>,JsonSerializer<?>> SERIALIZERS = new HashMap<> (); static final Map<Class<?>,JsonDeserializer<?>> DESERIALIZERS = new HashMap<> (); static { // Read - Write SERIALIZERS.put( Instance.class, new InstanceSerializer()); DESERIALIZERS.put( Instance.class, new InstanceDeserializer()); SERIALIZERS.put( ApplicationTemplate.class, new ApplicationTemplateSerializer()); DESERIALIZERS.put( ApplicationTemplate.class, new ApplicationTemplateDeserializer()); SERIALIZERS.put( Application.class, new ApplicationSerializer()); DESERIALIZERS.put( Application.class, new ApplicationDeserializer()); SERIALIZERS.put( Component.class, new ComponentSerializer()); DESERIALIZERS.put( Component.class, new ComponentDeserializer()); SERIALIZERS.put( Diagnostic.class, new DiagnosticSerializer()); DESERIALIZERS.put( Diagnostic.class, new DiagnosticDeserializer()); SERIALIZERS.put( DependencyInformation.class, new DependencyInformationSerializer()); DESERIALIZERS.put( DependencyInformation.class, new DependencyInformationDeserializer()); SERIALIZERS.put( TargetWrapperDescriptor.class, new TargetWDSerializer()); DESERIALIZERS.put( TargetWrapperDescriptor.class, new TargetWDDeserializer()); SERIALIZERS.put( StringWrapper.class, new StringWrapperSerializer()); DESERIALIZERS.put( StringWrapper.class, new StringWrapperDeserializer()); SERIALIZERS.put( MapWrapper.class, new MapWrapperSerializer()); DESERIALIZERS.put( MapWrapper.class, new MapWrapperDeserializer()); SERIALIZERS.put( ScheduledJob.class, new ScheduledJobSerializer()); DESERIALIZERS.put( ScheduledJob.class, new ScheduledJobDeserializer()); SERIALIZERS.put( Preference.class, new PreferenceSerializer()); DESERIALIZERS.put( Preference.class, new PreferenceDeserializer()); // Write ONLY SERIALIZERS.put( MappedCollectionWrapper.class, new MappedCollectionWrapperSerializer()); SERIALIZERS.put( TargetUsageItem.class, new TargetUsageItemSerializer()); SERIALIZERS.put( TargetAssociation.class, new TargetAssociationSerializer()); SERIALIZERS.put( ApplicationBindings.class, new ApplicationBindingsSerializer()); SERIALIZERS.put( WebSocketMessage.class, new WebSocketMessageSerializer()); SERIALIZERS.put( CommandHistoryItem.class, new CommandHistoryItemSerializer()); } /** * @return the serializers as an unmodifiable map */ public static Map<Class<?>,? super JsonSerializer<?>> getSerializers() { return Collections.unmodifiableMap( SERIALIZERS ); } private static final String NAME = "name"; private static final String DISPLAY_NAME = "displayName"; private static final String VERSION = "version"; private static final String DESC = "desc"; private static final String EEP = "eep"; private static final String EXT_VARS = "extVars"; private static final String EXT_DEP = "extDep"; private static final String S = "s"; private static final String PATH = "path"; private static final String CRON = "cron"; private static final String ID = "id"; private static final String BOUND = "bound"; private static final String APP_ICON = "icon"; private static final String APP_INFO = "info"; private static final String APP_INST_TPL_NAME = "tplName"; private static final String APP_INST_TPL_VERSION = "tplVersion"; private static final String APP_INST_TPL_EEP = "tplEep"; private static final String APP_TPL_APPS = "apps"; private static final String APP_TPL_TAGS = "tags"; private static final String COMP_INSTALLER = "installer"; private static final String INST_CHANNELS = "channels"; private static final String INST_COMPONENT = "component"; private static final String INST_STATUS = "status"; private static final String INST_EXPORTS = "exports"; private static final String INST_DATA = "data"; private static final String DEP_OPTIONAL = "optional"; private static final String DEP_RESOLVED = "resolved"; private static final String DIAG_PATH = "path"; private static final String DIAG_DEPENDENCIES = "dependencies"; private static final String TARGET_HANDLER = "handler"; private static final String TARGET_DEFAULT = "default"; private static final String TARGET_STATS_USING = "using"; private static final String TARGET_STATS_REFERENCING = "referencing"; private static final String PREF_VALUE = "value"; private static final String PREF_CATEGORY = "category"; private static final String JOB_NAME = "job-name"; private static final String JOB_APP_NAME = "app-name"; private static final String JOB_CMD_NAME = "cmd-name"; private static final String WS_EVENT = "event"; private static final String WS_APP = "app"; private static final String WS_TPL = "tpl"; private static final String WS_INST = "inst"; private static final String WS_MSG = "msg"; /** * Private constructor. */ private JSonBindingUtils() { // nothing } /** * Creates a mapper with specific binding for Roboconf types. * @return a non-null, configured mapper */ @SuppressWarnings( { "unchecked", "rawtypes" } ) public static ObjectMapper createObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false ); SimpleModule module = new SimpleModule( "RoboconfModule", new Version( 1, 0, 0, null, null, null )); for( Map.Entry<Class<?>,? super JsonSerializer<?>> entry : SERIALIZERS.entrySet()) module.addSerializer((Class) entry.getKey(), (JsonSerializer) entry.getValue()); for( Map.Entry<Class<?>,? super JsonDeserializer<?>> entry : DESERIALIZERS.entrySet()) module.addDeserializer((Class) entry.getKey(), (JsonDeserializer) entry.getValue()); mapper.registerModule( module ); return mapper; } /** * A JSon serializer for a bean describing a target usage. * <p> * No deserializer is provided, as it does not make sense for the REST API. * </p> * * @author Vincent Zurczak - Linagora */ public static class TargetUsageItemSerializer extends JsonSerializer<TargetUsageItem> { @Override public void serialize( TargetUsageItem item, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( item.getName() != null ) generator.writeStringField( NAME, item.getName()); if( item.getVersion() != null ) generator.writeStringField( VERSION, item.getVersion()); if( item.isUsing()) generator.writeStringField( TARGET_STATS_USING, "true" ); if( item.isReferencing()) generator.writeStringField( TARGET_STATS_REFERENCING, "true" ); generator.writeEndObject(); } } /** * A JSon serializer for a bean describing a scheduled job. * @author Vincent Zurczak - Linagora */ public static class ScheduledJobSerializer extends JsonSerializer<ScheduledJob> { @Override public void serialize( ScheduledJob job, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( job.getJobId() != null ) generator.writeStringField( ID, job.getJobId()); if( job.getAppName() != null ) generator.writeStringField( JOB_APP_NAME, job.getAppName()); if( job.getCmdName() != null ) generator.writeStringField( JOB_CMD_NAME, job.getCmdName()); if( job.getJobName() != null ) generator.writeStringField( JOB_NAME, job.getJobName()); if( job.getCron() != null ) generator.writeStringField( CRON, job.getCron()); generator.writeEndObject(); } } /** * A JSon deserializer for scheduled jobs. * @author Vincent Zurczak - Linagora */ public static class ScheduledJobDeserializer extends JsonDeserializer<ScheduledJob> { @Override public ScheduledJob deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); ScheduledJob job = new ScheduledJob(); JsonNode n; if(( n = node.get( ID )) != null ) job.setJobId( n.textValue()); if(( n = node.get( JOB_NAME )) != null ) job.setJobName( n.textValue()); if(( n = node.get( JOB_APP_NAME )) != null ) job.setAppName( n.textValue()); if(( n = node.get( JOB_CMD_NAME )) != null ) job.setCmdName( n.textValue()); if(( n = node.get( CRON )) != null ) job.setCron( n.textValue()); return job; } } /** * A JSon serializer for a bean describing a target association. * <p> * No deserializer is provided, as it does not make sense for the REST API. * </p> * * @author Vincent Zurczak - Linagora */ public static class TargetAssociationSerializer extends JsonSerializer<TargetAssociation> { @Override public void serialize( TargetAssociation item, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( item.getInstancePathOrComponentName() != null ) generator.writeStringField( PATH, item.getInstancePathOrComponentName()); if( item.getInstanceComponent() != null ) generator.writeStringField( INST_COMPONENT, item.getInstanceComponent()); if( item.getTargetDescriptor() != null ) generator.writeObjectField( DESC, item.getTargetDescriptor()); generator.writeEndObject(); } } /** * A JSon serializer for a bean describing a command execution. * <p> * No deserializer is provided, as it does not make sense for the REST API. * </p> * * @author Vincent Zurczak - Linagora */ public static class CommandHistoryItemSerializer extends JsonSerializer<CommandHistoryItem> { @Override public void serialize( CommandHistoryItem item, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( item.getApplicationName() != null ) generator.writeStringField( "app", item.getApplicationName()); if( item.getCommandName() != null ) generator.writeStringField( "cmd", item.getCommandName()); if( item.getOriginDetails() != null ) generator.writeStringField( "details", item.getOriginDetails()); long startInMilliSec = item.getStart(); long durationInMilliSec = TimeUnit.MILLISECONDS.convert( item.getDuration(), TimeUnit.NANOSECONDS ); generator.writeNumberField( "start", startInMilliSec ); generator.writeNumberField( "duration", durationInMilliSec ); generator.writeNumberField( "result", item.getExecutionResult()); generator.writeNumberField( "origin", item.getOrigin()); generator.writeEndObject(); } } /** * A JSon serializer for Roboconf preferences. * @author Vincent Zurczak - Linagora */ public static class PreferenceSerializer extends JsonSerializer<Preference> { @Override public void serialize( Preference item, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( item.getName() != null ) generator.writeStringField( NAME, item.getName()); if( item.getValue() != null ) generator.writeObjectField( PREF_VALUE, item.getValue()); if( item.getCategory() != null ) generator.writeObjectField( PREF_CATEGORY, item.getCategory().toString().toLowerCase()); generator.writeEndObject(); } } /** * A JSon deserializer for Roboconf preferences. * @author Vincent Zurczak - Linagora */ public static class PreferenceDeserializer extends JsonDeserializer<Preference> { @Override public Preference deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); String name = null, value = null, cat = null; JsonNode n; if(( n = node.get( NAME )) != null ) name = n.textValue(); if(( n = node.get( PREF_VALUE )) != null ) value = n.textValue(); if(( n = node.get( PREF_CATEGORY )) != null ) cat = n.textValue(); return new Preference( name, value, PreferenceKeyCategory.which( cat )); } } /** * A JSon serializer for target descriptors. * @author Vincent Zurczak - Linagora */ public static class TargetWDSerializer extends JsonSerializer<TargetWrapperDescriptor> { @Override public void serialize( TargetWrapperDescriptor twd, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( twd.getId() != null ) generator.writeStringField( ID, twd.getId()); if( twd.getName() != null ) generator.writeStringField( NAME, twd.getName()); if( twd.getHandler() != null ) generator.writeStringField( TARGET_HANDLER, twd.getHandler()); if( twd.getDescription() != null ) generator.writeStringField( DESC, twd.getDescription()); if( twd.isDefault()) generator.writeStringField( TARGET_DEFAULT, "true" ); generator.writeEndObject(); } } /** * A JSon deserializer for target descriptors. * @author Vincent Zurczak - Linagora */ public static class TargetWDDeserializer extends JsonDeserializer<TargetWrapperDescriptor> { @Override public TargetWrapperDescriptor deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); TargetWrapperDescriptor twd = new TargetWrapperDescriptor(); JsonNode n; if(( n = node.get( DESC )) != null ) twd.setDescription( n.textValue()); if(( n = node.get( TARGET_HANDLER )) != null ) twd.setHandler( n.textValue()); if(( n = node.get( ID )) != null ) twd.setId( n.textValue()); if(( n = node.get( NAME )) != null ) twd.setName( n.textValue()); return twd; } } /** * A JSon deserializer for string wrappers. * @author Vincent Zurczak - Linagora */ public static class StringWrapperDeserializer extends JsonDeserializer<StringWrapper> { @Override public StringWrapper deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); String s = null; JsonNode n; if(( n = node.get( S )) != null ) s = n.textValue(); return new StringWrapper( s ); } } /** * A JSon serializer for string wrappers. * @author Vincent Zurczak - Linagora */ public static class StringWrapperSerializer extends JsonSerializer<StringWrapper> { @Override public void serialize( StringWrapper s, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( s.toString() != null ) generator.writeStringField( S, s.toString()); generator.writeEndObject(); } } /** * A JSon deserializer for map wrappers. * @author Vincent Zurczak - Linagora */ public static class MapWrapperDeserializer extends JsonDeserializer<MapWrapper> { @Override public MapWrapper deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); Map<String,String> map = new HashMap<> (); for( Iterator<Map.Entry<String,JsonNode>> it = node.fields(); it.hasNext(); ) { Map.Entry<String,JsonNode> entry = it.next(); map.put( entry.getKey(), entry.getValue().textValue()); } return new MapWrapper( map ); } } /** * A JSon serializer for map wrappers. * @author Vincent Zurczak - Linagora */ public static class MapWrapperSerializer extends JsonSerializer<MapWrapper> { @Override public void serialize( MapWrapper m, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); for( Map.Entry<String,String> entry : m.getMap().entrySet()) { generator.writeStringField( entry.getKey() == null ? "" : entry.getKey(), entry.getValue() == null ? "" : entry.getValue()); } generator.writeEndObject(); } } /** * A JSon serializer for application templates. * @author Vincent Zurczak - Linagora */ public static class ApplicationTemplateSerializer extends JsonSerializer<ApplicationTemplate> { @Override public void serialize( ApplicationTemplate app, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( app.getName() != null ) generator.writeStringField( NAME, app.getName()); if( app.getDisplayName() != null ) generator.writeStringField( DISPLAY_NAME, app.getDisplayName()); if( app.getDescription() != null ) generator.writeStringField( DESC, app.getDescription()); if( app.getVersion() != null ) generator.writeStringField( VERSION, app.getVersion()); if( app.getExternalExportsPrefix() != null ) generator.writeStringField( EEP, app.getExternalExportsPrefix()); // Read-only information. // We do not expect it for deserialization if( ! app.externalExports.isEmpty()) generator.writeObjectField( EXT_VARS, new MapWrapper( app.externalExports )); // Read-only information. // We do not expect it for deserialization String iconLocation = IconUtils.findIconUrl( app ); if( ! Utils.isEmptyOrWhitespaces( iconLocation )) generator.writeStringField( APP_ICON, iconLocation ); // Read-only information. // We do not expect it for deserialization Set<String> prefixesForExternalImports = VariableHelpers.findPrefixesForExternalImports( app ); if( ! prefixesForExternalImports.isEmpty()) { generator.writeArrayFieldStart( EXT_DEP ); for( String prefix : prefixesForExternalImports ) generator.writeString( prefix ); generator.writeEndArray(); } // Read-only information. // We do not expect it for deserialization generator.writeArrayFieldStart( APP_TPL_APPS ); for( Application associatedApp : app.getAssociatedApplications()) { // #483 We do not know why, but after we delete an application // from the web console, the resulting JSon array sometimes contains null. // This prevents the deletion of a template that does not have applications anymore. // The "IF" is a WORKAROUND. if( associatedApp != null && associatedApp.getName() != null ) { // end of WORKAROUND generator.writeString( associatedApp.getName()); } } generator.writeEndArray(); // Tags Set<String> tags = app.getTags(); if( ! tags.isEmpty()) { generator.writeArrayFieldStart( APP_TPL_TAGS ); for( String s : tags ) generator.writeString( s ); generator.writeEndArray(); } generator.writeEndObject(); } } /** * A JSon serializer for mapped collection wrappers. * @author Vincent Zurczak - Linagora */ public static class MappedCollectionWrapperSerializer extends JsonSerializer<MappedCollectionWrapper> { @Override public void serialize( MappedCollectionWrapper m, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); for( Map.Entry<String,? extends Collection<String>> entry : m.getMap().entrySet()) { generator.writeArrayFieldStart( entry.getKey() == null ? "" : entry.getKey()); if( entry.getValue() != null ) { for( String item : entry.getValue()) generator.writeString( item ); } generator.writeEndArray(); } generator.writeEndObject(); } } /** * A JSon deserializer for application templates. * @author Vincent Zurczak - Linagora */ public static class ApplicationTemplateDeserializer extends JsonDeserializer<ApplicationTemplate> { @Override public ApplicationTemplate deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); ApplicationTemplate application = new ApplicationTemplate(); JsonNode n; if(( n = node.get( DISPLAY_NAME )) != null ) application.setName( n.textValue()); else if(( n = node.get( NAME )) != null ) application.setName( n.textValue()); if(( n = node.get( DESC )) != null ) application.setDescription( n.textValue()); if(( n = node.get( VERSION )) != null ) application.setVersion( n.textValue()); if(( n = node.get( EEP )) != null ) application.setExternalExportsPrefix( n.textValue()); if(( n = node.get( APP_TPL_TAGS )) != null ) { for( JsonNode arrayNodeItem : n ) application.addTag( arrayNodeItem.textValue()); } return application; } } /** * A JSon serializer for diagnostics. * @author Vincent Zurczak - Linagora */ public static class DiagnosticSerializer extends JsonSerializer<Diagnostic> { @Override public void serialize( Diagnostic diag, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( diag.getInstancePath() != null ) generator.writeStringField( DIAG_PATH, diag.getInstancePath()); generator.writeArrayFieldStart( DIAG_DEPENDENCIES ); for( DependencyInformation info : diag.getDependenciesInformation()) generator.writeObject( info ); generator.writeEndArray(); generator.writeEndObject(); } } /** * A JSon deserializer for diagnostics. * @author Vincent Zurczak - Linagora */ public static class DiagnosticDeserializer extends JsonDeserializer<Diagnostic> { @Override public Diagnostic deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); Diagnostic diag = new Diagnostic(); JsonNode n; if(( n = node.get( DIAG_PATH )) != null ) diag.setInstancePath( n.textValue()); if(( n = node.get( DIAG_DEPENDENCIES )) != null ) { for( JsonNode arrayNodeItem : n ) { ObjectMapper mapper = createObjectMapper(); DependencyInformation info = mapper.readValue( arrayNodeItem.toString(), DependencyInformation.class ); diag.getDependenciesInformation().add( info ); } } return diag; } } /** * A JSon serializer for dependencies information. * @author Vincent Zurczak - Linagora */ public static class DependencyInformationSerializer extends JsonSerializer<DependencyInformation> { @Override public void serialize( DependencyInformation info, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( info.getDependencyName() != null ) generator.writeStringField( NAME, info.getDependencyName()); generator.writeStringField( DEP_OPTIONAL, String.valueOf( info.isOptional())); generator.writeStringField( DEP_RESOLVED, String.valueOf( info.isResolved())); generator.writeEndObject(); } } /** * A JSon deserializer for dependencies information. * @author Vincent Zurczak - Linagora */ public static class DependencyInformationDeserializer extends JsonDeserializer<DependencyInformation> { @Override public DependencyInformation deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); DependencyInformation info = new DependencyInformation(); JsonNode n; if(( n = node.get( NAME )) != null ) info.setDependencyName( n.textValue()); if(( n = node.get( DEP_OPTIONAL )) != null ) info.setOptional( Boolean.valueOf( n.textValue())); if(( n = node.get( DEP_RESOLVED )) != null ) info.setResolved( Boolean.valueOf( n.textValue())); return info; } } /** * A JSon serializer for application bindings. * @author Vincent Zurczak - Linagora */ public static class ApplicationBindingsSerializer extends JsonSerializer<ApplicationBindings> { @Override public void serialize( ApplicationBindings bindings, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); for( Map.Entry<String,List<ApplicationBindingItem>> entry : bindings.prefixToItems.entrySet()) { generator.writeArrayFieldStart( entry.getKey()); for( ApplicationBindingItem item : entry.getValue()) { generator.writeStartObject(); generator.writeStringField( NAME, item.getApplicationName()); generator.writeBooleanField( BOUND, item.isBound()); generator.writeEndObject(); } generator.writeEndArray(); } generator.writeEndObject(); } } /** * A JSon serializer for web socket messages. * @author Vincent Zurczak - Linagora */ public static class WebSocketMessageSerializer extends JsonSerializer<WebSocketMessage> { @Override public void serialize( WebSocketMessage wsm, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( wsm.getEventType() != null ) generator.writeStringField( WS_EVENT, wsm.getEventType().toString()); if( wsm.getApplication() != null ) generator.writeObjectField( WS_APP, wsm.getApplication()); if( wsm.getApplicationTemplate() != null ) generator.writeObjectField( WS_TPL, wsm.getApplicationTemplate()); if( wsm.getInstance() != null ) generator.writeObjectField( WS_INST, wsm.getInstance()); if( wsm.getMessage() != null ) generator.writeObjectField( WS_MSG, wsm.getMessage()); generator.writeEndObject(); } } /** * A JSon serializer for applications. * @author Vincent Zurczak - Linagora */ public static class ApplicationSerializer extends JsonSerializer<Application> { @Override public void serialize( Application app, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( app.getName() != null ) generator.writeStringField( NAME, app.getName()); if( app.getDisplayName() != null ) generator.writeStringField( DISPLAY_NAME, app.getDisplayName()); if( app.getDescription() != null ) generator.writeStringField( DESC, app.getDescription()); if( app.getTemplate() != null ) { generator.writeStringField( APP_INST_TPL_NAME, app.getTemplate().getName()); if( app.getTemplate().getVersion() != null ) generator.writeStringField( APP_INST_TPL_VERSION, app.getTemplate().getVersion()); if( app.getTemplate().getExternalExportsPrefix() != null ) generator.writeStringField( APP_INST_TPL_EEP, app.getTemplate().getExternalExportsPrefix()); // Read-only information. // We do not expect it for deserialization Map<String,String> externalExports = app.getTemplate().externalExports; if( ! externalExports.isEmpty()) generator.writeObjectField( EXT_VARS, new MapWrapper( externalExports )); } // Read-only information. // We do not expect it for deserialization String iconLocation = IconUtils.findIconUrl( app ); if( ! Utils.isEmptyOrWhitespaces( iconLocation )) generator.writeStringField( APP_ICON, iconLocation ); // Read-only information. // We do not expect it for deserialization Set<String> prefixesForExternalImports = VariableHelpers.findPrefixesForExternalImports( app ); if( ! prefixesForExternalImports.isEmpty()) { generator.writeArrayFieldStart( EXT_DEP ); for( String prefix : prefixesForExternalImports ) generator.writeString( prefix ); generator.writeEndArray(); } // #357 Add a state for applications in JSon objects String info = null; for( Instance rootInstance : app.getRootInstances()) { if( rootInstance.getStatus() == InstanceStatus.PROBLEM ) { info = "warn"; break; } if( rootInstance.getStatus() != InstanceStatus.NOT_DEPLOYED ) { info = "ok"; break; } } if( info != null ) generator.writeObjectField( APP_INFO, info ); generator.writeEndObject(); } } /** * A JSon deserializer for applications. * @author Vincent Zurczak - Linagora */ public static class ApplicationDeserializer extends JsonDeserializer<Application> { @Override public Application deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); Application application; JsonNode n; if(( n = node.get( APP_INST_TPL_NAME )) != null ) { ApplicationTemplate appTemplate = new ApplicationTemplate(); appTemplate.setName( n.textValue()); n = node.get( APP_INST_TPL_VERSION ); if( n != null ) appTemplate.setVersion( n.textValue()); n = node.get( APP_INST_TPL_EEP ); if( n != null ) appTemplate.setExternalExportsPrefix( n.textValue()); application = new Application( appTemplate ); } else { application = new Application( null ); } if(( n = node.get( DISPLAY_NAME )) != null ) application.setName( n.textValue()); else if(( n = node.get( NAME )) != null ) application.setName( n.textValue()); if(( n = node.get( DESC )) != null ) application.setDescription( n.textValue()); return application; } } /** * A JSon serializer for instances. * @author Vincent Zurczak - Linagora */ public static class InstanceSerializer extends JsonSerializer<Instance> { @Override public void serialize( Instance instance, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( instance.getName() != null ) { generator.writeStringField( NAME, instance.getName()); generator.writeStringField( PATH, InstanceHelpers.computeInstancePath( instance )); } if( instance.getStatus() != null ) generator.writeStringField( INST_STATUS, String.valueOf( instance.getStatus())); if( instance.getComponent() != null ) generator.writeObjectField( INST_COMPONENT, instance.getComponent()); if( ! instance.channels.isEmpty()) { generator.writeArrayFieldStart( INST_CHANNELS ); for( String channel : instance.channels ) generator.writeString( channel ); generator.writeEndArray(); } // All exports are serialized in the same object (overridden or not). // Will be necessary in external apps, like web console (eg. to edit exports). Map<String, String> exports = InstanceHelpers.findAllExportedVariables(instance); if( ! exports.isEmpty()) { generator.writeFieldName( INST_EXPORTS ); generator.writeStartObject(); for( Map.Entry<String,String> entry : exports.entrySet()) generator.writeObjectField( entry.getKey(), entry.getValue()); generator.writeEndObject(); } // Write some meta-data (useful for web clients). // De-serializing this information is useless for the moment. if( ! instance.data.isEmpty()) { generator.writeFieldName( INST_DATA ); generator.writeStartObject(); for( Map.Entry<String,String> entry : instance.data.entrySet()) generator.writeObjectField( entry.getKey(), entry.getValue()); generator.writeEndObject(); } generator.writeEndObject(); } } /** * A JSon deserializer for instances. * @author Vincent Zurczak - Linagora */ public static class InstanceDeserializer extends JsonDeserializer<Instance> { @Override public Instance deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); Instance instance = new Instance(); JsonNode n; if(( n = node.get( NAME )) != null ) instance.setName( n.textValue()); if(( n = node.get( INST_STATUS )) != null ) instance.setStatus( InstanceStatus.whichStatus( n.textValue())); if(( n = node.get( INST_CHANNELS )) != null ) { for( JsonNode arrayNodeItem : n ) instance.channels.add( arrayNodeItem.textValue()); } ObjectMapper mapper = createObjectMapper(); // Consider all exports as overridden. This will be fixed later // (e.g. by comparison with component exports). if(( n = node.get( INST_EXPORTS )) != null ) { Map<String, String> exports = mapper.readValue( n.toString(), new TypeReference<HashMap<String,String>>(){}); instance.overriddenExports.putAll(exports); } if(( n = node.get( INST_COMPONENT )) != null ) { Component instanceComponent = mapper.readValue( n.toString(), Component.class ); instance.setComponent( instanceComponent ); } // Add all the data (IP address, etc) if(( n = node.get( INST_DATA )) != null ) { for( Iterator<String> it = n.fieldNames(); it.hasNext(); ) { String fieldName = it.next(); JsonNode dataNode = n.get( fieldName ); instance.data.put( fieldName, dataNode.asText()); } } // Add meta-data if(( n = node.get( PATH )) != null ) { instance.data.put( AT_INSTANCE_PATH, n.textValue()); } return instance; } } /** * A JSon serializer for components. * <p> * Only the name and alias are serialized. * </p> * * @author Vincent Zurczak - Linagora */ public static class ComponentSerializer extends JsonSerializer<Component> { @Override public void serialize( Component component, JsonGenerator generator, SerializerProvider provider ) throws IOException { generator.writeStartObject(); if( component.getName() != null ) generator.writeStringField( NAME, component.getName()); String installerName = ComponentHelpers.findComponentInstaller( component ); if( installerName != null ) generator.writeStringField( COMP_INSTALLER, installerName ); generator.writeEndObject(); } } /** * A JSon deserializer for components. * @author Vincent Zurczak - Linagora */ public static class ComponentDeserializer extends JsonDeserializer<Component> { @Override public Component deserialize( JsonParser parser, DeserializationContext context ) throws IOException { ObjectCodec oc = parser.getCodec(); JsonNode node = oc.readTree( parser ); Component component = new Component(); JsonNode n; if(( n = node.get( NAME )) != null ) component.setName( n.textValue()); if(( n = node.get( COMP_INSTALLER )) != null ) component.setInstallerName( n.textValue()); return component; } } }
30.609855
118
0.719699
efcf69246f1edf552477497b4e508395c8549385
1,292
package cn.newcapec.function.citycard.platform.privilege.biz.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import cn.newcapec.function.citycard.platform.privilege.biz.DepartmentRoleService; import cn.newcapec.function.citycard.platform.privilege.dao.DepartmentRoleDAO; import cn.newcapec.function.citycard.platform.privilege.model.DepartmentRole; /** * 权限部门业务接口实现类 * @author andy.li * */ @Service("departmentRoleService") @Transactional @SuppressWarnings("all") public class DepartmentRoleServiceImpl implements DepartmentRoleService { @Autowired DepartmentRoleDAO departmentRoleDAO; @Override @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED) public DepartmentRole get(String id) { return departmentRoleDAO.get(id); } @Override public void removeUnused(String id) { departmentRoleDAO.delete(id); } @Override public void saveOrUpdate(DepartmentRole entity) { departmentRoleDAO.saveOrUpdate(entity); } @Override public void deleteDepartmentRoleByRoleId(String roleid) { departmentRoleDAO.deleteDepartmentRoleByRoleId(roleid); } }
26.916667
82
0.815789
e2fb9576002efddd31a20a132a048c34a2f4fb50
4,847
package gms.shared.utilities.service; import static junit.framework.TestCase.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import org.junit.Test; public class ServiceDefinitionTests { @Test public void testBuilderUsesDefaults() { final ServiceDefinition def = ServiceDefinition.builder().build(); assertEquals(Defaults.JSON_MAPPER, def.getJsonMapper()); assertEquals(Defaults.MSGPACK_MAPPER, def.getMsgpackMapper()); assertEquals(Defaults.PORT, def.getPort()); assertEquals(Defaults.MIN_THREAD_POOL_SIZE, def.getMinThreadPoolSize()); assertEquals(Defaults.MAX_THREAD_POOL_SIZE, def.getMaxThreadPoolSize()); assertEquals(Defaults.THREAD_IDLE_TIMEOUT_MILLIS, def.getThreadIdleTimeoutMillis()); assertNotNull(def.getRoutes()); assertTrue(def.getRoutes().isEmpty()); } @Test public void testBuilder() { final Route r = createRoute(); final ObjectMapper jsonMapper = new ObjectMapper(); final ObjectMapper msgpackMapper = new ObjectMapper(); // set some properties of the object mapper to not match the defaults // so it can be determined that they were actually taken in by the ServiceDefinition jsonMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); msgpackMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); final ServiceDefinition def = ServiceDefinition.builder() .setJsonMapper(jsonMapper) .setMsgpackMapper(msgpackMapper) .setPort(1234) .setMinThreadPoolSize(5) .setMaxThreadPoolSize(13) .setThreadIdleTimeoutMillis(5000) .setRoutes(Set.of(r)) .build(); assertEquals(jsonMapper, def.getJsonMapper()); assertEquals(msgpackMapper, def.getMsgpackMapper()); assertEquals(1234, def.getPort()); assertEquals(5, def.getMinThreadPoolSize()); assertEquals(13, def.getMaxThreadPoolSize()); assertEquals(5000, def.getThreadIdleTimeoutMillis()); assertTrue("Expected the added route to be contained: " + r, def.getRoutes().contains(r)); } @Test public void testPortNumberNegativeValidation() { final int[] badPorts = new int[]{-Integer.MAX_VALUE - 1, 0, 65536, 123456789}; for (int p : badPorts) { assertIllegalArgumentExceptionThrown( () -> ServiceDefinition.builder().setPort(p).build(), "Port number " + p + " is not in range [0, 65535]"); } } @Test public void testMinThreadPoolSizeValidation() { assertValidationOnNonPositiveValues( s -> ServiceDefinition.builder().setMinThreadPoolSize(s).build(), s -> "min thread pool size is " + s + ", must be > 0" ); } @Test public void testMaxThreadPoolSizeValidation() { assertValidationOnNonPositiveValues( s -> ServiceDefinition.builder().setMaxThreadPoolSize(s).build(), s -> "max thread pool size is " + s + ", must be > 0" ); } @Test public void testThreadPoolSizeMinNotGreaterThanMaxValidation() { final int min = 5, max = 4; assertIllegalArgumentExceptionThrown( () -> ServiceDefinition.builder().setMinThreadPoolSize(5).setMaxThreadPoolSize(4).build(), String.format("min thread pool size must be <= max thread pool size (min=%d, max=%d)", min, max)); } @Test public void testThreadIdleTimeoutValidation() { assertValidationOnNonPositiveValues( s -> ServiceDefinition.builder().setThreadIdleTimeoutMillis(s).build(), s -> "thread timeout is " + s + ", must be > 0" ); } @Test(expected = UnsupportedOperationException.class) public void testRoutesImmutable() { ServiceDefinition.builder().build().getRoutes().add(createRoute()); } private static void assertIllegalArgumentExceptionThrown(Runnable r, String message) { try { r.run(); fail(message); } catch (IllegalArgumentException ex) { assertTrue("Expected exception message " + ex.getMessage() + " to contain message " + message, ex.getMessage() != null && ex.getMessage().contains(message)); } } private static void assertValidationOnNonPositiveValues(Consumer<Integer> c, Function<Integer, String> errorMessageFunction) { final int[] badValues = new int[]{-Integer.MAX_VALUE, -1, 0}; for (int s : badValues) { assertIllegalArgumentExceptionThrown( () -> c.accept(s), errorMessageFunction.apply(s)); } } private static Route createRoute() { return Route.create("/foo", (req, deserializer) -> Response.success("hello")); } }
36.443609
100
0.702909
ec37f8b10059b9f6859dea68b9503870ab6a093f
269
package com.github.lukasgail.chateditorFSM; import org.bukkit.block.Block; import org.bukkit.event.player.PlayerInteractEvent; public interface EditorState { void sendedInput(String input); void refresh(); void blockClick(PlayerInteractEvent event); }
19.214286
51
0.776952
60545a505720b880229c690016dfeefdf2df376c
1,146
package imooc.naga.server.query; import imooc.naga.core.exception.ErrorCodes; import imooc.naga.core.exception.NagaException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; @Component public class RedisPool { @Value("${custom.redis.ip}") private String redisIp; @Value("${custom.redis.port}") private int redisPort; private JedisPool jedisPool; public RedisPool() { try { JedisPoolConfig config = new JedisPoolConfig(); jedisPool = new JedisPool(config, redisIp,redisPort); } catch (Exception e) { throw new NagaException("init redis pool error", ErrorCodes.SYSTEM_EXCEPTION); } } private static final RedisPool INSTANCE = new RedisPool(); public static RedisPool getInstance() { return INSTANCE; } public JedisPool getJedisPool() { return jedisPool; } public Jedis getConnection() { return jedisPool.getResource(); } }
26.045455
90
0.692845
88219b0d452e9cacc5c5a8c979799e512f84fb18
897
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.sys.dao.gbj; import java.util.List; import com.thinkgem.jeesite.common.persistence.CrudDao; import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao; import com.thinkgem.jeesite.modules.sys.entity.gbj.GbjUserRewardComments; /** * 悬赏信息评论DAO接口 * * @author snnu * @version 2017-12-21 */ @MyBatisDao public interface GbjUserRewardCommentsDao extends CrudDao<GbjUserRewardComments> { // 根据reward_id查询卖标评论信息 public List<GbjUserRewardComments> getCommentsList(String reward_Id); public List<GbjUserRewardComments> findDomainArticleRewardCommentsList(String id); public List<GbjUserRewardComments> findDomainArticleRewardReplyCommentsList(String id); public int updateCount(GbjUserRewardComments gbjUserRewardComments); }
30.931034
108
0.810479
5b67f536d62d45c142cad0ad941199a85c79e107
3,012
package android.content; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @com.francetelecom.rd.stubs.annotation.ClassDone(0) public final class ComponentName implements java.lang.Comparable<ComponentName>, android.os.Parcelable, java.lang.Cloneable { // Fields public static final android.os.Parcelable.Creator<ComponentName> CREATOR = null; // Constructors @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "ComponentName-1", pos = {0, 1, 2}, report = "-") public ComponentName(java.lang.String arg1, java.lang.String arg2){ } @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "ComponentName-2", pos = {0, 2}, report = "-") public ComponentName(Context arg1, java.lang.String arg2){ } @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "ComponentName-3", pos = {0, 2}, report = "-") public ComponentName(Context arg1, java.lang.Class<?> arg2){ } @com.francetelecom.rd.stubs.annotation.ArgsRule(value = "ComponentName-4", pos = {0, 1}, report = "-") public ComponentName(android.os.Parcel arg1){ } private ComponentName(java.lang.String arg1, android.os.Parcel arg2){ } // Methods public boolean equals(java.lang.Object arg1){ return false; } public java.lang.String toString(){ return (java.lang.String) null; } public int hashCode(){ return 0; } public ComponentName clone(){ return (ComponentName) null; } public int compareTo(ComponentName arg1){ return 0; } public java.lang.String getClassName(){ return (java.lang.String) null; } public java.lang.String getPackageName(){ return (java.lang.String) null; } public void writeToParcel(android.os.Parcel arg1, int arg2){ } public static void writeToParcel(ComponentName arg1, android.os.Parcel arg2){ } public int describeContents(){ return 0; } public static ComponentName readFromParcel(android.os.Parcel arg1){ return (ComponentName) null; } public java.lang.String toShortString(){ return (java.lang.String) null; } public java.lang.String flattenToString(){ return (java.lang.String) null; } public static ComponentName unflattenFromString(java.lang.String arg1){ return (ComponentName) null; } public java.lang.String flattenToShortString(){ return (java.lang.String) null; } public java.lang.String getShortClassName(){ return (java.lang.String) null; } }
30.424242
107
0.707171
2ae966794b10f63f9f6651abe6b5cd0e8c7e4439
1,456
package org.apereo.cas.qr.web.flow; import org.apereo.cas.qr.authentication.QRAuthenticationTokenCredential; import org.apereo.cas.token.TokenConstants; import org.apereo.cas.web.flow.CasWebflowConstants; import org.apereo.cas.web.flow.actions.BaseCasWebflowAction; import org.apereo.cas.web.support.WebUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.springframework.webflow.action.EventFactorySupport; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; /** * This is {@link QRAuthenticationValidateTokenAction}. * * @author Misagh Moayyed * @since 6.3.0 */ @RequiredArgsConstructor @Slf4j public class QRAuthenticationValidateTokenAction extends BaseCasWebflowAction { @Override protected Event doExecute(final RequestContext requestContext) { val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext); val token = request.getParameter(TokenConstants.PARAMETER_NAME_TOKEN); val deviceId = request.getParameter("deviceId"); LOGGER.debug("Received QR token [{}] with device identifier [{}]", token, deviceId); val credential = new QRAuthenticationTokenCredential(token, deviceId); WebUtils.putCredential(requestContext, credential); return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_FINALIZE); } }
39.351351
97
0.791209
2fafa451e9539d7d7ea18bece689d3aa5aed0767
3,312
/******************************************************************************* * Copyright 2020 Grégoire Martinetti * * 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.gmart.codeGen.javaGen.model.referenceResolution; import java.util.List; import java.util.Optional; import java.util.function.Function; import org.gmart.codeGen.javaGen.model.TypeExpression; import org.gmart.codeGen.javaGen.model.referenceResolution.runtime.DependentInstance; import org.gmart.codeGen.javaGen.model.referenceResolution.runtime.DependentInstanceSource; public class AccessorBuilderFactoryFromConstructorArgument extends AbstractAccessorBuilder { private final Function<Function<List<Object>, Optional<Object>>, Function<List<Object>, Optional<Object>>> accessor; private final int paramIndex; public AccessorBuilderFactoryFromConstructorArgument(List<AccessorConstructorParameter> constructorParameters, List<String> path, int paramIndex){ super(); AccessorConstructorParameter accessorConstructorParameter = constructorParameters.get(paramIndex); this.toFillWithIOTypesForValidation.inputTypes.addAll(accessorConstructorParameter.getInputTypeParameters()); this.accessor = makeAccessorBuilder( accessorConstructorParameter.getOutputTypeParameter(), path, this.toFillWithIOTypesForValidation ); this.paramIndex = paramIndex; } private Function<Function<List<Object>, Optional<Object>>, Function<List<Object>, Optional<Object>>> makeAccessorBuilder(TypeExpression accessorParamOutputType, List<String> path, AccessPathKeyAndOutputTypes toFillWithIOTypesForValidation) { if(path.size() > 0) { Function<Object, Function<List<Object>, Optional<Object>>> accessor = accessorParamOutputType.makeAccessorBuilder(path, toFillWithIOTypesForValidation); Function<Function<List<Object>, Optional<Object>>, Function<List<Object>, Optional<Object>>> f = (Function<List<Object>, Optional<Object>> keysToObj) -> { Function<List<Object>, Optional<Object>> k = (List<Object> keys) -> { return keysToObj.apply(keys).flatMap(containerInstance -> accessor.apply(containerInstance).apply(keys)); }; return k; }; return f; } else { toFillWithIOTypesForValidation.setOutputType(accessorParamOutputType); return keysToObj -> keysToObj; } } /** about "instantiatedInstance": by analogy with the "constructor" syntax in the code that defines types */ @Override public Function<List<Object>, Optional<Object>> makeAccessor(DependentInstanceSource instantiatedInstance) { Function<List<Object>, Optional<Object>> constructionArgument = ((DependentInstance)instantiatedInstance).getConstructionArgument(paramIndex); return this.accessor.apply(constructionArgument); } }
52.571429
242
0.754529
7e3ea7d6d1649504fd759b557e6ca7fd5986843d
602
package com.example.demo.po; public class QAlogEntity { private int id; private String question; private String answer; private String remark; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
16.722222
43
0.694352
79fc8259d6ad2dac40cc9eb9aaf037ae09ee7f5e
2,255
package com.michaelwasher.bricker.views; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import com.michaelwasher.bricker.R; import androidx.appcompat.widget.AppCompatButton; public class LevelSelector extends AppCompatButton { //circle and text colors private int starLevel, levelNumber; private Context context; private Paint paint; private boolean isLocked; public LevelSelector(Context context, AttributeSet attrs) { super(context, attrs); Log.d("LevelSelector Created", "A LevelSelector has been created."); this.context = context; this.paint = new Paint(); this.isLocked = this.starLevel == 4; // Populate class based on Attributes TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.LevelSelector, 0, 0); try { this.starLevel = a.getInteger(R.styleable.LevelSelector_starLevel, 0); this.levelNumber = a.getInteger(R.styleable.LevelSelector_levelNumber, 0); } finally { a.recycle(); } this.setBackground(getSprite()); if (starLevel != 4) this.setText(String.valueOf(levelNumber)); else this.setText(""); } private Drawable getSprite() { Drawable sprite; switch (this.starLevel) { case 1: sprite = context.getDrawable(R.drawable.ic_level_selector_one_star); break; case 2: sprite = context.getDrawable(R.drawable.ic_level_selector_two_star); break; case 3: sprite = context.getDrawable(R.drawable.ic_level_selector_three_star); break; case 4: sprite = context.getDrawable(R.drawable.ic_level_selector_locked); break; default: sprite = context.getDrawable(R.drawable.ic_level_selector_zero_star); break; } return sprite; } public boolean getLocked(){ return this.isLocked; } }
31.319444
86
0.623947
68f5706b3a9f2568dc37c7bde63dd81e785437cf
9,500
package com.jiubang.goscreenlock.theme.cjpcardcool.weather.util; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.location.Location; import android.os.Handler; import android.os.Message; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean.City; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean.CityBean; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.bean.ForecastInfo; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.common.LocationConstants; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.http.Result; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.location.ReqLocation; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.location.ReqLocationListener; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.tianqi.IHttpConnListener; import com.jiubang.goscreenlock.theme.cjpcardcool.weather.tianqi.SyncWeatherInfoLoader; /** * * <br>类描述: 英文下添加城市的界面 * <br>功能详细描述: * * @date [2012-9-5] */ public class WeatherHelperBean { /** 定位完成后返回的各种状态 */ public static final int LOCATION_CHANGED = 1; // 获取当前位置的经纬度成功 public static final int LOCATION_TIME_OUT = 2; // 获取经纬度超时 public static final int LOCATION_NULL = 3; // 无法获取当前城市 public static final int LOCATION_CITY = 4; // 获取当前位置所处的城市成功 public static final int LOCATION_PROVIDER_UNABLE = 5; // 没有开启定位功能 public static final int LOCATION_NETWORK_ERROR = 6; // 基站定位网络不可用 public static final int LOCATION_DUPLICATED = 7; // 我的位置重复 public static final int LOCATION_AUTO_LOCATION_CLOSED = 8; // 定位完成时,自动定位选项已关闭 public static final int LOCATION_EMPTY = 9; // 获取到城市ID为空的我的位置 /**获取天气回来的各种状态**/ public static final int WEATHER_NETWORK_ERROR = 10; // 获取天气网络错误 public static final int WEATHER_ERRORGENERAL = 11; // 获取天气发生错误 public static final int WEATHER_ONNONEWDATA = 12; // 获取天气时间戳一样,不更新数据 public static final int WEATHER_SUCCED = 13; // 获取天气成功 private ReqLocation mReqLocation; Context mContext; private Handler mHandler; private String mLang; public WeatherHelperBean(Context mContext, Handler mHandler, String lang) { // 准备工具 this.mContext = mContext; this.mHandler = mHandler; this.mLang = lang; mReqLocation = new ReqLocation(mContext, mLang); } /*******************************************************定位城市**************************************************************/ public void startLocation(int second) { // Toast.makeText(mContext.getApplicationContext(), "Location...", Toast.LENGTH_LONG).show(); doStartLocation(0, LocationConstants.WAY_CELL_LOCATION, second); } private void doStartLocation(final int prevLocationWay, final int curLocationWay, int countTime) { mReqLocation.startLocation(prevLocationWay, curLocationWay, countTime, new ReqLocationListener() { @Override public void onLocationTimeout(int locationWay) { if (locationWay == LocationConstants.WAY_GPS_LOCATION) { // 按照定位顺序:基站定位->网络定位->GPS定位,最后一种定位方式为GPS if (mHandler != null) { mHandler.sendEmptyMessage(LOCATION_TIME_OUT); } } else { startNextLocationWay(prevLocationWay, curLocationWay, LOCATION_TIME_OUT); } } @Override public void onLocationNull() { // sendBroadcast(Constants.LOCATION_NULL); if (mHandler != null) { mHandler.sendEmptyMessage(LOCATION_NULL); } } @Override public void onLocationWayChanged(int switchType) { // sendSwitchLocationWayBroadcast(switchType); } @Override public void onLocationSuccess(CityBean curCity, Location curLocation) { Message message = Message.obtain(); message.obj = curCity; message.what = LOCATION_CITY; if (mHandler != null) { mHandler.sendMessage(message); } } @Override public void onLocationFailed(int status) { startNextLocationWay(prevLocationWay, curLocationWay, status); } @Override public void onLocationLatLngFectched(Location curLocation) { mReqLocation.fetchAddressInfo(curLocation); } }); } private void startNextLocationWay(int prevLocationWay, int curLocationWay, int status) { switch (curLocationWay) { case LocationConstants.WAY_CELL_LOCATION : if (status == LocationConstants.LOCATION_SIMCARD_NOT_READY || status == LocationConstants.LOCATION_NETWORK_ERROR) { // 基站定位不可用 doStartLocation(prevLocationWay, LocationConstants.WAY_NETWORK_LOCATION, 15); } else { // 基站定位失败 doStartLocation(curLocationWay, LocationConstants.WAY_NETWORK_LOCATION, 15); } break; case LocationConstants.WAY_NETWORK_LOCATION : if (status == LocationConstants.LOCATION_NETWORK_UNABLED || status == LocationConstants.LOCATION_UNSUPPORTED_BY_SYSYTEM) { // 网络定位不可用 doStartLocation(prevLocationWay, LocationConstants.WAY_GPS_LOCATION, 50); } else { // 网络定位失败 doStartLocation(curLocationWay, LocationConstants.WAY_GPS_LOCATION, 50); } break; case LocationConstants.WAY_GPS_LOCATION : // 按照定位顺序:基站定位->网络定位->GPS定位,最后一种定位方式为GPS // sendBroadcast(Constants.LOCATION_PROVIDER_UNABLE); if (mHandler != null) { mHandler.sendEmptyMessage(LOCATION_PROVIDER_UNABLE); } break; default : ; } } // ============================================================================== // 天气刷新的任务 public void startWeather(final CityBean curCity) { // Toast.makeText(mContext.getApplicationContext(), "Obtain Weather-info...", Toast.LENGTH_LONG).show(); new Thread(new Runnable() { @Override public void run() { new WeatherWorker(new City(curCity.getCityName(), curCity.getCityId(), 0)) .startRefresh(); } }).start(); } /** * * 类描述:处理天气刷新的工作任务 * */ private class WeatherWorker implements IHttpConnListener { /** * 需要服务器下发的时间制(只需要24小时制,默认为false) */ private final boolean mIs12Hours = false; private City mRefreshCity; public WeatherWorker(City city) { mRefreshCity = city; } /** 同步刷新天气 */ public void startRefresh() { SyncWeatherInfoLoader mSyncLoader = new SyncWeatherInfoLoader(mContext, mRefreshCity, this); mSyncLoader.setHourFormat(mIs12Hours); mSyncLoader.setLanguage(mLang); mSyncLoader.start(); } @Override public void onNetworkUnavailable(List<Result> results) { // 没有网络的情况 if (mHandler != null) { mHandler.sendEmptyMessage(WEATHER_NETWORK_ERROR); } } @Override public void onErrorGeneral(List<Result> results) { // 获取天气过程中发生错误 if (mHandler != null) { mHandler.sendEmptyMessage(WEATHER_ERRORGENERAL); } } @Override public void onSuccess(final City city, List<Result> results) { // 成功 // StringBuffer buffer = new StringBuffer(); // buffer.append("当前温度:" + city.mNow.getRealTemp() + "\n"); // buffer.append("最高温度:" + city.mNow.getHigh() + " ~ 最低温度:" + city.mNow.getLow() + "\n"); // buffer.append(" === 多天预报 === \n"); // for (ForecastInfo info : city.mForecastList) // { // buffer.append("日期:" + info.getLongDate()); // buffer.append(" 温度:" + info.getHigh() + "~" + info.getLow() + "\n"); // } // buffer.append(" === 小时预报 === \n"); // for (HourInfo info : city.mHourList) // { // buffer.append("时间:" + info.getDate() + " " + info.getHour() + "时"); // buffer.append(" 温度:" + info.getTemp() + "\n"); // } float curr = city.mNow.getRealTemp(); float high = city.mNow.getHigh(); float low = city.mNow.getLow(); WeatherDataBean temp = new WeatherDataBean(); temp.setmCityId(city.getCode()); temp.setmCityName(city.getName()); temp.setmWeatherType(city.mNow.getStatusType()); temp.setmWeatherCurrT(curr); temp.setmWeatherHighT(high); temp.setmWeatherLowT(low); temp.setmBuildTime(System.currentTimeMillis()); ArrayList<WeatherDataBean> weaterPreList = new ArrayList<WeatherDataBean>(); // 组装天气预报 for (int i = 0; i < city.mForecastList.size(); i++) { WeatherDataBean bean = new WeatherDataBean(); ForecastInfo info = city.mForecastList.get(i); bean.setmCityId(city.getCode()); bean.setmCityName(city.getName()); bean.setmWeatherType(info.getStatusType()); // 天气预报没有当前温度,所以算便传一个进去 bean.setmWeatherCurrT(0); bean.setmWeatherHighT(info.getHigh()); bean.setmWeatherLowT(info.getLow()); bean.setWeekDate(info.getWeekDate()); bean.setmBuildTime(System.currentTimeMillis()); weaterPreList.add(bean); } temp.setWeaterThemePreList(weaterPreList); Message message = Message.obtain(); message.obj = temp; message.what = WEATHER_SUCCED; if (mHandler != null) { mHandler.sendMessage(message); } } @Override public void onNoNewData(List<Result> results) { // 时间戳与服务器上的一致,说明没有新数据 if (mHandler != null) { mHandler.sendEmptyMessage(WEATHER_ONNONEWDATA); } } } public void onDestroy() { if (mReqLocation != null) { mReqLocation.cancel(); } } }
29.141104
125
0.650632
db128d98b5ad9d286a64a4142883c4cbab3197e5
4,038
/** * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * This file is part of the Smart Developer Hub Project: * http://www.smartdeveloperhub.org/ * * Center for Open Middleware * http://www.centeropenmiddleware.com/ * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Copyright (C) 2015-2016 Center for Open Middleware. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * 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. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Artifact : org.smartdeveloperhub.curator:sdh-curator-connector:0.2.0 * Bundle : sdh-curator-connector-0.2.0.jar * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ package org.smartdeveloperhub.curator.connector.io; import org.smartdeveloperhub.curator.connector.protocol.ProtocolFactory; import org.smartdeveloperhub.curator.connector.protocol.ProtocolFactory.FailureMessageBuilder; import org.smartdeveloperhub.curator.connector.util.ResourceUtil; import org.smartdeveloperhub.curator.protocol.FailureMessage; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; final class FailureMessageParser extends ResponseMessageParser<FailureMessage, FailureMessageBuilder> { private final class FailureWorker extends ResponseWorker { @Override public void parse() { super.parse(); updateCode(); updateSubcode(); updateReason(); updateDetail(); } private void updateDetail() { optional( new LiteralConsumer("detail","curator:detail") { @Override protected void consumeLiteral(FailureMessageBuilder builder, Literal literal) { builder.withDetail(literal.getLexicalForm()); } } ); } private void updateReason() { mandatory( new LiteralConsumer("reason","curator:reason") { @Override protected void consumeLiteral(FailureMessageBuilder builder, Literal literal) { builder.withReason(literal.getLexicalForm()); } } ); } private void updateSubcode() { optional( new LiteralConsumer("subcode","curator:subcode") { @Override protected void consumeLiteral(FailureMessageBuilder builder, Literal literal) { builder.withSubcode(literal.getLexicalForm()); } } ); } private void updateCode() { mandatory( new LiteralConsumer("code","curator:code") { @Override protected void consumeLiteral(FailureMessageBuilder builder, Literal literal) { builder.withCode(literal.getLexicalForm()); } } ); } } private static final Query QUERY= QueryFactory.create( ResourceUtil. loadResource( FailureMessageParser.class, "failure.sparql")); private FailureMessageParser(Model model, Resource resource) { super(model, resource,"curator:Failure","failure",QUERY); } @Override protected ResponseWorker solutionParser() { return new FailureWorker(); } @Override protected FailureMessageBuilder newBuilder() { return ProtocolFactory.newFailureMessage(); } static FailureMessage fromModel(Model model, Resource resource) { return new FailureMessageParser(model, resource).parse(); } }
32.564516
104
0.631996
e03a1f8e480ea29c4fedcce837c79401eb7d74d5
693
package com.chenws.netty.mqtt.protocol; import io.netty.channel.Channel; import io.netty.handler.codec.mqtt.*; import io.netty.util.AttributeKey; import lombok.extern.slf4j.Slf4j; /** * Created by chenws on 2019/10/11. */ @Slf4j public class PingReq { public void handlePingReq(Channel channel, MqttMessage msg) { MqttMessage pingRespMessage = MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.PINGRESP, false, MqttQoS.AT_MOST_ONCE, false, 0), null, null); log.info("PINGREQ - clientId: {}", channel.attr(AttributeKey.valueOf("clientId")).get()); channel.writeAndFlush(pingRespMessage); } }
30.130435
101
0.686869
8b09e6775b94d79b37234b5905e5496cf57534a7
2,904
package com.defano.hypertalk.util; import com.defano.hypertalk.ast.model.Convertible; import com.defano.hypertalk.ast.model.enums.ConvertibleDateFormat; import com.defano.hypertalk.ast.model.Value; import org.junit.Test; import java.util.Calendar; import java.util.Date; import static org.junit.Assert.assertEquals; public class TestDateUtils { @Test public void testSingleFormatIdentityConversion() { Calendar c = Calendar.getInstance(); c.set(Calendar.MILLISECOND, 0); Date now = c.getTime(); Value v; v = DateUtils.valueOf(now, new Convertible(ConvertibleDateFormat.SECONDS)); assertDateTimeSecond(now, DateUtils.dateOf(v, new Convertible(ConvertibleDateFormat.SECONDS))); assertDateTimeSecond(now, DateUtils.dateOf(v)); v = DateUtils.valueOf(now, new Convertible(ConvertibleDateFormat.DATE_ITEMS)); assertDateTimeSecond(now, DateUtils.dateOf(v, new Convertible(ConvertibleDateFormat.DATE_ITEMS))); assertDateTimeSecond(now, DateUtils.dateOf(v)); v = DateUtils.valueOf(now, new Convertible(ConvertibleDateFormat.LONG_DATE)); assertDate(now, DateUtils.dateOf(v, new Convertible(ConvertibleDateFormat.LONG_DATE))); assertDate(now, DateUtils.dateOf(v)); v = DateUtils.valueOf(now, new Convertible(ConvertibleDateFormat.SHORT_DATE)); assertDate(now, DateUtils.dateOf(v, new Convertible(ConvertibleDateFormat.SHORT_DATE))); assertDate(now, DateUtils.dateOf(v)); v = DateUtils.valueOf(now, new Convertible(ConvertibleDateFormat.ABBREV_DATE)); assertDate(now, DateUtils.dateOf(v, new Convertible(ConvertibleDateFormat.ABBREV_DATE))); assertDate(now, DateUtils.dateOf(v)); v = DateUtils.valueOf(now, new Convertible(ConvertibleDateFormat.LONG_TIME)); assertDateTimeSecond(now, DateUtils.dateOf(v, new Convertible(ConvertibleDateFormat.LONG_TIME))); assertDateTimeSecond(now, DateUtils.dateOf(v)); v = DateUtils.valueOf(now, new Convertible(ConvertibleDateFormat.SHORT_TIME)); assertDateTime(now, DateUtils.dateOf(v, new Convertible(ConvertibleDateFormat.SHORT_TIME))); assertDateTime(now, DateUtils.dateOf(v)); } @SuppressWarnings("deprecation") private void assertDate(Date d1, Date d2) { assertEquals(d1.getYear(), d2.getYear()); assertEquals(d1.getMonth(), d2.getMonth()); assertEquals(d1.getDate(), d2.getDate()); } @SuppressWarnings("deprecation") private void assertDateTime(Date d1, Date d2) { assertDate(d1, d2); assertEquals(d1.getHours(), d2.getHours()); assertEquals(d1.getMinutes(), d2.getMinutes()); } @SuppressWarnings("deprecation") private void assertDateTimeSecond(Date d1, Date d2) { assertDateTime(d1, d2); assertEquals(d1.getSeconds(), d2.getSeconds()); } }
38.72
106
0.711433
2c08de0bac544fffab3a463221778f97ea99e14e
3,933
package org.opencyc.inference.params; import java.util.Map; import org.opencyc.cycobject.CycSymbol; public class DefaultInferenceParameterValueDescription implements InferenceParameterValueDescription { private Object value; private String shortDescription; private String longDescription; private static final CycSymbol VALUE_SYMBOL; private static final CycSymbol[] REQUIRED_SYMBOLS; public DefaultInferenceParameterValueDescription(final Map propertyMap) { if (propertyMap == null) { throw new RuntimeException("Got null property map"); } if (propertyMap.size() < DefaultInferenceParameterValueDescription.REQUIRED_SYMBOLS.length) { throw new RuntimeException("Got too few symbols in map"); } for (int i = 0, size = DefaultInferenceParameterValueDescription.REQUIRED_SYMBOLS.length; i < size; ++i) { if (propertyMap.get(DefaultInferenceParameterValueDescription.REQUIRED_SYMBOLS[i]) == null) { throw new RuntimeException("Expected key not found in map " + DefaultInferenceParameterValueDescription.REQUIRED_SYMBOLS[i] + " for inference Parameter value" + propertyMap.get(DefaultInferenceParameterValueDescription.VALUE_SYMBOL)); } } final Object valueObj = propertyMap.get(DefaultInferenceParameterValueDescription.VALUE_SYMBOL); final Object shortDescObj = verifyObjectType(propertyMap, AbstractInferenceParameter.SHORT_DESC_SYMBOL, String.class); final Object longDescObj = verifyObjectType(propertyMap, AbstractInferenceParameter.LONG_DESC_SYMBOL, String.class); this.init(valueObj, (String)shortDescObj, (String)longDescObj); } DefaultInferenceParameterValueDescription(final Object value, final String shortDescription, final String longDescription) { this.init(value, shortDescription, longDescription); } public Object getValue() { return this.value; } public void setValue(final Object value) { this.value = value; } public String getLongDescription() { return this.longDescription; } public String getShortDescription() { return this.shortDescription; } @Override public boolean equals(final Object obj) { if (obj instanceof DefaultInferenceParameterValueDescription) { return ((DefaultInferenceParameterValueDescription)obj).getValue().equals(this.getValue()); } return this.getValue().equals(obj); } @Override public int hashCode() { return this.getValue().hashCode(); } @Override public String toString() { return this.getShortDescription(); } static Object verifyObjectType(final Map<CycSymbol, Object> propertyMap, final CycSymbol property, final Class expectedType) { final Object propertyValueObj = propertyMap.get(property); if (!expectedType.isInstance(propertyValueObj)) { throw new RuntimeException("Expected a " + expectedType + " for " + property + "; got " + propertyValueObj); } return propertyValueObj; } private void init(final Object value, final String shortDescription, final String longDescription) { this.value = value; this.longDescription = longDescription; this.shortDescription = shortDescription; } public static void main(final String[] args) { } static { VALUE_SYMBOL = new CycSymbol(":VALUE"); REQUIRED_SYMBOLS = new CycSymbol[] { DefaultInferenceParameterValueDescription.VALUE_SYMBOL, AbstractInferenceParameter.SHORT_DESC_SYMBOL, AbstractInferenceParameter.LONG_DESC_SYMBOL }; } } /* DECOMPILATION REPORT Decompiled from: G:\opt\CYC_JRTL_with_CommonLisp\platform\lib\client-lib\opencyc-0.0.1-SNAPSHOT.jar Total time: 60 ms Decompiled with Procyon 0.5.32. */
39.33
250
0.70684
942e6f106727a4a7420597f37d2ab97662df2d79
576
package com.david; import com.david.begin.Duck; import com.david.begin.Duck.*; import com.david.begin.MallardDuck; import com.david.begin.ModelDuck; public class Main { public static void main(String[] args) { //System.out.println("Hello World!"); Duck mallard = new MallardDuck(); mallard.performFly(); mallard.performQuack(); mallard.display(); Duck modelDuck = new ModelDuck(); modelDuck.performFly(); modelDuck.setFlyBehavior(modelDuck.new FlyRocketPowered()); modelDuck.performFly(); } }
26.181818
67
0.657986
ae6794185e7395798738d8436f9b0798f0a71abc
4,231
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.securityinsights.implementation; import com.azure.core.management.SystemData; import com.azure.core.util.Context; import com.azure.resourcemanager.securityinsights.fluent.models.SentinelOnboardingStateInner; import com.azure.resourcemanager.securityinsights.models.SentinelOnboardingState; public final class SentinelOnboardingStateImpl implements SentinelOnboardingState, SentinelOnboardingState.Definition { private SentinelOnboardingStateInner innerObject; private final com.azure.resourcemanager.securityinsights.SecurityInsightsManager serviceManager; SentinelOnboardingStateImpl( SentinelOnboardingStateInner innerObject, com.azure.resourcemanager.securityinsights.SecurityInsightsManager serviceManager) { this.innerObject = innerObject; this.serviceManager = serviceManager; } public String id() { return this.innerModel().id(); } public String name() { return this.innerModel().name(); } public String type() { return this.innerModel().type(); } public String etag() { return this.innerModel().etag(); } public SystemData systemData() { return this.innerModel().systemData(); } public Boolean customerManagedKey() { return this.innerModel().customerManagedKey(); } public SentinelOnboardingStateInner innerModel() { return this.innerObject; } private com.azure.resourcemanager.securityinsights.SecurityInsightsManager manager() { return this.serviceManager; } private String resourceGroupName; private String workspaceName; private String sentinelOnboardingStateName; public SentinelOnboardingStateImpl withExistingWorkspace(String resourceGroupName, String workspaceName) { this.resourceGroupName = resourceGroupName; this.workspaceName = workspaceName; return this; } public SentinelOnboardingState create() { this.innerObject = serviceManager .serviceClient() .getSentinelOnboardingStates() .createWithResponse( resourceGroupName, workspaceName, sentinelOnboardingStateName, this.innerModel(), Context.NONE) .getValue(); return this; } public SentinelOnboardingState create(Context context) { this.innerObject = serviceManager .serviceClient() .getSentinelOnboardingStates() .createWithResponse( resourceGroupName, workspaceName, sentinelOnboardingStateName, this.innerModel(), context) .getValue(); return this; } SentinelOnboardingStateImpl( String name, com.azure.resourcemanager.securityinsights.SecurityInsightsManager serviceManager) { this.innerObject = new SentinelOnboardingStateInner(); this.serviceManager = serviceManager; this.sentinelOnboardingStateName = name; } public SentinelOnboardingState refresh() { this.innerObject = serviceManager .serviceClient() .getSentinelOnboardingStates() .getWithResponse(resourceGroupName, workspaceName, sentinelOnboardingStateName, Context.NONE) .getValue(); return this; } public SentinelOnboardingState refresh(Context context) { this.innerObject = serviceManager .serviceClient() .getSentinelOnboardingStates() .getWithResponse(resourceGroupName, workspaceName, sentinelOnboardingStateName, context) .getValue(); return this; } public SentinelOnboardingStateImpl withEtag(String etag) { this.innerModel().withEtag(etag); return this; } public SentinelOnboardingStateImpl withCustomerManagedKey(Boolean customerManagedKey) { this.innerModel().withCustomerManagedKey(customerManagedKey); return this; } }
33.314961
119
0.684708
41423adfb92cdf9145a02c82cbdff2af152985f3
661
package org.firstinspires.ftc.blackswan; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import org.firstinspires.ftc.blackswan.Robot; @Autonomous public class AutonomousBlueWarehouse extends LinearOpMode { Robot robot; @Override public void runOpMode() throws InterruptedException { robot = new Robot(hardwareMap,telemetry,this); waitForStart(); robot.forward(1.5,.5); robot.right(2,.5); robot.armThing(3); robot.back(.2,.5); robot.turnLeft(70,.5); robot.forward(5,1); robot.turnLeft(30,.5); } }
26.44
60
0.6823
90ebc67d15317b8f5673c9eb9071480b1979959e
1,914
package com.ezequiel.addresses.domain; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Date; import java.util.UUID; @Entity @Table(name = "address") @NoArgsConstructor @Data public class Address implements Serializable { @Id @GeneratedValue @Setter(AccessLevel.NONE) @Column(columnDefinition = "uuid", name = "id", updatable = false) private UUID id; @NotEmpty @Size(max = 255) @Column(name = "street_name") private String streetName; @NotEmpty @Size(max = 255) @Column(name = "number") private String number; @Size(max = 255) @Column(name = "complement") private String complement; @NotEmpty @Size(max = 255) @Column(name = "neighbourhood") private String neighbourhood; @NotEmpty @Size(max = 255) @Column(name = "city") private String city; @NotEmpty @Size(max = 255) @Column(name = "state") private String state; @NotEmpty @Size(max = 255) @Column(name = "country") private String country; @NotEmpty @Size(max = 255) @Column(name = "zipcode") private String zipcode; @Column(name = "latitude") private Double latitude; @Column(name = "longitude") private Double longitude; @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) @Setter(AccessLevel.NONE) @Column(name = "created_at", updatable = false) private Date createdAt; @UpdateTimestamp @Temporal(TemporalType.TIMESTAMP) @Setter(AccessLevel.NONE) @Column(name = "updated_at", insertable = false) private Date updatedAt; }
22
70
0.685475