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
|
|---|---|---|---|---|---|
59b097f51f4d170018a184b7cc515437c424fc50
| 3,009
|
package com.poseidon.user.dao.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import java.time.OffsetDateTime;
import java.time.ZoneId;
@Entity
//todo : add schema
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long userId;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@Column(name = "role")
private String role;
@Column(name = "expired")
private Boolean expired;
@Column(name = "createdOn")
private OffsetDateTime createdOn;
@Column(name = "modifiedOn")
private OffsetDateTime modifiedOn;
@Column(name = "createdBy")
private String createdBy;
@Column(name = "modifiedBy")
private String modifiedBy;
public Long getUserId() {
return userId;
}
public void setUserId(final Long userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public Boolean getExpired() {
return expired;
}
public void setExpired(final Boolean expired) {
this.expired = expired;
}
public String getRole() {
return role;
}
public void setRole(final String role) {
this.role = role;
}
public void setCreatedOn(final OffsetDateTime createdOn) {
this.createdOn = createdOn;
}
public void setModifiedOn(final OffsetDateTime modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(final String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public OffsetDateTime getCreatedOn() {
return createdOn;
}
public OffsetDateTime getModifiedOn() {
return modifiedOn;
}
/**
* initialize/update dates.
*/
@PrePersist
@PreUpdate
public void initializeDate() {
if (this.getUserId() == null) {
createdOn = OffsetDateTime.now(ZoneId.systemDefault());
}
modifiedOn = OffsetDateTime.now(ZoneId.systemDefault());
}
}
| 21.041958
| 67
| 0.640412
|
15695a61c82dc6cc2c7a6e9bb849904aa2d73ac9
| 2,993
|
package swim.core.network.misc;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public abstract class Matrix<T> {
/**
* Number of columns
*/
protected final int M;
/**
* Number of rows
*/
protected final int N;
/**Initialize the matrix dimensions
* @param N number of rows
* @param M number of columns
*/
public Matrix(int N, int M){
this.M = M;
this.N = N;
}
/**Set the value of the cell at row i and column j
* @param i row index in [1 , n]
* @param j column index in [1, m]
* @param value
*/
public abstract void set(int i, int j, T value);
/**Get the value of the cell at row i and column j
* @param i row index in [1, n]
* @param j column index in [1, m]
* @return the value at row i and column j
*/
public abstract T get(int i, int j);
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
for(int i=1;i<=N; i++){
for(int j=1; j<=M; j++){
b.append(String.format("%s, ", get(i,j).toString()));
}
b.append('\n');
}
return b.toString();
}
public void setRow(int i, Map<Integer, T> row) {
for(int j=1; j<=M; j++){
set(i,j, row.get(j));
}
}
public void setRow(int i, T[] row) {
for(int j=1; j<=M; j++){
set(i,j, row[j]);
}
}
static class IntegerArrayMatrix extends Matrix<Integer>{
int[][] array;
public IntegerArrayMatrix(int N, int M){
super(N, M);
array = new int[N][M];
}
/* (non-Javadoc)
* @see tn.algorithm.Martix#set(int, int, int)
*/
public void set(int i, int j, Integer value){
array[i-1][j-1] = value;
}
/* (non-Javadoc)
* @see tn.algorithm.Martix#get(int, int)
*/
public Integer get(int i, int j){
return array[i-1][j-1];
}
}
public static class DoubleArrayMatrix extends Matrix<Double>{
double[][] array;
public DoubleArrayMatrix(int N, int M){
super(N, M);
array = new double[N][M];
}
/* (non-Javadoc)
* @see tn.algorithm.Martix#set(int, int, int)
*/
public void set(int i, int j, Double value){
array[i-1][j-1] = value;
}
/* (non-Javadoc)
* @see tn.algorithm.Martix#get(int, int)
*/
public Double get(int i, int j){
return array[i-1][j-1];
}
}
public static class IntegerListArrayMatrix extends Matrix<List<Integer>>{
List<Integer>[][] array;
@SuppressWarnings("unchecked")
public IntegerListArrayMatrix(int N, int M){
super(N, M);
array = new LinkedList[N][M];
}
/* (non-Javadoc)
* @see tn.algorithm.Martix#set(int, int, int)
*/
public void set(int i, int j, List<Integer> value){
array[i-1][j-1] = value;
}
/* (non-Javadoc)
* @see tn.algorithm.Martix#get(int, int)
*/
public List<Integer> get(int i, int j){
return array[i-1][j-1];
}
}
}
| 20.641379
| 75
| 0.567324
|
458ebc68aa6453e9f33aa1ce806d51b926b205cb
| 4,262
|
package org.atdl4j.data.validation;
import org.apache.log4j.Logger;
import org.atdl4j.data.ValidationRule;
import org.atdl4j.data.exception.ValidationException;
import org.atdl4j.fixatdl.validation.OperatorT;
import org.atdl4j.ui.Atdl4jWidget;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* Base class for ValidationRule.
*
* @param <E>
*
* @author renato.gallart
*/
public abstract class AbstractOperatorValidationRule
implements ValidationRule
{
private static final Logger logger = Logger.getLogger( AbstractOperatorValidationRule.class );
@SuppressWarnings("unchecked")
protected void validateValues(Atdl4jWidget<?> target, Object value1, OperatorT operator, Object value2) throws ValidationException
{
// 3/11/2010 Scott Atwell added to normalize DateTime comparisons
// -- Work-around to 'handle' joda's DateTime.equals() failing if timezones are expressed differently
// -- for same underlying time in millis. DateTime.isEqual() behaves as expected
// -- using DateTimeZone.getDefault() will result in any values displayed in error messages to be in local zone (with "-0600" suffix if US CST)
if ( ( value1 != null ) && ( value1 instanceof DateTime ) )
{
value1 = ((DateTime) value1).withZone( DateTimeZone.getDefault() );
}
if ( ( value2 != null ) && ( value2 instanceof DateTime ) )
{
value2 = ((DateTime) value2).withZone( DateTimeZone.getDefault() );
}
switch ( operator )
{
case NE :
if ( value1 == value2 || ( value2 != null && value2.equals( value1 ) ) )
{
throw new ValidationException( target, "Rule tested: [" + value1 + " NE " + value2 + "]" );
}
break;
case EX :
if ( value1 == null || "".equals( value1.toString() ) )
{
throw new ValidationException( target, "Rule tested: [" + value1 + " EX]" );
}
break;
case LT :
if ( value1 instanceof Comparable )
{
Comparable<Object> c = (Comparable<Object>) value1;
if ( c.compareTo( value2 ) >= 0 )
{
throw new ValidationException( target, "Rule tested: [" + value1 + " LT " + value2 + "]" );
}
}
else
{
throw new ValidationException( target, "Value is not comparable [" + (value1 != null ? (value1 + " class: " + value1.getClass()) : "value is null") + "]" );
}
break;
case LE :
if ( value1 instanceof Comparable )
{
Comparable<Object> c = (Comparable<Object>) value1;
if ( c.compareTo( value2 ) > 0 )
{
throw new ValidationException(target, "Rule tested: [" + value1 + " LE " + value2 + "]" );
}
}
else
{
throw new ValidationException( target, "Value is not comparable [" + (value1 != null ? (value1 + " class: " + value1.getClass()) : "value is null") + "]" );
}
break;
case GT :
if ( value1 instanceof Comparable )
{
Comparable<Object> c = (Comparable<Object>) value1;
if ( c.compareTo( value2 ) <= 0 )
{
throw new ValidationException(target, "Rule tested: [" + value1 + " GT " + value2 + "]" );
}
}
else
{
throw new ValidationException( target, "Value is not comparable [" + (value1 != null ? (value1 + " class: " + value1.getClass()) : "value is null") + "]" );
}
break;
case GE :
if ( value1 instanceof Comparable )
{
Comparable<Object> c = (Comparable<Object>) value1;
if ( c.compareTo( value2 ) < 0 )
{
throw new ValidationException(target, "Rule tested: [" + value1 + " GE " + value2 + "]" );
}
}
else
{
throw new ValidationException( target, "Value is not comparable [" + (value1 != null ? (value1 + " class: " + value1.getClass()) : "value is null") + "]" );
}
break;
case EQ :
if ( !value2.equals( value1 ) )
{
throw new ValidationException(target, "Rule tested: [" + value1 + " EQ " + value2 + "]" );
}
break;
case NX :
if ( value1 != null && !"".equals( value1.toString() ) )
{
throw new ValidationException(target, "Rule tested: [" + value1 + " NX]" );
}
break;
default:
// Supposed to never happen, since the schema enforces an enumerated
// base restriction.
logger.error( "Invalid operator: " + operator );
break;
}
}
}
| 30.442857
| 161
| 0.613796
|
a8a2284090085bde3fff1847ee4b5e1e89a8671f
| 12,071
|
package info.exascale.statix;
import java.text.ParseException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.io.File;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
public class main {
public static final String clirev = ""; // ATTENTION: Substituted during the build
public static void main(String[] args) throws Exception {
CommandLineParser parser = new DefaultParser();
// Mutually exclusive group of the supervised options / input format
final OptionGroup optspv = new OptionGroup();
// Option(String opt, String longOpt, boolean hasArg, String description)
// ground-truth or annotated, labeled
optspv.addOption(new Option("g", "groundtruth-sample", true, "The ground-truth sample (subset of the input dataset or another similar dataset with the specified type properties)"));
optspv.addOption(new Option("b", "brief-hints", true, "Brief hits, possible values:\n'--' - interactive hints \n'<filename" + Statix.extHints + ">' - read from the file having the format for each line:\n<indicativity> <property> \nwhere indicativity E [0, 1]; 0 - the property has no any impact on the entity type, 1 - the property fully specifies the entity type, line comments starting with '#' are allowed. \n'-[<nopts=INF>]' - automatic generation of the hints to the <inpfile_marks" + Statix.extHints + ">, where <marks> is the range of marks (>= 2) on supervision, which defines the indicativity precision eps=0.5/(marks + 1): eps=0.167 for 2 marks")); // Center of each band is eps + eps*i, delta: +/-eps, wide: eps*2
Options options = new Options();
options.addOption("h", "help", false, "Show usage");
// Workflow: analyze input dataset, ask to rate potentially indicative properties (that might have huge impact)
//options.addOption("p", "supervised", true, "Supervision hint data in the format: <indicativity>\t <property>, where indicativity E [0, 1], '#' line comments are allowed.");
options.addOptionGroup(optspv);
options.addOption("o", "output", true, "Output file, default: <inpfile>" + Statix.extCls);
options.addOption("n", "id-name", true, "Output map of the instance id names (labels) to the <inpfile>.idm in tab separated format: <id> <subject_name>, default: disabled. Note: all instances are mapped including non-typed ones");
options.addOption("l", "cl-label", true, "Output map of the cluster labels (names) (<inpfile>.clb in the label per line format, default: disabled, requires: -e");
options.addOption("m", "multi-level", false, "Output type inference for multiple scales (representative clusters from all hierarchy levels) besides the macro scale (top level, root)");
options.addOption("s", "scale", true, "Scale (resolution, gamma parameter of the clustering), -1 is automatic scale inference for each cluster, >=0 is the forced static scale (<=1 for the macro clustering); default: -1");
options.addOption("r", "reduce", true, "Reduce graph links (similarity matrix) on the graph clustering (after the graph is constructed) by non-significant relations to reduce memory consumption and speedup the clustering (recommended for large datasets). Options X[Y]; X: a - accurate, m - mean, s - severe; Y: o - use optimization function for the links reduction (default), w - reduce links by their raw weight. Examples: -r m, -r mw. Note: all non-zero unique items (half of the symmetric matrix) are supplied for the graph construction, which is the memory consumption bottleneck");
options.addOption("c", "cut-ratio", true, "Cut the graph links (similarity matrix) iteratively on the graph construction before the construction is completed discarding instance (node) links lighter than cut-ratio * avg_ndlinks_weight, cut-ratio E [0, 1), recommended value if applied: ~0.25, 0 means skip the cutting. Reduces the memory consumption and speedups the clustering but affects the accuracy, see \"reduce\" for the more accurate links reduction during the clustering");
options.addOption("f", "filter", false, "Filter out from the resulting clusters all subjects that do not have the '#type' property in the input dataset, used for the type inference evaluation");
options.addOption("w", "weigh-instance", false, "Weight RDF instances (subjects, consider the self-relation) or use only the weighted relations between the instances");
options.addOption("j", "jaccard-similarity", false, "Use (weighted) Jaccard instead of the Cosine similarity");
options.addOption("e", "extract-groundtruth", true, "Extract ground-truth (ids of the subjects per each type) to the specified file in the " + Statix.extCls + " format, optionally with subjects and type labels");
options.addOption("u", "unique-triples", false, "Unique triples only are present in the ground-truth dataset (natty, clean data without duplicates), so there is no need of the possible duplicates identification and omission");
options.addOption("p", "network", true, "Produce .rcg input network file for the clustering without the type inference itself and respecting the \"cut-ratio\", \"filter\", \"weigh-instance\" and \"jaccard-similarity\" options");
options.addOption("v", "version", false, "Show version number");
HelpFormatter formatter = new HelpFormatter();
String[] argsOpt = new String[]{"args"};
final String appusage = //main.class.getCanonicalName()
//new File(main.class.getProtectionDomain().getCodeSource()
//.getLocation().getPath()).getName() +
"./run.sh [OPTIONS...] <inputfile.rdf>";
final String desription = "Statistical type inference in fully automatic and semi supervised modes\nOptions:";
final String reference = "\nSee details in https://github.com/eXascaleInfolab/StaTIX";
Statix statix = new Statix();
try {
final CommandLine cmd = parser.parse(options, args);
// Check for the help option
if(cmd.hasOption("h")) {
formatter.printHelp(appusage, desription, options, reference);
System.exit(0);
}
// Check for the version
if(cmd.hasOption("v")) {
// Convert <revision>(<date>)[+] to the pure revision + date
String clirevPure = clirev;
String clirevTime = "";
final int ibdate = clirevPure.indexOf('(');
if(ibdate >= 0) {
final int iedate = clirevPure.indexOf(')');
clirevTime = clirev.substring(ibdate + 1, iedate);
clirevPure = clirev.substring(0, ibdate) + clirev.substring(iedate + 1);
}
System.out.println("r-" + Statix.daocRevision() + "." + clirevPure);
System.out.println("= Client Build =\nRevision: " + clirevPure + "\nTime: " + clirevTime);
if(!Statix.daocSwigRevision().isEmpty())
System.out.println("SWIG revision: " + Statix.daocSwigRevision());
System.out.println("= Library Build =\n" + Statix.daocBuildInfo());
System.exit(0);
}
String[] files = cmd.getArgs();
if(files.length != 1)
throw new IllegalArgumentException("A single input dataset is expected with optimal parameters");
String idMapFName = cmd.hasOption("n") ? cmd.getOptionValue("n") : null;
final boolean dirty = !cmd.hasOption("u"); // Dirty input: triples might include duplicates
// Check for the filtering option
// ATTENTION: should be done before the input datasets reading
final boolean filteringOn = cmd.hasOption("f");
// Check for the GT extraction
if(cmd.hasOption("l") && !cmd.hasOption("e"))
throw new IllegalArgumentException("Parameter -l requires -e");
if(cmd.hasOption("e")) {
final String tpLblFName = cmd.hasOption("l") ? cmd.getOptionValue("l") : null;
SimilarityMatix.extractGT(files[0], cmd.getOptionValue("e"), filteringOn, idMapFName, tpLblFName, dirty);
if(!cmd.hasOption("p") && !cmd.hasOption("o"))
System.exit(0);
idMapFName = null;
}
if(cmd.hasOption("g")) {
String gtDataset = cmd.getOptionValue("g");
//System.out.println("Ground-truth file= "+gtDataset);
statix.loadDatasets(files[0], gtDataset, filteringOn, idMapFName, dirty);
}
else {
String hints = cmd.hasOption("b") ? cmd.getOptionValue("b") : null;
// Validate hints to fail early in case of issues
if(hints != null) {
if(hints.isEmpty()) // '' or ""
throw new IllegalArgumentException("The hints parameter should not be empty");
if(!hints.startsWith("-") && !Files.isReadable(Paths.get(hints))) {
// Note: the hints are not loaded if not required for the particular dataset
throw new IllegalArgumentException("The hints file is not readable");
//if(!Files.exists(hints)) {
// // Allow absence of the specified file showing a warning, which is useful the
// // batch mode for the case when the hints are not necessary for this dataset
// System.err.println("WARNING, switching to the non-supervised mode because the hints file does not exist: " + hints);
// hints = null;
//} else
//if(!Files.isReadable(hints))
// throw new IllegalArgumentException("The hints file is not readable");
}
if(hints != "--" && hints.length() >= 2 && Integer.parseInt(hints.substring(1)) <= 1)
throw new IllegalArgumentException("The number of marks is too small");
}
statix.loadDataset(files[0], filteringOn, idMapFName, hints, dirty);
}
// Scale
float scale = -1;
if(cmd.hasOption("s")) {
scale = Float.parseFloat(cmd.getOptionValue("s"));
if(scale != -1 && scale < 0)
throw new IllegalArgumentException("The scale parameter is out of the expected range");
}
// Reduction policy
char reduction = 'n'; // None
boolean reduceByWeight = false;
if(cmd.hasOption("r")) {
String val = cmd.getOptionValue("r");
if(!val.isEmpty()) {
if(val.length() >= 3 || "ams".indexOf(val.charAt(0)) == -1
|| (val.length() == 2 && "ow".indexOf(val.charAt(1)) == -1))
throw new IllegalArgumentException("The reduction parameter is out of the expected range");
reduction = val.charAt(0);
reduceByWeight = val.length() == 2 && val.charAt(1) == 'w';
}
}
// Links cutting ratio
float lnscut = 0;
if(cmd.hasOption("c")) {
lnscut = Float.parseFloat(cmd.getOptionValue("c"));
if(lnscut < 0 || lnscut >= 1)
throw new IllegalArgumentException("The cut-ratio parameter is out of the expected range");
}
final boolean weighnode = cmd.hasOption("w");
final boolean jaccard = cmd.hasOption("j");
if(cmd.hasOption("p")) {
// Construct and output the input network for the subsequent clustering without the type inference itself
final String netfile = cmd.getOptionValue("p");
try {
// Apply additional raw links reduction on preprocessing for the severe reduction policy
statix.saveNet(netfile, weighnode, jaccard, lnscut);
} catch(IOException e) {
System.err.println("ERROR on saving to the network file (" + netfile + "):\n");
e.printStackTrace();
System.exit(1);
}
} else {
// Set output file
String outpfile = null;
if(cmd.hasOption("o")) {
outpfile = cmd.getOptionValue("o");
}
else {
outpfile = files[0];
// Replace the extension to the clustering results
outpfile = Statix.updateFileExtension(outpfile, Statix.extCls); // Default extension for the output file
}
// Perform type inference
statix.cluster(outpfile, scale, cmd.hasOption("m"), lnscut, reduction, reduceByWeight, filteringOn, weighnode, jaccard);
}
}
catch (ParseException e) { // | IllegalArgumentException
e.printStackTrace();
formatter.printHelp(appusage, desription, options, reference);
System.exit(1);
}
}
}
| 58.882927
| 731
| 0.686604
|
090bc4e50d50d64cdef3daea60a19ae3892ebd6e
| 815
|
package br.jus.tst.esocial.dominio.enums;
public enum TpAcConv {
/**
* Acordo Coletivo de Trabalho
*
*/
A,
/**
* Legislação federal, estadual, municipal ou distrital
*
*/
B,
/**
* Convenção Coletiva de Trabalho
*
*/
C,
/**
* Sentença normativa - Dissídio
*
*/
D,
/**
* Conversão de licença saúde em acidente de trabalho
*
*/
E,
/**
* Outras verbas de natureza salarial ou não salarial devidas após o
* desligamento
*
*/
F,
/**
* Antecipação de diferenças de acordo, convenção ou dissídio coletivo
*
*/
G,
/**
* Recolhimento mensal de FGTS anterior ao início de obrigatoriedade dos eventos
* periódicos
*
*/
H;
public String value() {
return name();
}
public static TpAcConv fromValue(String v) {
return valueOf(v);
}
}
| 12.734375
| 81
| 0.617178
|
97b6502ab0ccf3b23a6e09fcc471fa10dad73473
| 2,060
|
package cn.evergrand.it.bluetooth.search.le;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Build;
import cn.evergrand.it.bluetooth.search.BluetoothSearcher;
import cn.evergrand.it.bluetooth.search.SearchResult;
import cn.evergrand.it.bluetooth.search.response.BluetoothSearchResponse;
import cn.evergrand.it.bluetooth.utils.BluetoothLog;
import cn.evergrand.it.bluetooth.utils.BluetoothUtils;
public class BluetoothLESearcher extends BluetoothSearcher {
private BluetoothLESearcher() {
mBluetoothAdapter = BluetoothUtils.getBluetoothAdapter();
}
public static BluetoothLESearcher getInstance() {
return BluetoothLESearcherHolder.instance;
}
private static class BluetoothLESearcherHolder {
private static BluetoothLESearcher instance = new BluetoothLESearcher();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@SuppressWarnings("deprecation")
@Override
public void startScanBluetooth(BluetoothSearchResponse response) {
// TODO Auto-generated method stub
super.startScanBluetooth(response);
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@SuppressWarnings("deprecation")
@Override
public void stopScanBluetooth() {
// TODO Auto-generated method stub
try {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} catch (Exception e) {
BluetoothLog.e(e);
}
super.stopScanBluetooth();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@SuppressWarnings("deprecation")
@Override
protected void cancelScanBluetooth() {
// TODO Auto-generated method stub
mBluetoothAdapter.stopLeScan(mLeScanCallback);
super.cancelScanBluetooth();
}
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
// TODO Auto-generated method stub
notifyDeviceFounded(new SearchResult(device, rssi, scanRecord));
}
};
}
| 28.611111
| 104
| 0.794175
|
33283e2a6f7b9746b8bddb0aeab0e71914ef70c8
| 1,767
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.metatron.discovery.domain.audit;
import org.hibernate.envers.RevisionType;
import java.util.Set;
import app.metatron.discovery.domain.revision.MetatronRevisionEntity;
/**
* Audit for domain
*/
public class DomainAudit {
Object domain;
MetatronRevisionEntity revInfo;
RevisionType revType;
Set<String> properties;
public DomainAudit() {
}
public DomainAudit(Object domain, MetatronRevisionEntity revInfo, RevisionType revType, Set<String> properties) {
this.domain = domain;
this.revInfo = revInfo;
this.revType = revType;
this.properties = properties;
}
public Object getDomain() {
return domain;
}
public void setDomain(Object domain) {
this.domain = domain;
}
public MetatronRevisionEntity getRevInfo() {
return revInfo;
}
public void setRevInfo(MetatronRevisionEntity revInfo) {
this.revInfo = revInfo;
}
public RevisionType getRevType() {
return revType;
}
public void setRevType(RevisionType revType) {
this.revType = revType;
}
public Set<String> getProperties() {
return properties;
}
public void setProperties(Set<String> properties) {
this.properties = properties;
}
}
| 23.878378
| 115
| 0.723826
|
c0cc29a99a432a3d0e9adc1bd1f5bc526bad0802
| 5,515
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.tasklist.scanningscopes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
/**
* Iterates all files and sub-folders under the given root folders.
*
* @author S. Aubrecht
*/
class FileObjectIterator implements Iterator<FileObject> {
private Collection<FileObject> roots;
private Collection<FileObject> editedFiles;
private Iterator<FileObject> rootsIterator;
private Iterator<FileObject> editedFilesIterator;
private Enumeration<? extends FileObject> rootChildrenEnum;
private boolean scanSubFolders = true;
/** Creates a new instance of FileObjectIterator */
public FileObjectIterator( Collection<FileObject> roots, Collection<FileObject> editedFiles ) {
this.roots = roots;
this.editedFiles = editedFiles;
}
/**
* Iterate the given folder and ignore sub-folders.
*/
public FileObjectIterator( FileObject folder, Collection<FileObject> editedFiles ) {
this.roots = new ArrayList<FileObject>(1);
roots.add( folder );
this.editedFiles = editedFiles;
this.scanSubFolders = false;
}
public boolean hasNext() {
if( null == rootsIterator ) {
checkEditedFiles();
rootsIterator = roots.iterator();
return rootsIterator.hasNext();
}
return (null != rootChildrenEnum && rootChildrenEnum.hasMoreElements())
|| rootsIterator.hasNext()
|| editedFilesIterator.hasNext();
}
public FileObject next() {
//make sure opened files are scanned first
if( editedFilesIterator.hasNext() ) {
return editedFilesIterator.next();
}
FileObject result = null;
if( null == rootChildrenEnum || !rootChildrenEnum.hasMoreElements() ) {
if( rootsIterator.hasNext() ) {
result = rootsIterator.next();
rootChildrenEnum = result.getChildren( scanSubFolders );
} else {
throw new NoSuchElementException();
}
} else {
result = rootChildrenEnum.nextElement();
}
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
private void checkEditedFiles() {
if( null != editedFiles ) {
ArrayList<FileObject> editedFilesUnderRoots = new ArrayList<FileObject>( editedFiles.size() );
for( FileObject fo : editedFiles ) {
if( isUnderRoots( fo ) ) {
editedFilesUnderRoots.add( fo );
}
}
editedFiles = null;
editedFilesIterator = editedFilesUnderRoots.iterator();
} else {
editedFilesIterator = new EmptyIterator();
}
}
private boolean isUnderRoots( FileObject fo ) {
for( FileObject root : roots ) {
if( scanSubFolders ) {
if( FileUtil.isParentOf( root, fo ) )
return true;
} else {
if( root.equals( fo.getParent() ) )
return true;
}
}
return false;
}
}
| 37.773973
| 106
| 0.658205
|
56187a6310692911c9ce02464cef18a26a5f06d8
| 9,240
|
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.commodity.multicurvecommodity.derivative;
import com.opengamma.analytics.financial.commodity.definition.SettlementType;
import com.opengamma.analytics.financial.commodity.multicurvecommodity.underlying.CommodityUnderlying;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
/**
* Abstract commodity future security.
*/
public abstract class CommodityFutureSecurity implements InstrumentDerivative {
/**
* Future last trading time. Corresponds to the expiry time.
*/
private final double _lastTradingTime;
/**
* The underlying commodity
*/
private final CommodityUnderlying _underlying;
/**
* Description of unit size (for example : barrel)
*/
private final String _unitName;
/**
* Size of a unit
*/
private final double _unitAmount;
/**
* The first notice time.
* Some future contracts have no notice date. The seller of the future have to notice the delivery but without an explicit notice date.
* In this case the notice time can be null
*/
private final double _noticeFirstTime;
/**
* The last notice time.
* Some future contracts have no notice date. The seller of the future have to notice the delivery but without an explicit notice date.
* In this case the notice time can be null
*/
private final double _noticeLastTime;
/**
* time of first delivery - for PHYSICAL settlement only
*
*/
private final double _firstDeliveryTime;
/**
* Date of last delivery - for PHYSICAL settlement only
* The delivery is done during a month, the first delivery date is the first business day of this month.
*/
private final double _lastDeliveryTime;
/**
* Settlement type - PHYSICAL or CASH
* Some future are physical but with the option to settle it with cash, in this case the settlement type is PHYSICAL.
*/
private final SettlementType _settlementType;
/**
* Settlement time.
*/
private final double _settlementTime;
/**
* Future name.
*/
private final String _name;
/**
* The holiday calendar.
*/
private final Calendar _calendar;
/**
* Constructor with all details.
* @param lastTradingTime The last trading date, not null
* @param underlying The commodity underlying, not null
* @param unitName name of the unit of the commodity delivered, not null
* @param unitAmount The size of a unit, not null
* @param noticeFirstTime The notice first date, can be null
* @param noticeLastTime The notice last date, can be null
* @param firstDeliveryTime The first delivery date, not null for physical contract
* @param lastDeliveryTime The last delivery date, not null for physical contract
* @param settlementType The settlement type, CASH or PHYSICAL
* @param settlementTime The settlement date, not null
* @param name The name of the future, not null
* @param calendar The holiday calendar, not null
*/
public CommodityFutureSecurity(final double lastTradingTime, final CommodityUnderlying underlying, final String unitName, final double unitAmount,
final double noticeFirstTime, final double noticeLastTime, final double firstDeliveryTime, final double lastDeliveryTime,
final SettlementType settlementType, final double settlementTime, final String name, final Calendar calendar) {
ArgumentChecker.isTrue(lastTradingTime >= 0, "last trading time must be positive");
ArgumentChecker.isTrue(settlementTime >= 0, "settlement time must be positive");
ArgumentChecker.notNull(underlying, "underlying");
ArgumentChecker.notNegativeOrZero(unitAmount, "unit amount");
ArgumentChecker.notEmpty(unitName, "unit name");
ArgumentChecker.notNull(settlementType, "settlement type");
ArgumentChecker.notNull(name, "Name");
ArgumentChecker.notNull(calendar, "calendar");
_lastTradingTime = lastTradingTime;
_underlying = underlying;
_unitAmount = unitAmount;
_noticeFirstTime = noticeFirstTime;
_noticeLastTime = noticeLastTime;
_firstDeliveryTime = firstDeliveryTime;
_lastDeliveryTime = lastDeliveryTime;
_unitName = unitName;
_settlementType = settlementType;
_settlementTime = settlementTime;
_name = name;
_calendar = calendar;
}
/**
* @return the _lastTradingTime
*/
public double getLastTradingTime() {
return _lastTradingTime;
}
/**
* @return the _underlying
*/
public CommodityUnderlying getUnderlying() {
return _underlying;
}
/**
* @return the _underlying
*/
public Currency getCurrency() {
return _underlying.getCurrency();
}
/**
* @return the _unitName
*/
public String getUnitName() {
return _unitName;
}
/**
* @return the _unitAmount
*/
public double getUnitAmount() {
return _unitAmount;
}
/**
* @return the _noticeFirstTime
*/
public double getNoticeFirstTime() {
return _noticeFirstTime;
}
/**
* @return the _noticeLastTime
*/
public double getNoticeLastTime() {
return _noticeLastTime;
}
/**
* @return the _firstDeliveryTime
*/
public double getFirstDeliveryTime() {
return _firstDeliveryTime;
}
/**
* @return the _lastDeliveryTime
*/
public double getLastDeliveryTime() {
return _lastDeliveryTime;
}
/**
* @return the _settlementType
*/
public SettlementType getSettlementType() {
return _settlementType;
}
/**
* @return the _settlementTime
*/
public double getSettlementTime() {
return _settlementTime;
}
/**
* @return the _name
*/
public String getName() {
return _name;
}
/**
* @return the _calendar
*/
public Calendar getCalendar() {
return _calendar;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(_firstDeliveryTime);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_lastDeliveryTime);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_lastTradingTime);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((_name == null) ? 0 : _name.hashCode());
temp = Double.doubleToLongBits(_noticeFirstTime);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_noticeLastTime);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(_settlementTime);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((_settlementType == null) ? 0 : _settlementType.hashCode());
result = prime * result + ((_underlying == null) ? 0 : _underlying.hashCode());
temp = Double.doubleToLongBits(_unitAmount);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((_unitName == null) ? 0 : _unitName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CommodityFutureSecurity other = (CommodityFutureSecurity) obj;
if (Double.doubleToLongBits(_firstDeliveryTime) != Double.doubleToLongBits(other._firstDeliveryTime)) {
return false;
}
if (Double.doubleToLongBits(_lastDeliveryTime) != Double.doubleToLongBits(other._lastDeliveryTime)) {
return false;
}
if (Double.doubleToLongBits(_lastTradingTime) != Double.doubleToLongBits(other._lastTradingTime)) {
return false;
}
if (_name == null) {
if (other._name != null) {
return false;
}
} else if (!_name.equals(other._name)) {
return false;
}
if (Double.doubleToLongBits(_noticeFirstTime) != Double.doubleToLongBits(other._noticeFirstTime)) {
return false;
}
if (Double.doubleToLongBits(_noticeLastTime) != Double.doubleToLongBits(other._noticeLastTime)) {
return false;
}
if (Double.doubleToLongBits(_settlementTime) != Double.doubleToLongBits(other._settlementTime)) {
return false;
}
if (_settlementType != other._settlementType) {
return false;
}
if (_underlying == null) {
if (other._underlying != null) {
return false;
}
} else if (!_underlying.equals(other._underlying)) {
return false;
}
if (Double.doubleToLongBits(_unitAmount) != Double.doubleToLongBits(other._unitAmount)) {
return false;
}
if (_unitName == null) {
if (other._unitName != null) {
return false;
}
} else if (!_unitName.equals(other._unitName)) {
return false;
}
return true;
}
}
| 30
| 148
| 0.683009
|
e6ac13b7bb83b0fcedca683418072e1bf7dd70d2
| 4,929
|
package com.roubsite.smarty4j.expression;
import static org.objectweb.asm.Opcodes.*;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.Label;
import com.roubsite.smarty4j.MethodVisitorProxy;
import com.roubsite.smarty4j.Node;
import com.roubsite.smarty4j.VariableManager;
/**
* 对象表达式节点, 向JVM语句栈内放入对象
*
* @version 1.1.0, 2015/05/16
* @author Ouyang Xianwei
* @since Smarty 1.1
*/
public abstract class ObjectExpression extends Expression {
/** ASM名称 */
public static final String NAME = ObjectExpression.class.getName().replace('.', '/');
/** 变量的扩展访问节点列表 */
List<Node> extendeds;
public static double weak(Object o) {
if (o == null || o.equals("")) {
return 0.0d;
}
String s = o.toString();
if (isNumeric(s) != 0) {
return Double.parseDouble(s);
} else {
return Double.NaN;
}
}
private static int isNumeric(String s) {
int len = s.length();
int ret;
char c = s.charAt(0);
if (c == '.') {
ret = 1;
} else if (!Character.isDigit(c) && c != '-') {
return 0;
} else {
ret = -1;
}
for (int i = 1; i < len; i++) {
c = s.charAt(i);
if (c == '.') {
if (ret > 0) {
return 0;
} else {
ret = i + 1;
}
} else if (!Character.isDigit(c)) {
return 0;
}
}
return ret;
}
/**
* 对象转换成逻辑型数据, 对于NULL对象, 空字符串, 以及数值型的0, 均对应false, 否则对应true
*
* @param o
* 源对象
* @return 转换的结果, 0表示<tt>false</tt>, 1表示 <tt>true</tt>
*/
public static boolean o2b(Object o) {
if (o == null || o.equals("")) {
return false;
} else if (o instanceof Boolean) {
return (Boolean) o;
} else if (o instanceof Double) {
return ((Double) o).doubleValue() != 0.0;
} else if (o instanceof Number) {
return ((Number) o).intValue() != 0;
}
return true;
}
/**
* 对象转换成整型数值, 对于数值类型的对象返回对应的整数值, 对于布尔对象用1/0表示 <tt>true</tt>/<tt>false</tt>, 其它对象将调用类型转换,
* 如果无法转换对象的信息成为一个整数将返回0值
*
* @param o
* 需要转换的对象
* @return 对象表示的整数
*/
public static int o2i(Object o) {
if (o == null || o.equals("")) {
return 0;
}
if (o instanceof Number) {
return ((Number) o).intValue();
}
if (o instanceof Boolean) {
return ((Boolean) o) ? 1 : 0;
}
String s = o.toString();
int ret = isNumeric(s);
switch (ret) {
case 0:
case 1:
return 0;
case -1:
return Integer.parseInt(s);
default:
return Integer.parseInt(s.substring(0, ret - 1));
}
}
/**
* 对象转换成整型数值, 对于数值类型的对象返回对应的整数值, 对于布尔对象用1/0表示 <tt>true</tt>/<tt>false</tt>, 其它对象将调用类型转换,
* 如果无法转换对象的信息成为一个整数将返回NaN值
*
* @param o
* 需要转换的对象
* @return 对象表示的浮点数
*/
public static double o2d(Object o) {
if (o == null || o.equals("")) {
return Double.NaN;
}
if (o instanceof Number) {
return ((Number) o).doubleValue();
}
if (o instanceof Boolean) {
return ((Boolean) o) ? 1 : 0;
}
String s = o.toString();
if (isNumeric(s) == 0) {
return Double.NaN;
} else {
return Double.parseDouble(s);
}
}
/**
* 弱类型转换, 将对象转换为字符串, 其中<tt>null</tt>被转换成空字符串
*
* @param o
* 源对象
* @return 源对象对应的字符串
*/
public static String o2s(Object o) {
return o == null ? "" : o.toString();
}
public boolean hasExtended() {
return extendeds != null;
}
/**
* 添加一个扩展引用节点, 变量可以要求进行列表或映射型的扩展, 实现源数据容器中复杂的对象描述
*
* @param extended
* 变量访问扩展节点
*/
public void add(Node extended) {
if (extendeds == null) {
extendeds = new ArrayList<Node>();
}
extendeds.add(extended);
}
/**
* 输出自身
*
* @param mv
* ASM方法访问对象
* @param local
* ASM方法内部的语句栈局部变量起始位置
* @param vm
* 变量管理器
*/
public abstract void parseSelf(MethodVisitorProxy mv, int local, VariableManager vm);
@Override
public void parseCheck(MethodVisitorProxy mv, int local, VariableManager vm, Label lblTrue,
Label lblFalse) {
parseObject(mv, local, vm);
mv.visitMethodInsn(INVOKESTATIC, NAME, "o2b", "(Ljava/lang/Object;)Z");
}
@Override
public void parseInteger(MethodVisitorProxy mv, int local, VariableManager vm) {
parseObject(mv, local, vm);
mv.visitMethodInsn(INVOKESTATIC, NAME, "o2i", "(Ljava/lang/Object;)I");
}
@Override
public void parseDouble(MethodVisitorProxy mv, int local, VariableManager vm) {
parseObject(mv, local, vm);
mv.visitMethodInsn(INVOKESTATIC, NAME, "o2d", "(Ljava/lang/Object;)D");
}
@Override
public void parseString(MethodVisitorProxy mv, int local, VariableManager vm) {
parseObject(mv, local, vm);
mv.visitMethodInsn(INVOKESTATIC, "java/lang/String", "valueOf",
"(Ljava/lang/Object;)Ljava/lang/String;");
}
@Override
public void parseObject(MethodVisitorProxy mv, int local, VariableManager vm) {
parseSelf(mv, local, vm);
if (extendeds != null) {
for (Node extended : extendeds) {
extended.parse(mv, local, vm);
}
}
}
@Override
public void parse(MethodVisitorProxy mv, int local, VariableManager vm) {
parseObject(mv, local, vm);
}
}
| 21.713656
| 92
| 0.621221
|
a3a4b9bfe28fc54c249b1623634f4c0d3a67dfec
| 14,868
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.cognitiveservices.search.entitysearch.samples;
import com.microsoft.azure.cognitiveservices.search.entitysearch.BingEntitySearchAPI;
import com.microsoft.azure.cognitiveservices.search.entitysearch.BingEntitySearchManager;
import com.microsoft.azure.cognitiveservices.search.entitysearch.models.EntityScenario;
import com.microsoft.azure.cognitiveservices.search.entitysearch.models.Error;
import com.microsoft.azure.cognitiveservices.search.entitysearch.models.ErrorResponse;
import com.microsoft.azure.cognitiveservices.search.entitysearch.models.ErrorResponseException;
import com.microsoft.azure.cognitiveservices.search.entitysearch.models.Place;
import com.microsoft.azure.cognitiveservices.search.entitysearch.models.SearchOptionalParameter;
import com.microsoft.azure.cognitiveservices.search.entitysearch.models.SearchResponse;
import com.microsoft.azure.cognitiveservices.search.entitysearch.models.Thing;
import java.util.ArrayList;
import java.util.List;
/**
* Sample code for searching entities using Bing Entiy Search, an Azure Cognitive Service.
* - Search the entities for "Satya Nadella" and print out a short description.
* - Search the entities and handle disambiguation results for an ambiguous query "William Gates".
* - Search the entities for a single store "Microsoft Store" and print out its phone number.
* - Search the entities for a list of restaurants "seattle restaurants" and present their names and phone numbers.
* - Trigger a bad request and shows how to read the error response.
*/
public class BingEntitySearchSample {
/**
* Main function which runs the actual sample.
*
* @param client instance of the Bing Entity Search API client
* @return true if sample runs successfully
*/
public static boolean runSample(BingEntitySearchAPI client) {
try {
//=============================================================
// This will look up a single entity "Satya Nadella" and print out a short description of it.
SearchResponse entityData = client.bingEntities().search()
.withQuery("Satya Nadella")
.withMarket("en-us")
.execute();
if (entityData.entities().value().size() > 0) {
// find the entity that represents the dominant one
List<Thing> entrys = entityData.entities().value();
boolean hasDominateEntry = false;
for (Thing thing : entrys) {
if (thing.entityPresentationInfo().entityScenario() == EntityScenario.DOMINANT_ENTITY) {
System.out.println("Searched for \"Satya Nadella\" and found a dominant entity with this description:");
System.out.println(thing.description());
hasDominateEntry = true;
break;
}
}
if (!hasDominateEntry) {
System.out.println("Couldn't find main entity Satya Nadella!");
}
} else {
System.out.println("Didn't see any data..");
}
//=============================================================
// This will handle disambiguation results for an ambiguous query "harry potter".
int maxTries = 2;
for (int i = 1; i <= 2; i++) {
try {
entityData = client.bingEntities().search()
.withQuery("William Gates")
.withMarket("en-us")
.execute();
if (entityData.entities().value().size() > 0) {
// find the entity that represents the dominant one
List<Thing> entrys = entityData.entities().value();
boolean hasDominateEntry = false;
for (Thing thing : entrys) {
if (thing.entityPresentationInfo().entityScenario() == EntityScenario.DOMINANT_ENTITY) {
System.out.println("Searched for \"William Gates\" and found a dominant entity with this description:");
System.out.println(thing.description());
hasDominateEntry = true;
break;
}
}
if (!hasDominateEntry) {
System.out.println("Couldn't find main entity \"William Gates\"!");
} else {
List<Thing> dominateEntries = new ArrayList<>();
for (Thing thing : entrys) {
if (thing.entityPresentationInfo().entityScenario() == EntityScenario.DISAMBIGUATION_ITEM) {
dominateEntries.add(thing);
}
}
if (dominateEntries.size() > 1) {
System.out.println("This query is pretty ambiguous and can be referring to multiple things. Did you mean one of these:");
for (Thing thing : dominateEntries) {
System.out.format("\t%s (%s)\n", thing.name(), thing.entityPresentationInfo().entityTypeDisplayHint());
}
} else {
System.out.println("We didn't find any disambiguation items for William Gates, so we must be certain what you're talking about!");
}
}
} else {
System.out.println("Didn't see any data..");
}
break;
} catch (ErrorResponseException e) {
System.out.println(
String.format("Exception occurred when searching for William Gates, status code %s with reason %s.", e.response().code(), e.response().message()));
if (e.response().code() == 429) {
System.out.println("You are getting a request exceeded error because you are using the free tier for this sample. Code will wait 1 second before resending request");
} else {
throw e;
}
if (i == maxTries) {
throw e;
}
Thread.sleep(1000);
}
}
//=============================================================
// This will look up a single store "Microsoft Store" and print out its phone number.
System.out.println("Searching for \"Microsoft Store\"");
for (int i = 1; i <= 2; i++) {
try {
entityData = client.bingEntities().search()
.withQuery("Microsoft Store")
.withMarket("en-us")
.execute();
if (entityData.places() != null && entityData.places().value().size() > 0) {
// Some local entities will be places, others won't be. Depending on the data you want, try to cast to the appropriate schema
// In this case, the item being returned is technically a Store, but the Place schema has the data we want (telephone)
Place store = (Place) entityData.places().value().get(0);
if (store != null) {
System.out.println("Searched for \"Microsoft Store\" and found a store with this phone number:");
System.out.println(store.telephone());
} else {
System.out.println("Couldn't find a place!");
}
} else {
System.out.println("Didn't see any data..");
}
break;
} catch (ErrorResponseException e) {
System.out.println(
String.format("Exception occurred when searching for Microsoft Store, status code %s with reason %s.", e.response().code(), e.response().message()));
if (e.response().code() == 429) {
System.out.println("You are getting a request exceeded error because you are using the free tier for this sample. Code will wait for 1 second before resending request");
} else {
throw e;
}
if (i == maxTries) {
throw e;
}
Thread.sleep(1000);
}
}
//=============================================================
// This will look up a list of restaurants "seattle restaurants" and present their names and phone numbers.
for (int i = 1; i <= 2; i++) {
try {
SearchResponse restaurants = client.bingEntities().search("",
new SearchOptionalParameter()
.withMarket("en-us"));
if (restaurants.places() != null && restaurants.places().value().size() > 0) {
List<Thing> listItems = new ArrayList<Thing>();
for (Thing place : restaurants.places().value()) {
if (place.entityPresentationInfo().entityScenario() == EntityScenario.LIST_ITEM) {
listItems.add(place);
}
}
if (listItems.size() > 0) {
StringBuilder sb = new StringBuilder();
for (Thing item : listItems) {
Place place = (Place) item;
if (place == null) {
System.out.println(String.format("Unexpectedly found something that isn't a place named \"%s\"", item.toString()));
continue;
}
sb.append(String.format(",%s (%s) ", place.name(), place.telephone()));
}
System.out.println("Ok, we found these places: ");
System.out.println(sb.toString().substring(1));
} else {
System.out.println("Couldn't find any relevant results for \"seattle restaurants\"");
}
} else {
System.out.println("Didn't see any data..");
}
break;
} catch (ErrorResponseException e) {
System.out.println(
String.format("Exception occurred when searching for seattle restaurants, status code %s with reason %s.", e.response().code(), e.response().message()));
if (e.response().code() == 429) {
System.out.println("You are getting a request exceeded error because you are using the free tier for this sample. Code will wait for 1 second before resending request");
} else {
throw e;
}
if (i == maxTries) {
throw e;
}
Thread.sleep(1000);
}
}
//=============================================================
// This triggers a bad request and shows how to read the error response.
try {
SearchResponse errorQuery = client.bingEntities().search()
.withQuery("harry potter")
.withMarket("no-NO")
.execute();
} catch (ErrorResponseException ex) {
// The status code of the error should be a good indication of what occurred. However, if you'd like more details, you can dig into the response.
// Please note that depending on the type of error, the response schema might be different, so you aren't guaranteed a specific error response schema.
System.out.println(
String.format("Exception occurred, status code %s with reason %s.", ex.response().code(), ex.response().message()));
// Attempting to parse the content as an ErrorResponse
ErrorResponse issue = ex.body();
if (issue != null && issue.errors() != null && issue.errors().size() > 0 ) {
Error error = issue.errors().get(0);
System.out.println(
String.format("Turns out the issue is parameter \"%s\" has an invalid value \"%s\". Detailed message is \"%s\"",
error.parameter(), error.value(), error.message()));
}
}
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
}
return false;
}
/**
* Main entry point.
*
* @param args the parameters
*/
public static void main(String[] args) {
try {
//=============================================================
// Authenticate
// If you are going to set the BING_ENTITY_SEARCH_SUBSCRIPTION_KEY environment variable, make sure you set it for your OS, then reopen your command prompt or IDE.
// If not, you may get an API key not found exception.
// IMPORTANT: if you have not set the BING_ENTITY_SEARCH_SUBSCRIPTION_KEY environment variable to your cognitive services API key:
// 1. comment out the below line
final String subscriptionKey = System.getenv("BING_ENTITY_SEARCH_SUBSCRIPTION_KEY");
// 2. add your key to your environment variables, and uncomment the line
//final String subscriptionKey = System.getenv("BING_ENTITY_SEARCH_SUBSCRIPTION_KEY");
BingEntitySearchAPI client = BingEntitySearchManager.authenticate(subscriptionKey);
runSample(client);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
| 51.268966
| 193
| 0.504237
|
88efc534a043254bd04b224e704d3b8d6dbabd8c
| 370
|
package com.langdashu.flexible.uid.zookeeper.hook;
/**
* 回调结果
*
* <p>更多内容参看<a href="https://langdashu.com"><b>浪大叔</b></a>
* @author 浪大叔
*/
public class Result {
private Throwable throwable;
public Throwable getThrowable() {
return throwable;
}
public void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
}
| 16.818182
| 58
| 0.640541
|
b5ac67f7b3b55f477649c82e4a772176b545fbc5
| 2,305
|
package cz.johnyapps.jecnakvkapse.Receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Slouží k rozpoznání připojení k internetu
*/
public class NetworkState {
/**
* Inicializace
*/
public NetworkState() {
}
/**
* Vrátí stav připojení
* @param context Context
* @return True - připojen; False - nepřipojen
*/
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
/**
* Slouží k rozpoznání připojení k internetu real-time pomocí {@link ConnectivityReceiverListener}
*/
public static class Receiver extends BroadcastReceiver {
private ConnectivityReceiverListener connectivityReceiverListener;
/**
* Inicializace
*/
public Receiver() {
super();
}
/**
* Zachytí změnu internetového připojení
* @param context Context
* @param intent Intent
*/
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean connected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(connected);
}
}
/**
* Listener pro změny připojení
*/
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean connected);
}
/**
* Nastaví listener
* @param listener Listener
*/
public void setConnectivityReceiverListener(ConnectivityReceiverListener listener) {
this.connectivityReceiverListener = listener;
}
}
}
| 29.177215
| 114
| 0.645553
|
2f8313b65f1aa1e20b5c2d14ffe166f66d2ecc8b
| 1,480
|
package org.sirix.cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.sirix.page.interfaces.Page;
import javax.annotation.Nonnull;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public final class UnorderedKeyValuePageCache implements Cache<IndexLogKey, Page> {
private final com.github.benmanes.caffeine.cache.Cache<IndexLogKey, Page> pageCache;
public UnorderedKeyValuePageCache() {
pageCache = Caffeine.newBuilder()
.maximumSize(1_000)
.expireAfterWrite(10, TimeUnit.SECONDS)
.expireAfterAccess(10, TimeUnit.SECONDS)
.build();
}
@Override
public void clear() {
pageCache.invalidateAll();
}
@Override
public Page get(IndexLogKey key) {
return pageCache.getIfPresent(key);
}
@Override
public void put(IndexLogKey key, @Nonnull Page value) {
pageCache.put(key, value);
}
@Override
public void putAll(Map<? extends IndexLogKey, ? extends Page> map) {
pageCache.putAll(map);
}
@Override
public void toSecondCache() {
throw new UnsupportedOperationException();
}
@Override
public Map<IndexLogKey, Page> getAll(Iterable<? extends IndexLogKey> keys) {
return pageCache.getAllPresent(keys);
}
@Override
public void remove(IndexLogKey key) {
pageCache.invalidate(key);
}
@Override
public void close() {
}
}
| 24.262295
| 88
| 0.656757
|
5b2a56d0ea8fcf534355df8f13f056da4021bc97
| 5,097
|
package com.aayaffe.sailingracecoursemanager.adapters;
import android.app.Activity;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.aayaffe.sailingracecoursemanager.events.Event;
import com.aayaffe.sailingracecoursemanager.R;
import com.aayaffe.sailingracecoursemanager.Users.User;
import com.aayaffe.sailingracecoursemanager.Users.Users;
import com.aayaffe.sailingracecoursemanager.activities.ChooseEventActivity;
import com.aayaffe.sailingracecoursemanager.db.IDBManager;
import com.firebase.ui.database.FirebaseListAdapter;
import com.firebase.ui.database.FirebaseListOptions;
/**
* Avi Marine Innovations - www.avimarine.in
*
* Created by Amit Y. on 14/01/2017.
*/
public class EventsListAdapter extends FirebaseListAdapter<Event> {
private final IDBManager commManager;
private final Users users;
private final Activity mActivity;
/**
* @param activity The activity containing the ListView
* @param users
*/
public EventsListAdapter(FirebaseListOptions options, Activity activity, IDBManager commManager, Users users) {
super(options);
this.mActivity = activity;
this.commManager = commManager;
this.users = users;
}
@Override
protected void populateView(View view, final Event event, int position) {
((TextView)view.findViewById(android.R.id.text1)).setText(event.getName());
String dates = getDateRangeString(event);
User manager = commManager.findUser(event.getManagerUuid());
final ImageButton delete =(ImageButton)view.findViewById(R.id.delete_event_button);
final ImageButton viewOnly =(ImageButton)view.findViewById(R.id.view_only_event_button);
final ImageView rc_flag = view.findViewById(R.id.rc_icon);
final LinearLayout ll2 = view.findViewById(R.id.ll2);
if ((manager!=null && manager.equals(users.getCurrentUser()))||users.isAdmin(users.getCurrentUser())){
delete.setVisibility(View.VISIBLE);
delete.setEnabled(true);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((ChooseEventActivity)mActivity).deleteEvent(event);
}
});
}
else {
delete.setVisibility(View.GONE);
delete.setEnabled(false);
}
if (manager!=null && manager.equals(users.getCurrentUser())){
rc_flag.setVisibility(View.VISIBLE);
}
else{
rc_flag.setVisibility(View.GONE);
}
if (users.isAdmin(users.getCurrentUser())){
viewOnly.setVisibility(View.VISIBLE);
viewOnly.setEnabled(true);
viewOnly.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((ChooseEventActivity)mActivity).viewOnly(event);
}
});
// RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ll15.getLayoutParams();
// params.addRule(RelativeLayout.START_OF, R.id.ll2);
// ll15.setLayoutParams(params);
// RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ll2.getLayoutParams();
// params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
// ll2.setLayoutParams(params);
}
else {
viewOnly.setVisibility(View.GONE);
viewOnly.setEnabled(false);
// RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ll2.getLayoutParams();
// params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
// ll2.setLayoutParams(params);
}
if (manager==null) {
((TextView) view.findViewById(android.R.id.text2)).setText(mActivity.getString(R.string.race_officer) + ": " +mActivity.getString(R.string.unknown));
}
else {
((TextView) view.findViewById(android.R.id.text2)).setText(mActivity.getString(R.string.race_officer) + ": " + manager.DisplayName);
}
((TextView) view.findViewById(R.id.text3)).setText(dates);
}
@NonNull
public static String getDateRangeString(Event event) {
return getDateRangeString(event.yearStart,event.yearEnd,event.monthStart,event.monthEnd,event.dayStart,event.dayEnd);
}
public static String getDateRangeString(int yearStart, int yearEnd, int monthStart, int monthEnd, int dayStart, int dayEnd) {
if ( dayEnd == 0 || yearStart == 0 || dayStart == 0 || yearEnd == 0)
return "";
if (dayStart == dayEnd && monthStart == monthEnd && yearStart == yearEnd)
return String.valueOf(dayStart) + '/' + (monthStart+1) + '/' + yearStart;
return String.valueOf(dayStart) + '/' + (monthStart+1) + '/' + yearStart + " - " + dayEnd + '/' + (monthEnd+1) + '/' + yearEnd;
}
}
| 41.778689
| 161
| 0.660585
|
0101f2c68f6ded9a90a1456f337070e3aff63aa0
| 1,089
|
package org.d11.boot.camel.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.d11.boot.download.WebPage;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Processes a WebPage JMS message by setting downloadFileName properties in the Camel exchange.
*/
public class WebPageProcessor implements Processor {
/**
* Date time formatter for file name timestamp.
*/
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
@Override
public void process(final Exchange exchange) {
final WebPage webPage = exchange.getIn().getBody(WebPage.class);
final String fileName = String.format("%s-%s.html",
webPage.getTitle().replace("/", "-").replace("&", "and"),
LocalDateTime.now().format(DATE_TIME_FORMATTER));
exchange.setProperty("downloadFileName", fileName);
exchange.getIn().setBody(webPage.getPageSource());
}
}
| 33
| 109
| 0.668503
|
f789bcdf670fa44211f8c15a6597f0e8fb1f0007
| 6,663
|
/*
* 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.openejb.core.entity;
import org.apache.openejb.BeanContext;
import org.apache.openejb.Container;
import org.apache.openejb.InterfaceType;
import org.apache.openejb.core.ivm.EjbObjectProxyHandler;
import org.apache.openejb.util.proxy.ProxyManager;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
public class EntityEjbObjectHandler extends EjbObjectProxyHandler {
/*
* The registryId is a logical identifier that is used as a key when placing EntityEjbObjectHandler into
* the BaseEjbProxyHanlder's liveHandleRegistry. EntityEjbObjectHandlers that represent the same
* bean identity (keyed by the registry id) will be stored together so that they can be removed together
* when the BaseEjbProxyHandler.invalidateAllHandlers is invoked. The EntityEjbObjectHandler uses a
* compound key composed of the entity bean's primary key, deployment id, and
* container id. This uniquely identifies the bean identity that is proxied by this handler allowing it
* to be removed with other handlers bound to the same registry id.
*/
private Object registryId;
public EntityEjbObjectHandler(final BeanContext beanContext, final Object pk, final InterfaceType interfaceType, final List<Class> interfaces, final Class mainInterface) {
super(beanContext, pk, interfaceType, interfaces, mainInterface);
}
/*
* This method generates a logically unique entity bean identifier from the primary key,
* deployment id, and container id. This registry key is then used as an index for the associated
* entity bean in the BaseEjbProxyHandler.liveHandleRegistry. The liveHandleRegistry tracks
* handler for the same bean identity so that they can removed together when one of the remove() operations
* is called.
*/
public static Object getRegistryId(final Container container, final Object deploymentId, final Object primaryKey) {
return new RegistryId(container, deploymentId, primaryKey);
}
public Object getRegistryId() {
if (registryId == null) {
registryId = getRegistryId(container, deploymentID, primaryKey);
}
return registryId;
}
protected Object getPrimaryKey(final Method method, final Object[] args, final Object proxy) throws Throwable {
return primaryKey;
}
protected Object isIdentical(final Method method, final Object[] args, final Object proxy) throws Throwable {
checkAuthorization(method);
if (args.length != 1) {
throw new IllegalArgumentException("Expected one argument to isIdentical, but received " + args.length);
}
final Object that = args[0];
final Object invocationHandler = ProxyManager.getInvocationHandler(that);
if (invocationHandler instanceof EntityEjbObjectHandler) {
final EntityEjbObjectHandler handler = (EntityEjbObjectHandler) invocationHandler;
/*
* The registry id is a compound key composed of the bean's primary key, deployment id, and
* container id. It uniquely identifies the entity bean that is proxied by the EntityEjbObjectHandler
* within the IntraVM.
*/
return this.getRegistryId().equals(handler.getRegistryId());
}
return false;
}
protected Object remove(final Class interfce, final Method method, final Object[] args, final Object proxy) throws Throwable {
checkAuthorization(method);
final Object value = container.invoke(deploymentID, interfaceType, interfce, method, args, primaryKey);
/*
* This operation takes care of invalidating all the EjbObjectProxyHanders associated with
* the same RegistryId. See this.createProxy().
*/
invalidateAllHandlers(getRegistryId());
return value;
}
public void invalidateReference() {
// entity bean object references should not be invalidated since they
// will automatically hook up to a new instance of the bean using the
// primary key (we will load a new instance from the db)
}
private static class RegistryId implements Serializable {
private static final long serialVersionUID = -6009230402616418827L;
private final Object containerId;
private final Object deploymentId;
private final Object primaryKey;
public RegistryId(final Container container, final Object deploymentId, final Object primaryKey) {
if (container == null) {
throw new NullPointerException("container is null");
}
if (deploymentId == null) {
throw new NullPointerException("deploymentId is null");
}
this.containerId = container.getContainerID();
this.deploymentId = deploymentId;
this.primaryKey = primaryKey;
}
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final RegistryId that = (RegistryId) o;
return containerId.equals(that.containerId) &&
deploymentId.equals(that.deploymentId) &&
Objects.equals(primaryKey, that.primaryKey);
}
public int hashCode() {
int result;
result = containerId.hashCode();
result = 31 * result + deploymentId.hashCode();
result = 31 * result + (primaryKey != null ? primaryKey.hashCode() : 0);
return result;
}
public String toString() {
return "[" + containerId + ", " + deploymentId + ", " + primaryKey + "]";
}
}
}
| 41.90566
| 175
| 0.681075
|
f8873418c2b2aa25b99339f62264de95ca011ed9
| 2,798
|
/**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2015 the original author or authors.
*/
package org.assertj.core.internal;
import static org.assertj.core.error.ShouldBeEqual.shouldBeEqual;
import static org.assertj.core.error.ShouldNotBeEqual.shouldNotBeEqual;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.util.VisibleForTesting;
/**
* Reusable assertions for <code>{@link Boolean}</code>s.
*
* @author Alex Ruiz
*/
public class Booleans {
private static final Booleans INSTANCE = new Booleans();
/**
* Returns the singleton instance of this class.
* @return the singleton instance of this class.
*/
public static Booleans instance() {
return INSTANCE;
}
@VisibleForTesting
Failures failures = Failures.instance();
@VisibleForTesting
Booleans() {}
/**
* Asserts that two booleans are equal.
* @param info contains information about the assertion.
* @param actual the actual value.
* @param expected the expected value.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is not equal to the expected one. This method will throw a
* {@code org.junit.ComparisonFailure} instead if JUnit is in the classpath and the expected and actual values are not
* equal.
*/
public void assertEqual(AssertionInfo info, Boolean actual, boolean expected) {
assertNotNull(info, actual);
if (actual == expected) return;
throw failures.failure(info, shouldBeEqual(actual, expected, info.representation()));
}
/**
* Asserts that two longs are not equal.
* @param info contains information about the assertion.
* @param actual the actual value.
* @param other the value to compare the actual value to.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is equal to the other one.
*/
public void assertNotEqual(AssertionInfo info, Boolean actual, boolean other) {
assertNotNull(info, actual);
if (actual != other) return;
throw failures.failure(info, shouldNotBeEqual(actual, other));
}
private static void assertNotNull(AssertionInfo info, Boolean actual) {
Objects.instance().assertNotNull(info, actual);
}
}
| 35.417722
| 130
| 0.72659
|
576db0af549646291f70a53d2a945ec8feccffa2
| 945
|
// package com.example.food_delivery.config;
// import org.springframework.context.annotation.Bean;
// import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
// import org.springframework.security.config.annotation.web.builders.HttpSecurity;
// import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
// import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
// public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// @Override
// protected void configure(HttpSecurity httpSecurity) throws Exception {
// }
// @Bean
// public BCryptPasswordEncoder passwordEncoder() {
// BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
// return bCryptPasswordEncoder;
// }
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// }
// }
| 35
| 110
| 0.798942
|
c867aa38f576c3747d8e44e095047fa944c93635
| 395
|
package com.scoproject.carmudi.model;
import com.scoproject.carmudi.CarmudiApp;
import com.scoproject.carmudi.data.db.DaoSession;
import com.scoproject.carmudi.di.component.AppComponent;
/**
* Created by ibnumuzzakkir on 6/2/17.
*/
public class BaseModel {
protected final DaoSession mDaoSession;
public BaseModel(DaoSession daoSession) {
mDaoSession = daoSession;
}
}
| 21.944444
| 56
| 0.75443
|
6cb7b4fe217584af02ae3baa9c99bcf29ada9732
| 357
|
package com.so.affinitas.profilematcher.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import com.so.affinitas.profilematcher.entity.Profile;
public interface ProfileRepository extends JpaRepository<Profile, Long>, JpaSpecificationExecutor<Profile> {
}
| 32.454545
| 108
| 0.854342
|
431887805e82e74769da362a7df03fe634617731
| 668
|
package ru.fizteh.fivt.students.Kudriavtsev_Dmitry.fileMap;
import java.util.HashMap;
/**
* Created by Дмитрий on 04.10.14.
*/
public class Remove extends Command {
public Remove() {
name = "remove";
argLen = 1;
}
@Override
public boolean exec(HashMap<String, String> dBase, String[] args) {
if (args.length != argLen) {
System.err.println("Incorrect number of arguments in " + name);
return false;
}
if (dBase.remove(args[0]) != null) {
System.out.println("removed");
} else {
System.out.println("not found");
}
return true;
}
}
| 23.034483
| 75
| 0.562874
|
e2453e4eb6e417bc71a4defa20f373e82d3c735a
| 293
|
package io.coin.ccbc.infra.exchange.config.properties;
import lombok.Getter;
import lombok.Setter;
/**
* @author Bomi
* @date 2021/08/07
*/
@Getter
@Setter
public class KorbitProperties {
public static final String PROPERTIES_PREFIX = "app.exchange.korbit";
private String host;
}
| 15.421053
| 71
| 0.740614
|
55281e7d2fda9f378441afedf219636ce32164f0
| 6,817
|
package com.popularmovies.android.repository;
import android.support.annotation.NonNull;
import com.popularmovies.android.model.DetailMovie;
import com.popularmovies.android.model.GetMoviesCallback;
import com.popularmovies.android.model.MoviesResponse;
import com.popularmovies.android.model.ReviewsResponse;
import com.popularmovies.android.model.TrailerResponse;
import com.popularmovies.android.utils.ApiMovie;
import com.popularmovies.android.utils.Constant;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MoviesRepository {
private static MoviesRepository repository;
private ApiMovie api;
private MoviesRepository(ApiMovie api) {
this.api = api;
}
public static MoviesRepository getInstance() {
if (repository == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
repository = new MoviesRepository(retrofit.create(ApiMovie.class));
}
return repository;
}
public void getPopularMovies(int page, final GetMoviesCallback callback) {
api.getPopularMovies(Constant.APIKEY, Constant.LANGUAGE, page)
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
callback.onSuccess(moviesResponse.getPage(), moviesResponse.getMovies());
} else {
callback.onError();
}
} else {
callback.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
callback.onError();
}
});
}
public void getTopRatedMovies(int page, final GetMoviesCallback callback) {
api.getTopRatedMovies(Constant.APIKEY, Constant.LANGUAGE, page)
.enqueue(new Callback<MoviesResponse>() {
@Override
public void onResponse(@NonNull Call<MoviesResponse> call, @NonNull Response<MoviesResponse> response) {
if (response.isSuccessful()) {
MoviesResponse moviesResponse = response.body();
if (moviesResponse != null && moviesResponse.getMovies() != null) {
callback.onSuccess(moviesResponse.getPage(), moviesResponse.getMovies());
} else {
callback.onError();
}
} else {
callback.onError();
}
}
@Override
public void onFailure(Call<MoviesResponse> call, Throwable t) {
callback.onError();
}
});
}
public void getDetailMovie(int movieId, final GetMoviesCallback callback) {
api.getMovieById(movieId, Constant.APIKEY, Constant.LANGUAGE)
.enqueue(new Callback<DetailMovie>() {
@Override
public void onResponse(Call<DetailMovie> call, Response<DetailMovie> response) {
if (response.isSuccessful()) {
DetailMovie movieDetail = response.body();
if (movieDetail != null) {
callback.onSuccess(movieDetail.getId(), movieDetail);
} else {
callback.onError();
}
} else {
callback.onError();
}
}
@Override
public void onFailure(Call<DetailMovie> call, Throwable t) {
callback.onError();
}
});
}
public void getTrailerMovie(final int movieId, final GetMoviesCallback callback) {
api.getTrailer(movieId, Constant.APIKEY, Constant.LANGUAGE)
.enqueue(new Callback<TrailerResponse>() {
@Override
public void onResponse(Call<TrailerResponse> call, Response<TrailerResponse> response) {
if (response.isSuccessful()) {
TrailerResponse trailerResponse = response.body();
if (trailerResponse != null) {
callback.onSuccess(movieId, trailerResponse.getTrailers());
} else {
callback.onError();
}
} else {
callback.onError();
}
}
@Override
public void onFailure(Call<TrailerResponse> call, Throwable t) {
callback.onError();
}
});
}
public void getReviewsMovie(final int movieId, final int page, final GetMoviesCallback callback) {
api.getReviews(movieId, page, Constant.APIKEY, Constant.LANGUAGE)
.enqueue(new Callback<ReviewsResponse>() {
@Override
public void onResponse(Call<ReviewsResponse> call, Response<ReviewsResponse> response) {
if (response.isSuccessful()) {
ReviewsResponse reviewsResponse = response.body();
if (reviewsResponse != null) {
callback.onSuccess(movieId, page, reviewsResponse.getReviews());
} else {
callback.onError();
}
} else {
callback.onError();
}
}
@Override
public void onFailure(Call<ReviewsResponse> call, Throwable t) {
callback.onError();
}
});
}
}
| 40.1
| 124
| 0.495966
|
fce0c0069088eb6aec4abbf8d79de89b7787b1e5
| 3,118
|
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import static com.google.errorprone.refaster.Unifier.unifyList;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.TryTree;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCTry;
import java.util.List;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of a {@code TryTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UTry extends USimpleStatement implements TryTree {
static UTry create(
Iterable<? extends UTree<?>> resources,
UBlock block,
Iterable<UCatch> catches,
@Nullable UBlock finallyBlock) {
return new AutoValue_UTry(
ImmutableList.copyOf(resources), block, ImmutableList.copyOf(catches), finallyBlock);
}
@Override
public abstract List<UTree<?>> getResources();
@Override
public abstract UBlock getBlock();
@Override
public abstract List<UCatch> getCatches();
@Override
@Nullable
public abstract UBlock getFinallyBlock();
@Override
public Kind getKind() {
return Kind.TRY;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitTry(this, data);
}
@Override
public JCTry inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Try(
inliner.<JCTree>inlineList(getResources()),
getBlock().inline(inliner),
inliner.inlineList(getCatches()),
inlineFinallyBlock(inliner));
}
/** Skips the finally block if the result would be empty. */
@Nullable
private JCBlock inlineFinallyBlock(Inliner inliner) throws CouldNotResolveImportException {
if (getFinallyBlock() != null) {
JCBlock block = getFinallyBlock().inline(inliner);
if (!block.getStatements().isEmpty()) {
return block;
}
}
return null;
}
@Override
@Nullable
public Choice<Unifier> visitTry(TryTree node, @Nullable Unifier unifier) {
return unifyList(unifier, getResources(), node.getResources())
.thenChoose(unifications(getBlock(), node.getBlock()))
.thenChoose(unifications(getCatches(), node.getCatches()))
.thenChoose(unifications(getFinallyBlock(), node.getFinallyBlock()));
}
}
| 30.871287
| 100
| 0.716164
|
f87206db503049251661046cbb5ade7f4192de31
| 1,349
|
/*
*
* * All Application code is Copyright 2016, The Department of Homeland Security (DHS), U.S. Customs and Border Protection (CBP).
* *
* * Please see LICENSE.txt for details.
*
*/
package gov.gtas.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import javax.annotation.Resource;
@Configuration
@ComponentScan("gov.gtas")
@PropertySource("classpath:default.application.properties")
@PropertySource(value = "file:${catalina.home}/conf/application.properties", ignoreResourceNotFound = true)
public class Neo4JConfig {
@Resource
private Environment env;
private static final String PROPERTY_NAME_USERNAME = "neo4jusername";
private static final String PROPERTY_NAME_PASSWORD = "neo4jpassword";
private static final String NEO_4_J_ENABLED = "neo4jEnabled";
public Neo4JConfig() {
}
public String neoUserName() {
return env.getRequiredProperty(PROPERTY_NAME_USERNAME);
}
public boolean enabled() {
return Boolean.parseBoolean(env.getRequiredProperty(NEO_4_J_ENABLED));
}
public String neoPassword() {
return env.getRequiredProperty(PROPERTY_NAME_PASSWORD);
}
}
| 28.104167
| 130
| 0.75315
|
90597b885777333ed8dac177d13d91413343791c
| 3,456
|
/*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.server.distributed.impl.task;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.orient.server.distributed.*;
import java.io.IOException;
import java.util.Collection;
/**
* Factory for remote tasks.
*
* @author Luca Garulli
*/
public class ORemoteTaskFactoryManagerImpl implements ORemoteTaskFactoryManager {
private final ODistributedServerManager dManager;
private ORemoteTaskFactory[] factories = new ODefaultRemoteTaskFactoryV0[2];
public ORemoteTaskFactoryManagerImpl(final ODistributedServerManager dManager) {
this.dManager = dManager;
factories[0] = new ODefaultRemoteTaskFactoryV0();
factories[1] = new ODefaultRemoteTaskFactoryV1();
}
@Override
public ORemoteTaskFactory getFactoryByServerId(final int serverId) {
final String remoteNodeName = dManager.getNodeNameById(serverId);
if (remoteNodeName == null)
throw new IllegalArgumentException("Invalid serverId " + serverId);
return getFactoryByServerName(remoteNodeName);
}
@Override
public ORemoteTaskFactory getFactoryByServerNames(final Collection<String> serverNames) {
int minVersion = ORemoteServerController.CURRENT_PROTOCOL_VERSION;
ORemoteTaskFactory factory = getFactoryByVersion(minVersion);
for (String server : serverNames) {
final ORemoteTaskFactory f = getFactoryByServerName(server);
if (f.getProtocolVersion() < minVersion) {
factory = f;
minVersion = f.getProtocolVersion();
}
}
return factory;
}
@Override
public ORemoteTaskFactory getFactoryByServerName(final String serverName) {
try {
final ORemoteServerController remoteServer = dManager.getRemoteServer(serverName);
final ORemoteTaskFactory factory = getFactoryByVersion(remoteServer.getProtocolVersion());
if (factory == null)
throw new IllegalArgumentException("Cannot find a factory for remote task for server " + serverName);
return factory;
} catch (ODistributedException e) {
// SERVER NOT AVAILABLE, CONSIDER CURRENT PROTOCOL FOR THE MISSING ONE
return getFactoryByVersion(ORemoteServerController.CURRENT_PROTOCOL_VERSION);
} catch (IOException e) {
throw OException.wrapException(new OIOException("Cannot determine protocol version for server " + serverName), e);
}
}
@Override
public ORemoteTaskFactory getFactoryByVersion(final int version) {
if (version < 0 || version >= factories.length)
throw new IllegalArgumentException("Invalid remote task factory version " + version);
return factories[version];
}
}
| 36
| 120
| 0.741609
|
5bfae5efce35fdb791292a1c198b9fcb7fcea231
| 2,482
|
package com.bop.zz.refresh.core.ui.adapter;
import java.util.ArrayList;
import java.util.List;
import com.bop.zz.R;
import com.bop.zz.refresh.core.Global;
import com.squareup.picasso.Picasso;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import cn.finalteam.toolsfinal.adapter.RecyclingPagerAdapter;
public class BannerAdapter extends RecyclingPagerAdapter {
private Context mContext;
private int mBannerHeight = Global.SCREEN_HEIGHT / 3;
private List<Integer> mImageList;
public BannerAdapter(Context context) {
this.mContext = context;
mImageList = new ArrayList<Integer>();
mImageList.add(R.mipmap.banner01);
mImageList.add(R.mipmap.banner02);
mImageList.add(R.mipmap.banner03);
mImageList.add(R.mipmap.banner04);
}
@Override
public View getView(int position, View convertView, ViewGroup container) {
ViewHolder holder;
if (convertView == null) {
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mBannerHeight);
ImageView ivCover = new ImageView(mContext);
ivCover.setImageResource(R.mipmap.ic_launcher);
ivCover.setLayoutParams(params);
holder = new ViewHolder();
holder.imageView = ivCover;
convertView = ivCover;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
int pos = getPosition(position);
int resId = mImageList.get(pos);
holder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
Picasso.with(mContext)
.load(resId)
.placeholder(R.drawable.ic_gf_default_photo)
.error(R.drawable.ic_gf_default_photo)
.resize(Global.SCREEN_WIDTH, mBannerHeight)
.config(Bitmap.Config.ARGB_8888)
.centerCrop()
.into(holder.imageView);
holder.imageView.setFocusable(false);
holder.imageView.setFocusableInTouchMode(false);
return convertView;
}
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
public int getPosition(int position) {
return position % mImageList.size();
}
public static class ViewHolder {
private ImageView imageView;
}
}
| 33.093333
| 123
| 0.66116
|
405cbe4c478a002419ee247b4c5743fb26c36e75
| 6,649
|
package kernitus.plugin.OldCombatMechanics.module;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableMap;
import kernitus.plugin.OldCombatMechanics.OCMMain;
import kernitus.plugin.OldCombatMechanics.utilities.reflection.MemoizingFeatureBranch;
import kernitus.plugin.OldCombatMechanics.utilities.reflection.Reflector;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FishHook;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.plugin.RegisteredListener;
import org.bukkit.util.Vector;
import java.util.EnumMap;
/**
* Brings back the old fishing knockback.
*/
public class ModuleFishingKnockback extends Module {
private MemoizingFeatureBranch<PlayerFishEvent, Entity> hookEntityFeature;
public ModuleFishingKnockback(OCMMain plugin){
super(plugin, "old-fishing-knockback");
//noinspection Convert2MethodRef as the Method reference would error at initialization, not just when invoked
hookEntityFeature = MemoizingFeatureBranch.onException(
playerFishEvent -> playerFishEvent.getHook(),
playerFishEvent -> playerFishEvent.getHook(),
// fall back to reflection on 1.12 and suck up some performance penalty
Reflector.memoizeMethodAndInvoke(PlayerFishEvent.class, "getHook")
);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onRodLand(ProjectileHitEvent e){
Entity hookEntity = e.getEntity();
World world = hookEntity.getWorld();
if(!isEnabled(world)) return;
if(e.getEntityType() != EntityType.FISHING_HOOK)
return;
Entity hitEntity;
try{
hitEntity = e.getHitEntity();
} catch(NoSuchMethodError e1){ //For older version that don't have such method
hitEntity = world.getNearbyEntities(hookEntity.getLocation(), 0.25, 0.25, 0.25).stream()
.filter(entity -> entity instanceof Player)
.findFirst()
.orElse(null);
}
if(hitEntity == null) return;
if(!(hitEntity instanceof Player)) return;
// Do not move Citizens NPCs
// See https://wiki.citizensnpcs.co/API#Checking_if_an_entity_is_a_Citizens_NPC
if(hitEntity.hasMetadata("NPC")) return;
FishHook hook = (FishHook) hookEntity;
Player rodder = (Player) hook.getShooter();
Player player = (Player) hitEntity;
debug("You were hit by a fishing rod!", player);
if(player.equals(rodder))
return;
if(player.getGameMode() == GameMode.CREATIVE) return;
//Check if cooldown time has elapsed
if(player.getNoDamageTicks() > player.getMaximumNoDamageTicks() / 2f){
return;
}
double damage = module().getDouble("damage");
if(damage < 0) damage = 0.2;
EntityDamageEvent event = makeEvent(rodder, player, damage);
Bukkit.getPluginManager().callEvent(event);
if(module().getBoolean("checkCancelled") && event.isCancelled()){
if(plugin.getConfig().getBoolean("debug.enabled")){
debug("You can't do that here!", rodder);
HandlerList hl = event.getHandlers();
// This is to check what plugins are listening to the event
for(RegisteredListener rl : hl.getRegisteredListeners())
debug("Plugin Listening: " + rl.getPlugin().getName(), rodder);
}
return;
}
player.damage(damage);
player.setVelocity(calculateKnockbackVelocity(player.getVelocity(), player.getLocation(), hook.getLocation()));
}
private Vector calculateKnockbackVelocity(Vector currentVelocity, Location player, Location hook){
double xDistance = hook.getX() - player.getX();
double zDistance = hook.getZ() - player.getZ();
// ensure distance is not zero and randomise in that case (I guess?)
while(xDistance * xDistance + zDistance * zDistance < 0.0001){
xDistance = (Math.random() - Math.random()) * 0.01D;
zDistance = (Math.random() - Math.random()) * 0.01D;
}
double distance = Math.sqrt(xDistance * xDistance + zDistance * zDistance);
double y = currentVelocity.getY() / 2;
double x = currentVelocity.getX() / 2;
double z = currentVelocity.getZ() / 2;
// Normalize distance to have similar knockback, no matter the distance
x -= xDistance / distance * 0.4;
// slow the fall or throw upwards
y += 0.4;
// Normalize distance to have similar knockback, no matter the distance
z -= zDistance / distance * 0.4;
// do not shoot too high up
if(y >= 0.4){
y = 0.4;
}
return new Vector(x, y, z);
}
/**
* This is to cancel dragging the player closer when you reel in
*/
@EventHandler(priority = EventPriority.HIGHEST)
private void onReelIn(PlayerFishEvent e){
if(!isSettingEnabled("cancelDraggingIn") || e.getState() != PlayerFishEvent.State.CAUGHT_ENTITY) return;
hookEntityFeature.apply(e).remove(); // Nuke the bobber and don't do anything else
e.setCancelled(true);
}
@SuppressWarnings({"rawtypes", "deprecation"})
private EntityDamageEvent makeEvent(Player rodder, Player player, double damage){
if(module().getBoolean("useEntityDamageEvent"))
return new EntityDamageEvent(player,
EntityDamageEvent.DamageCause.PROJECTILE,
new EnumMap<>(ImmutableMap.of(EntityDamageEvent.DamageModifier.BASE, damage)),
new EnumMap<>(ImmutableMap.of(EntityDamageEvent.DamageModifier.BASE, Functions.constant(damage))));
else
return new EntityDamageByEntityEvent(rodder, player,
EntityDamageEvent.DamageCause.PROJECTILE,
new EnumMap<>(ImmutableMap.of(EntityDamageEvent.DamageModifier.BASE, damage)),
new EnumMap<>(ImmutableMap.of(EntityDamageEvent.DamageModifier.BASE, Functions.constant(damage))));
}
}
| 38.433526
| 119
| 0.659648
|
f882e3cbedf2282945a9092c6dfa9c9e184acda3
| 1,859
|
/*
* Copyright 2016 Elizabeth Harper
*
* 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.vulpine.connectwise.type.agreement;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@RunWith( Parameterized.class )
public class ApplicationUnitTest
{
private static Field value;
private final ApplicationUnit type;
public ApplicationUnitTest( ApplicationUnit type )
{
this.type = type;
}
@BeforeClass
public static void setUpClass() throws NoSuchFieldException
{
value = ApplicationUnit.class.getDeclaredField("value");
value.setAccessible(true);
}
@Parameterized.Parameters( name = "{index}: {0}" )
public static Object[] data()
{
return ApplicationUnit.values();
}
@Test
public void toString_returns_enum_value() throws Exception
{
assertEquals(value.get(type), type.toString());
}
@Test
public void fromString_returns_enum_instance_by_value() throws Exception
{
assertEquals(type, ApplicationUnit.fromString((String) value.get(type)));
}
@Test
public void fromString_returns_null_on_unknown_value()
{
assertNull(ApplicationUnit.fromString("asdl;fjfasd"));
}
}
| 25.465753
| 77
| 0.745562
|
5834ba9b360827b5b3bfe7c5ce5a9f6b9d822973
| 4,758
|
package cloud.celldata.membrane.mapper;
import cloud.celldata.membrane.pojo.vo.CertificationBean;
import cloud.celldata.membrane.pojo.vo.FunctionBean;
import cloud.celldata.membrane.pojo.vo.ModuleBean;
import cloud.celldata.membrane.pojo.bo.PrivilegeRoleDTO;
import cloud.celldata.membrane.pojo.entity.ApiEntity;
import cloud.celldata.membrane.pojo.entity.ApiUrlEntity;
import cloud.celldata.membrane.pojo.entity.RoleApiEntity;
import cloud.celldata.membrane.pojo.entity.UrlEntity;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 功能权限Mapper
*/
public interface ApiMapper {
/**
* 根据角色id查询功能权限列表
* @param privilegeRoleDTO 查询条件
* @return 功能权限列表
*/
List<ApiEntity> getApiByRoleId(PrivilegeRoleDTO privilegeRoleDTO);
/**
* 添加功能权限关系表数据
* @param roleApiEntity 角色实体
* @return 新增成功记录条数
*/
int addRoleApi(RoleApiEntity roleApiEntity);
/**
* 新增模块,功能
* @param apiEntityList
* @return 主键Id
*/
void insertModuleAndFunction(ApiEntity apiEntityList);
/**
* 新增功能对应URL
* @param urlEntity URL实体
*
*/
void insertUrl(UrlEntity urlEntity);
/**
* 新增功能 和URL对应中间表
* @param apiUrlEntity
*/
void insertApiUrl(ApiUrlEntity apiUrlEntity);
/**
* 根据应用ID 模块名 模块ID 查询是否有模块名重复的情况
*
* @param clientId 应用ID
* @param apiName 模块名
* @param moduleId 模块ID
* @return 0代表没有重复 非0代表有重复
*/
Integer countModuleNameByClientIdAndApiName(@Param("clientId") Integer clientId,
@Param("apiName") String apiName,
@Param("moduleId") Integer moduleId
);
/**
* 根据应用ID 功能名 模块功能名 查询是否有功能名重复的情况
*
* @param clientId 应用ID
* @param apiName 模块名
* @param functionId 模块ID
* @return 0代表没有重复 非0代表有重复
*/
Integer countFunctionNameByClientIdAndApiName(@Param("clientId") Integer clientId,
@Param("apiName") String apiName,
@Param("moduleId") Integer moduleId,
@Param("functionId") Integer functionId
);
/**
* 查询 应用对应 模块和功能
*
* @param clientID 应用ID
* @param moduleId 模块ID
* @return 模块和功能
*/
List<ModuleBean> selectModuleAndFunctionByClientID(@Param("clientID")Integer clientID,@Param("moduleId")Integer moduleId);
/**
* 删除 功能
*
* @param functionId 功能ID
* @param userId 删除用户ID
*/
void removeFunctionApi(@Param("functionId") Integer functionId, @Param("userId") Integer userId);
/**
* 删除 功能和URL对应中间表
*
* @param functionId 功能ID
* @param userId 删除用户ID
*/
void removeFunctionApiURI(@Param("functionId") Integer functionId, @Param("userId") Integer userId);
/**
* 查询模块下有多少个功能
*
* @param moduleId
* @return
*/
Integer selectFunctionCountByModuleId(Integer moduleId);
/**
* 删除 模块
*
* @param moduleId 模块Id
* @param userId 用户ID
*/
void removeModuleApi(@Param("moduleId") Integer moduleId, @Param("userId") Integer userId);
/**
* 编辑模块
*
* @param moduleBean 模块实体
* @param userId 编辑用户ID
*/
void updateModule(@Param("moduleBean") ModuleBean moduleBean, @Param("userId") Integer userId);
/**
* 删除URI
*
* @param functionId 功能ID
* @param userId 用户ID
*/
void removeFunctionURI(@Param("functionId") Integer functionId, @Param("userId") Integer userId);
/**
* 功能编辑
*
* @param functionBean 功能实体
* @param userId 用户ID
*/
void updateFunction(@Param("functionBean") FunctionBean functionBean, @Param("userId") Integer userId);
/**
* 查询应用下有多少个模块
*
* @param clientId 应用ID
* @return 模块数量
*/
Integer selectModuleByClientid(Integer clientId);
/**
* 删除应用
*
* @param clientId 应用ID
* @param userId 用户ID
*/
void removeApp(@Param("clientId") Integer clientId, @Param("userId") Integer userId);
/**
* 认证管理
*
* @param certificationBean 认证管理实体
* @param userId 用户ID
*/
void certificationApp(@Param("certificationBean") CertificationBean certificationBean, @Param("userId") Integer userId);
/**
* 通过AppId查询所有功能权限url
* @param appId
* @return urilist
*/
List<String> selectAllUriListForAppId(Integer appId);
/**
* 通过appId 和 uri 查询次uri是什么类型
* @param appId 应用ID
* @param uri url
* @return 类型 0代表 非查询类型 1代表查询类型
*/
Integer selectApiTypeByAppIdAndURI(@Param("appId") Integer appId,@Param("uri") String uri);
}
| 25.718919
| 126
| 0.606978
|
fbba6ccd0ac8a24172ec4a8e13e7b6ddd52a7886
| 1,554
|
package com.reincarnation.cache.impl;
import com.reincarnation.cache.ThreadLocalCacheAdapter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.inject.Singleton;
/**
* <p>
* Description: ThreadLocalCacheAdapterImpl
* </p>
* <p>
* Copyright: 2017
* </p>
*
* @author twj
* @version 1.0
*/
@Singleton
class ThreadLocalCacheAdapterImpl implements ThreadLocalCacheAdapter {
private static class Context {
boolean enable = false;
Map<Integer, Object> cache;
}
private static final ThreadLocal<Context> CONTEXTS = ThreadLocal.withInitial(Context::new);
@Override
public void start() {
CONTEXTS.get().enable = true;
}
@Override
public void end() {
CONTEXTS.remove();
}
@SuppressWarnings("unchecked")
@Override
public <T> T getOrElse(int key, Callable<T> callable) throws Exception {
Context context = CONTEXTS.get();
if (context.enable) {
Map<Integer, Object> cache = context.cache;
// Only initialize map when used
if (cache == null) {
cache = new HashMap<>();
context.cache = cache;
}
T value = (T) cache.get(key);
if (value != null) {
return value;
}
T value2 = callable.call();
cache.put(key, value2);
return value2;
}
return callable.call();
}
}
| 23.19403
| 95
| 0.565637
|
de65af005c752b5dfe27b2f5478ccd906e9e2104
| 1,907
|
package alainvanhout.json;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
/**
* Interface for converting to and from JSON, with a number of convenience methods
*/
public interface JsonConverter {
/**
* Converts an object to the equivalent JSON representation.
* @param object The object to be converted
* @return The object's JSON representation
*/
String toJson(final Object object);
/**
* Produces an object based on the provided JSON string and a {@link Class} reference.
* @param json The JSON string
* @param clazz The class of object that is to be produced
* @param <T> The generic associated with the class of the object that is to be produced
* @return The object that is to be produced
*/
<T> T toObject(final String json, final Class<T> clazz);
/**
* Produces an object based on the provided JSON string and a {@link Type} reference.
* @param json The JSON string
* @param type The type of object that is to be produced
* @param <T> The generic associated with the type of the object that is to be produced
* @return The object that is to be produced
*/
<T> T toObject(final String json, final Type type);
/**
* Produces a list based on the provided JSON string and a {@link Type} reference.
* @param json The JSON string
* @param type The Generic {@link Type} of the list that is to be produced
* @param <T> The generic associated with the type of the list that is to be produced
* @return The list that is to be produced
*/
<T> List<T> toList(final String json, final Type type);
/**
* Convenience method to produce a {@link Map} instance based on the provided JSON string
* @param json The JSON string
* @return The Map instance that is to be produced
*/
Map toMap(final String json);
}
| 36.673077
| 93
| 0.674882
|
382b191ada36ca60256ed0e32f53aea775ac4f6c
| 3,686
|
/* Copyright 2008 Ben Gunter
*
* 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.sourceforge.stripes.util;
import net.sourceforge.stripes.controller.StripesConstants;
import javax.servlet.http.HttpServletRequest;
/**
* Provides helper methods for working with HTTP requests and responses.
*
* @author Ben Gunter
* @since Stripes 1.5.1
*/
public class HttpUtil {
/**
* <p>
* Get the path from the given request. This method is different from
* {@link HttpServletRequest#getRequestURI()} in that it concatenates and
* returns the servlet path plus the path info from the request. These are
* usually the same, but in some cases they are not.
* </p>
* <p>
* One case where they are known to differ is when a request for a directory
* is forwarded by the servlet container to a welcome file. In that case,
* {@link HttpServletRequest#getRequestURI()} returns the path that was
* actually requested (e.g., {@code "/"}), whereas the servlet path plus
* path info is the path to the welcome file (e.g. {@code "/index.jsp"}).
* </p>
* @param request
* @return
*/
public static String getRequestedPath(HttpServletRequest request) {
String servletPath, pathInfo;
// Check to see if the request is processing an include, and pull the path
// information from the appropriate source.
// only request attributes need decoding, not servletPath and pathInfo
// see https://stripesframework.atlassian.net/browse/STS-899
servletPath = urlDecodeNullSafe((String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH));
if (servletPath != null) {
pathInfo = urlDecodeNullSafe((String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH_INFO));
} else {
servletPath = request.getServletPath();
pathInfo = request.getPathInfo();
}
if (servletPath == null) {
return pathInfo == null ? "" : pathInfo;
} else if (pathInfo == null) {
return servletPath;
} else {
return servletPath + pathInfo;
}
}
/**
* Get the servlet path of the current request. The value returned by this
* method may differ from {@link HttpServletRequest#getServletPath()}. If
* the given request is an include, then the servlet path of the included
* resource is returned.
* @param request
* @return
*/
public static String getRequestedServletPath(HttpServletRequest request) {
// Check to see if the request is processing an include, and pull the path
// information from the appropriate source.
String path = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH);
if (path == null) {
path = request.getServletPath();
}
return path == null ? "" : path;
}
/**
* No instances
*/
private HttpUtil() {
}
private static String urlDecodeNullSafe(String url) {
if (url == null) {
return null;
}
return StringUtil.urlDecode(url);
}
}
| 36.49505
| 117
| 0.658166
|
c087191d18350699cd293e56a70104b1991ef593
| 589
|
package com.eldermoraes.ch10.async.websocket;
import java.util.Date;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
/**
*
* @author eldermoraes
*/
@Stateless
@Path("asyncService")
public class AsyncService {
@GET
public void asyncService(@Suspended AsyncResponse response){
AsyncClient client = new AsyncClient(response);
client.connect();
client.send("Message from client " + new Date().getTime());
client.close();
}
}
| 21.814815
| 67
| 0.697793
|
90001276bc3cac2bc27e32306db2f85187e650f9
| 192
|
package org.apdoer.condition.quot.service;
/**
* 行情模块初始化
* @author apdoer
*/
public interface QuotInitService {
/**
* 整体初始化
*/
void init();
/**
* 刷新渠道
*/
void flush();
}
| 9.142857
| 42
| 0.578125
|
146213457c1533ef76ce683a360b99be33a87cb1
| 14,514
|
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.stdlib.graphql.runtime.engine;
import io.ballerina.runtime.api.TypeTags;
import io.ballerina.runtime.api.creators.TypeCreator;
import io.ballerina.runtime.api.creators.ValueCreator;
import io.ballerina.runtime.api.types.ArrayType;
import io.ballerina.runtime.api.types.RecordType;
import io.ballerina.runtime.api.types.Type;
import io.ballerina.runtime.api.utils.StringUtils;
import io.ballerina.runtime.api.values.BArray;
import io.ballerina.runtime.api.values.BError;
import io.ballerina.runtime.api.values.BMap;
import io.ballerina.runtime.api.values.BObject;
import io.ballerina.runtime.api.values.BString;
import io.ballerina.runtime.api.values.BTable;
import io.ballerina.runtime.api.values.BValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static io.ballerina.stdlib.graphql.runtime.engine.Engine.executeResourceMethod;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.ALIAS_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.ARGUMENTS_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.ERRORS_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.FRAGMENT_NODE;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.KEY;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.NAME_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.ON_TYPE_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.SELECTIONS_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.TYPENAME_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.VALUE_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.VARIABLE_DEFINITION;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.VARIABLE_VALUE_FIELD;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.copyAndUpdateResourcePathsList;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.createDataRecord;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.getErrorDetailRecord;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.isScalarType;
import static io.ballerina.stdlib.graphql.runtime.engine.EngineUtils.updatePathSegments;
/**
* Used to generate the response for a GraphQL request in Ballerina.
*/
public class ResponseGenerator {
private ResponseGenerator() {
}
static synchronized void populateResponse(ExecutionContext executionContext, BObject node, Object result,
BMap<BString, Object> data, List<Object> pathSegments) {
if (TYPENAME_FIELD.equals(node.getStringValue(NAME_FIELD).getValue())) {
data.put(node.getStringValue(ALIAS_FIELD), StringUtils.fromString(executionContext.getTypeName()));
} else if (result instanceof BError) {
data.put(node.getStringValue(ALIAS_FIELD), null);
BError bError = (BError) result;
appendErrorToVisitor(bError, executionContext.getVisitor(), node, pathSegments);
} else if (result instanceof BValue) {
int tag = ((BValue) result).getType().getTag();
if (tag < TypeTags.JSON_TAG) {
data.put(node.getStringValue(ALIAS_FIELD), result);
} else if (tag == TypeTags.RECORD_TYPE_TAG) {
getDataFromRecord(executionContext, node, (BMap<BString, Object>) result, data, pathSegments);
} else if (tag == TypeTags.MAP_TAG) {
getDataFromMap(executionContext, node, (BMap<BString, Object>) result, data, pathSegments);
} else if (tag == TypeTags.ARRAY_TAG) {
getDataFromArray(executionContext, node, (BArray) result, data, pathSegments);
} else if (tag == TypeTags.TABLE_TAG) {
getDataFromTable(executionContext, node, (BTable) result, data, pathSegments);
} else if (tag == TypeTags.SERVICE_TAG) {
getDataFromService(executionContext, (BObject) result, node, data, new ArrayList<>(), pathSegments);
} // Here, `else` should not be reached.
} else {
data.put(node.getStringValue(ALIAS_FIELD), result);
}
}
static void getDataFromService(ExecutionContext executionContext, BObject service, BObject node,
BMap<BString, Object> data, List<String> paths, List<Object> pathSegments) {
ResourceCallback callback = new ResourceCallback(executionContext, node, createDataRecord(), pathSegments);
executionContext.getCallbackHandler().addCallback(callback);
BArray selections = node.getArrayValue(SELECTIONS_FIELD);
BMap<BString, Object> subData = createDataRecord();
if (TYPENAME_FIELD.equals(node.getStringValue(NAME_FIELD).getValue())) {
data.put(node.getStringValue(ALIAS_FIELD), StringUtils.fromString(executionContext.getTypeName()));
} else {
executionContext.setTypeName(service.getType().getName());
for (int i = 0; i < selections.size(); i++) {
BObject subNode = (BObject) selections.get(i);
BString typeName = StringUtils.fromString(subNode.getType().getName());
data.put(node.getStringValue(ALIAS_FIELD), subData);
if (FRAGMENT_NODE.equals(typeName)) {
if (service.getType().getName().equals(subNode.getStringValue(ON_TYPE_FIELD).getValue())) {
executeResourceForFragmentNodes(executionContext, service, subNode, subData, paths,
pathSegments);
}
} else {
executeResourceWithPath(executionContext, subNode, service, subData, paths, pathSegments);
}
}
}
executionContext.getCallbackHandler().markComplete(callback);
}
static void getDataFromRecord(ExecutionContext executionContext, BObject node, BMap<BString, Object> record,
BMap<BString, Object> data, List<Object> pathSegments) {
BArray selections = node.getArrayValue(SELECTIONS_FIELD);
String recordTypeName = getTypeNameFromRecordValue((RecordType) record.getType());
executionContext.setTypeName(recordTypeName);
BMap<BString, Object> subData = createDataRecord();
for (int i = 0; i < selections.size(); i++) {
BObject subNode = (BObject) selections.get(i);
BString typeName = StringUtils.fromString(subNode.getType().getName());
if (FRAGMENT_NODE.equals(typeName)) {
if (subNode.getStringValue(ON_TYPE_FIELD).getValue().equals(recordTypeName)) {
processFragmentNodes(executionContext, subNode, record, subData, pathSegments);
}
} else {
BString fieldName = subNode.getStringValue(NAME_FIELD);
Object fieldValue = record.get(fieldName);
List<Object> updatedPathSegments =
updatePathSegments(pathSegments, node.getStringValue(NAME_FIELD).getValue());
populateResponse(executionContext, subNode, fieldValue, subData, updatedPathSegments);
}
}
data.put(node.getStringValue(ALIAS_FIELD), subData);
}
static void getDataFromMap(ExecutionContext executionContext, BObject node, BMap<BString, Object> map,
BMap<BString, Object> data, List<Object> pathSegments) {
BArray argumentArray = node.getArrayValue(ARGUMENTS_FIELD);
for (int i = 0; i < argumentArray.size(); i++) {
BObject argumentNode = (BObject) argumentArray.get(i);
if (Objects.equals(StringUtils.fromString(KEY), argumentNode.getStringValue(NAME_FIELD))) {
if (argumentNode.getBooleanValue(VARIABLE_DEFINITION)) {
BString key = argumentNode.getStringValue(VARIABLE_VALUE_FIELD);
Object result = map.get(key);
populateResponse(executionContext, node, result, data, pathSegments);
} else {
BString key = argumentNode.getStringValue(VALUE_FIELD);
Object result = map.get(key);
populateResponse(executionContext, node, result, data, pathSegments);
}
}
}
}
static void getDataFromArray(ExecutionContext executionContext, BObject node, BArray result,
BMap<BString, Object> data, List<Object> pathSegments) {
if (isScalarType(result.getElementType())) {
data.put(node.getStringValue(ALIAS_FIELD), result);
} else {
BArray resultArray = ValueCreator.createArrayValue(getDataRecordArrayType());
for (int i = 0; i < result.size(); i++) {
List<Object> updatedPathSegments = updatePathSegments(pathSegments, i);
Object resultElement = result.get(i);
BMap<BString, Object> subData = createDataRecord();
populateResponse(executionContext, node, resultElement, subData, updatedPathSegments);
if (result.get(i) instanceof BError) {
BMap<BString, Object> subField = createDataRecord();
subField.put(node.getStringValue(NAME_FIELD), null);
resultArray.append(subField);
} else {
resultArray.append(subData.get(node.getStringValue(NAME_FIELD)));
}
}
data.put(node.getStringValue(ALIAS_FIELD), resultArray);
}
}
private static void getDataFromTable(ExecutionContext executionContext, BObject node, BTable table,
BMap<BString, Object> data, List<Object> pathSegments) {
Object[] valueArray = table.values().toArray();
ArrayType arrayType = TypeCreator.createArrayType(((BValue) valueArray[0]).getType());
BArray valueBArray = ValueCreator.createArrayValue(valueArray, arrayType);
populateResponse(executionContext, node, valueBArray, data, pathSegments);
}
static void processFragmentNodes(ExecutionContext executionContext, BObject node, BMap<BString, Object> record,
BMap<BString, Object> data, List<Object> pathSegments) {
BArray selections = node.getArrayValue(SELECTIONS_FIELD);
for (int i = 0; i < selections.size(); i++) {
BObject subNode = (BObject) selections.get(i);
BString typeName = StringUtils.fromString(subNode.getType().getName());
if (FRAGMENT_NODE.equals(typeName)) {
processFragmentNodes(executionContext, subNode, record, data, pathSegments);
} else {
BString fieldName = subNode.getStringValue(NAME_FIELD);
Object fieldValue = record.get(fieldName);
List<Object> updatedPathSegments = updatePathSegments(pathSegments,
node.getStringValue(NAME_FIELD).getValue());
populateResponse(executionContext, subNode, fieldValue, data, updatedPathSegments);
}
}
}
private static void executeResourceForFragmentNodes(ExecutionContext executionContext, BObject service,
BObject node, BMap<BString, Object> data, List<String> paths,
List<Object> pathSegments) {
BArray selections = node.getArrayValue(SELECTIONS_FIELD);
for (int i = 0; i < selections.size(); i++) {
BObject subNode = (BObject) selections.get(i);
BString typeName = StringUtils.fromString(subNode.getType().getName());
if (FRAGMENT_NODE.equals(typeName)) {
executeResourceForFragmentNodes(executionContext, service, subNode, data, paths, pathSegments);
} else {
executeResourceWithPath(executionContext, subNode, service, data, paths, pathSegments);
}
}
}
private static void executeResourceWithPath(ExecutionContext executionContext, BObject node, BObject service,
BMap<BString, Object> data, List<String> paths,
List<Object> pathSegments) {
List<String> updatedPaths = copyAndUpdateResourcePathsList(paths, node);
List<Object> updatedPathSegments = updatePathSegments(pathSegments, node.getStringValue(NAME_FIELD).getValue());
executeResourceMethod(executionContext, service, node, data, updatedPaths, updatedPathSegments);
}
private static ArrayType getDataRecordArrayType() {
BMap<BString, Object> data = createDataRecord();
return TypeCreator.createArrayType(data.getType());
}
static void appendErrorToVisitor(BError bError, BObject visitor, BObject node, List<Object> pathSegments) {
BArray errors = visitor.getArrayValue(ERRORS_FIELD);
errors.append(getErrorDetailRecord(bError, node, pathSegments));
}
private static String getTypeNameFromRecordValue(RecordType recordType) {
if (recordType.getName().contains("&") && recordType.getIntersectionType().isPresent()) {
for (Type constituentType : recordType.getIntersectionType().get().getConstituentTypes()) {
if (constituentType.getTag() != TypeTags.READONLY_TAG) {
return constituentType.getName();
}
}
}
return recordType.getName();
}
}
| 56.474708
| 120
| 0.66143
|
1149839e474f68541e2023ef269bade264345a63
| 2,679
|
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright holder is ArangoDB GmbH, Cologne, Germany
*/
package com.arangodb.velocypack;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import com.arangodb.velocypack.exception.VPackKeyTypeException;
import com.arangodb.velocypack.exception.VPackNeedAttributeTranslatorException;
import com.arangodb.velocypack.exception.VPackValueTypeException;
/**
* @author Mark Vollmary
*
*/
public class ObjectIterator extends SliceIterator<Entry<String, VPackSlice>> {
public ObjectIterator(final VPackSlice slice) throws VPackValueTypeException {
super(slice);
if (!slice.isObject()) {
throw new VPackValueTypeException(ValueType.OBJECT);
}
if (size > 0) {
final byte head = slice.head();
if (head == 0x14) {
current = slice.keyAt(0).getStart();
} else {
current = slice.getStart() + slice.findDataOffset();
}
}
}
@Override
public Entry<String, VPackSlice> next() {
if (position++ > 0) {
if (position <= size && current != 0) {
// skip over key
current += getCurrent().getByteSize();
// skip over value
current += getCurrent().getByteSize();
} else {
throw new NoSuchElementException();
}
}
final VPackSlice currentField = getCurrent();
return new Entry<String, VPackSlice>() {
@Override
public VPackSlice setValue(final VPackSlice value) {
throw new UnsupportedOperationException();
}
@Override
public VPackSlice getValue() {
return new VPackSlice(currentField.getBuffer(), currentField.getStart() + currentField.getByteSize());
}
@Override
public String getKey() {
try {
return currentField.makeKey().getAsString();
} catch (final VPackKeyTypeException e) {
throw new NoSuchElementException();
} catch (final VPackNeedAttributeTranslatorException e) {
throw new NoSuchElementException();
}
}
};
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| 28.5
| 107
| 0.686077
|
1900cdcb575895266d7bdda19e63c12d9baf0675
| 355
|
/*
* Copyright (c) 2014. Josh Lospinoso. All rights reserved
*/
package net.lospi.juno.elements;
public class SimpleState implements State {
private final Network network;
public SimpleState(Network network) {
this.network = network;
}
@Override
public Network getNetwork(String aspect) {
return network;
}
}
| 18.684211
| 58
| 0.673239
|
ccb08889943132d210c65132197402b971137297
| 2,803
|
package com.lin.web.util;
public class LinMobileVariablesProduction {
public static final String REDIRECT_URL= "http://linmobile-backend.appspot.com";
public static final String CUSTOM_REDIRECT_URL= "http://analytics.linone.com";
public static final String CALLBACK_URL = REDIRECT_URL+"/oauth2callback";
public static final String SENDER_EMAIL_ADDRESS="noreply@linone.com";
public static final String SENDER_NAME="ONE Analytics";
public static final String AUTHORIZATION_URL = CUSTOM_REDIRECT_URL+"/authorizeEmail.lin?authorize=";
public static final String FORGET_PASSWORD_URL = CUSTOM_REDIRECT_URL+"/forgetPasswordEmail.lin?reset=";
public static final String APPLICATION_URL =REDIRECT_URL;
public static final String GOOGLE_LOGIN_CLIENT_ID = "15890596879-i9fvr59p30gil3uur0asg3llfrn8c7jn.apps.googleusercontent.com";
public static final String GOOGLE_LOGIN_CLIENT_SECRET = "agTicP0lefgUtQTMVDTlbfrP";
public static final String GOOGLE_LOGIN_REDIRECT_URI= REDIRECT_URL+"/googleLoginCallback";
public static final String GOOGLE_BIGQUERY_DATASET_ID = "LIN";
public static final String GOOGLE_BIGQUERY_RAW_DATASET_ID = "LIN_RAW";
public static final String APPLICATION_BUCKET_NAME = "linmobile";
public static final String LIN_DIGITAL_CLOUD_STORAGE_BUCKET = "lindigital_prod";
public static final String LIN_MEDIA_CLOUD_STORAGE_BUCKET = "linmedia_prod";
public static final String LIN_MOBILE_CLOUD_STORAGE_BUCKET = "prod_linmobile";
public static final String TRIBUNE_CLOUD_STORAGE_BUCKET = "tribune_prod";
public static final String AD_EXCHANGE_CALLBACK_URL = REDIRECT_URL+"/oauth2callback";
public static final String AD_EXCHANGE_CLIENT_ID = "15890596879-32ud3ferr9eo5oo5p0rpfsc26c8b8ftp.apps.googleusercontent.com";
public static final String AD_EXCHANGE_CLIENT_SECRET = "AZvu35VUnTb2xeZi2l1rSty6";
public static final String APPLICATION_TYPE = "SynergyProd";
public static final String BACKEND_NAME="linbackend";
public static final String FUSION_TABLE_CLIENT_ID="904092960638-5f266ghcmcag8irhgna3rsu25ilc5b2l.apps.googleusercontent.com" ;
public static final String FUSION_TABLE_CLIENT_SECRET="dOnphK3jmh7JNdsvZMq7e63b" ;
public static final String FUSION_TABLE_CALLBACK_URL=REDIRECT_URL+"/fusionCallback.lin";
public static final String FUSION_POOL_MAP_MERGED_TABLE="1cTLtS6TAMB3N9Bv4cfq6BaBgjGBUtN6VR0nxMN8";
public static final String FUSION_INVENTORY_FORECAST_TABLE="165G9r9SIPgWgZXDW3iecy_BtRzxMtJlvyJxsWao";
public static final String SERVICE_ACCOUNT_KEY="linmobile-backend-11f89afed7aa.p12";
public static final String SERVICE_ACCOUNT_EMAIL="84127901856-b3t8ooqte83lr03kj344hbkmqkp6fluc@developer.gserviceaccount.com";
// Added by Anup for Geo-Census Module
public static final String LINMEDIA_BIGQUERY_GEO_DATASET = "GEO";
}
| 54.960784
| 129
| 0.836604
|
aa71d1965000e11d0aef20927c749a8141b6405c
| 2,180
|
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package keywhiz.service.daos;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.util.Map;
import javax.inject.Inject;
import keywhiz.api.ApiDate;
import keywhiz.api.model.SecretContent;
import keywhiz.jooq.tables.records.SecretsContentRecord;
import org.jooq.RecordMapper;
class SecretContentMapper implements RecordMapper<SecretsContentRecord, SecretContent> {
private static final TypeReference MAP_STRING_STRING_TYPE =
new TypeReference<Map<String, String>>() {};
private final ObjectMapper mapper;
@Inject SecretContentMapper(ObjectMapper mapper) {
this.mapper = mapper;
}
public SecretContent map(SecretsContentRecord r) {
return SecretContent.of(
r.getId(),
r.getSecretid(),
r.getEncryptedContent(),
r.getContentHmac(),
new ApiDate(r.getCreatedat()),
r.getCreatedby(),
new ApiDate(r.getUpdatedat()),
r.getUpdatedby(),
tryToReadMapFromMetadata(r.getMetadata()),
r.getExpiry());
}
public ImmutableMap<String, String> tryToReadMapFromMetadata(String value) {
if (!value.isEmpty()) {
try {
Map<String, String> t = mapper.readValue(value, MAP_STRING_STRING_TYPE);
return ImmutableMap.copyOf(t);
} catch (IOException e) {
throw new RuntimeException(
"Failed to create a Map from data. Bad json in metadata column?", e);
}
}
return ImmutableMap.of();
}
}
| 33.030303
| 88
| 0.712385
|
d6a572a9c564c2e8b99734d359c51fdec4161eef
| 14,380
|
/*
* An XML document type.
* Localname: a
* Namespace: xhtml:NPfIT:PresentationText
* Java type: uk.nhs.connect.npfit.presentationtext.ADocument
*
* Automatically generated - do not modify.
*/
package uk.nhs.connect.npfit.presentationtext.impl;
/**
* A document containing one a(@xhtml:NPfIT:PresentationText) element.
*
* This is a complex type.
*/
public class ADocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements uk.nhs.connect.npfit.presentationtext.ADocument
{
private static final long serialVersionUID = 1L;
public ADocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName A$0 =
new javax.xml.namespace.QName("xhtml:NPfIT:PresentationText", "a");
/**
* Gets the "a" element
*/
public uk.nhs.connect.npfit.presentationtext.ADocument.A getA()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.connect.npfit.presentationtext.ADocument.A target = null;
target = (uk.nhs.connect.npfit.presentationtext.ADocument.A)get_store().find_element_user(A$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "a" element
*/
public void setA(uk.nhs.connect.npfit.presentationtext.ADocument.A a)
{
generatedSetterHelperImpl(a, A$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "a" element
*/
public uk.nhs.connect.npfit.presentationtext.ADocument.A addNewA()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.connect.npfit.presentationtext.ADocument.A target = null;
target = (uk.nhs.connect.npfit.presentationtext.ADocument.A)get_store().add_element_user(A$0);
return target;
}
}
/**
* An XML a(@xhtml:NPfIT:PresentationText).
*
* This is a complex type.
*/
public static class AImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements uk.nhs.connect.npfit.presentationtext.ADocument.A
{
private static final long serialVersionUID = 1L;
public AImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName ID$0 =
new javax.xml.namespace.QName("", "id");
private static final javax.xml.namespace.QName HREF$2 =
new javax.xml.namespace.QName("", "href");
private static final javax.xml.namespace.QName IIREF$4 =
new javax.xml.namespace.QName("", "iiref");
private static final javax.xml.namespace.QName CLASS1$6 =
new javax.xml.namespace.QName("", "class");
/**
* Gets the "id" attribute
*/
public java.lang.String getId()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(ID$0);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "id" attribute
*/
public org.apache.xmlbeans.XmlNMTOKEN xgetId()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlNMTOKEN target = null;
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().find_attribute_user(ID$0);
return target;
}
}
/**
* True if has "id" attribute
*/
public boolean isSetId()
{
synchronized (monitor())
{
check_orphaned();
return get_store().find_attribute_user(ID$0) != null;
}
}
/**
* Sets the "id" attribute
*/
public void setId(java.lang.String id)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(ID$0);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(ID$0);
}
target.setStringValue(id);
}
}
/**
* Sets (as xml) the "id" attribute
*/
public void xsetId(org.apache.xmlbeans.XmlNMTOKEN id)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlNMTOKEN target = null;
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().find_attribute_user(ID$0);
if (target == null)
{
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().add_attribute_user(ID$0);
}
target.set(id);
}
}
/**
* Unsets the "id" attribute
*/
public void unsetId()
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_attribute(ID$0);
}
}
/**
* Gets the "href" attribute
*/
public java.lang.String getHref()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(HREF$2);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "href" attribute
*/
public uk.nhs.connect.npfit.presentationtext.LocalURI xgetHref()
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.connect.npfit.presentationtext.LocalURI target = null;
target = (uk.nhs.connect.npfit.presentationtext.LocalURI)get_store().find_attribute_user(HREF$2);
return target;
}
}
/**
* True if has "href" attribute
*/
public boolean isSetHref()
{
synchronized (monitor())
{
check_orphaned();
return get_store().find_attribute_user(HREF$2) != null;
}
}
/**
* Sets the "href" attribute
*/
public void setHref(java.lang.String href)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(HREF$2);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(HREF$2);
}
target.setStringValue(href);
}
}
/**
* Sets (as xml) the "href" attribute
*/
public void xsetHref(uk.nhs.connect.npfit.presentationtext.LocalURI href)
{
synchronized (monitor())
{
check_orphaned();
uk.nhs.connect.npfit.presentationtext.LocalURI target = null;
target = (uk.nhs.connect.npfit.presentationtext.LocalURI)get_store().find_attribute_user(HREF$2);
if (target == null)
{
target = (uk.nhs.connect.npfit.presentationtext.LocalURI)get_store().add_attribute_user(HREF$2);
}
target.set(href);
}
}
/**
* Unsets the "href" attribute
*/
public void unsetHref()
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_attribute(HREF$2);
}
}
/**
* Gets the "iiref" attribute
*/
public java.lang.String getIiref()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(IIREF$4);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "iiref" attribute
*/
public org.apache.xmlbeans.XmlNMTOKEN xgetIiref()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlNMTOKEN target = null;
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().find_attribute_user(IIREF$4);
return target;
}
}
/**
* True if has "iiref" attribute
*/
public boolean isSetIiref()
{
synchronized (monitor())
{
check_orphaned();
return get_store().find_attribute_user(IIREF$4) != null;
}
}
/**
* Sets the "iiref" attribute
*/
public void setIiref(java.lang.String iiref)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(IIREF$4);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(IIREF$4);
}
target.setStringValue(iiref);
}
}
/**
* Sets (as xml) the "iiref" attribute
*/
public void xsetIiref(org.apache.xmlbeans.XmlNMTOKEN iiref)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlNMTOKEN target = null;
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().find_attribute_user(IIREF$4);
if (target == null)
{
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().add_attribute_user(IIREF$4);
}
target.set(iiref);
}
}
/**
* Unsets the "iiref" attribute
*/
public void unsetIiref()
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_attribute(IIREF$4);
}
}
/**
* Gets the "class" attribute
*/
public java.lang.String getClass1()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(CLASS1$6);
if (target == null)
{
return null;
}
return target.getStringValue();
}
}
/**
* Gets (as xml) the "class" attribute
*/
public org.apache.xmlbeans.XmlNMTOKEN xgetClass1()
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlNMTOKEN target = null;
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().find_attribute_user(CLASS1$6);
return target;
}
}
/**
* True if has "class" attribute
*/
public boolean isSetClass1()
{
synchronized (monitor())
{
check_orphaned();
return get_store().find_attribute_user(CLASS1$6) != null;
}
}
/**
* Sets the "class" attribute
*/
public void setClass1(java.lang.String class1)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.SimpleValue target = null;
target = (org.apache.xmlbeans.SimpleValue)get_store().find_attribute_user(CLASS1$6);
if (target == null)
{
target = (org.apache.xmlbeans.SimpleValue)get_store().add_attribute_user(CLASS1$6);
}
target.setStringValue(class1);
}
}
/**
* Sets (as xml) the "class" attribute
*/
public void xsetClass1(org.apache.xmlbeans.XmlNMTOKEN class1)
{
synchronized (monitor())
{
check_orphaned();
org.apache.xmlbeans.XmlNMTOKEN target = null;
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().find_attribute_user(CLASS1$6);
if (target == null)
{
target = (org.apache.xmlbeans.XmlNMTOKEN)get_store().add_attribute_user(CLASS1$6);
}
target.set(class1);
}
}
/**
* Unsets the "class" attribute
*/
public void unsetClass1()
{
synchronized (monitor())
{
check_orphaned();
get_store().remove_attribute(CLASS1$6);
}
}
}
}
| 31.26087
| 152
| 0.48943
|
b5e39fb1104521ac58084f63cb62056b0fb6c455
| 870
|
package com.test.processor.bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
/*
* Created by wlx on 2020/2/5
*/
@Component
public class TestBeanPostProcessor implements BeanPostProcessor , PriorityOrdered {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("testDao")) {
System.out.println("BeforeInitialization0");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("testDao")) {
System.out.println("AfterInitialization0");
}
return bean;
}
@Override
public int getOrder() {
return 0;
}
}
| 25.588235
| 100
| 0.77931
|
190facc7553db5333eebcd4708e985114be65eed
| 8,405
|
package net.buycraft.plugin.bungeecord;
import com.bugsnag.Client;
import lombok.Getter;
import lombok.Setter;
import net.buycraft.plugin.IBuycraftPlatform;
import net.buycraft.plugin.bungeecord.command.*;
import net.buycraft.plugin.bungeecord.logging.BugsnagGlobalLoggingHandler;
import net.buycraft.plugin.bungeecord.logging.BugsnagLoggingHandler;
import net.buycraft.plugin.bungeecord.logging.BugsnagNilLogger;
import net.buycraft.plugin.bungeecord.util.AnalyticsUtil;
import net.buycraft.plugin.bungeecord.util.VersionCheck;
import net.buycraft.plugin.client.ApiClient;
import net.buycraft.plugin.client.ApiException;
import net.buycraft.plugin.client.ProductionApiClient;
import net.buycraft.plugin.config.BuycraftConfiguration;
import net.buycraft.plugin.data.responses.ServerInformation;
import net.buycraft.plugin.data.responses.Version;
import net.buycraft.plugin.execution.DuePlayerFetcher;
import net.buycraft.plugin.execution.placeholder.NamePlaceholder;
import net.buycraft.plugin.execution.placeholder.PlaceholderManager;
import net.buycraft.plugin.execution.placeholder.UuidPlaceholder;
import net.buycraft.plugin.execution.strategy.CommandExecutor;
import net.buycraft.plugin.execution.strategy.QueuedCommandExecutor;
import net.buycraft.plugin.util.Ipv4PreferDns;
import net.buycraft.plugin.util.VersionUtil;
import net.md_5.bungee.api.plugin.Plugin;
import okhttp3.Cache;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
public class BuycraftPlugin extends Plugin {
@Getter
@Setter
private ApiClient apiClient;
@Getter
private DuePlayerFetcher duePlayerFetcher;
@Getter
private final PlaceholderManager placeholderManager = new PlaceholderManager();
@Getter
private final BuycraftConfiguration configuration = new BuycraftConfiguration();
@Getter
private ServerInformation serverInformation;
@Getter
private OkHttpClient httpClient;
@Getter
private IBuycraftPlatform platform;
@Getter
private CommandExecutor commandExecutor;
@Override
public void onEnable() {
// Pre-initialization.
platform = new BungeeCordBuycraftPlatform(this);
// Initialize configuration.
getDataFolder().mkdir();
try {
Path configPath = getDataFolder().toPath().resolve("config.properties");
if (!configPath.toFile().exists()) {
configuration.fillDefaults();
configuration.save(configPath);
} else {
configuration.load(getDataFolder().toPath().resolve("config.properties"));
configuration.fillDefaults();
}
} catch (IOException e) {
throw new RuntimeException("Unable to load configuration!", e);
}
// Initialize API client.
// This has to be done partially async due to the SecurityManager.
FutureTask<Cache> cacheFutureTask = new FutureTask<>(new Callable<Cache>() {
@Override
public Cache call() throws Exception {
return new Cache(new File(getDataFolder(), "cache"), 1024 * 1024 * 10);
}
});
getProxy().getScheduler().runAsync(this, cacheFutureTask);
Cache cache;
try {
cache = cacheFutureTask.get();
} catch (InterruptedException | ExecutionException e) {
getLogger().log(Level.SEVERE, "Can't create cache", e);
cache = null;
}
httpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.writeTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)
.dispatcher(new Dispatcher(getExecutorService()))
.cache(cache)
.dns(new Ipv4PreferDns())
.build();
String serverKey = configuration.getServerKey();
if (serverKey == null || serverKey.equals("INVALID")) {
getLogger().info("Looks like this is a fresh setup. Get started by using 'buycraft secret <key>' in the console.");
} else {
getLogger().info("Validating your server key...");
final ApiClient client = new ProductionApiClient(configuration.getServerKey(), httpClient);
// Hack due to SecurityManager shenanigans.
FutureTask<Void> hackTask = new FutureTask<>(new Callable<Void>() {
@Override
public Void call() throws Exception {
updateInformation(client);
return null;
}
});
getProxy().getScheduler().runAsync(this, hackTask);
try {
hackTask.get();
} catch (InterruptedException | ExecutionException e) {
getLogger().severe(String.format("We can't check if your server can connect to Buycraft: %s", e.getMessage()));
}
apiClient = client;
}
// Check for latest version.
VersionCheck check = new VersionCheck(this, getDescription().getVersion());
try {
check.verify();
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Can't check for updates", e);
}
getProxy().getPluginManager().registerListener(this, check);
// Initialize placeholders.
placeholderManager.addPlaceholder(new NamePlaceholder());
placeholderManager.addPlaceholder(new UuidPlaceholder());
// Queueing tasks.
getProxy().getScheduler().schedule(this, duePlayerFetcher = new DuePlayerFetcher(platform, configuration.isVerbose()), 1, TimeUnit.SECONDS);
commandExecutor = new QueuedCommandExecutor(platform);
getProxy().getScheduler().schedule(this, (Runnable) commandExecutor, 50, 50, TimeUnit.MILLISECONDS);
// Register listener.
getProxy().getPluginManager().registerListener(this, new BuycraftListener(this));
// Initialize and register commands.
BuycraftCommand command = new BuycraftCommand();
command.getSubcommandMap().put("forcecheck", new ForceCheckSubcommand(this));
command.getSubcommandMap().put("secret", new SecretSubcommand(this));
command.getSubcommandMap().put("info", new InformationSubcommand(this));
command.getSubcommandMap().put("report", new ReportCommand(this));
getProxy().getPluginManager().registerCommand(this, command);
// Send data to Keen IO
if (serverInformation != null) {
getProxy().getScheduler().schedule(this, new Runnable() {
@Override
public void run() {
AnalyticsUtil.postServerInformation(BuycraftPlugin.this);
}
}, 0, 1, TimeUnit.DAYS);
}
// Set up Bugsnag.
// Hack due to SecurityManager shenanigans.
FutureTask<Client> clientInit = new FutureTask<>(new Callable<Client>() {
@Override
public Client call() throws Exception {
return new Client("cac4ea0fdbe89b5004d8ab8d5409e594", false);
}
});
getProxy().getScheduler().runAsync(this, clientInit);
try {
Client bugsnagClient = clientInit.get();
bugsnagClient.setAppVersion(getDescription().getVersion());
bugsnagClient.setLogger(new BugsnagNilLogger());
getProxy().getLogger().addHandler(new BugsnagGlobalLoggingHandler(bugsnagClient, this));
getLogger().addHandler(new BugsnagLoggingHandler(bugsnagClient, this));
} catch (InterruptedException | ExecutionException e) {
getLogger().log(Level.SEVERE, "Unable to initialize Bugsnag", e);
}
}
public void saveConfiguration() throws IOException {
Path configPath = getDataFolder().toPath().resolve("config.properties");
configuration.save(configPath);
}
public void updateInformation(ApiClient client) throws IOException, ApiException {
serverInformation = client.getServerInformation();
}
}
| 42.449495
| 148
| 0.665675
|
19019b2785473c316dca77e3547b553ae1468e31
| 423
|
package de.fhg.fokus.ims.core;
import javax.ims.core.Message;
import javax.ims.core.ServiceMethod;
public interface ServiceMethod2 extends ServiceMethod
{
void setRemoteUserId(String value);
Message getNextResponse();
String getFromTag();
String getToTag();
boolean sendNextRequest(String recipientAddress, int recipientPort) ;
void setReferenceInformationListener(ReferenceInformationListener listener);
}
| 21.15
| 77
| 0.808511
|
5f307a99fb046e4f6ee06eb5939b46d9eb286f9b
| 10,501
|
package br.system;
import br.dao.AlunoDAO;
import br.model.Aluno;
import java.util.List;
import java.util.Scanner;
public class Program {
public static final String RESET = "\u001B[0m";
public static final String WHITE = "\u001B[30m";
public static final String RED = "\u001B[31m";
public static final String GREEN = "\u001B[32m";
public static final String YELLOW = "\u001B[33m";
public static final String BLUE = "\u001B[34m";
public static final String PURPLE = "\u001B[35m";
public static final String CYAN = "\u001B[36m";
public static final String BLACK = "\u001B[37m";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int modo;
// escolha do modo
System.out.printf("%s= MODOS\n" +
"[1] Aluno\n" +
"[2] Não Aluno\n" +
"[3] Professor\n" +
"[4] Admin%s\n",
BLUE, RESET);
do {
System.out.print("Selecione o modo: ");
modo = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (modo < 1 || modo > 4)
System.out.printf("%s<!> Modo inválido. Digite novamente%s\n", RED, RESET);
} while (modo < 1 || modo > 4);
switch (modo) {
case 1 -> modoAluno();
case 2 -> modoNaoAluno();
case 3 -> modoProfessor();
case 4 -> modoAdmin();
}
}
public static void modoAluno() {
Scanner input = new Scanner(System.in);
AlunoDAO alunoDAO = new AlunoDAO();
List<Aluno> alunoList = alunoDAO.listar();
Aluno aluno;
int codAluno;
int confirmar;
int servico;
int continuar;
do {
do {
System.out.printf("%sInforme a sua matrícula: %s", WHITE, RESET);
codAluno = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (codAluno < 1 || codAluno >= alunoList.size())
System.out.printf("%s<!> Matrícula inválida. Digite novamente%s\n", RED, RESET);
} while (codAluno < 1 || codAluno >= alunoList.size());
aluno = alunoDAO.buscarPorId(codAluno);
System.out.printf("%sVocê é %s? [1] Confirmar [0] Cancelar%s\n", YELLOW, aluno.getNome(), RESET);
do {
System.out.print("Selecione: ");
confirmar = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (confirmar < 0 || confirmar > 1)
System.out.printf("%s<!> Digite novamente%s\n", RED, RESET);
} while (confirmar < 0 || confirmar > 1);
} while (confirmar != 1);
do {
System.out.printf("%s= SERVIÇOS E CONSULTAS\n" +
"[1] Consultar os cursos\n" +
"[2] Verificar notas\n" +
"[3] Reservar livros na biblioteca\n" +
"[4] Agendar uma reunião\n" +
"[5] Atualizar dados pessoais%s\n",
BLUE, RESET);
do {
System.out.print("Selecione o serviço: ");
servico = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (servico < 1 || servico > 5)
System.out.printf("%s<!> Serviço não encontrado. Digite novamente%s\n", RED, RESET);
} while (servico < 1 || servico > 5);
switch (servico) {
case 1 -> ModoNaoAluno.consultaCursos();
case 2 -> ModoAluno.consultaNotas(codAluno);
case 3 -> ModoAluno.reservarLivros(codAluno);
case 4 -> ModoAluno.agendamentoReuniao(codAluno);
case 5 -> ModoAluno.atualizarDados(codAluno);
}
System.out.printf("%sDeseja realizar mais algum serviço? [1] Sim [0] Não%s\n", YELLOW, RESET);
do {
System.out.print("Selecione: ");
continuar = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (continuar < 0 || continuar > 1)
System.out.printf("%s<!> Digite novamente%s\n", RED, RESET);
} while (continuar < 0 || continuar > 1);
} while (continuar == 1);
}
public static void modoNaoAluno() {
Scanner input = new Scanner(System.in);
int servico;
int continuar;
System.out.printf("%s-x- BEM VINDO! -x-%s\n", YELLOW, RESET);
do {
System.out.printf("%s= SERVIÇOS E CONSULTAS\n" +
"[1] Cadastro\n" +
"[2] Ver cursos%s\n",
BLUE, RESET);
do {
System.out.print("Selecione: ");
servico = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (servico < 1 || servico > 2)
System.out.printf("%s<!> Digite novamente.%s\n", RED, RESET);
} while (servico < 1 || servico > 2);
switch (servico) {
case 1 -> ModoNaoAluno.cadastroAluno();
case 2 -> ModoNaoAluno.consultaCursos();
}
System.out.printf("%sDeseja realizar mais algum serviço? [1] Sim [0] Não%s\n", YELLOW, RESET);
do {
System.out.print("Selecione: ");
continuar = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (continuar < 0 || continuar > 1)
System.out.printf("%s<!> Digite novamente%s\n", RED, RESET);
} while (continuar < 0 || continuar > 1);
} while (continuar == 1);
}
public static void modoProfessor() {
Scanner input = new Scanner(System.in);
int servico;
int continuar;
do {
System.out.printf("%s= SERVIÇOS E CONSULTAS\n" +
"[1] Cadastrar Notas\n" +
"[2] Ver alunos\n" +
"[3] Ver agendamentos marcados%s\n", BLUE, RESET);
do {
System.out.print("Selecione: ");
servico = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (servico < 1 || servico > 3)
System.out.printf("%s<!> Digite novamente.%s\n", RED, RESET);
} while (servico < 1 || servico > 3);
switch (servico) {
case 1 -> ModoProfessor.cadastroNotas();
case 2 -> ModoProfessor.consultarAlunos();
case 3 -> ModoProfessor.consultarAgendamento();
}
System.out.printf("%sDeseja realizar mais algum serviço? [1] Sim [0] Não%s\n", YELLOW, RESET);
do {
System.out.print("Selecione: ");
continuar = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (continuar < 0 || continuar > 1)
System.out.printf("%s<!> Digite novamente%s\n", RED, RESET);
} while (continuar < 0 || continuar > 1);
} while (continuar == 1);
}
public static void modoAdmin() {
Scanner input = new Scanner(System.in);
int servico;
int modoEdicao;
int continuar;
do {
System.out.printf("%s= SERVIÇOS\n" +
"[1] Editar Funcionários\n" +
"[2] Editar Cursos\n" +
"[3] Editar Disciplinas\n" +
"[4] Editar Livros%s\n", BLUE, RESET);
do {
System.out.print("Selecione: ");
servico = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (servico < 1 || servico > 4)
System.out.printf("%s<!> Digite novamente%s\n", RED, RESET);
} while (servico < 1 || servico > 4);
switch (servico) {
case 1 -> {
modoEdicao = escolherModo();
switch (modoEdicao) {
case 1 -> ModoAdmin.cadastroFuncionario();
case 2 -> ModoAdmin.atualizarFuncionario();
case 3 -> ModoAdmin.deletarFuncionario();
}
}
case 2 -> {
modoEdicao = escolherModo();
switch (modoEdicao) {
case 1 -> ModoAdmin.cadastroCurso();
case 2 -> ModoAdmin.atualizarCurso();
case 3 -> ModoAdmin.deletarCurso();
}
}
case 3 -> {
modoEdicao = escolherModo();
switch (modoEdicao) {
case 1 -> ModoAdmin.cadastroDisciplina();
case 2 -> ModoAdmin.atualizarDisciplina();
case 3 -> ModoAdmin.deletarDisciplina();
}
}
case 4 -> {
modoEdicao = escolherModo();
switch (modoEdicao) {
case 1 -> ModoAdmin.cadastroLivro();
case 2 -> ModoAdmin.atualizarLivro();
case 3 -> ModoAdmin.deletarLivro();
}
}
}
System.out.printf("%sDeseja realizar mais algum serviço? [1] Sim [0] Não%s\n", YELLOW, RESET);
do {
System.out.print("Selecione: ");
continuar = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (continuar < 0 || continuar > 1)
System.out.printf("%s<!> Digite novamente%s\n", RED, RESET);
} while (continuar < 0 || continuar > 1);
} while (continuar == 1);
}
public static int escolherModo() {
Scanner input = new Scanner(System.in);
int modoEdicao;
System.out.printf("%s= MODO DE EDIÇÃO\n" +
"[1] Cadastrar\n" +
"[2] Atualizar\n" +
"[3] Deletar%s\n", BLUE, RESET);
do {
System.out.print("Selecione: ");
modoEdicao = Integer.parseInt(input.nextLine().replaceAll("[^0-9]", ""));
if (modoEdicao < 1 || modoEdicao > 3)
System.out.printf("%s<!> Digite novamente%s\n", RED, RESET);
} while (modoEdicao < 1 || modoEdicao > 3);
return modoEdicao;
}
}
| 37.106007
| 109
| 0.48024
|
4e3942de37165f146201806798b8ef2840138991
| 1,464
|
package madgik.exareme.master.db;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class FinalUnionExecutor implements Runnable {
private ResultBuffer resultBuffer;
private PreparedStatement st;
private int noOfUnions;
private int results;
private boolean print;
public FinalUnionExecutor(ResultBuffer resultBuffer, PreparedStatement s, int unions, boolean print) {
super();
this.resultBuffer = resultBuffer;
this.st = s;
this.noOfUnions = unions;
this.results = 0;
this.print=print;
}
@Override
public void run() {
// System.out.println("abla");
synchronized (resultBuffer) {
while (true) {
//System.out.println("yep");
while (!resultBuffer.isEmpty()) {
List<Object> tuple = resultBuffer.getNext();
if(print){
System.out.println(tuple);
}
results++;
// for(int i=1;i<tuple.size()+1;i++){
// st.setObject(i, tuple.get(i-1));
// }
// st.addBatch();
}
// System.out.println("executing batch");
// System.out.println(resultBuffer.size());
// st.executeBatch();
resultBuffer.notifyAll();
if (resultBuffer.getFinished() == noOfUnions) {
System.out.println("results:" + results);
return;
}
try {
// System.out.println("final waiting");
resultBuffer.wait();
} catch (InterruptedException e) {
// System.out.println("inter");
}
}
}
}
}
| 22.875
| 103
| 0.653005
|
884f637c8f3968c4256689d5dbbfe153a9947e6a
| 1,384
|
package com.gitee.linzl.advanced;
//package com.nick.advanced;
//
//import org.springframework.kafka.annotation.KafkaListener;
//import org.springframework.kafka.annotation.PartitionOffset;
//import org.springframework.kafka.annotation.TopicPartition;
//import org.springframework.kafka.support.KafkaHeaders;
//import org.springframework.messaging.handler.annotation.Header;
//import org.springframework.messaging.handler.annotation.Payload;
//import org.springframework.stereotype.Component;
//
///**
// * Created by dreamcatchernick on 22/09/2017.
// */
//@Component
//public class AdvancedConsumer {
// @KafkaListener(topics = "${kafka.topic.advancedtopic}", containerFactory = "advancedKafkaListenerContainerFactory")
// public void receive(@Payload String payload, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) {
// System.out.println(String.format("From partition %d : %s", partition, payload));
// }
//
// @KafkaListener(containerFactory = "advancedKafkaListenerContainerFactory", topicPartitions = @TopicPartition(topic = "${kafka.topic.advancedtopic}", partitionOffsets = @PartitionOffset(partition = "0", initialOffset = "0")))
// public void receiveFromBegin(@Payload String payload, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) {
// System.out.println(String.format("Read all message from partition %d : %s", partition, payload));
// }
//
//}
| 49.428571
| 227
| 0.776012
|
4ed2c0c46c3d89894f97dd5a70d56697aa81c834
| 969
|
package top.itning.server.shwnotice.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import top.itning.server.shwnotice.entity.Notice;
import top.itning.server.shwnotice.repository.NoticeRepository;
import top.itning.server.shwnotice.service.NoticeService;
/**
* 通知服务实现
*
* @author itning
* @date 2019/5/4 17:04
*/
@Service
public class NoticeServiceImpl implements NoticeService {
private final NoticeRepository noticeRepository;
@Autowired
public NoticeServiceImpl(NoticeRepository noticeRepository) {
this.noticeRepository = noticeRepository;
}
@Override
public Flux<Notice> getAllNoticeByStudentId(String studentId) {
Notice notice = new Notice();
notice.setReceiveId(studentId);
return noticeRepository.findAll(Example.of(notice));
}
}
| 29.363636
| 67
| 0.768834
|
e3644c70e63d932c42699a4940c33a0012b52e0f
| 4,444
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.cassandra.test.microbench;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.apache.cassandra.dht.RandomPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.PendingRangeMaps;
import org.apache.cassandra.locator.Replica;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 1, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 50, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 3, jvmArgsAppend = "-Xmx512M")
@Threads(1)
@State(Scope.Benchmark)
public class PendingRangesBench
{
PendingRangeMaps pendingRangeMaps;
int maxToken = 256 * 100;
Multimap<Range<Token>, Replica> oldPendingRanges;
private Range<Token> genRange(String left, String right)
{
return new Range<Token>(new RandomPartitioner.BigIntegerToken(left), new RandomPartitioner.BigIntegerToken(right));
}
@Setup
public void setUp() throws UnknownHostException
{
pendingRangeMaps = new PendingRangeMaps();
oldPendingRanges = HashMultimap.create();
List<InetAddressAndPort> endpoints = Lists.newArrayList(InetAddressAndPort.getByName("127.0.0.1"),
InetAddressAndPort.getByName("127.0.0.2"));
for (int i = 0; i < maxToken; i++)
{
for (int j = 0; j < ThreadLocalRandom.current().nextInt(2); j ++)
{
Range<Token> range = genRange(Integer.toString(i * 10 + 5), Integer.toString(i * 10 + 15));
Replica replica = Replica.fullReplica(endpoints.get(j), range);
pendingRangeMaps.addPendingRange(range, replica);
oldPendingRanges.put(range, replica);
}
}
// add the wrap around range
for (int j = 0; j < ThreadLocalRandom.current().nextInt(2); j ++)
{
Range<Token> range = genRange(Integer.toString(maxToken * 10 + 5), Integer.toString(5));
Replica replica = Replica.fullReplica(endpoints.get(j), range);
pendingRangeMaps.addPendingRange(range, replica);
oldPendingRanges.put(range, replica);
}
}
@Benchmark
public void searchToken(final Blackhole bh)
{
int randomToken = ThreadLocalRandom.current().nextInt(maxToken * 10 + 5);
Token searchToken = new RandomPartitioner.BigIntegerToken(Integer.toString(randomToken));
bh.consume(pendingRangeMaps.pendingEndpointsFor(searchToken));
}
@Benchmark
public void searchTokenForOldPendingRanges(final Blackhole bh)
{
int randomToken = ThreadLocalRandom.current().nextInt(maxToken * 10 + 5);
Token searchToken = new RandomPartitioner.BigIntegerToken(Integer.toString(randomToken));
Set<Replica> replicas = new HashSet<>();
for (Map.Entry<Range<Token>, Collection<Replica>> entry : oldPendingRanges.asMap().entrySet())
{
if (entry.getKey().contains(searchToken))
replicas.addAll(entry.getValue());
}
bh.consume(replicas);
}
}
| 38.310345
| 123
| 0.691944
|
c021636e3594f2c770c9d141efafa4d33a8a9b35
| 3,149
|
package org.sa.rainbow.probes.test;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sa.rainbow.core.error.BadLifecycleStepException;
import org.sa.rainbow.translator.probes.AbstractProbe;
import org.sa.rainbow.translator.probes.IProbe.Kind;
import org.sa.rainbow.translator.probes.IProbe.State;
import auxtestlib.DefaultTCase;
public class ProbeLifecycleTest extends DefaultTCase {
class Probe extends AbstractProbe {
public Probe (String id, String type, Kind kind) {
super (id, type, kind);
}
}
private static String s_currentDirectory;
@BeforeClass
public static void rememberUserDir () {
s_currentDirectory = System.getProperty ("user.dir");
}
private Probe m_probe;
@After
public void pullDownProbe () {
if (m_probe != null) {
if (m_probe.lcState () == State.ACTIVE) {
m_probe.deactivate ();
}
if (m_probe.lcState () == State.INACTIVE) {
m_probe.destroy ();
}
}
}
@Before
public void createProbe () throws IOException {
configureTestProperties ();
m_probe = new Probe (UUID.randomUUID ().toString (), "test", Kind.SCRIPT);
}
protected void configureTestProperties () throws IOException {
File basePath = new File (System.getProperty ("user.dir"));
File testMasterDir = new File (basePath, "src/test/resources/RainbowTest/eseb");
System.setProperty ("user.dir", testMasterDir.getCanonicalPath ());
}
@Test
public void testProbeLifecycleCorrect () {
assertTrue (m_probe.lcState () == State.NULL);
m_probe.create ();
assertTrue (m_probe.lcState () == State.INACTIVE);
m_probe.activate ();
assertTrue (m_probe.lcState () == State.ACTIVE);
m_probe.deactivate ();
assertTrue (m_probe.lcState () == State.INACTIVE);
}
@Test (expected = BadLifecycleStepException.class)
public void testProbeLifecycleDeactivateNonActive () {
assertTrue (m_probe.lcState () == State.NULL);
m_probe.deactivate ();
}
@Test (expected = BadLifecycleStepException.class)
public void testProbeLifecycleActivateNonCreated () {
assertTrue (m_probe.lcState () == State.NULL);
m_probe.activate ();
}
@Test (expected = BadLifecycleStepException.class)
public void testProbeLifecycleActivateAlreadyActivated () {
assertTrue (m_probe.lcState () == State.NULL);
m_probe.create ();
m_probe.activate ();
m_probe.activate ();
}
@Test (expected = BadLifecycleStepException.class)
public void testProbeLifecycleDeactivateAlreadyDeactivated () {
assertTrue (m_probe.lcState () == State.NULL);
m_probe.create ();
m_probe.activate ();
m_probe.deactivate ();
m_probe.deactivate ();
}
}
| 31.178218
| 89
| 0.627501
|
cf033d36e5e2489e8ea702f341a2fd7bb2e50c44
| 463
|
package com.jbaysolutions.framework.websockets.response;
/**
* (c) JBay Solutions 2010-2012 All rights reserved.
* <p>
* User: RuiP
* Date: 24-01-2020
* Time: 19:30
*/
public class TrainingStartedMessage extends WSBaseResponse {
public String uuid;
public TrainingStartedMessage() {
this.type = WSBaseResponseType.TRAINING_STARTED;
}
public TrainingStartedMessage(String uuid) {
this();
this.uuid = uuid;
}
}
| 20.130435
| 60
| 0.673866
|
47c80fbf72f6514bd863bcdf27b42249a5d1e3a3
| 344
|
package org.wickedsource.budgeteer.imports.api;
public class InvalidFileFormatException extends Exception {
private String fileName;
public InvalidFileFormatException(String message, String fileName){
super(message);
this.fileName = fileName;
}
public String getFileName(){
return fileName;
}
}
| 20.235294
| 71
| 0.706395
|
e10611b225026bd89abacacb991d7c39974d30e3
| 598
|
package cn.az.replica.mall.service;
import cn.az.replica.mall.controller.vo.ShopCartVo;
import cn.az.replica.mall.entity.ShopCart;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* The interface Shopping cart item service.
*
* @author az
*/
public interface IShopCartService extends IService<ShopCart> {
/**
* Save cart.
*
* @param item the item
*/
void saveCart(ShopCart item);
/**
* Gets cart.
*
* @param userId the user id
* @return the cart
*/
List<ShopCartVo> getCart(Long userId);
}
| 19.290323
| 62
| 0.658863
|
72c68be5fff8fbeee14289594d52c8f606af5921
| 2,681
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands;
import javax.swing.RootPaneContainer;
import PursellJaques.FalconFXSwerveDrive;
import PursellJaques.FalconFXSwerveModule;
import PursellJaques.N_PID;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.Constants;
import frc.robot.RobotContainer;
public class DriveDistanceCommand extends CommandBase {
// Instance variables
private double targetDistance;
private N_PID distancePIDController;
private double counter;
/** Creates a new DriveDistanceCommand. */
public DriveDistanceCommand(double targetDistance) {
// Use addRequirements() here to declare subsystem dependencies.
this.targetDistance = targetDistance;
distancePIDController = new N_PID(Constants.DDC_KP, Constants.DDC_KI, Constants.DDC_KD);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
for(FalconFXSwerveModule swerveModule: RobotContainer.swerveDrive.swerveModules){
swerveModule.driveMotor.setSelectedSensorPosition(0.0);
}
distancePIDController.reset(0);
counter = 0;
RobotContainer.cancelAllExcept(this);
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
// Calculate average sensor position
double sensorAccumulator = 0;
for(FalconFXSwerveModule swerveModule: RobotContainer.swerveDrive.swerveModules){
sensorAccumulator += swerveModule.driveMotor.getSelectedSensorPosition();
}
sensorAccumulator /= RobotContainer.swerveDrive.swerveModules.length;
// Drive forward using PID
RobotContainer.swerveDrive.drive(0, distancePIDController.run(sensorAccumulator, targetDistance), 0);
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {}
// Returns true when the command should end.
@Override
public boolean isFinished() {
// Get average sensor position
double sensorAccumulator = 0;
for(FalconFXSwerveModule swerveModule: RobotContainer.swerveDrive.swerveModules){
sensorAccumulator += swerveModule.driveMotor.getSelectedSensorPosition();
}
sensorAccumulator /= RobotContainer.swerveDrive.swerveModules.length;
if(sensorAccumulator < targetDistance * (1 + Constants.DDC_TOLERANCE) && sensorAccumulator > targetDistance * (1 - Constants.DDC_TOLERANCE)){
counter ++;
}
else{
counter = 0;
}
return (counter > Constants.DDC_MAX_COUNT);
}
}
| 34.371795
| 145
| 0.759418
|
587379affcd71084c594c267d879c1bc2587c48c
| 1,187
|
package jcache.web.rest;
import java.net.URI;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.DELETE;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import jcache.web.service.CalcService;
@RequestScoped
@Path("calc")
public class CalcResource {
@Inject
private CalcService calcService;
@GET
@Path("add")
public String add(@QueryParam("p1") int p1, @QueryParam("p2") int p2) {
return "Result = " + calcService.add(p1, p2);
}
@GET
@Path("update")
public void update(@QueryParam("p1") int p1, @QueryParam("p2") int p2) {
calcService.update(p1, p2, p1 + p2);
}
@DELETE
@Path("delete")
public void delete(@QueryParam("p1") int p1, @QueryParam("p2") int p2) {
calcService.remove(p1, p2);
}
@DELETE
@Path("delete-all")
public void deleteAll() {
calcService.removeAll();
}
}
| 22.826923
| 76
| 0.671441
|
1baa5bf27307b9dbab42df5355a6f9c7826e1063
| 1,834
|
package se.cygni.snake.arena;
import com.google.common.eventbus.EventBus;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import se.cygni.snake.game.GameManager;
import java.util.HashMap;
import java.util.Map;
@Component
public class ArenaSelectionManager {
public static final String OFFICIAL_ARENA_NAME = "official";
private static final Logger log = LoggerFactory.getLogger(ArenaSelectionManager.class);
private final GameManager gameManager;
private final EventBus globalEventBus;
private Map<String, ArenaManager> arenas = new HashMap<>();
@Autowired
public ArenaSelectionManager(GameManager gameManager, EventBus globalEventBus) {
this.gameManager = gameManager;
this.globalEventBus = globalEventBus;
}
public synchronized ArenaManager getArena(String arenaName) {
if (StringUtils.isEmpty(arenaName)) {
arenaName = OFFICIAL_ARENA_NAME;
}
ArenaManager ret = arenas.get(arenaName);
if (ret == null) {
ret = createNewArenaManager();
ret.setArenaName(arenaName);
if (arenaName.equals(OFFICIAL_ARENA_NAME)) {
ret.setRanked(true);
}
arenas.put(arenaName, ret);
log.info("Created new arena with name "+arenaName);
}
return ret;
}
private ArenaManager createNewArenaManager() {
return new ArenaManager(gameManager, globalEventBus);
}
@Scheduled(fixedRate = 1000)
public void runGameScheduler() {
arenas.values().forEach(ArenaManager::runGameScheduler);
}
}
| 30.065574
| 91
| 0.7012
|
3a05c6665d20de42ff52728b7e1f262058474097
| 3,280
|
package co.lq.modules.shop.rest;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import co.lq.aop.log.Log;
import co.lq.modules.shop.domain.Brand;
import co.lq.modules.shop.service.BrandService;
import co.lq.modules.shop.service.dto.BrandQueryCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @author billy
* @date 2020-03-27
*/
@Api(tags = "品牌包管理")
@RestController
@RequestMapping("/api/brand")
public class BrandController {
private final BrandService storeBrandService;
public BrandController(BrandService storeBrandService) {
this.storeBrandService = storeBrandService;
}
@Log("导出数据")
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('storeBrand:list')")
public void download(HttpServletResponse response, BrandQueryCriteria criteria) throws IOException {
storeBrandService.download(storeBrandService.queryAll(criteria), response);
}
@GetMapping
@Log("查询品牌包")
@ApiOperation("查询品牌包")
@PreAuthorize("@el.check('storeBrand:list')")
public ResponseEntity<Object> getStoreBrands(BrandQueryCriteria criteria, Pageable pageable) {
return new ResponseEntity<>(storeBrandService.queryAll(criteria, pageable), HttpStatus.OK);
}
@GetMapping(value = "detail/{id}")
@Log("查询品牌包")
@ApiOperation("查询品牌包")
@PreAuthorize("@el.check('storeBrand:list')")
public ResponseEntity<Object> getStoreBrandInfo(@PathVariable(value = "id") Long id) {
return new ResponseEntity<>(storeBrandService.findById(id), HttpStatus.OK);
}
@PostMapping
@Log("新增品牌包")
@ApiOperation("新增品牌包")
@PreAuthorize("@el.check('storeBrand:add')")
public ResponseEntity<Object> create(@Validated @RequestBody Brand resources) {
return new ResponseEntity<>(storeBrandService.create(resources), HttpStatus.CREATED);
}
@PutMapping
@Log("修改品牌包")
@ApiOperation("修改品牌包")
@PreAuthorize("@el.check('storeBrand:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody Brand resources) {
storeBrandService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除品牌包")
@ApiOperation("删除品牌包")
@PreAuthorize("@el.check('storeBrand:del')")
@DeleteMapping
public ResponseEntity<Object> deleteAll(@RequestBody Long[] ids) {
storeBrandService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
| 35.268817
| 104
| 0.746951
|
5308e087a725daf07c10bab3d687ea27cc3de85b
| 8,658
|
/**
* Copyright 2017 Alessandro Simi
*
* 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.exemplary.aws;
import com.almworks.sqlite4java.SQLite;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.exceptions.AmazonServiceExceptionType;
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
import com.amazonaws.services.dynamodbv2.local.server.LocalDynamoDBServerHandler;
import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest;
import com.amazonaws.services.dynamodbv2.model.ListTablesRequest;
import com.amazonaws.services.dynamodbv2.model.ListTablesResult;
import java.io.File;
import java.net.ServerSocket;
import java.net.URISyntaxException;
import java.util.logging.Logger;
/**
* Local server that implements Aws DynamoDB API.
*/
public class DynamoDBServer {
private static final Logger logger = Logger.getLogger(DynamoDBServer.class.getName());
private final static String EMPTY_CORS_PARAMS = null;
private final int port;
private final RequestHandler requestHandler;
private final DynamoDBProxyServer server;
public DynamoDBServer(int port) {
this.port = port;
requestHandler = new RequestHandler();
LocalDynamoDBServerHandler serverHandler = new LocalDynamoDBServerHandler(requestHandler, EMPTY_CORS_PARAMS);
server = new DynamoDBProxyServer(port, serverHandler);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
DynamoDBServer.this.stop();
}
});
}
public DynamoDBServer() {
this(findPort());
}
private static int findPort() {
try {
ServerSocket socket = null;
try {
socket = new ServerSocket(0);
socket.setReuseAddress(true);
return socket.getLocalPort();
} finally {
socket.close();
}
} catch (Exception e) {
throw new IllegalStateException("Impossible to find a free port");
}
}
/**
* Start the server.
*/
public void start() {
loadSqlLiteLibraries();
try {
logger.info("Start dynamo db server on port " + port);
server.start();
} catch (Exception e) {
throw new IllegalStateException("Impossible to start Dynamo DB Server", e);
}
}
private void loadSqlLiteLibraries() {
SqliteLibrary.unload();
File sqLiteJar = getSqLiteJar();
File sqLiteRoot = getSqLiteRoot(sqLiteJar);
boolean loadedLibraries = loadLibrariesFromSubDirectories(sqLiteRoot);
if (!loadedLibraries) throw new IllegalStateException("Impossible to load sql lite libraries");
}
private File getSqLiteJar() {
try {
return new File(SQLite.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (URISyntaxException e) {
throw new IllegalStateException("Impossible to load sql lite jar", e);
}
}
private final static String SQLITE = "sqlite4java";
private File getSqLiteRoot(File jar) {
File parent = jar;
while (parent.getParentFile().getPath().contains(SQLITE)) {
parent = parent.getParentFile();
}
return parent;
}
private boolean loadLibrariesFromSubDirectories(File directory) {
boolean result = loadLibrariesFromDirectory(directory);
if (result) return true;
else for(File file : directory.listFiles()) if (file.isDirectory()) {
if (loadLibrariesFromSubDirectories(file)) return true;
}
return false;
}
private boolean loadLibrariesFromDirectory(File directory) {
try {
String path = directory.getPath();
SQLite.setLibraryPath(path);
SQLite.loadLibrary();
return true;
} catch (Exception e) {
return false;
}
}
/**
* Stop the server.
*/
public void stop() {
try {
logger.info("Stop dynamo db server");
server.stop();
} catch (Exception e) {
throw new IllegalStateException("Impossible to stop Dynamo DB Server", e);
}
}
/**
* @return the server endpoint. The URI always point to localhost while
* the port depends how the server has been created.
*/
public String getEndpoint() {
return "http://localhost:" + port;
}
/**
* Reset the server status, bringing it back to the same position
* after the creation. All the tables will be deleted, forced
* errors cleaned and provisioned throughput reset.
*/
public void reset() {
doesNotFail();
deleteAllTables();
}
private void deleteAllTables() {
AmazonDynamoDBClient client = new AmazonDynamoDBClient(new BasicAWSCredentials("accessKey", "secretKey"));
client.setEndpoint(getEndpoint());
ListTablesResult result = client.listTables(new ListTablesRequest());
for (String tableName : result.getTableNames()) {
client.deleteTable(new DeleteTableRequest(tableName));
}
client.shutdown();
}
/**
* The server behaves normally without any forces failures.
*/
public void doesNotFail() {
requestHandler.doesNotFail();
}
/**
* The server is forced to fail with a predefined exception.
* @param exception of type {@link AmazonServiceExceptionType}.
* @return the server injected failure.
*/
public InjectedFailure failsWith(AmazonServiceExceptionType exception) {
return new InjectedFailure(
exception.getResponseStatus(),
exception.getErrorCode(),
exception.getMessage(),
null
);
}
/**
* The server is forced to fail with a an response code.
* @param responseCode the error response code.
* @return the server injected failure.
*/
public InjectedFailure failsWithResponseCode(int responseCode) {
return new InjectedFailure(responseCode, "", "", null);
}
public class InjectedFailure {
final int responseCode;
final String errorCode;
final String errorMessage;
final ErrorCondition<? extends AmazonWebServiceRequest> errorCondition;
private InjectedFailure(int responseCode, String errorCode, String errorMessage, ErrorCondition<? extends AmazonWebServiceRequest> errorCondition) {
this.responseCode = responseCode;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.errorCondition = errorCondition;
requestHandler.setInjectedFailure(this);
}
/**
* The server is forced to fail with a an error code.
* @param errorCode the string summary of the error code.
* @return the server injected failure.
*/
public InjectedFailure withAwsErrorCode(String errorCode) {
return new InjectedFailure(responseCode, errorCode, errorMessage, errorCondition);
}
/**
* The server is forced to fail with a an error message.
* @param errorMessage the string summary of the error message.
* @return the server injected failure.
*/
public InjectedFailure withAwsErrorMessage(String errorMessage) {
return new InjectedFailure(responseCode, errorCode, errorMessage, errorCondition);
}
/**
* The server is forced to fail for a specific request depending on the condition.
* @param errorCondition the failing condition.
* @return the server injected failure.
*/
public InjectedFailure withErrorCondition(ErrorCondition<? extends AmazonWebServiceRequest> errorCondition) {
return new InjectedFailure(responseCode, errorCode, errorMessage, errorCondition);
}
}
}
| 34.357143
| 156
| 0.653615
|
f182495c551399526f45a613adc433482086e121
| 3,791
|
package com.safie.rtsp.action;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.rtsp.RtspHeaders;
import io.netty.handler.codec.rtsp.RtspHeaders.Names;
import io.netty.handler.codec.rtsp.RtspResponseStatuses;
import io.netty.handler.codec.rtsp.RtspVersions;
import java.util.concurrent.Callable;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.safie.rtsp.core.RtspController;
class Action implements Callable<HttpResponse> {
private Logger logger = LogManager.getLogger(Action.class);
protected HttpRequest request;
public Action(HttpRequest request) {
this.request = request;
}
@Override
public HttpResponse call() throws Exception {
return internalServerErrorWithoutCseq();
}
protected String checkCseq(){
String cseq = request.headers().get(Names.CSEQ);
if (null == cseq || "".equals(cseq)) {
logger.error("cesq is null.........");
return null;
}else{
return cseq;
}
}
protected String getRequire(){
String require = request.headers().get(Names.REQUIRE);
if (null == require || "".equals(require)
|| (!require.equals(RtspController.REQUIRE_VALUE_NGOD_R2))) {
return null;
}else{
return require;
}
}
protected boolean checkRequire(){
String require = getRequire();
if (require == null) return true;
else{
logger.error("option not supported : "+ getRequire());
// 対応しているかどうかのチェックをすること
return false;
}
}
protected HttpResponse internalServerErrorWithoutCseq(){
HttpResponse response =
new DefaultFullHttpResponse(RtspVersions.RTSP_1_0,
RtspResponseStatuses.INTERNAL_SERVER_ERROR);
response.headers().set(Names.SERVER, RtspController.SERVER);
response.headers().set("OnDemandSessionId", request.headers().get("OnDemandSessionId"));
return response;
}
protected HttpResponse internalServerErrorWithCseq(){
HttpResponse response =
new DefaultFullHttpResponse(RtspVersions.RTSP_1_0,
RtspResponseStatuses.INTERNAL_SERVER_ERROR);
response.headers().set(HttpHeaders.Names.SERVER, RtspController.SERVER);
response.headers().set(RtspHeaders.Names.CSEQ, request.headers().get(RtspHeaders.Names.CSEQ));
String odsi = request.headers().get("OnDemandSessionId");
if (odsi != null) response.headers().set("OnDemandSessionId", odsi);
return response;
}
protected HttpResponse optionNotSupported(){
HttpResponse response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0,
RtspResponseStatuses.OPTION_NOT_SUPPORTED);
response.headers().set(HttpHeaders.Names.SERVER, RtspController.SERVER);
response.headers().set(RtspHeaders.Names.CSEQ, request.headers().get(RtspHeaders.Names.CSEQ));
response.headers().set(RtspHeaders.Names.UNSUPPORTED, getRequire());
String odsi = request.headers().get("OnDemandSessionId");
if (odsi != null) response.headers().set("OnDemandSessionId", odsi);
return response;
}
protected HttpResponse badRequestResponse(){
HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.BAD_REQUEST);
response.headers().set(Names.SERVER, RtspController.SERVER);
response.headers().set(Names.CSEQ, request.headers().get(Names.CSEQ));
String odsi = request.headers().get("OnDemandSessionId");
if (odsi != null) response.headers().set("OnDemandSessionId", odsi);
return response;
}
}
| 34.779817
| 109
| 0.723556
|
a0aacb3374f01aeb060b4f87af0cd815353b239a
| 6,496
|
package com.team2.controller.admin;
import com.github.pagehelper.PageInfo;
import com.team2.pojo.base.CountInfo;
import com.team2.pojo.cmt.Category;
import com.team2.pojo.cmt.Information;
import com.team2.pojo.cmt.Report;
import com.team2.pojo.sys.User;
import com.team2.service.cmt.CategoryService;
import com.team2.service.cmt.InformationService;
import com.team2.service.cmt.ReportService;
import com.team2.service.sys.UserService;
import com.team2.utils.UserUtil;
import com.team2.vo.cmt.CategoryQuery;
import com.team2.vo.cmt.InformationQuery;
import com.team2.vo.cmt.ReportQuery;
import com.team2.vo.sys.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
@RequestMapping("/admin")
@Controller
public class AdminController {
@Autowired
public UserService userService;
@Autowired
public InformationService informationService;
@Autowired
public CategoryService categoryService;
@Autowired
public ReportService reportService;
@RequestMapping("/login")
public String login() {
return "/admin/login";
}
// @PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping("/welcome")
public String welcome(Model model) {
User user = UserUtil.getLoginUser();
CountInfo countInfo = informationService.getCountInfo();
model.addAttribute("userInfo",user);
model.addAttribute("countInfo",countInfo);
return "/admin/welcome";
}
// @PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping("/index")
public String index(Model model) {
User user = UserUtil.getLoginUser();
model.addAttribute("user",user);
return "/admin/index";
}
// @PreAuthorize("hasAuthority('ADMIN')")
@GetMapping(value="/cateEdit")
public String cateEdit(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "type", required = true) String type,
Model model) {
//类型0:需求1:资源(字符长度为1-1)
if(page == null) page = 1;
CategoryQuery categoryQuery = new CategoryQuery();
categoryQuery.setType(type);
PageInfo<Category> cateList = categoryService.list(page,10,categoryQuery);
model.addAttribute("cateList",cateList);
model.addAttribute("type",Integer.valueOf(type));
return "/admin/cateEdit";
}
// @PreAuthorize("hasAuthority('ADMIN')")
@GetMapping(value="/infoDetial")
public String cateEdit(@RequestParam(value = "id", required = false) Long id,
Model model) {
Information information = informationService.getById(id);
model.addAttribute("info",information);
return "/admin/infoDetial";
}
// @PreAuthorize("hasAuthority('ADMIN')")
@GetMapping(value="/userList")
public String userList(@RequestParam(value = "page", required = false) Integer page,
Model model) {
if(page == null) page = 1;
PageInfo<User> userList = userService.list(page,10,new UserQuery());
model.addAttribute("userList",userList);
return "/admin/userList";
}
// @PreAuthorize("hasAuthority('ADMIN')")
@GetMapping(value="/infoList")
public String infoList(@RequestParam(value = "page", required = false) Integer page,
@RequestParam(value = "type", required = true) String type,
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "cateId", required = false) Long cateId,
Model model) {
if(page == null) page = 1;
InformationQuery informationQuery = new InformationQuery();
informationQuery.setType(type);
if(title != null){
informationQuery.setTitle(title);
}
if(cateId != null && cateId >= 0){
informationQuery.setCategoryId(cateId);
}
PageInfo<Information> infoList = informationService.listDetail(page,10,informationQuery);
List<String> endTimeList = new ArrayList<>();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for(Information info : infoList.getList()){
if(info.getEndTime() == null){
endTimeList.add("未设置");
}else {
endTimeList.add(df.format(info.getEndTime()));
}
if(info.getPicture() == null){
info.setPicture("");
}
}
CategoryQuery categoryQuery = new CategoryQuery();
categoryQuery.setType(type);
List<Category> categoryList = categoryService.listAll(categoryQuery);
Category everyCate = new Category();
everyCate.setName("所有分类");
everyCate.setId(Long.valueOf(-1));
categoryList.add(0,everyCate);
model.addAttribute("infoList",infoList);
model.addAttribute("endTimeList",endTimeList);
model.addAttribute("type",Integer.valueOf(type));
model.addAttribute("cateList",categoryList);
return "/admin/infoList";
}
// @PreAuthorize("hasAuthority('ADMIN')")
@GetMapping(value="/report")
public String report(@RequestParam(value = "page", required = false) Integer page,
Model model) {
if(page == null) page = 1;
PageInfo<Report> reportList = reportService.list(page,10,new ReportQuery());
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Information> infoList = new ArrayList<>();
for(Report report : reportList.getList()){
report.setMemo(df.format(report.getCreateTime()));
infoList.add(informationService.getById(report.getInformationId()));
}
model.addAttribute("reportList",reportList);
model.addAttribute("infoList",infoList);
return "/admin/report";
}
}
| 40.347826
| 98
| 0.636392
|
bee2891e22d314af30a160d45398fba54d02f005
| 1,090
|
package com.github.white.at.framework.message;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Service;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Data
@Slf4j
@Service
@ServerEndpoint("/api/websocket/{sid}")
public class WebSocketServer {
private Session session;
private String sid;
@OnOpen
public void open(Session session, @PathParam("sid") String sid) {
this.session = session;
this.sid = sid;
WssHolder.get().add(this);
}
@OnClose
public void close() {
WssHolder.get().sub(this);
}
@OnMessage
public void message(String message, Session session) {
WssHolder.get().sendMessage(this, message);
}
@OnError
public void error(Session session, Throwable t) {
log.error("An error occurred", t);
}
}
| 21.8
| 69
| 0.702752
|
7983652cb4db51193f9daa780db1f05c61acc502
| 1,182
|
package com.yaamani.satellitesimulation.SatellitesOrrbits;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
/**
* Created by Yamani on 3/25/18.
*/
public abstract class Orbit {
private Satellite satellite;
protected double orbitalPeriod;
private long startTime;
private double currentTime;
public Orbit(Satellite satellite) {
this.satellite = satellite;
}
public abstract void updateSatellite();
public abstract void drawPath(ShapeRenderer shapeRenderer);
protected abstract void setOrbitalPeriod();
public double getOrbitalPeriod() {
if (orbitalPeriod == 0) setOrbitalPeriod();
return orbitalPeriod;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public double getCurrentTime() {
return currentTime;
}
public void setCurrentTime(double currentTime) {
this.currentTime = currentTime;
}
public Satellite getSatellite() {
return satellite;
}
public void setSatellite(Satellite satellite) {
this.satellite = satellite;
}
}
| 22.730769
| 63
| 0.680203
|
528d7d83e7de2e4f617ef930590e8cc81d359c47
| 647
|
package service;
import service.jerarquia.AnimalService;
import service.jerarquia.GatoService;
import service.jerarquia.PerroService;
public class ServiceFactory {
public static Service getService(String service){
Service result = null;
switch(service){
case "Casa":
result = new CasaService();
break;
case "Direccion":
result = new DireccionService();
break;
case "Persona":
result = new PersonaService();
break;
case "Animal":
result = new AnimalService();
break;
case "Perro":
result = new PerroService();
break;
case "Gato":
result = new GatoService();
break;
}
return result;
}
}
| 19.029412
| 50
| 0.68779
|
8aef19bc662b3216630c392fffa768682a53ecc6
| 3,536
|
package io.polyglotted.elastic.admin;
import io.polyglotted.common.model.MapResult;
import io.polyglotted.common.util.MapBuilder;
import io.polyglotted.common.util.TokenUtil;
import lombok.SneakyThrows;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import java.util.List;
import java.util.Map;
import static io.polyglotted.common.util.BaseSerializer.deserialize;
import static io.polyglotted.common.util.BaseSerializer.serialize;
import static io.polyglotted.common.util.ListBuilder.immutableList;
import static io.polyglotted.common.util.MapRetriever.optStr;
import static io.polyglotted.common.util.NullUtil.nonNull;
import static io.polyglotted.elastic.admin.Type.TYPE_DOC;
import static io.polyglotted.elastic.search.ExprConverter.buildFilter;
import static io.polyglotted.elastic.search.Expressions.allIndex;
import static io.polyglotted.elastic.search.Expressions.approvalRejected;
import static io.polyglotted.elastic.search.Expressions.archiveIndex;
import static io.polyglotted.elastic.search.Expressions.liveIndex;
import static io.polyglotted.elastic.search.Expressions.pendingApproval;
import static org.elasticsearch.client.Requests.createIndexRequest;
import static org.elasticsearch.common.xcontent.XContentType.JSON;
@SuppressWarnings({"unused", "WeakerAccess"})
public abstract class IndexRequestor {
private static final Map<String, QueryBuilder> FILTER_BUILDERS = MapBuilder.<String, QueryBuilder>immutableMapBuilder()
.put("ALL", buildFilter(allIndex())).put("LIVE", buildFilter(liveIndex())).put("ARCHIVE", buildFilter(archiveIndex()))
.put("PENDING", buildFilter(pendingApproval())).put("REJECTED", buildFilter(approvalRejected())).build();
public static String indexName(IndexSetting setting) { return nonNull(optStr(setting.mapResult, "index_name"), TokenUtil::uniqueToken); }
public static Alias aliasFrom(String name, String filter) { return new Alias(name).filter(FILTER_BUILDERS.get(filter)); }
public static String indexFile(IndexSetting setting, Type type, String alias) { return indexFile(setting, type, alias, immutableList()); }
@SneakyThrows public static String indexFile(IndexSetting setting, Type mapping, String writeAlias, List<Alias> readAliases) {
CreateIndexRequest request = createIndexRequest(indexName(setting))
.updateAllTypes(true).settings(setting.toJson(), JSON).mapping(TYPE_DOC, mapping.toJson(), JSON);
if (writeAlias != null) { request.alias(new Alias(writeAlias)); }
for (Alias alias : readAliases) { request.alias(alias); }
XContentBuilder builder = XContentFactory.jsonBuilder();
request.toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.close();
return builder.string();
}
public static String templateFile(IndexSetting setting, Type type, String alias) { return templateFile(setting, type, alias, immutableList()); }
@SneakyThrows public static String templateFile(IndexSetting setting, Type mapping, String writeAlias, List<Alias> readAliases) {
MapResult result = deserialize(indexFile(setting, mapping, null, readAliases));
result.put("index_patterns", immutableList(writeAlias));
return serialize(result);
}
}
| 56.126984
| 148
| 0.786199
|
be0dc8014d9befbea775c8287fd77a3871afd9c1
| 1,528
|
/******************************************************************************
** Copyright (c) 2014-2015 Basis Technology Corporation.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
******************************************************************************/
package com.basistech.rosette.apimodel.jackson;
import java.io.IOException;
import com.basistech.rosette.apimodel.AccuracyMode;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
/**
* Arrange for {@link AccuracyMode} to serialize as its code.
*/
public class AccuracyModeDeserializer extends StdDeserializer<AccuracyMode> {
public AccuracyModeDeserializer() {
super(AccuracyMode.class);
}
@Override
public AccuracyMode deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
String code = jp.getText();
return AccuracyMode.forValue(code);
}
}
| 37.268293
| 100
| 0.67212
|
8f729cc5ac9da9f6f21f10041cec0714523ae9d1
| 1,397
|
/*
* Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED
*
* 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://mindorks.com/license/apache-v2
*
* 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 ai.aiprog.template.di.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier;
/**
* Author : Arvindo Mondal
* Created on : 09-05-2019
* Email : arvindo@aiprog.ai
* Company : AIPROG
* Designation : Programmer
* About : I am a human can only think, I can't be a person like machine which have lots of memory and knowledge.
* Quote : No one can measure limit of stupidity but stupid things bring revolutions
* Strength : Never give up
* Motto : To be known as great Mathematician
* Skills : Algorithms and logic
* Website : www.aiprog.ai
*/
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiService {
}
| 32.488372
| 120
| 0.709377
|
cc6f3df13eecd273cea8930188d9b1620c5ad99f
| 2,974
|
package de.demmer.dennis.autopost.controller;
import de.demmer.dennis.autopost.entities.user.Facebookuser;
import de.demmer.dennis.autopost.services.BugReportService;
import de.demmer.dennis.autopost.services.facebook.FacebookService;
import de.demmer.dennis.autopost.services.userhandling.SessionService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
@Log4j2
@Controller
public class ErrorControllerImpl implements ErrorController {
@Autowired
BugReportService bugReportService;
@Autowired
SessionService sessionService;
@Autowired
FacebookService facebookService;
/**
* Is called when an unspecific error is thrown
*
* @param model
* @return
*/
@GetMapping(value = "/error")
public String error(Model model){
Facebookuser activeUser = sessionService.getActiveUser();
if (activeUser != null) {
model.addAttribute("pageList", activeUser.getPageList());
model.addAttribute("pageName", "Choose Facebook page");
}
model.addAttribute("loginlink", facebookService.createFacebookAuthorizationURL());
return "error";
}
/**
* Mapped by the "Send message" button on the bug report form
*
* @param firstName
* @param lastName
* @param replyAdress
* @param bugType
* @param message
* @param model
* @return
*/
@PostMapping(value = "/bugreport")
public String bugreport(@RequestParam(value = "firstName") String firstName,
@RequestParam(value = "lastName") String lastName,
@RequestParam(value = "replyAdress") String replyAdress,
@RequestParam(value = "bugType") String bugType,
@RequestParam(value = "message") String message, Model model){
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequestUri();
builder.scheme("https");
URI newUri = builder.build().toUri();
bugReportService.sendMail(firstName,lastName,message,replyAdress,bugType,newUri.toString());
Facebookuser activeUser = sessionService.getActiveUser();
if (activeUser!=null) model.addAttribute("pageList", activeUser.getPageList());
model.addAttribute("loginlink", facebookService.createFacebookAuthorizationURL());
return "mailsent";
}
@Override
public String getErrorPath() {
return "/error";
}
}
| 33.044444
| 100
| 0.697377
|
aab37b4cab8b729ad1346e26b5515e6304cf56d3
| 520
|
package co.airy.core.api.admin;
import co.airy.avro.communication.Channel;
import co.airy.payload.response.ChannelPayload;
public class Mapper {
public static ChannelPayload fromChannel(Channel channel) {
return ChannelPayload.builder()
.name(channel.getName())
.id(channel.getId())
.imageUrl(channel.getImageUrl())
.source(channel.getSource())
.sourceChannelId(channel.getSourceChannelId())
.build();
}
}
| 30.588235
| 63
| 0.619231
|
bd225f809bf9482959513beb10ad9b0357b73cf7
| 2,696
|
package com.github.joschi.nosqlunit.elasticsearch2;
import org.junit.rules.ExternalResource;
public class ManagedElasticsearch extends ExternalResource {
private ManagedElasticsearch() {
super();
}
protected ManagedElasticsearchLifecycleManager managedElasticsearchLifecycleManager;
public static class ManagedElasticsearchRuleBuilder {
private ManagedElasticsearchLifecycleManager managedElasticsearchLifecycleManager;
private ManagedElasticsearchRuleBuilder() {
this.managedElasticsearchLifecycleManager = new ManagedElasticsearchLifecycleManager();
}
public static ManagedElasticsearchRuleBuilder newManagedElasticsearchRule() {
return new ManagedElasticsearchRuleBuilder();
}
public ManagedElasticsearchRuleBuilder elasticsearchPath(String elasticsearchPath) {
this.managedElasticsearchLifecycleManager.setElasticsearchPath(elasticsearchPath);
return this;
}
public ManagedElasticsearchRuleBuilder port(int port) {
this.managedElasticsearchLifecycleManager.setPort(port);
return this;
}
public ManagedElasticsearchRuleBuilder targetPath(String targetPath) {
this.managedElasticsearchLifecycleManager.setTargetPath(targetPath);
return this;
}
public ManagedElasticsearchRuleBuilder appendCommandLineArguments(
String argumentName, String argumentValue) {
this.managedElasticsearchLifecycleManager.addExtraCommandLineArgument(argumentName,
argumentValue);
return this;
}
public ManagedElasticsearchRuleBuilder appendSingleCommandLineArguments(
String argument) {
this.managedElasticsearchLifecycleManager.addSingleCommandLineArgument(argument);
return this;
}
public ManagedElasticsearch build() {
if (this.managedElasticsearchLifecycleManager.getElasticsearchPath() == null) {
throw new IllegalArgumentException(
"No Path to Elasticsearch is provided.");
}
ManagedElasticsearch managedElasticsearch = new ManagedElasticsearch();
managedElasticsearch.managedElasticsearchLifecycleManager = this.managedElasticsearchLifecycleManager;
return managedElasticsearch;
}
}
@Override
protected void before() throws Throwable {
this.managedElasticsearchLifecycleManager.startEngine();
}
@Override
protected void after() {
this.managedElasticsearchLifecycleManager.stopEngine();
}
}
| 34.126582
| 114
| 0.702893
|
fa51271e1af83d451204e159e93beffb75ec3360
| 2,490
|
/**
* 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.marmotta.ldclient.provider.xml.mapping;
import org.apache.marmotta.ldclient.api.provider.ValueMapper;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Abstract class that manages an XPath expression for mapping.
* <p/>
* Author: Sebastian Schaffert
*/
public abstract class XPathValueMapper implements ValueMapper {
private String xpath;
private XPathExpression<Object> compiled;
protected XPathValueMapper(String xpath) {
this(xpath, (Map<String, String>) null);
}
protected XPathValueMapper(String xpath, Map<String,String> namespaces) {
this.xpath = xpath;
Set<Namespace> xnamespaces = new HashSet<Namespace>();
if(namespaces != null) {
for(Map.Entry<String,String> ns : namespaces.entrySet()) {
xnamespaces.add(Namespace.getNamespace(ns.getKey(), ns.getValue()));
}
}
this.compiled = XPathFactory.instance().compile(xpath, Filters.fpassthrough(),null,xnamespaces);
}
protected XPathValueMapper(String xpath, Collection<Namespace> namespaces) {
this.xpath = xpath;
this.compiled = XPathFactory.instance().compile(xpath, Filters.fpassthrough(),null,namespaces);
}
public String getXpath() {
return xpath;
}
/**
* Return the precompiled XPath expression represented in this value mapper
* @return
*/
public XPathExpression<Object> getCompiled() {
return compiled;
}
}
| 32.763158
| 104
| 0.710442
|
a3938a34a3e318873f069beedd4ae95670cbc0a5
| 1,199
|
package net.brutus5000.deltaforge.client.api;
import org.mapstruct.BeforeMapping;
import org.mapstruct.Context;
import org.mapstruct.MappingTarget;
import org.mapstruct.TargetType;
import org.springframework.stereotype.Component;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* A type to be used as {@link Context} parameter to track cycles in graphs for Mapstruct mapping.
* <p>
* Depending on the actual use case, the two methods below could also be changed to only accept certain argument types,
* e.g. base classes of patchGraph nodes, avoiding the need to capture any other objects that wouldn't necessarily result in
* cycles.
*
* @author Andreas Gudian
*/
@Component
public class CycleAvoidingMappingContext {
private Map<Object, Object> knownInstances = new IdentityHashMap<>();
@BeforeMapping
public <T> T getMappedInstance(Object source, @TargetType Class<T> targetType) {
return (T) knownInstances.get(source);
}
@BeforeMapping
public void storeMappedInstance(Object source, @MappingTarget Object target) {
knownInstances.put(source, target);
}
public void clearCache() {
knownInstances.clear();
}
}
| 30.74359
| 124
| 0.743953
|
b48545d8756802b223e6175ea839c7bc0d886edd
| 15,945
|
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.operator.assembly;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.strimzi.api.kafka.StrimziPodSetList;
import io.strimzi.api.kafka.model.Kafka;
import io.strimzi.api.kafka.model.KafkaBuilder;
import io.strimzi.api.kafka.model.KafkaResources;
import io.strimzi.api.kafka.model.StrimziPodSet;
import io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerBuilder;
import io.strimzi.api.kafka.model.listener.arraylistener.KafkaListenerType;
import io.strimzi.api.kafka.model.status.ListenerStatus;
import io.strimzi.certs.CertManager;
import io.strimzi.certs.OpenSslCertManager;
import io.strimzi.operator.KubernetesVersion;
import io.strimzi.operator.PlatformFeaturesAvailability;
import io.strimzi.operator.cluster.ClusterOperatorConfig;
import io.strimzi.operator.cluster.KafkaVersionTestUtils;
import io.strimzi.operator.cluster.ResourceUtils;
import io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier;
import io.strimzi.operator.cluster.operator.resource.StatefulSetOperator;
import io.strimzi.operator.common.PasswordGenerator;
import io.strimzi.operator.common.Reconciliation;
import io.strimzi.operator.common.model.Labels;
import io.strimzi.operator.common.operator.resource.CrdOperator;
import io.strimzi.operator.common.operator.resource.PodOperator;
import io.strimzi.operator.common.operator.resource.ServiceOperator;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.junit5.Checkpoint;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static java.util.Collections.emptyList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ExtendWith(VertxExtension.class)
public class KafkaAssemblyOperatorLoadBalancerKafkaListenerTest {
public static final String NAMESPACE = "test";
public static final String NAME = "my-kafka";
public static final String DNS_NAME_FOR_BROKER_0 = "broker-0.test.dns.name";
public static final String DNS_NAME_FOR_BROKER_1 = "broker-1.test.dns.name";
public static final String DNS_NAME_FOR_BROKER_2 = "broker-2.test.dns.name";
public static final String DNS_NAME_FOR_BOOTSTRAP_SERVICE = "bootstrap-broker.test.dns.name";
public static final int LISTENER_PORT = 9094;
private static Vertx vertx;
private final OpenSslCertManager certManager = new OpenSslCertManager();
private final PasswordGenerator passwordGenerator = new PasswordGenerator(12,
"abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789");
@BeforeAll
public static void before() {
vertx = Vertx.vertx();
}
@AfterAll
public static void after() {
vertx.close();
}
@Test
public void testLoadBalancerSkipBootstrapService(VertxTestContext context) {
Kafka kafka = new KafkaBuilder()
.withNewMetadata()
.withName(NAME)
.withNamespace(NAMESPACE)
.endMetadata()
.withNewSpec()
.withNewKafka()
.withReplicas(3)
.withListeners(new GenericKafkaListenerBuilder()
.withName("external")
.withPort(LISTENER_PORT)
.withTls(true)
.withType(KafkaListenerType.LOADBALANCER)
.withNewConfiguration()
.withCreateBootstrapService(false)
.endConfiguration()
.build())
.withNewEphemeralStorage()
.endEphemeralStorage()
.endKafka()
.withNewZookeeper()
.withReplicas(3)
.withNewEphemeralStorage()
.endEphemeralStorage()
.endZookeeper()
.withNewEntityOperator()
.withNewUserOperator()
.endUserOperator()
.withNewTopicOperator()
.endTopicOperator()
.endEntityOperator()
.endSpec()
.build();
ResourceOperatorSupplier supplier = prepareResourceOperatorSupplier(kafka);
KafkaAssemblyOperator op = new MockKafkaAssemblyOperatorForLoadBalancerTests(vertx, new PlatformFeaturesAvailability(false, KubernetesVersion.V1_16), certManager, passwordGenerator,
supplier, ResourceUtils.dummyClusterOperatorConfig(KafkaVersionTestUtils.getKafkaVersionLookup()));
Reconciliation reconciliation = new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, NAMESPACE, NAME);
Checkpoint async = context.checkpoint();
op.reconcile(reconciliation)
.onComplete(context.succeeding(v -> context.verify(() -> {
assertThat(kafka.getStatus().getListeners().size(), is(1));
ListenerStatus listenerStatus = kafka.getStatus().getListeners().get(0);
assertThat(listenerStatus.getBootstrapServers(), is("broker-0.test.dns.name:9094,broker-1.test.dns.name:9094,broker-2.test.dns.name:9094"));
assertThat(listenerStatus.getAddresses().size(), is(3));
assertThat(listenerStatus.getAddresses().get(0).getHost(), is(DNS_NAME_FOR_BROKER_0));
assertThat(listenerStatus.getAddresses().get(1).getHost(), is(DNS_NAME_FOR_BROKER_1));
assertThat(listenerStatus.getAddresses().get(2).getHost(), is(DNS_NAME_FOR_BROKER_2));
assertThat(listenerStatus.getAddresses().get(0).getPort(), is(LISTENER_PORT));
assertThat(listenerStatus.getAddresses().get(1).getPort(), is(LISTENER_PORT));
assertThat(listenerStatus.getAddresses().get(2).getPort(), is(LISTENER_PORT));
async.flag();
})));
}
@Test
public void testLoadBalancerWithBootstrapService(VertxTestContext context) {
Kafka kafka = new KafkaBuilder()
.withNewMetadata()
.withName(NAME)
.withNamespace(NAMESPACE)
.endMetadata()
.withNewSpec()
.withNewKafka()
.withReplicas(3)
.withListeners(new GenericKafkaListenerBuilder()
.withName("external")
.withPort(LISTENER_PORT)
.withTls(true)
.withType(KafkaListenerType.LOADBALANCER)
.withNewConfiguration()
.withCreateBootstrapService(true)
.endConfiguration()
.build())
.withNewEphemeralStorage()
.endEphemeralStorage()
.endKafka()
.withNewZookeeper()
.withReplicas(3)
.withNewEphemeralStorage()
.endEphemeralStorage()
.endZookeeper()
.withNewEntityOperator()
.withNewUserOperator()
.endUserOperator()
.withNewTopicOperator()
.endTopicOperator()
.endEntityOperator()
.endSpec()
.build();
ResourceOperatorSupplier supplier = prepareResourceOperatorSupplier(kafka);
KafkaAssemblyOperator op = new MockKafkaAssemblyOperatorForLoadBalancerTests(vertx, new PlatformFeaturesAvailability(false, KubernetesVersion.V1_16), certManager, passwordGenerator,
supplier, ResourceUtils.dummyClusterOperatorConfig(KafkaVersionTestUtils.getKafkaVersionLookup()));
Reconciliation reconciliation = new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, NAMESPACE, NAME);
Checkpoint async = context.checkpoint();
op.reconcile(reconciliation)
.onComplete(context.succeeding(v -> context.verify(() -> {
assertThat(kafka.getStatus().getListeners().size(), is(1));
ListenerStatus listenerStatus = kafka.getStatus().getListeners().get(0);
assertThat(listenerStatus.getBootstrapServers(), is("bootstrap-broker.test.dns.name:9094"));
assertThat(listenerStatus.getAddresses().size(), is(1));
assertThat(listenerStatus.getAddresses().get(0).getHost(), is(DNS_NAME_FOR_BOOTSTRAP_SERVICE));
assertThat(listenerStatus.getAddresses().get(0).getPort(), is(LISTENER_PORT));
async.flag();
})));
}
@Test
public void testLoadBalancer(VertxTestContext context) {
Kafka kafka = new KafkaBuilder()
.withNewMetadata()
.withName(NAME)
.withNamespace(NAMESPACE)
.endMetadata()
.withNewSpec()
.withNewKafka()
.withReplicas(3)
.withListeners(new GenericKafkaListenerBuilder()
.withName("external")
.withPort(LISTENER_PORT)
.withTls(true)
.withType(KafkaListenerType.LOADBALANCER)
.build())
.withNewEphemeralStorage()
.endEphemeralStorage()
.endKafka()
.withNewZookeeper()
.withReplicas(3)
.withNewEphemeralStorage()
.endEphemeralStorage()
.endZookeeper()
.withNewEntityOperator()
.withNewUserOperator()
.endUserOperator()
.withNewTopicOperator()
.endTopicOperator()
.endEntityOperator()
.endSpec()
.build();
ResourceOperatorSupplier supplier = prepareResourceOperatorSupplier(kafka);
KafkaAssemblyOperator op = new MockKafkaAssemblyOperatorForLoadBalancerTests(vertx, new PlatformFeaturesAvailability(false, KubernetesVersion.V1_16), certManager, passwordGenerator,
supplier, ResourceUtils.dummyClusterOperatorConfig(KafkaVersionTestUtils.getKafkaVersionLookup()));
Reconciliation reconciliation = new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, NAMESPACE, NAME);
Checkpoint async = context.checkpoint();
op.reconcile(reconciliation)
.onComplete(context.succeeding(v -> context.verify(() -> {
assertThat(kafka.getStatus().getListeners().size(), is(1));
ListenerStatus listenerStatus = kafka.getStatus().getListeners().get(0);
assertThat(listenerStatus.getBootstrapServers(), is("bootstrap-broker.test.dns.name:9094"));
assertThat(listenerStatus.getAddresses().size(), is(1));
assertThat(listenerStatus.getAddresses().get(0).getHost(), is(DNS_NAME_FOR_BOOTSTRAP_SERVICE));
assertThat(listenerStatus.getAddresses().get(0).getPort(), is(LISTENER_PORT));
async.flag();
})));
}
/**
* Override KafkaAssemblyOperator to only run reconciliation steps that concern the load balancer resources feature
*/
class MockKafkaAssemblyOperatorForLoadBalancerTests extends KafkaAssemblyOperator {
public MockKafkaAssemblyOperatorForLoadBalancerTests(
Vertx vertx,
PlatformFeaturesAvailability pfa,
CertManager certManager,
PasswordGenerator passwordGenerator,
ResourceOperatorSupplier supplier,
ClusterOperatorConfig config
) {
super(vertx, pfa, certManager, passwordGenerator, supplier, config);
}
@Override
Future<Void> reconcile(ReconciliationState reconcileState) {
return reconcileState.getKafkaClusterDescription()
.compose(state -> state.kafkaIngresses())
.compose(state -> state.kafkaLoadBalancerServicesReady())
.map((Void) null);
}
}
private ResourceOperatorSupplier prepareResourceOperatorSupplier(Kafka kafka) {
ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false);
// Mock the CRD Operator for Kafka resources
CrdOperator mockKafkaOps = supplier.kafkaOperator;
when(mockKafkaOps.getAsync(eq(NAMESPACE), eq(NAME))).thenReturn(Future.succeededFuture(kafka));
when(mockKafkaOps.get(eq(NAMESPACE), eq(NAME))).thenReturn(kafka);
when(mockKafkaOps.updateStatusAsync(any(), any(Kafka.class))).thenReturn(Future.succeededFuture());
// Mock the KafkaSet operations
StatefulSetOperator mockStsOps = supplier.stsOperations;
when(mockStsOps.getAsync(eq(NAMESPACE), eq(KafkaResources.kafkaStatefulSetName(NAME)))).thenReturn(Future.succeededFuture());
// Mock the StrimziPodSet operator
CrdOperator<KubernetesClient, StrimziPodSet, StrimziPodSetList> mockPodSetOps = supplier.strimziPodSetOperator;
when(mockPodSetOps.getAsync(any(), any())).thenReturn(Future.succeededFuture(null));
// Mock the Pod operations
PodOperator mockPodOps = supplier.podOperations;
when(mockPodOps.listAsync(eq(NAMESPACE), any(Labels.class))).thenReturn(Future.succeededFuture(emptyList()));
// Mock the Services for the kafka.
Service mockServiceBootstrap = mock(Service.class, RETURNS_DEEP_STUBS);
Service mockServiceBroker0 = mock(Service.class, RETURNS_DEEP_STUBS);
Service mockServiceBroker1 = mock(Service.class, RETURNS_DEEP_STUBS);
Service mockServiceBroker2 = mock(Service.class, RETURNS_DEEP_STUBS);
when(mockServiceBootstrap.getStatus().getLoadBalancer().getIngress().get(0).getHostname()).thenReturn(DNS_NAME_FOR_BOOTSTRAP_SERVICE);
when(mockServiceBroker0.getStatus().getLoadBalancer().getIngress().get(0).getHostname()).thenReturn(DNS_NAME_FOR_BROKER_0);
when(mockServiceBroker1.getStatus().getLoadBalancer().getIngress().get(0).getHostname()).thenReturn(DNS_NAME_FOR_BROKER_1);
when(mockServiceBroker2.getStatus().getLoadBalancer().getIngress().get(0).getHostname()).thenReturn(DNS_NAME_FOR_BROKER_2);
// Mock the ServiceOperator for the kafka services.
ServiceOperator mockServiceOperator = supplier.serviceOperations;
when(mockServiceOperator.getAsync(NAMESPACE, NAME + "-kafka-external-bootstrap")).thenReturn(Future.succeededFuture(mockServiceBootstrap));
when(mockServiceOperator.getAsync(NAMESPACE, NAME + "-kafka-0")).thenReturn(Future.succeededFuture(mockServiceBroker0));
when(mockServiceOperator.getAsync(NAMESPACE, NAME + "-kafka-1")).thenReturn(Future.succeededFuture(mockServiceBroker1));
when(mockServiceOperator.getAsync(NAMESPACE, NAME + "-kafka-2")).thenReturn(Future.succeededFuture(mockServiceBroker2));
return supplier;
}
}
| 51.270096
| 189
| 0.647476
|
dcce86821119096a75f9eee08a0c218963190be4
| 11,585
|
package com.seckill.dis.gateway.seckill;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.seckill.dis.common.api.cache.RedisServiceApi;
import com.seckill.dis.common.api.cache.vo.GoodsKeyPrefix;
import com.seckill.dis.common.api.cache.vo.OrderKeyPrefix;
import com.seckill.dis.common.api.cache.vo.SkKeyPrefix;
import com.seckill.dis.common.api.goods.GoodsServiceApi;
import com.seckill.dis.common.api.goods.vo.GoodsVo;
import com.seckill.dis.common.api.mq.MqProviderApi;
import com.seckill.dis.common.api.mq.vo.SkMessage;
import com.seckill.dis.common.api.order.OrderServiceApi;
import com.seckill.dis.common.api.seckill.SeckillServiceApi;
import com.seckill.dis.common.api.seckill.vo.VerifyCodeVo;
import com.seckill.dis.common.api.user.vo.UserVo;
import com.seckill.dis.common.domain.SeckillOrder;
import com.seckill.dis.common.result.CodeMsg;
import com.seckill.dis.common.result.Result;
import com.seckill.dis.common.util.MD5Util;
import com.seckill.dis.common.util.UUIDUtil;
import com.seckill.dis.common.util.VerifyCodeUtil;
import com.seckill.dis.gateway.config.access.AccessLimit;
import com.seckill.dis.gateway.exception.MyBlockHandler;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 秒杀接口
*
* @author mata
*/
@Controller
@RequestMapping("/seckill/")
public class SeckillController implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(SeckillController.class);
@Reference(interfaceClass = RedisServiceApi.class)
RedisServiceApi redisService;
@Reference(interfaceClass = GoodsServiceApi.class)
GoodsServiceApi goodsService;
@Reference(interfaceClass = SeckillServiceApi.class)
SeckillServiceApi seckillService;
@Reference(interfaceClass = OrderServiceApi.class)
OrderServiceApi orderService;
@Reference(interfaceClass = MqProviderApi.class)
MqProviderApi sender;
/**
* 用于内存标记,标记库存是否为空,从而减少对redis的访问
*/
private Map<Long, Boolean> localOverMap = new HashMap<>();
/**
* 获取秒杀接口地址
* 1. 每一次点击秒杀,都会生成一个随机的秒杀地址返回给客户端
* 2. 对秒杀的次数做限制(通过自定义拦截器注解完成)
*
* @param user
* @param goodsId 秒杀的商品id
* @param verifyCode 验证码
* @return 被隐藏的秒杀接口路径
*/
@AccessLimit(seconds = 5, maxAccessCount = 5, needLogin = true)
@RequestMapping(value = "path", method = RequestMethod.GET)
@ResponseBody
@SentinelResource(value = "Seckill",blockHandler ="blockHandlerFordoSeckill",blockHandlerClass = {MyBlockHandler.class})
// public Result<String> getSeckillPath( UserVo user,
// @RequestParam("goodsId") long goodsId) {
public Result<String> getSeckillPath( UserVo user,
@RequestParam("goodsId") long goodsId,
@RequestParam(value = "verifyCode") int verifyCode) {
/** 在执行下面的逻辑之前,会先对path请求进行拦截处理(@AccessLimit, AccessInterceptor),防止访问次数过于频繁,对服务器造成过大的压力 */
boolean check_goodsID=redisService.exists(GoodsKeyPrefix.seckillGoodsInf, ""+goodsId);
if(!check_goodsID) return Result.error(CodeMsg.SECKILL_DOODS_ILLEGAL);
long startTime = redisService.get(GoodsKeyPrefix.seckillGoodsInf, ""+goodsId ,GoodsVo.class).getStartDate().getTime();
if(startTime >new Date().getTime()){
return Result.error(CodeMsg.SECKILL_TIME_ILLEGAL);
}
// 校验验证码
boolean check = this.checkVerifyCode(user, goodsId, verifyCode);
if (!check)
return Result.error(CodeMsg.VERITF_FAIL);// 检验不通过,请求非法
// 检验通过,获取秒杀路径
String path = this.createSkPath(user, goodsId);
// 向客户端回传随机生成的秒杀地址
return Result.success(path);
}
/* 压力测试时候注释掉 :验证码和秒杀地址隐藏 */
/**
* 秒杀逻辑(页面静态化分离,不需要直接将页面返回给客户端,而是返回客户端需要的页面动态数据,返回数据时json格式)
* GET/POST的@RequestMapping是有区别的
* <p>
* 通过随机的path,客户端隐藏秒杀接口
* <p>
* 优化: 不同于每次都去数据库中读取秒杀订单信息,而是在第一次生成秒杀订单成功后,
* 将订单存储在redis中,再次读取订单信息的时候就直接从redis中读取
*
* @param user
* @param goodsId
* @param path 隐藏的秒杀地址,为客户端回传的path,最初也是有服务端产生的
* @return 订单详情或错误码
*/
// {path}为客户端回传的path,最初也是有服务端产生的
@RequestMapping(value = "doSeckill", method = RequestMethod.POST)
@ResponseBody
// public Result<Integer> doSeckill( UserVo user,
// @RequestParam("goodsId") long goodsId) {
public Result<Integer> doSeckill( UserVo user,
@RequestParam("goodsId") long goodsId,
@PathVariable("path") String path) {
// 验证path是否正确
boolean check = this.checkPath(user, goodsId, path);
if (!check)
return Result.error(CodeMsg.REQUEST_ILLEGAL);// 请求非法
if (user == null) {
return Result.error(CodeMsg.SESSION_ERROR);
}
// 通过内存标记,减少对redis的访问,秒杀未结束才继续访问redis
Boolean over = localOverMap.get(goodsId);
if (over)
return Result.error(CodeMsg.SECKILL_OVER);
// 预减库存,同时在库存为0时标记该商品已经结束秒杀
Long stock = redisService.decr(GoodsKeyPrefix.GOODS_STOCK, "" + goodsId);
if (stock < 0) {
localOverMap.put(goodsId, true);// 秒杀结束。标记该商品已经秒杀结束
redisService.set(GoodsKeyPrefix.GOODS_STOCK, "" +goodsId, 0);
return Result.error(CodeMsg.SECKILL_OVER);
}
// 判断是否重复秒杀
// 从redis中取缓存,减少数据库的访问
SeckillOrder order = redisService.get(OrderKeyPrefix.SK_ORDER, ":" + user.getUuid() + "_" + goodsId, SeckillOrder.class);
// 如果缓存中不存该数据,则从数据库中取
if (order == null) {
order = orderService.getSeckillOrderByUserIdAndGoodsId(user.getUuid(), goodsId);
}
if (order != null) {
return Result.error(CodeMsg.REPEATE_SECKILL);
}
// 商品有库存且用户为秒杀商品,则将秒杀请求放入MQ
SkMessage message = new SkMessage(user.getUuid(),goodsId);
// 放入MQ(对秒杀请求异步处理,直接返回)
sender.sendSkMessage(message);
// 排队中
return Result.success(0);
}
/**
* 用于返回用户秒杀的结果
*
* @param model
* @param user
* @param goodsId
* @return orderId:成功, -1:秒杀失败, 0: 排队中
*/
@RequestMapping(value = "result", method = RequestMethod.GET)
@ResponseBody
public Result<Long> getSeckillResult( UserVo user,
@RequestParam("goodsId") long goodsId) {
long result = seckillService.getSeckillResult(user.getUuid(), goodsId);
if(result!=-1L) return Result.success(result);
boolean isOver = localOverMap.get(goodsId);
if(!isOver){
return Result.success(0L);
}
return Result.success(-1L);
}
/**
* goods_detail.htm: $("#verifyCodeImg").attr("src", "/seckill/verifyCode?goodsId=" + $("#goodsId").val());
* 使用HttpServletResponse的输出流返回客户端异步获取的验证码(异步获取的代码如上所示)
*
* @param response
* @param user
* @param goodsId
* @return
*/
@RequestMapping(value = "verifyCode", method = RequestMethod.GET)
@ResponseBody
@SentinelResource(value = "verifyCode",blockHandler ="blockHandlerForVerifyCodel",blockHandlerClass = {MyBlockHandler.class})
public Result<String> getVerifyCode(HttpServletResponse response, UserVo user,
@RequestParam("goodsId") long goodsId) {
logger.info("获取验证码");
if (user == null ) {
return Result.error(CodeMsg.SESSION_ERROR);
}
boolean check_goodsID=redisService.exists(GoodsKeyPrefix.seckillGoodsInf, ""+goodsId);
if(!check_goodsID) return Result.error(CodeMsg.SECKILL_DOODS_ILLEGAL);
// 刷新验证码的时候置缓存中的随机地址无效
String path = redisService.get(SkKeyPrefix.SK_PATH, "" + user.getUuid() + "_" + goodsId, String.class);
if (path != null)
redisService.delete(SkKeyPrefix.SK_PATH, "" + user.getUuid() + "_" + goodsId);
// 创建验证码
try {
// String verifyCodeJsonString = seckillService.createVerifyCode(user, goodsId);
VerifyCodeVo verifyCode = VerifyCodeUtil.createVerifyCode();
// 验证码结果预先存到redis中
redisService.set(SkKeyPrefix.VERIFY_RESULT, user.getUuid() + "_" + goodsId, verifyCode.getExpResult());
ServletOutputStream out = response.getOutputStream();
// 将图片写入到resp对象中
ImageIO.write(verifyCode.getImage(), "JPEG", out);
out.close();
out.flush();
return null;
} catch (Exception e) {
e.printStackTrace();
return Result.error(CodeMsg.SECKILL_FAIL);
}
}
/**
* 调试接口,可以动态加载商品信息到redis缓存中
*
* @return
*/
@RequestMapping(value = "test", method = RequestMethod.GET)
@ResponseBody
public Result<Boolean> test() {
logger.info("商品信息热加载");
afterPropertiesSet();
return Result.success(true);
}
/**
* 检验检验码的计算结果
*
* @param user
* @param goodsId
* @param verifyCode
* @return
*/
private boolean checkVerifyCode(UserVo user, long goodsId, int verifyCode) {
// 从redis中获取验证码计算结果
Integer oldCode = redisService.get(SkKeyPrefix.VERIFY_RESULT, user.getUuid() + "_" + goodsId, Integer.class);
// logger.info(verifyCode+" "+oldCode);
if (oldCode == null || oldCode - verifyCode != 0) {
return false;
}
// 如果校验成功,则说明校验码过期,删除校验码缓存,防止重复提交同一个验证码
redisService.delete(SkKeyPrefix.VERIFY_RESULT, user.getUuid() + "_" + goodsId);
return true;
}
/**
* 创建秒杀地址, 并将其存储在redis中
*
* @param user
* @param goodsId
* @return
*/
public String createSkPath(UserVo user, long goodsId) {
// 随机生成秒杀地址
String path = MD5Util.md5(UUIDUtil.uuid() + "123456");
// 将随机生成的秒杀地址存储在redis中(保证不同的用户和不同商品的秒杀地址是不一样的)
redisService.set(SkKeyPrefix.SK_PATH, "" + user.getUuid() + "_" + goodsId, path);
return path;
}
/**
* 验证路径是否正确
*
* @param user
* @param goodsId
* @param path
* @return
*/
public boolean checkPath(UserVo user, long goodsId, String path) {
if (user == null || path == null)
return false;
// 从redis中读取出秒杀的path变量是否为本次秒杀操作执行前写入redis中的path
// logger.info(goodsId+"");
String oldPath = redisService.get(SkKeyPrefix.SK_PATH, "" + user.getUuid() + "_" + goodsId, String.class);
// logger.info(oldPath+" "+path);
return path.equals(oldPath);
}
/**
* 服务器程序启动的时候加载商品列表信息
*/
@Override
public void afterPropertiesSet() {
List<GoodsVo> goods = goodsService.listGoodsVo();
if (goods == null) {
return;
}
// 将商品的库存信息存储在redis中
for (GoodsVo good : goods) {
redisService.set(GoodsKeyPrefix.GOODS_STOCK, "" + good.getId(), good.getStockCount());
redisService.set(GoodsKeyPrefix.seckillGoodsInf, ""+ good.getId() , good);
// 在系统启动时,标记库存不为空
localOverMap.put(good.getId(), false);
}
}
}
| 34.174041
| 129
| 0.63798
|
a144adb903b310b1a2b53f5156cd411771be2a86
| 14,247
|
/****************************************************************************************
* GeoAtomOutputStream.java
*
* Created: Jul 16, 2010
*
* @author DRAND
*
* (C) Copyright MITRE Corporation 2010
*
* The program is provided "as is" without any warranty express or implied, including
* the warranty of non-infringement and the implied warranties of merchantibility and
* fitness for a particular purpose. The Copyright owner will not be liable for any
* damages suffered by you as a result of using the Program. In no event will the
* Copyright owner be liable for any special, indirect or consequential damages or
* lost profits even if the Copyright owner has been advised of the possibility of
* their occurrence.
*
***************************************************************************************/
package org.opensextant.giscore.output.atom;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.lang.StringUtils;
import org.opensextant.geodesy.Geodetic2DPoint;
import org.opensextant.giscore.Namespace;
import org.opensextant.giscore.events.AtomAuthor;
import org.opensextant.giscore.events.AtomHeader;
import org.opensextant.giscore.events.AtomLink;
import org.opensextant.giscore.events.Element;
import org.opensextant.giscore.events.Feature;
import org.opensextant.giscore.events.Row;
import org.opensextant.giscore.events.SimpleField;
import org.opensextant.giscore.events.SimpleField.Type;
import org.opensextant.giscore.geometry.Circle;
import org.opensextant.giscore.geometry.Geometry;
import org.opensextant.giscore.geometry.Line;
import org.opensextant.giscore.geometry.LinearRing;
import org.opensextant.giscore.geometry.Point;
import org.opensextant.giscore.geometry.Polygon;
import org.opensextant.giscore.input.kml.IKml;
import org.opensextant.giscore.output.XmlOutputStreamBase;
import org.opensextant.geodesy.SafeDateFormat;
/**
* Output ATOM 1.0 format with OGC and other extensions to contain information
* appropriate for GIS and extended data.
*
* @author DRAND
*/
public class GeoAtomOutputStream extends XmlOutputStreamBase implements
IAtomConstants {
private static final SafeDateFormat fmt = new SafeDateFormat(
IKml.ISO_DATE_FMT);
private static final Namespace ATOM_NS = Namespace.getNamespace(ATOM_URI_NS);
private final DecimalFormat dfmt;
private final static Set<SimpleField> ms_builtinFields = new HashSet<SimpleField>(4);
static {
ms_builtinFields.add(LINK_ATTR);
ms_builtinFields.add(TITLE_ATTR);
ms_builtinFields.add(UPDATED_ATTR);
ms_builtinFields.add(AUTHOR_ATTR);
}
private static final Namespace gns = Namespace.getNamespace("geo", GIS_NS);
private boolean headerwritten = false;
public GeoAtomOutputStream(OutputStream outputStream, Object[] arguments)
throws XMLStreamException {
/* GeoAtomOutputStream(OutputStream stream, Date updateDTM,
String title, String link, List<String> authors) */
super(outputStream);
writer.writeStartDocument();
dfmt = new DecimalFormat("##.######");
}
/* (non-Javadoc)
* @see org.mitre.giscore.output.XmlOutputStreamBase#close()
*/
@Override
public void close() throws IOException {
try {
writer.writeEndElement();
writer.writeEndDocument();
super.close();
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see org.mitre.giscore.output.StreamVisitorBase#visit(org.mitre.giscore.events.AtomHeader)
*/
@Override
public void visit(AtomHeader header) {
try {
writer.writeStartElement("feed");
writer.writeDefaultNamespace(ATOM_URI_NS);
writer.writeNamespace("ext", EXT_DATA_NS);
writer.writeNamespace("geo", GIS_NS);
namespaces.put("ext", EXT_DATA_NS);
namespaces.put("geo", GIS_NS);
if (header.getNamespaces() != null) {
for(Namespace ns : header.getNamespaces()) {
writer.writeNamespace(ns.getPrefix(), ns.getURI());
namespaces.put(ns.getPrefix(), ns.getURI());
}
}
handleSimpleElement("generator", header.getGenerator());
handleSimpleElement("id", header.getId());
handleSimpleElement("title", header.getTitle());
handleSimpleElement("updated", fmt.format(header.getUpdated()));
handleLink(header.getSelflink());
if (header.getRelatedlinks() != null) {
for(AtomLink rel : header.getRelatedlinks()) {
handleLink(rel);
}
}
if (header.getAuthors() != null && header.getAuthors().size() > 0) {
for (AtomAuthor author : header.getAuthors()) {
handleAuthor(author);
}
}
if (header.getElements() != null && header.getElements().size() > 0) {
for(Element el : header.getElements()) {
visit(el);
}
}
headerwritten = true;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
/**
* Handle an author
* @param author
* @throws XMLStreamException
*/
private void handleAuthor(AtomAuthor author) throws XMLStreamException {
writer.writeStartElement("author");
handleSimpleElement("name", author.getName());
if (author.getUri() != null) {
handleSimpleElement("uri", author.getUri());
}
handleSimpleElement("email", author.getEmail());
writer.writeEndElement();
}
/**
* Handle a link
* @param link link data
* @throws XMLStreamException
*/
private void handleLink(AtomLink link) throws XMLStreamException {
writer.writeStartElement("link");
writer.writeAttribute("href", link.getHref().toExternalForm());
if (link.getHreflang() != null) {
writer.writeAttribute("hreflang", link.getHreflang());
}
if (link.getType() != null) {
writer.writeAttribute("type", link.getType().toString());
}
if (link.getRel() != null) {
writer.writeAttribute("rel", link.getRel());
}
writer.writeEndElement();
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.output.StreamVisitorBase#visit(org.mitre.giscore.events
* .Element)
*/
@Override
public void visit(Element element) {
try {
handleXmlElement(element, ATOM_NS);
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.output.StreamVisitorBase#visit(org.mitre.giscore.events
* .Row)
*/
@Override
public void visit(Row row) {
Object u = row.getData(UPDATED_ATTR);
Date updated = null;
if (u != null && u instanceof Date) {
updated = (Date) u;
}
Object title = row.getData(TITLE_ATTR);
outputRow(row, updated, title != null ? title.toString() : "", null, null, Collections.<Element>emptyList());
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.output.StreamVisitorBase#visit(org.mitre.giscore.events
* .Feature)
*/
@Override
public void visit(Feature feature) {
Object u = feature.getData(UPDATED_ATTR);
Date updated = feature.getStartTime();
if (updated == null && u != null && u instanceof Date) {
updated = (Date) u;
}
outputRow(feature, updated, feature.getName(), feature.getDescription(), feature.getGeometry(), feature.getElements());
}
/**
* Output a row plus other info, a refactoring of outputting the information
* contained in a feature to allow the same code to output either a feature
* or a row.
* @param row
* @param updated
* @param description
* @param geo
*/
private void outputRow(Row row, Date updated, String title,
String description, Geometry geo, List<Element> extraElements) {
if (! headerwritten) {
throw new IllegalStateException("Must output atom header before any feature or row");
}
String id = row.getId();
Object a = row.getData(AUTHOR_ATTR);
List<String> alist = new ArrayList<String>();
if (a != null) {
String authors = a.toString();
String parts[] = authors.split(",");
for(String part : parts) {
alist.add(part);
}
}
Object link = row.getData(LINK_ATTR);
Map<SimpleField, String> data = new HashMap<SimpleField, String>();
for (SimpleField field : row.getFields()) {
if (ms_builtinFields.contains(field)) continue;
String name = field.getName();
Object val = row.getData(field);
if (val != null) {
data.put(field, writeValue(field.getType(), val));
}
}
outputEntry(id, title,
description, updated,
link != null ? link.toString() : "", data,
geo, alist, extraElements);
}
/**
* Process the string value according to the type. By default just store the
* string.
* @param type
* @param val
* @return
*/
private String writeValue(Type type, Object val) {
switch(type) {
case DOUBLE:
case FLOAT:
if (val instanceof Number) {
return dfmt.format((Number) val);
}
break;
case LONG:
if (val instanceof Number) {
return Long.toString(((Number) val).longValue());
}
break;
case INT:
case UINT:
if (val instanceof Number) {
return Integer.toString(((Number) val).intValue());
}
break;
case SHORT:
case USHORT:
if (val instanceof Number) {
return Short.toString(((Number) val).shortValue());
}
break;
case BOOL:
if (val instanceof Boolean) {
return Boolean.toString((Boolean) val);
}
break;
case DATE:
if (val instanceof Date) {
return fmt.format((Date) val);
}
}
return val.toString();
}
/**
* Output the data in an entry
*
* @param id
* the atom id for the entry
* @param title
* @param description
* @param updated
* @param link
* @param data
* extended data for the entry, extracted, filtered and formatted
* from the original's extended data. The atom id does not have
* to be removed as it will be skipped.
* @param geo
* @param alist
*/
public void outputEntry(String id, String title, String description,
Date updated, String link, Map<SimpleField, String> data, Geometry geo, List<String> alist) {
outputEntry(id, title, description, updated, link, data, geo, alist, Collections.<Element>emptyList());
}
/**
* Output the data in an entry
*
* @param id
* the atom id for the entry
* @param title
* @param description
* @param updated
* @param link
* @param data
* extended data for the entry, extracted, filtered and formatted
* from the original's extended data. The atom id does not have
* to be removed as it will be skipped.
* @param geo
* @param alist
* @param children
*/
public void outputEntry(String id, String title, String description,
Date updated, String link, Map<SimpleField, String> data, Geometry geo, List<String> alist, List<Element> children) {
try {
writer.writeStartElement("entry");
for(String author : alist) {
writer.writeStartElement("author");
handleSimpleElement("name", author);
writer.writeEndElement();
}
handleSimpleElement("id", id);
handleSimpleElement("title", title);
handleSimpleElement("content", description);
handleSimpleElement("updated", fmt.format(updated));
if (StringUtils.isNotBlank(link)) {
writer.writeStartElement("link");
writer.writeAttribute("href", link);
writer.writeEndElement();
}
for(Map.Entry<SimpleField, String> entry : data.entrySet()) {
SimpleField key = entry.getKey();
writer.writeStartElement("ext", "data", EXT_DATA_NS);
writer.writeAttribute("name", key.getName());
writer.writeAttribute("type", key.getType().name());
writer.writeCharacters(entry.getValue());
writer.writeEndElement();
}
if (geo != null) {
geo.accept(this);
}
if (children != null) {
for(Element el : children) {
visit(el);
}
}
writer.writeEndElement();
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.output.StreamVisitorBase#visit(org.mitre.giscore.geometry
* .Point)
*/
@Override
public void visit(Point point) {
Geodetic2DPoint center = point.getCenter();
try {
handleSimpleElement(
gns,
"point",
dfmt.format(center.getLatitudeAsDegrees()) + " "
+ dfmt.format(center.getLongitudeAsDegrees()));
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.output.StreamVisitorBase#visit(org.mitre.giscore.geometry
* .Line)
*/
@Override
public void visit(Line line) {
try {
handleSimpleElement(gns, "line", getCoords(line.getPoints()));
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
private String getCoords(List<Point> points) {
StringBuilder coords = new StringBuilder();
for (Point p : points) {
Geodetic2DPoint center = p.getCenter();
coords.append(" ");
coords.append(dfmt.format(center.getLatitudeAsDegrees()));
coords.append(" ");
coords.append(dfmt.format(center.getLongitudeAsDegrees()));
}
return coords.toString().trim();
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.output.StreamVisitorBase#visit(org.mitre.giscore.geometry
* .LinearRing)
*/
@Override
public void visit(LinearRing ring) {
try {
handleSimpleElement(gns, "polygon", getCoords(ring.getPoints()));
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
/*
* (non-Javadoc)
*
* @see
* org.mitre.giscore.output.StreamVisitorBase#visit(org.mitre.giscore.geometry
* .Polygon)
*/
@Override
public void visit(Polygon polygon) {
try {
handleSimpleElement(gns, "polygon", getCoords(polygon.getPoints()));
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
@Override
public void visit(Circle circle) {
final Geodetic2DPoint center = circle.getCenter();
try {
handleSimpleElement(gns, "circle", dfmt.format(center.getLatitudeAsDegrees()) + " "
+ dfmt.format(center.getLongitudeAsDegrees()) + " "
+ dfmt.format(circle.getRadius()));
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
}
| 28.665996
| 121
| 0.677476
|
9cc0b2a443f186f0014398351451055447d82664
| 1,449
|
package org.infinispan.server.configuration.security;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSerializer;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.ConfigurationElement;
import org.infinispan.server.configuration.Attribute;
import org.infinispan.server.configuration.Element;
/**
* @since 10.0
*/
public class SSLEngineConfiguration extends ConfigurationElement<SSLEngineConfiguration> {
static final AttributeDefinition<String[]> ENABLED_PROTOCOLS = AttributeDefinition.builder(Attribute.ENABLED_PROTOCOLS, null, String[].class)
.serializer(AttributeSerializer.STRING_ARRAY).immutable().build();
static final AttributeDefinition<String> ENABLED_CIPHERSUITES = AttributeDefinition.builder(Attribute.ENABLED_CIPHERSUITES, null, String.class)
.immutable().build();
static AttributeSet attributeDefinitionSet() {
return new AttributeSet(SSLEngineConfiguration.class, ENABLED_PROTOCOLS, ENABLED_CIPHERSUITES);
}
SSLEngineConfiguration(AttributeSet attributes) {
super(Element.ENGINE, attributes);
}
public String[] enabledProtocols() {
return attributes.attribute(ENABLED_PROTOCOLS).get();
}
public String enabledCiphersuites() {
return attributes.attribute(ENABLED_CIPHERSUITES).get();
}
}
| 41.4
| 146
| 0.799862
|
8ff3a911aecbe46becc4a922cd9b1720805f6584
| 764
|
package com.me.data.xml;
public class Point {
private int x;
private int y;
public Point() {
}
public Point(int x, int y){
setX(x);
setY(y);
}
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public int getY() { return y; }
public void setY(int y) { this.y = y; }
public String toString(){
return "(" + x + ", " + y + ")";
}
public void print(){
System.out.println(toString());
}
public void myInit(){
System.out.println(" - Point " + toString() + " has been created!");
}
public void myDestroy(){
System.out.println(" - Point " + toString() + " has been destroyed!");
}
}
| 20.105263
| 79
| 0.490838
|
bdd875a5f34a03526fdafb5c9f7017b3224c264f
| 543
|
package org.mozartoz.truffle.nodes.literal;
import org.mozartoz.truffle.nodes.DerefNode;
import org.mozartoz.truffle.nodes.OzGuards;
import org.mozartoz.truffle.nodes.OzNode;
import com.oracle.truffle.api.frame.VirtualFrame;
public class EnsureOzLiteralNode extends OzNode {
@Child OzNode child;
public EnsureOzLiteralNode(OzNode child) {
this.child = DerefNode.create(child);
}
@Override
public Object execute(VirtualFrame frame) {
Object value = child.execute(frame);
assert OzGuards.isLiteral(value);
return value;
}
}
| 21.72
| 49
| 0.780847
|
3c4594c3ccca4a9a37b737dd6c7de53ec9c13ab8
| 1,811
|
/*
* Dog - Core
*
* Copyright (c) 2013 Dario Bonino and Luigi De Russis
* Copyright (c) 2012 Dmytro Pishchukhin
*
* 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 it.polito.elite.dog.core.monitoradmin;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
/**
* MonitorAdmin ServiceFactory implementation
*
* @author dpishchukhin
*/
public class MonitorAdminFactory implements ServiceFactory<Object> {
private final LogVisitor logVisitor;
private final MonitorAdminCommon common;
public MonitorAdminFactory(LogVisitor logVisitor, MonitorAdminCommon common) {
this.logVisitor = logVisitor;
this.common = common;
}
public Object getService(Bundle bundle, ServiceRegistration<Object> serviceRegistration) {
logVisitor.debug(String.format("Bind MonitorAdmin instance to %s bundle", bundle.getSymbolicName()), null);
return new MonitorAdminImpl(logVisitor, common, bundle);
}
public void ungetService(Bundle bundle, ServiceRegistration<Object> serviceRegistration, Object o) {
logVisitor.debug(String.format("Unbind MonitorAdmin instance from %s bundle", bundle.getSymbolicName()), null);
}
}
| 36.959184
| 120
| 0.727775
|
ab4626a5f1ec6372a72f2db2c4a359308adfdcf5
| 3,301
|
package car.ccut.com.vehicle.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import car.ccut.com.vehicle.R;
import car.ccut.com.vehicle.adapter.NewsFragPageAdp;
import car.ccut.com.vehicle.base.BaseFragment;
import car.ccut.com.vehicle.bean.NewsCate;
import car.ccut.com.vehicle.interf.ConstantValue;
import car.ccut.com.vehicle.util.Utils;
import car.ccut.com.vehicle.view.ViewPagerIndicator;
/**
* *
* へ /|
* /\7 ∠_/
* / │ / /
* │ Z _,< / /`ヽ
* │ ヽ / 〉
* Y ` / /
* イ● 、 ● ⊂⊃〈 /
* () へ | \〈
* >ー 、_ ィ │ // 去吧!
* / へ / ノ<| \\ 比卡丘~
* ヽ_ノ (_/ │// 消灭代码BUG
* 7 |/
* >―r ̄ ̄`ー―_
* Created by WangXin on 2016/7/28 0028.
*/
public class NewsFragment extends BaseFragment{
private ArrayList<Fragment> fragments = new ArrayList<>();
private List<NewsCate> cateList = new ArrayList<>();
@Bind(R.id.news_pager)
ViewPager mViewPager;
@Bind(R.id.indicator)
ViewPagerIndicator indicator;
@Bind(R.id.network_fault)
TextView networkFault;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showWaitDialog();
initData();
}
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_news,container,
false);
ButterKnife.bind(this, view);
initView(view);
return view;
}
@Override
public void initData() {
for (int i=0;i< ConstantValue.newsCate.length;i++){
NewsCate cate = new NewsCate(ConstantValue.newsId[i],ConstantValue.newsCate[i]);
cateList.add(cate);
}
}
@Override
public void initView(View view) {
if (Utils.hasNetwork(getActivity())){
networkFault.setVisibility(View.GONE);
if (cateList!=null&&!cateList.isEmpty()){
initFragment();
}
}else {
networkFault.setVisibility(View.VISIBLE);
}
}
/**
* 初始化Fragment
* */
private void initFragment() {
fragments.clear();//清空
int count = cateList.size();
for (int i = 0; i < count; i++) {
Bundle data = new Bundle();
data.putString("text", cateList.get(i).getCateName());
data.putString("cate_id", cateList.get(i).getCateId());
NewsDetailsFragment newfragment = new NewsDetailsFragment();
newfragment.setArguments(data);
fragments.add(newfragment);
}
mViewPager.setAdapter(new NewsFragPageAdp(this.getChildFragmentManager(), fragments, cateList));
indicator.setTabItemTitles(cateList);
indicator.setViewPager(mViewPager,0);
}
}
| 30.284404
| 104
| 0.6186
|
24bbbbee9a8d8a36329bffdfbb1f0545096afc77
| 381
|
package sweng;
/**
* Cache implementation that does nothing
*/
public class UselessCache<K, V> implements Cache<K, V> {
@Override
public boolean contains(K key) {
return false;
}
@Override
public void put(K key, V value) {
}
@Override
public V get(K key) {
return null;
}
@Override
public void clear() {
}
}
| 13.607143
| 56
| 0.572178
|
d389166312d29f5e057dd384cdaf1eb5687fa393
| 3,903
|
package com.dalimao.library;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import com.dalimao.library.constants.StandOutFlags;
import com.dalimao.library.util.DeviceInfoUtil;
/**
* Created by liuguangli on 16/10/21.
*/
public class CommonWindowWrapper extends WindowWrapper {
private Animation mAnimationShowContainer;
private Animation mAnimationCloseWindow;
private boolean mAnimating;
public CommonWindowWrapper(StandOutWindowManager manager, Integer id) {
super(manager, id);
}
@Override
public void setWindowAnchor(Window window) {
super.setWindowAnchor(window);
}
@Override
public StandOutLayoutParams onRequestLayoutParams() {
return mStandOutLayoutParams;
}
@Override
public int onRequestWindowFlags() {
return StandOutFlags.FLAG_BODY_MOVE_ENABLE
| StandOutFlags.FLAG_WINDOW_HIDE_ENABLE
| StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TAP
| StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE;
}
@Override
protected boolean onPrepareMove(Window window, View view, MotionEvent event) {
return !canMove;
}
@Override
public void onCreateAndAttachView(FrameLayout frame) {
prepareAnimations();
}
private void prepareAnimations() {
updateOrInitAnimation();
}
@Override
public boolean handleOutSideAction() {
if (mAnimating) {
return super.handleOutSideAction();
}
return super.handleOutSideAction();
}
private void updateOrInitAnimation() {
if (mAnimationCloseWindow != null){
mAnimationCloseWindow.cancel();
}
if (mAnimationShowContainer != null){
mAnimationShowContainer.cancel();
}
mAnimationCloseWindow = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,0.5f);
mAnimationCloseWindow.setFillAfter(true);
mAnimationCloseWindow.setDuration(300);
mAnimationCloseWindow.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimating = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimating = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mAnimationShowContainer = new ScaleAnimation(0.1f, 1.0f, 0.1f, 1.0f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
mAnimationShowContainer.setFillAfter(true);
mAnimationShowContainer.setDuration(300);
mAnimationShowContainer.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimating = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimating = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
@Override
public Animation getShowAnimation() {
return mAnimationShowContainer;
}
@Override
public Animation getHideAnimation() {
return mAnimationCloseWindow;
}
@Override
public Animation getCloseAnimation() {
return mAnimationCloseWindow;
}
@Override
protected void onInitParam(Bundle params) {
}
}
| 25.677632
| 104
| 0.647963
|
913f54c5f29b9c7d9c235e98d4e644689b352227
| 2,244
|
/*
******************************************************************************
* MIT License *
* Copyright (c) (2021 - Present) Viral Lalakia *
******************************************************************************
*/
package com.virallalakia.googlecodejam.cj2021.r1c.problemB_RoaringYears;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/*
* This is a solution for one of the problems for Google Code Jam 2021.
* Round: 1C
* Problem: Problem B (Roaring Years)
*/
public class Solution {
private static final Scanner SYS_IN =
new Scanner(new BufferedReader(new InputStreamReader(System.in)));
private static final Map<Integer, List<String>> UNEVEN_SEGMENT_ROARING_YEARS =
Map.ofEntries(
Map.entry(3, List.of("910")),
Map.entry(4, List.of("8910")),
Map.entry(5, List.of("78910", "91011", "99100")),
Map.entry(6, List.of("678910","891011")),
Map.entry(7, List.of("5678910", "7891011", "9101112", "9899100", "9991000")),
Map.entry(8, List.of("45678910", "67891011", "89101112", "99100101")),
Map.entry(9, List.of("345678910", "567891011", "789101112", "910111213", "979899100", "999910000")),
Map.entry(10, List.of("2345678910", "4567891011", "6789101112", "8910111213", "9899100101")),
Map.entry(11, List.of()),
Map.entry(12, List.of()),
Map.entry(13, List.of()),
Map.entry(14, List.of()),
Map.entry(15, List.of()),
Map.entry(16, List.of()),
Map.entry(17, List.of()),
Map.entry(18, List.of()),
Map.entry(19, List.of()));
public static void main(String[] args) {
int _T_ = SYS_IN.nextInt();
SYS_IN.nextLine();
for (int t = 0; t < _T_; t++) {
System.out.println(evaluateCase(t + 1));
}
SYS_IN.close();
}
private static String evaluateCase(final int t) {
long _A_ = SYS_IN.nextLong();
SYS_IN.nextLine();
try {
} catch (Exception ignored) {
}
return String.format("Case #%d: %d %d %d %d", t);
}
}
| 35.0625
| 110
| 0.536542
|
a3e2816ebaa4198351f4eef65d7e294392ac0402
| 10,503
|
/* Copyright (C) 2017 Red Hat, Inc.
This file is part of IcedTea.
IcedTea is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2.
IcedTea 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 for more details.
You should have received a copy of the GNU General Public License
along with IcedTea; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
*/
package cryptotest.tests;
import cryptotest.Settings;
import cryptotest.utils.AlgorithmInstantiationException;
import cryptotest.utils.AlgorithmRunException;
import cryptotest.utils.AlgorithmTest;
import cryptotest.utils.Misc;
import cryptotest.utils.TestResult;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;
import sun.security.jgss.GSSNameImpl;
import sun.security.jgss.krb5.Krb5NameElement;
import sun.security.krb5.PrincipalName;
import sun.security.krb5.Realm;
import sun.security.krb5.RealmException;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.kerberos.KerberosTicket;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.Provider;
import java.util.ArrayList;
import java.util.Arrays;
/*
* IwishThisCouldBeAtTest
*/
public class GssApiMechanismTests extends AlgorithmTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
TestResult r = new GssApiMechanismTests().mainLoop();
System.out.println(r.getExplanation());
System.out.println(r.toString());
r.assertItself();
}
private final boolean debug = false;
@Override
protected void checkAlgorithm(final Provider.Service service, final String alias) throws AlgorithmInstantiationException, AlgorithmRunException {
if (Settings.skipAgentTests) {
return;
}
try {
if (debug) {
System.setProperty("sun.security.jgss.debug", "true");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("java.security.debug", "logincontext,policy,scl,gssloginconfig");
}
//first get TCK tgt
///see http://icedtea.classpath.org/wiki/JCKDistilled#kerberos_prep for agent's setup
// in adition to user 1+2, service principal is needed:
// admin.local: addprinc -randkey http/service.redhat.com
// WARNING: no policy specified for http/service.redhat.com@JCKTEST; defaulting to no policy
// Principal "http/service.redhat.com@JCKTEST" created.
//System.setProperty("java.security.krb5.realm", "JCKTEST");
//System.setProperty("java.security.krb5.kdc", Misc.getAgentHostName());
//setting the proeprties diable cross-realm authentication.
//we must set krb5.cfg file
File f = Misc.createTmpKrb5File();
System.setProperty("java.security.krb5.conf", f.getAbsolutePath());
final LoginContext lc = new LoginContext("user1", new Subject(), new CallbackHandler() {
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName("user1");;
}
if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword("user1".toCharArray());;
}
}
}
}, Misc.getKrb5Configuration());
lc.login();
final Subject subject = lc.getSubject();
final Principal p = new ArrayList<>(subject.getPrincipals()).get(0);
final KerberosTicket t = (KerberosTicket) new ArrayList<>(subject.getPrivateCredentials()).get(0);
//this one is currently empty
subject.getPublicCredentials();
final GSSManager instance = GSSManager.getInstance();
//surprisingly getMechsbyName did nto found a thing....
//see names formechs in bellow
final Oid[] b = instance.getMechs();
Oid ffound = null;
for (Oid oid : b) {
if (oid.toString().equals(alias)) {
ffound = oid;
}
}
if (ffound == null) {
throw new RuntimeException("Manual search for " + alias + " in " + Arrays.toString(b) + " failed");
}
final Oid found = ffound;
//thisis bad attempt to enforce provider as given by general contract of this testsute, as it will fallback to default if necessary
instance.addProviderAtFront(service.getProvider(), found);
Subject.doAs(subject, new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
Oid[] names = instance.getNamesForMech(found);
for (Oid q : names) {
printResult(q.toString());
Oid[] a = instance.getMechsForName(q);
if (a.length == 0) {
throw new RuntimeException("more then 0 was expected for " + alias + " in " + service.getProvider() + " was " + a.length);
}
GSSName clientName = instance.createName("user1@JCKTEST", GSSName.NT_USER_NAME);
GSSCredential clientCred = instance.createCredential(clientName,
8 * 3600,
found,
GSSCredential.INITIATE_ONLY);
GSSName serverName = instance.createName("http@service."+Misc.getAgentDomain(), GSSName.NT_HOSTBASED_SERVICE);
//finish(serverName); no longer needed, configfile do it for us
GSSContext context = instance.createContext(serverName,
found,
clientCred,
//GSSContext.DEFAULT_LIFETIME);
60);
context.requestMutualAuth(true);
context.requestConf(false);
context.requestInteg(true);
final byte[] outToken = context.initSecContext(new byte[0], 0, 0);
printResult(outToken);
final GSSCredential creds = instance.createCredential(clientName, 10, found, GSSCredential.INITIATE_AND_ACCEPT);
context.dispose();
}
} catch (GSSException ex) {
throw new RuntimeException(ex);
}
return null;
}
private void finish(GSSName serverName) {
try {
finishImpl(serverName);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void finishImpl(GSSName serverName) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, RealmException {
Field f = GSSNameImpl.class.getDeclaredField("mechElement");
f.setAccessible(true);
Krb5NameElement o = (Krb5NameElement) f.get(serverName);
Field ff = Krb5NameElement.class.getDeclaredField("krb5PrincipalName");
ff.setAccessible(true);
PrincipalName oo = (PrincipalName) ff.get(o);
Field realmField = PrincipalName.class.getDeclaredField("nameRealm");
Field deductedField = PrincipalName.class.getDeclaredField("realmDeduced");
realmField.setAccessible(true);
deductedField.setAccessible(true);
deductedField.set(oo, false);
realmField.set(oo, new Realm("JCKTEST"));
}
});
} catch (LoginException | RuntimeException ex) {
throw new AlgorithmInstantiationException(ex);
} catch (GSSException ex) {
throw new AlgorithmRunException(ex);
}
}
@Override
public String getTestedPart() {
return "GssApiMechanism";
}
}
| 45.665217
| 155
| 0.609159
|
ff10f7b76ca45fed3702f27468b76cb5322d21cc
| 3,239
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.eventhubs.jproxy;
import com.azure.core.util.logging.ClientLogger;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
/**
*
*/
public class SimpleProxy implements ProxyServer {
private ClientLogger logger = new ClientLogger(SimpleProxy.class);
private final int port;
private final String hostname;
private final AtomicBoolean isRunning;
private Consumer<Throwable> onErrorHandler;
private volatile AsynchronousServerSocketChannel serverSocket;
public SimpleProxy(final String hostname, final int port) {
this.port = port;
this.hostname = hostname;
this.isRunning = new AtomicBoolean(false);
}
@Override
public void start(final Consumer<Throwable> onError) throws IOException {
if (isRunning.getAndSet(true)) {
throw new IllegalStateException("ProxyServer is already running");
}
onErrorHandler = onError;
serverSocket = AsynchronousServerSocketChannel.open();
serverSocket.bind(new InetSocketAddress("localhost", port));
scheduleListener(serverSocket);
}
@Override
public void stop() throws IOException {
if (isRunning.getAndSet(false)) {
serverSocket.close();
}
}
private void scheduleListener(final AsynchronousServerSocketChannel serverSocket) {
serverSocket.accept(serverSocket, new SocketListener(logger, onErrorHandler, isRunning));
}
private static final class SocketListener implements
CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> {
private final ClientLogger logger;
private final Consumer<Throwable> onErrorHandler;
private final AtomicBoolean isRunning;
private SocketListener(ClientLogger logger, Consumer<Throwable> onErrorHandler, AtomicBoolean isRunning) {
this.logger = logger;
this.onErrorHandler = onErrorHandler;
this.isRunning = isRunning;
}
@Override
public void completed(AsynchronousSocketChannel client, AsynchronousServerSocketChannel serverSocket) {
try {
logger.warning("Client connected from: {}", client.getRemoteAddress().toString());
} catch (IOException e) {
logger.error("Error occurred while getting remote address.", e);
}
logger.info("Setting negotiation handler.");
serverSocket.accept(serverSocket, this);
try {
new ProxyNegotiationHandler(client);
} catch (IOException e) {
onErrorHandler.accept(e);
}
}
@Override
public void failed(Throwable exception, AsynchronousServerSocketChannel attachment) {
isRunning.set(false);
onErrorHandler.accept(exception);
}
}
}
| 33.739583
| 114
| 0.686014
|
ff144992eb39f0f1015a8a58a210e8b019a153f4
| 2,500
|
package ie.adapt.tcd.nlp.text;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import ie.adapt.tcd.iostream.DocsReader;
/**
*
* @author Mostafa Bayomi
* This class is to hold the document that is being processed.
* The class has different methods to help in getting the required fields in the document to be used in processing that document.
* It has functionalities to retrieve:<br><ul>
* - The document's text,
* - document's unique terms
* - sentences as strings
* - sentences as tokens
* - tokens of each sentence
*/
public class Document {
private String documentText="";
public ArrayList<String> docSentences;
private TextProcessor tp;
String sentencesBreak = null;
private String filePath="";
public Document(String filePath, String sBreak){
this.filePath = filePath;
sentencesBreak = sBreak;
documentText = DocsReader.readFile(filePath);
try {
tp = new TextProcessor();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* A method to return the document sentences
* @return ArrayList of all sentences of the file
*/
public ArrayList<String> getDocumentSentences(){
String [] lines = documentText.split(sentencesBreak);
return new ArrayList<String>(Arrays.asList(lines));
}
public ArrayList<String> getDocumentSentences(int haps){ // this splitter is just for haps dataset
documentText = documentText.trim(); // to add the last segment of the text
//documentText +="\n";
String sentenceBreak = "\n";
String [] lines = documentText.split(sentenceBreak);
boolean newSegment = false;
ArrayList<String> returned = new ArrayList<String>();
String segment ="";
for (int i = 0; i < lines.length; i++) {
String line = lines[i].trim();
if(!line.equals("")){
newSegment = true;
segment+=lines[i];
if(i==lines.length-1)// for the last segment
returned.add(segment);
}
else{
if(newSegment){
returned.add(segment);
segment = "";
newSegment = false;
}
}
}
return returned;
}
public String getFileName(){
//As I am returning a string from the readFile method, I cannot use file.getName(), I have to implement it myself
String pattern = Pattern.quote(System.getProperty("file.separator"));
String [] fileNameParts= filePath.split(pattern);
String fileName = fileNameParts[fileNameParts.length-1];
return fileName;
}
}
| 27.472527
| 129
| 0.6992
|
19109a07475eba6753075d643d45ddf5ae06dfc5
| 803
|
package com.df.aizhuan.trade.api.params;
public class AuditBuyingOrderParam {
private String buyingOrderNo;
private String auditor;
private Boolean pass;
private String remark;
public String getBuyingOrderNo() {
return buyingOrderNo;
}
public void setBuyingOrderNo(String buyingOrderNo) {
this.buyingOrderNo = buyingOrderNo;
}
public String getAuditor() {
return auditor;
}
public void setAuditor(String auditor) {
this.auditor = auditor;
}
public Boolean getPass() {
return pass;
}
public void setPass(Boolean pass) {
this.pass = pass;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
| 19.119048
| 56
| 0.630137
|
cfca2bb970061bc964e60ecea47f5708cef3dc64
| 397
|
package com.template.config;
import org.springframework.beans.factory.annotation.*;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import springfox.documentation.swagger2.annotations.*;
@EnableSwagger2
@Configuration
@Profile("PREPRODUCTION")
public class PreproductionTemplateConfiguration {
@Autowired private Environment environment;
}
| 26.466667
| 54
| 0.831234
|
7626ca9b3796ff9ff56f453da802282b49ababfc
| 1,012
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
public class SortIncDec {
/*
11.2
*/
public static List<Integer> sort(List<Integer> list) {
List<PriorityQueue<Integer>> priorityQueueList = new ArrayList<>();
if (list.size() < 2) return list;
boolean increasing = list.get(0) < list.get(1);
int e = 0;
priorityQueueList.add(new PriorityQueue<>(Integer::compareTo));
for (int i = 1; i < list.size(); i++) {
if (increasing == (list.get(i-1) < list.get(i))) {
priorityQueueList.get(e).offer(list.get(i));
}
}
//PUT PRIORITY QUEUES INTO LIST OF LISTS TO BE PROCESSED BY THE SOLUTION TO 11.1
List<List<Integer>> result = new ArrayList<>();
for (PriorityQueue<Integer> pq : priorityQueueList) {
result.add(new ArrayList<>(pq));
}
return MergeSortedFiles.mergeSorted(result);
}
}
| 28.914286
| 88
| 0.596838
|
6d8b5d069bea157914b9e995e577c245a8e25777
| 970
|
package com.heanbian.block.zabbix.api;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ZabbixHostGroupGetRequest {
private Map<String, Object> params = new HashMap<>();
public Map<String, Object> getParams() {
return params;
}
public ZabbixHostGroupGetRequest addField(String fieldName, Object fieldValue) {
this.params.put(fieldName, fieldValue);
return this;
}
/**
*
* @param output "extend"
* @return ZabbixHostGroupGetRequest
*/
public ZabbixHostGroupGetRequest setOutput(String output) {
this.params.put("output", output);
return this;
}
public ZabbixHostGroupGetRequest setFilterNames(String... names) {
return this.setFilterNames(Arrays.asList(names));
}
public ZabbixHostGroupGetRequest setFilterNames(List<String> names) {
Map<String, Object> filter = new HashMap<>(1);
filter.put("name", names);
this.params.put("filter", filter);
return this;
}
}
| 22.045455
| 81
| 0.735052
|
7bc383adf3a12fa4a4b0d17d94de3edcd2d3da4f
| 1,421
|
package info.fingo.urlopia.history;
import info.fingo.urlopia.config.persistance.BaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime;
import java.util.List;
public interface HistoryLogRepository extends BaseRepository<HistoryLog>, JpaRepository<HistoryLog, Long> {
HistoryLog findFirstByUserIdOrderById(Long userId);
HistoryLog findFirstByUserIdOrderByIdDesc(Long userId);
HistoryLog findFirstByRequestId(Long requestId);
List<HistoryLogExcerptProjection> findByUserId(long userId);
Page<HistoryLogExcerptProjection> findByUserId(long userId, Pageable pageable);
List<HistoryLogExcerptProjection> findFirst5ByUserIdOrderByCreatedDesc(Long userId);
List<HistoryLog> findLogsByUserIdAndCreatedBetween(long userId,
LocalDateTime startDate,
LocalDateTime endDate);
List<HistoryLog> findLogsByUserId(long userId);
@Query("""
SELECT COALESCE(SUM(h.hours), 0)
FROM HistoryLog h
WHERE h.user.id = :userId
""")
Float sumHours(@Param("userId") Long userId);
}
| 35.525
| 107
| 0.719212
|
36948c9ee08f8a3ea7651812fffea7fb59979e05
| 390
|
package com.lennon.tom;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) {
String sourceFile = args[0];
String sourceColumn = args[1];
String compareFile = args[2];
String compareColumn = args[3];
OnOff status = OnOff.ON;
new ExcelMerger(sourceFile, sourceColumn, compareFile, compareColumn);
}
}
| 20.526316
| 78
| 0.617949
|
adaee212bde2254c02e0f9e406924f71da7d6cdf
| 1,217
|
package tw.com.mitake;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import tw.com.mitake.response.GetTimelineEventsResponse;
import tw.com.mitake.response.GetTimelineEventsResponse.GetTimelineEventsResponseResponse.GetTimelineEventsResponseData.GetTimelineEventsResponseEvent;
import tw.com.mitake.response.PostTimelineEventResponse;
public class QmiAnotherUrlTest {
private Qmi qmi;
@Before
public void setup() {
qmi = Qmi.init(System.getenv("QMI_TOKEN"), System.getenv("QMI_BASE_URL"));
}
@Test
public void testPostToTimeline() {
PostTimelineEventResponse response = qmi.postToTimeline("Hello World from Qmi OpenAPI for Java library");
Assert.assertNotNull(response.getEventId());
}
@Test
public void testGetEventsFromTimeline() {
GetTimelineEventsResponse response = qmi.getEventsFromTimeline();
for (GetTimelineEventsResponseEvent event : response.getEvents()) {
Assert.assertNotNull(event.getMessage());
Assert.assertNotNull(event.getCreatedTime());
Assert.assertNotNull(event.getEventId());
Assert.assertNotNull(event.getEventType());
}
}
}
| 33.805556
| 151
| 0.727198
|
fe00aa9c616ec01f6e97567ed2dde83c0cb75165
| 277
|
package sexy.fairly.smartwatch.game2048;
public class Cell {
public int x;
public int y;
public Cell(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "cell; x: " + x + ", y: " + y;
}
}
| 16.294118
| 45
| 0.512635
|
5b93a9aa7133d1feed1b141d41ff4bc31507f70f
| 490
|
package com.oberasoftware.home.zwave.api;
import com.oberasoftware.base.event.EventHandler;
import com.oberasoftware.home.zwave.api.actions.ZWaveAction;
import com.oberasoftware.home.zwave.exceptions.HomeAutomationException;
/**
* @author renarj
*/
public interface Controller {
void initializeNetwork();
int getControllerId();
void subscribe(EventHandler topicListener);
int send(ZWaveAction message) throws HomeAutomationException;
boolean isNetworkReady();
}
| 23.333333
| 71
| 0.781633
|
268098bb45f5d50cb4bb98585fff83c02b94dd8d
| 4,347
|
package com.latex.generator.views.TeacherInformation;
import com.latex.generator.backend.Database;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.vaadin.flow.component.*;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.polymertemplate.Id;
import com.vaadin.flow.component.polymertemplate.PolymerTemplate;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.PasswordField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import com.vaadin.flow.templatemodel.TemplateModel;
import com.latex.generator.MainView;
import org.bson.Document;
import java.util.ArrayList;
import java.util.prefs.Preferences;
import static com.mongodb.client.model.Filters.eq;
@Route(value = "Teacher-Information", layout = MainView.class)
@RouteAlias(value = "", layout = MainView.class)
@PageTitle("Teacher-Information")
@JsModule("src/views/TeacherInformation/teacher-information.js")
@Tag("Teacher-Information")
public class TeacherInformation extends PolymerTemplate<TeacherInformation.FormViewModel> {
ArrayList<String> names = new ArrayList<>();
String teacherEmail = "";
public static interface FormViewModel extends TemplateModel {
}
@Id
private TextField FirstName;
@Id
private TextField LastName;
@Id
private TextField UniversityName;
@Id
private TextField EstablishmentName;
@Id
private Button Save;
@Id
private EmailField Email;
@Id
private PasswordField NewPassword;
@Id
private PasswordField RepeatPassword;
public TeacherInformation() {
if (Database.db == null) {
Database.connect();
}
Preferences prefs = Preferences.userNodeForPackage(MainView.class);
teacherEmail = prefs.get("TeacherEmail", "Undefined");
String db_coll_name = "Users";
MongoCollection<Document> col = Database.db.getCollection(db_coll_name);
FindIterable<Document> fi = col.find(eq("Email", teacherEmail));
MongoCursor<Document> cursor = fi.iterator();
if (cursor.hasNext()) {
Document dc = cursor.next();
FirstName.setValue(dc.getString("FirstName"));
LastName.setValue(dc.getString("LastName"));
Email.setValue(dc.getString("Email"));
UniversityName.setValue(dc.getString("UniversityName"));
EstablishmentName.setValue(dc.getString("EstablishmentName"));
}
Save.addClickListener(e -> {
updateTeacherInformation(Database.db.getCollection("Users"));
});
}
private void updateTeacherInformation(MongoCollection<Document> collection) {
collection.updateOne(eq("Email", teacherEmail), new Document("$set", new Document("FirstName", FirstName.getValue())));
collection.updateOne(eq("Email", teacherEmail), new Document("$set", new Document("LastName", Email.getValue())));
collection.updateOne(eq("Email", teacherEmail), new Document("$set", new Document("Email", Email.getValue())));
collection.updateOne(eq("Email", teacherEmail), new Document("$set", new Document("UniversityName", UniversityName.getValue())));
collection.updateOne(eq("Email", teacherEmail), new Document("$set", new Document("EstablishmentName",EstablishmentName.getValue())));
Notification.show("The teacher information has been updated successfully !", 2000, Notification.Position.BOTTOM_CENTER);
}
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
}
| 34.5
| 144
| 0.699333
|
28455c3d03204461296d41441afe8be80a93680d
| 743
|
package seedu.stock.logic.commands;
import static seedu.stock.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.stock.logic.commands.ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT;
import org.junit.jupiter.api.Test;
import seedu.stock.model.Model;
import seedu.stock.model.ModelManager;
public class ExitCommandTest {
private Model model = new ModelManager();
private Model expectedModel = new ModelManager();
@Test
public void execute_exit_success() {
CommandResult expectedResult = new CommandResult(MESSAGE_EXIT_ACKNOWLEDGEMENT,
null, false, false, null, false, null, false, true);
assertCommandSuccess(new ExitCommand(), model, expectedResult, expectedModel);
}
}
| 32.304348
| 86
| 0.761777
|
93d6a70ae757725d8fa6f3da59d241fed281277b
| 8,589
|
package de.konfidas.ttc.messages.systemlogs;
import de.konfidas.ttc.exceptions.BadFormatForLogMessageException;
import de.konfidas.ttc.messages.SystemLogMessage;
import de.konfidas.ttc.utilities.DLTaggedObjectConverter;
import org.bouncycastle.asn1.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
/**
* Diese Klasse repräsentiert eine authenticateUserSystemLog Message. Dabei werden in der Methode
* parseSystemOperationDataContent die folgenden Elemente aus systemOperationData geparst
* <pre>
* ╔═══════════════════════╤══════╤═══════════════════════════════════════════════════════════════╤════════════╗
* ║ Data field │ Tag │ Data Type │ Mandatory? ║
* ╠═══════════════════════╪══════╪═══════════════════════════════════════════════════════════════╪════════════╣
* ║ userID │ 0x81 │ PrintableString │ m ║
* ╟───────────────────────┼──────┼───────────────────────────────────────────────────────────────┼────────────╢
* ║ oldVersion │ 0x84 │ OCTECTSTRING │ m ║
* ╚═══════════════════════╧══════╧══════════════════════════════════╧═════════════════════════════════════════╝
* </pre>
*/
public class UpdateDeviceSystemLogMessage extends SystemLogMessage {
final static Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
static Locale locale = new Locale("de", "DE"); //NON-NLS
static ResourceBundle properties = ResourceBundle.getBundle("ttc",locale);//NON-NLS
public DLTaggedObject getUserId() {
return userId;
}
public void setUserId(DLTaggedObject userId) {
this.userId = userId;
}
public DLTaggedObject getOldVersion() {
return oldVersion;
}
public void setOldVersion(DLTaggedObject oldVersion) {
this.oldVersion = oldVersion;
}
public String getUserIDAsString() {
return userIDAsString;
}
public void setUserIDAsString(String userIDAsString) {
this.userIDAsString = userIDAsString;
}
public String getOldVersionComponentName() {
return oldVersionComponentName;
}
public void setOldVersionComponentName(String oldVersionComponentName) {
this.oldVersionComponentName = oldVersionComponentName;
}
public String getOldVersionManufacturer() {
return oldVersionManufacturer;
}
public void setOldVersionManufacturer(String oldVersionManufacturer) {
this.oldVersionManufacturer = oldVersionManufacturer;
}
public String getOldVersionModel() {
return oldVersionModel;
}
public void setOldVersionModel(String oldVersionModel) {
this.oldVersionModel = oldVersionModel;
}
public String getOldVersionVersion() {
return oldVersionVersion;
}
public void setOldVersionVersion(String oldVersionVersion) {
this.oldVersionVersion = oldVersionVersion;
}
public String getOldVersionCertificationID() {
return oldVersionCertificationID;
}
public void setOldVersionCertificationID(String oldVersionCertificationID) {
this.oldVersionCertificationID = oldVersionCertificationID;
}
DLTaggedObject userId;
DLTaggedObject oldVersion;
String userIDAsString;
String oldVersionComponentName;
String oldVersionManufacturer;
String oldVersionModel;
String oldVersionVersion;
String oldVersionCertificationID;
public UpdateDeviceSystemLogMessage(byte[] content, String filename) throws BadFormatForLogMessageException {
super(content, filename);
}
@Override
protected void parseSystemOperationDataContent(ASN1InputStream stream) throws IOException {
ASN1Primitive systemOperationData = stream.readObject();
if (!(systemOperationData instanceof ASN1Sequence)) this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorParsingSystemOperationDataContent")));
List<ASN1Primitive> systemOperationDataAsAsn1List = Collections.list(((ASN1Sequence) systemOperationData).getObjects());
ListIterator<ASN1Primitive> systemOperationDataIterator = systemOperationDataAsAsn1List.listIterator();
try {
//userID einlesen
DLTaggedObject nextElement = (DLTaggedObject) systemOperationDataAsAsn1List.get(systemOperationDataIterator.nextIndex());
if (nextElement.getTagNo() != 1) this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorParsingSystemOperationDataContentUserIDNotFound")));
this.userId = (DLTaggedObject) systemOperationDataIterator.next();
this.userIDAsString = DLTaggedObjectConverter.dLTaggedObjectToString(this.userId);
//oldVersion einlesen
nextElement = (DLTaggedObject) systemOperationDataAsAsn1List.get(systemOperationDataIterator.nextIndex());
if (nextElement.getTagNo() != 3) this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorParsingSystemOperationDataContentOldVersionNotFound")));
this.oldVersion = (DLTaggedObject) systemOperationDataIterator.next();
//oldVersion is a Sequence in itself. Parsing follows
if (this.oldVersion.getObject() instanceof ASN1Sequence) {
List<ASN1Primitive> deviceInformationSetAsASN1List = Collections.list(((ASN1Sequence) this.oldVersion.getObject()).getObjects());
ListIterator<ASN1Primitive> deviceInformationSetIterator = deviceInformationSetAsASN1List.listIterator();
if (!deviceInformationSetIterator.hasNext()) this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorDeviceInformationSetOfUpdateTimeEndedEarly")));
List<ASN1Primitive> componentInformationSetAsASN1 = Collections.list(((ASN1Sequence) deviceInformationSetAsASN1List.get(deviceInformationSetIterator.nextIndex())).getObjects());
ListIterator<ASN1Primitive> componentInformationSetItertator = componentInformationSetAsASN1.listIterator();
//component Name
if (!deviceInformationSetIterator.hasNext()) this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorComponentInformationSetOfUpdateTimeEndedEarly")));
ASN1Primitive element = deviceInformationSetIterator.next();
this.oldVersionComponentName = ((ASN1String) element).getString();
//manufacturer
if (!deviceInformationSetIterator.hasNext()) this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorComponentInformationSetOfUpdateTimeEndedEarly")));
element = deviceInformationSetIterator.next();
this.oldVersionManufacturer = ((ASN1String) element).getString();
//model
if (!deviceInformationSetIterator.hasNext()) this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorComponentInformationSetOfUpdateTimeEndedEarly")));
element = deviceInformationSetIterator.next();
this.oldVersionModel = ((ASN1String) element).getString();
//version
if (!deviceInformationSetIterator.hasNext()) this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorComponentInformationSetOfUpdateTimeEndedEarly")));
element = deviceInformationSetIterator.next();
this.oldVersionVersion = ((ASN1String) element).getString(); //version
if (deviceInformationSetIterator.hasNext()) {
element = deviceInformationSetIterator.next();
this.oldVersionCertificationID = ((ASN1String) element).getString();
}
}
else this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorOldVersionDoesNotStartWithSequence")));
}
catch (NoSuchElementException ex){
this.allErrors.add(new SystemLogParsingError(properties.getString("de.konfidas.ttc.messages.systemlogs.errorEarlyEndOfSystemOperationData"), ex));
}
}
}
| 46.177419
| 219
| 0.673652
|
db17fd61fa88511b7359e50df6c69827b1ed4cdb
| 7,745
|
/*
* Copyright 2017-2018 floragunn GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.floragunn.searchguard.tools.util;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Strings;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class EsNodeConfig {
@JsonProperty("searchguard.ssl.transport.pemcert_filepath")
private String transportPemCertFilePath;
@JsonProperty("searchguard.ssl.transport.pemkey_filepath")
private String transportPemKeyFilePath;
@JsonProperty("searchguard.ssl.transport.pemkey_password")
private String transportPemKeyPassword;
@JsonProperty("searchguard.ssl.transport.pemtrustedcas_filepath")
private String transportPemTrustedCasFilePath;
@JsonProperty("searchguard.ssl.transport.enforce_hostname_verification")
private boolean transportEnforceHostnameVerification = false;
@JsonProperty("searchguard.ssl.transport.resolve_hostname")
private boolean transportResolveDns = false;
@JsonProperty("searchguard.ssl.http.enabled")
private boolean httpsEnabled = true;
@JsonProperty("searchguard.ssl.http.pemcert_filepath")
private String httpPemCertFilePath;
@JsonProperty("searchguard.ssl.http.pemkey_filepath")
private String httpPemKeyFilePath;
@JsonProperty("searchguard.ssl.http.pemkey_password")
private String httpPemKeyPassword;
@JsonProperty("searchguard.ssl.http.pemtrustedcas_filepath")
private String httpPemTrustedCasFilePath;
@JsonProperty("searchguard.nodes_dn")
private List<String> nodesDn;
@JsonProperty("searchguard.authcz.admin_dn")
private List<String> authczAdminDn;
@JsonProperty("searchguard.cert.oid")
private String certOid = null;
@JsonProperty("searchguard.ssl.http.clientauth_mode")
private String clientAuthMode = null;
@JsonProperty("searchguard.ssl.transport.keystore_filepath")
private String transportKeystoreFilePath;
@JsonProperty("searchguard.ssl.transport.truststore_filepath")
private String transportTruststoreFilepath;
@JsonProperty("searchguard.ssl.http.keystore_filepath")
private String httpKeystoreFilepath;
@JsonProperty("searchguard.ssl.http.truststore_filepath")
private String httpTruststoreFilepath;
public String getTransportPemCertFilePath() {
return transportPemCertFilePath;
}
public void setTransportPemCertFilePath(String transportPemCertFilePath) {
this.transportPemCertFilePath = transportPemCertFilePath;
}
public String getTransportPemKeyFilePath() {
return transportPemKeyFilePath;
}
public void setTransportPemKeyFilePath(String transportPemKeyFilePath) {
this.transportPemKeyFilePath = transportPemKeyFilePath;
}
public String getTransportPemKeyPassword() {
return transportPemKeyPassword;
}
public void setTransportPemKeyPassword(String transportPemKeyPassword) {
this.transportPemKeyPassword = transportPemKeyPassword;
}
public String getTransportPemTrustedCasFilePath() {
return transportPemTrustedCasFilePath;
}
public void setTransportPemTrustedCasFilePath(String transportPemTrustedCasFilePath) {
this.transportPemTrustedCasFilePath = transportPemTrustedCasFilePath;
}
public boolean isTransportEnforceHostnameVerification() {
return transportEnforceHostnameVerification;
}
public void setTransportEnforceHostnameVerification(boolean transportEnforceHostnameVerification) {
this.transportEnforceHostnameVerification = transportEnforceHostnameVerification;
}
public boolean isHttpsEnabled() {
return httpsEnabled;
}
public void setHttpsEnabled(boolean httpsEnabled) {
this.httpsEnabled = httpsEnabled;
}
public String getHttpPemCertFilePath() {
return httpPemCertFilePath;
}
public void setHttpPemCertFilePath(String httpPemCertFilePath) {
this.httpPemCertFilePath = httpPemCertFilePath;
}
public String getHttpPemKeyFilePath() {
return httpPemKeyFilePath;
}
public void setHttpPemKeyFilePath(String httpPemKeyFilePath) {
this.httpPemKeyFilePath = httpPemKeyFilePath;
}
public String getHttpPemKeyPassword() {
return httpPemKeyPassword;
}
public void setHttpPemKeyPassword(String httpPemKeyPassword) {
this.httpPemKeyPassword = httpPemKeyPassword;
}
public String getHttpPemTrustedCasFilePath() {
return httpPemTrustedCasFilePath;
}
public void setHttpPemTrustedCasFilePath(String httpPemTrustedCasFilePath) {
this.httpPemTrustedCasFilePath = httpPemTrustedCasFilePath;
}
public List<String> getNodesDn() {
return nodesDn;
}
public void setNodesDn(List<String> nodesDn) {
this.nodesDn = nodesDn;
}
public List<String> getAuthczAdminDn() {
return authczAdminDn;
}
public void setAuthczAdminDn(List<String> authczAdminDn) {
this.authczAdminDn = authczAdminDn;
}
public String getCertOid() {
return certOid;
}
public void setCertOid(String certOid) {
this.certOid = certOid;
}
public String getClientAuthMode() {
return clientAuthMode;
}
public void setClientAuthMode(String clientAuthMode) {
this.clientAuthMode = clientAuthMode;
}
public boolean isTransportResolveDns() {
return transportResolveDns;
}
public void setTransportResolveDns(boolean transportResolveDns) {
this.transportResolveDns = transportResolveDns;
}
public String getTransportKeystoreFilePath() {
return transportKeystoreFilePath;
}
public void setTransportKeystoreFilePath(String transportKeystoreFilePath) {
this.transportKeystoreFilePath = transportKeystoreFilePath;
}
public String getTransportTruststoreFilepath() {
return transportTruststoreFilepath;
}
public void setTransportTruststoreFilepath(String transportTruststoreFilepath) {
this.transportTruststoreFilepath = transportTruststoreFilepath;
}
public String getHttpKeystoreFilepath() {
return httpKeystoreFilepath;
}
public void setHttpKeystoreFilepath(String httpKeystoreFilepath) {
this.httpKeystoreFilepath = httpKeystoreFilepath;
}
public String getHttpTruststoreFilepath() {
return httpTruststoreFilepath;
}
public void setHttpTruststoreFilepath(String httpTruststoreFilepath) {
this.httpTruststoreFilepath = httpTruststoreFilepath;
}
@JsonIgnore
public boolean isKeystoreOrTruststoreAttributeSet() {
return !Strings.isNullOrEmpty(transportKeystoreFilePath) || !Strings.isNullOrEmpty(transportTruststoreFilepath)
|| !Strings.isNullOrEmpty(httpKeystoreFilepath) || !Strings.isNullOrEmpty(httpTruststoreFilepath);
}
}
| 31.229839
| 119
| 0.749645
|
7113b83ab2b7aeda84f8d166c5a134bdb02cb116
| 2,674
|
package com.tp.challenge.restapi.familym;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FamilyMController {
@Autowired
private FamilyMService familyMService;
@RequestMapping("/families/{id}/familiesm")
public List<FamilyM> getAllFamiliesM(@PathVariable String id){
return familyMService.getAllFamiliesmByFamilyId(id);
}
@RequestMapping("/familiesm/GRatio/{criteria}")
public List<FindFamily> GetFamilyGRatio(@PathVariable String criteria){
return familyMService.GetFamilyGrowingRatio(criteria);
}
@RequestMapping("/familiesm/GetFAAge/{criteria}")
public List<FindFamily> GetAcumulatedAge(@PathVariable String criteria){
return familyMService.GetFamilyAcumulatedAge(criteria);
}
@RequestMapping("/familiesm")
public List<FamilyM> getAllFamiliesM(){
return familyMService.getAllFamiliesM();
}
@RequestMapping("/familiesm/{id}")
@ResponseStatus(HttpStatus.OK)
public FamilyM getFamilyM(@PathVariable long id){
return familyMService.getFamilyM(id);
}
@RequestMapping(method=RequestMethod.POST , value="/familiesm")
public ResponseEntity<?> addFamilyM(@RequestBody @Valid FamilyM familym, String family_id){
familyMService.addFamilyM(familym);
return ResponseEntity.ok("Resource POST");
}
@RequestMapping(method=RequestMethod.DELETE , value="/familiesm/{id}")
public ResponseEntity<?> deleteFamilyM(@PathVariable long id){
if (familyMService.deleteFamilyM(id)) {
return ResponseEntity.ok("Resource DELETED");
}
return ResponseEntity.ok(HttpStatus.NOT_FOUND);
}
@RequestMapping(method=RequestMethod.PATCH , value="/familiesm/{id}")
public ResponseEntity<?> updateparcialFamilyM(@RequestBody @Valid FamilyM familym,@PathVariable long id){
familyMService.updparcialFamilyM(id, familym);
return ResponseEntity.ok("Resource PATCH");
}
@RequestMapping(method=RequestMethod.PUT , value="/familiesm/{id}")
public ResponseEntity<?> updateFamilyM(@RequestBody @Valid FamilyM familym,String familyid,@PathVariable String id){
familyMService.updFamilyM(familym);
return ResponseEntity.ok("Resource PUT");
}
}
| 33.012346
| 117
| 0.786836
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.