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 |
|---|---|---|---|---|---|
fce4042c9a61aabf31d8570d692899a234e1cbc4 | 1,067 | package top.niunaijun.blackbox.utils.compat;
import java.lang.reflect.Method;
import java.util.List;
import reflection.android.content.pm.ParceledListSlice;
import reflection.android.content.pm.ParceledListSliceJBMR2;
public class ParceledListSliceCompat {
public static boolean isReturnParceledListSlice(Method method) {
return method != null && method.getReturnType() == ParceledListSlice.REF.getClazz();
}
public static boolean isParceledListSlice(Object obj) {
return obj != null && obj.getClass() == ParceledListSlice.REF.getClazz();
}
public static Object create(List<?> list) {
if (ParceledListSliceJBMR2.constructor != null) {
return ParceledListSliceJBMR2.constructor.newInstance(list);
} else {
Object slice = ParceledListSlice.constructor.newInstance();
for (Object item : list) {
ParceledListSlice.append.call(slice, item);
}
ParceledListSlice.setLastSlice.call(slice, true);
return slice;
}
}
}
| 32.333333 | 92 | 0.677601 |
6b13c0733065e3f3462f3accc2694f8b61fc4115 | 1,023 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tictactoe;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
*
* @author supriyasingh
*/
public class XOButton extends JButton implements ActionListener {
ImageIcon X, O;
byte value = 0;// 0= nothing, 1= X, 2 =O
public XOButton() {
X = new ImageIcon(this.getClass().getResource("circle.png"));
O = new ImageIcon(this.getClass().getResource("X_G.png"));
this.addActionListener(this); // button is triggering action and listening also.
}
public void actionPerformed(ActionEvent e) {
value++;
value %= 3;
switch (value) {
case 0:
setIcon(null);
break;
case 1:
setIcon(X);
break;
case 2:
setIcon(O);
break;
}
}
}
| 23.25 | 88 | 0.57087 |
040b67fc17446b36b8854644834c9037eff6012b | 1,739 | package es.rcs.tfm.db.model;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.envers.RevisionEntity;
import org.hibernate.envers.RevisionNumber;
import org.hibernate.envers.RevisionTimestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.annotation.LastModifiedBy;
import es.rcs.tfm.db.setup.RevisionEntityListener;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter()
@Setter
@ToString
@EqualsAndHashCode(callSuper = false)
@Table(name="cfg_revisions")
@Entity
@RevisionEntity(value = RevisionEntityListener.class)
public class AuditedRevisionEntity {
@Transient
private static final long serialVersionUID = 8285764735164645528L;
@Transient
private static final Logger LOG = LoggerFactory.getLogger(AuditedBaseEntity.class);
@RevisionNumber
@Id
@GeneratedValue(
strategy = GenerationType.IDENTITY)
@Column(
unique = true,
nullable = false,
insertable = true,
updatable = true)
protected int id;
@RevisionTimestamp
@Column(
unique = false,
nullable = false,
insertable = true,
updatable = true)
private Long timestamp;
@Column(
unique = false,
nullable = false,
length = 256)
@LastModifiedBy
private String modifiedBy;
@Transient
public LocalDateTime getRevisionDate() {
return Instant.ofEpochMilli(timestamp).atZone(ZoneId.of("UTC")).toLocalDateTime();
}
}
| 23.186667 | 84 | 0.780334 |
47bb66d4a5f873cf89657095b7e7278641748452 | 2,247 | package ilusr.textadventurecreator.statusbars;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.AnchorPane;
/**
*
* @author Jeff Riggle
*
*/
public class ProjectStatus extends AnchorPane implements Initializable {
@FXML
private Label statusText;
@FXML
private ProgressBar progress;
private ProjectStatusModel model;
private String lastClass;
/**
*
* @param model A @see ProjectStatusModel to bind to.
*/
public ProjectStatus(ProjectStatusModel model) {
this.model = model;
FXMLLoader loader = new FXMLLoader(getClass().getResource("ProjectStatus.fxml"));
loader.setController(this);
loader.setRoot(this);
try {
loader.load();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
this.getStylesheets().add(getClass().getResource("ProjectStatus.css").toExternalForm());
toggleVisibility(false);
statusText.textProperty().bind(model.statusText());
progress.progressProperty().bind(model.progressAmount());
model.statusText().addListener((v, o, n) -> {
if (n == null) {
toggleVisibility(false);
} else {
toggleVisibility(true);
}
});
updateIndicator(model.indicator().get());
model.indicator().addListener((v, o, n) -> {
updateIndicator(n);
});
}
private void toggleVisibility(boolean visible) {
statusText.visibleProperty().set(visible);
progress.visibleProperty().set(visible);
}
private void updateIndicator(StatusIndicator indicator) {
if (indicator == null) {
return;
}
String styleClass = null;
switch (indicator) {
case Error:
styleClass = "error";
break;
case Good:
styleClass = "good";
break;
case Normal:
styleClass = "normal";
break;
case Warning:
styleClass = "warning";
break;
}
if (styleClass == null) {
return;
}
if (lastClass != null) {
progress.getStyleClass().remove(lastClass);
}
progress.getStyleClass().add(styleClass);
lastClass = styleClass;
}
}
| 20.614679 | 90 | 0.689809 |
f0fd3b8af2e3185c10d71d1fa25b2d2874d75868 | 533 | package com.instantappsamples.base;
import android.app.Application;
import android.util.Log;
//import com.example.baselibrary.DebugHelp;
/**
* Created by zhangyu on 2017/8/22.
*/
public class InstantApplication extends Application {
public InstantApplication() {
super();
}
@Override
public void onCreate() {
super.onCreate();
Log.v("Instant", "InstantApplication onCreate");
// DebugHelp debugHelp = new DebugHelp();
// debugHelp.Debug("This is base module");
}
}
| 19.035714 | 56 | 0.658537 |
7ff665d9d06a02c15494fe0fb8b682e9d275295d | 404 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package da;
import da.medios.medios;
import java.util.Collection;
/**
*
* @author Druet Rodriguez
*/
public interface ImediosManager {
public Collection<medios> obtener_medios();
}
| 20.2 | 80 | 0.680693 |
8cc75a62f8490ed856bfbd3da4e16760f69f614b | 1,164 | package fr.kbertet.lattice.io;
/*
* ConceptLatticeWriter.java
*
* Copyright: 2010-2014 Karell Bertet, France
*
* License: http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html CeCILL-B license
*
* This file is part of java-lattices, free package. You can redistribute it and/or modify
* it under the terms of CeCILL-B license.
*/
import java.io.BufferedWriter;
import java.io.IOException;
import fr.kbertet.lattice.ConceptLattice;
/**
* This interface defines a standard way for writing a concept lattice.
*
* 
*
* @uml ConceptLatticeWriter.png
* !include resources/fr/kbertet/lattice/io/ConceptLatticeWriter.iuml
*
* hide members
* show ConceptLatticeWriter members
* class ConceptLatticeWriter #LightCyan
* title ConceptLatticeWriter UML graph
*/
public interface ConceptLatticeWriter {
/**
* Write a concept lattice to a file.
*
* @param lattice a concept lattice to write
* @param file a file
*
* @throws IOException When an IOException occurs
*/
void write(ConceptLattice lattice, BufferedWriter file) throws IOException;
}
| 26.454545 | 90 | 0.728522 |
d89fb2f00e7a564a37c38cc4e62746e7e50a0824 | 239 | package com.tts.day3;
// all interfaces are abstract by default
public interface Abstractable {
// this method is abstract
// we are only defining the return type
// the name, and the parameters
void abstractMethod();
}
| 19.916667 | 43 | 0.702929 |
2706450c579a9fff37e5b29f0e606066e3d63c04 | 5,726 | package chav1961.purelib.streams.char2byte.asm.macro;
import java.util.Arrays;
import chav1961.purelib.basic.exceptions.CalculationException;
import chav1961.purelib.basic.growablearrays.GrowableCharArray;
import chav1961.purelib.basic.intern.UnsafedCharUtils;
import chav1961.purelib.streams.char2byte.asm.AssignableExpressionNodeInterface;
public abstract class MacroExecutor implements MacroExecutorInterface {
static final char[] TRUE_CONTENT = "true".toCharArray();
public final char[] stringResource;
protected final long[] longResult = new long[1];
protected final double[] doubleResult = new double[1];
protected MacroExecutor(final char[] stringResource) {
this.stringResource = stringResource;
}
@Override
public abstract void exec(final AssignableExpressionNodeInterface[] memory, final GrowableCharArray<?> target) throws CalculationException;
public char[] extractString(final int from, final int len) throws CalculationException {
return Arrays.copyOfRange(stringResource,from,from+len);
}
public static boolean exists(@SuppressWarnings("exports") final AssignableExpressionNode[] memory, final int variableIndex) throws CalculationException {
return memory[variableIndex].getValueType() != null;
}
public static char[] toString(final long value) throws CalculationException {
return String.valueOf(value).toCharArray();
}
public static char[] toString(final long[] value) throws CalculationException {
final StringBuilder sb = new StringBuilder();
char prefix = '{';
for (long item : value) {
sb.append(prefix).append(item);
prefix=',';
}
if (sb.length() == 0) {
sb.append(prefix);
}
sb.append('}');
final char[] result = new char[sb.length()];
sb.getChars(0, result.length, result, 0);
return result;
}
public static char[] toString(final double value) throws CalculationException {
return String.valueOf(value).toCharArray();
}
public static char[] toString(final double[] value) throws CalculationException {
final StringBuilder sb = new StringBuilder();
char prefix = '{';
for (double item : value) {
sb.append(prefix).append(item);
prefix=',';
}
if (sb.length() == 0) {
sb.append(prefix);
}
sb.append('}');
final char[] result = new char[sb.length()];
sb.getChars(0, result.length, result, 0);
return result;
}
public static char[] toString(final char[][] value) throws CalculationException {
final StringBuilder sb = new StringBuilder();
char prefix = '{';
for (char[] item : value) {
sb.append(prefix).append('\"').append(item).append('\"');
prefix=',';
}
if (sb.length() == 0) {
sb.append(prefix);
}
sb.append('}');
final char[] result = new char[sb.length()];
sb.getChars(0, result.length, result, 0);
return result;
}
public static char[] toString(final boolean value) throws CalculationException {
return String.valueOf(value).toCharArray();
}
public static char[] toString(final boolean[] value) throws CalculationException {
final StringBuilder sb = new StringBuilder();
char prefix = '{';
for (boolean item : value) {
sb.append(prefix).append(item);
prefix=',';
}
if (sb.length() == 0) {
sb.append(prefix);
}
sb.append('}');
final char[] result = new char[sb.length()];
sb.getChars(0, result.length, result, 0);
return result;
}
public static int compareStrings(final char[] left, final char[] right) {
final int leftLen = left.length, rightLen = right.length, lim = Math.min(leftLen,rightLen);
int result;
for (int index = 0; index < lim; index++) {
if ((result = left[index] - right[index]) != 0) {
return result;
}
}
return leftLen - rightLen;
}
public static void testInitialized(final AssignableExpressionNodeInterface node) throws CalculationException {
if (!node.hasValue()) {
throw new CalculationException("Variable/parameter ["+new String(node.getName())+"] is not initialized. Assign some value to it");
}
}
public static boolean valueExists(final AssignableExpressionNodeInterface node) throws CalculationException {
return node.hasValue();
}
public static boolean toBoolean(final char[] content) throws CalculationException {
if (content == null) {
throw new CalculationException("Attempt to convert null string to boolean");
}
else {
return UnsafedCharUtils.uncheckedCompare(content,0,TRUE_CONTENT,0,TRUE_CONTENT.length);
}
}
public static char[][] split(final char[] source, final char splitter[]) throws CalculationException {
if (source == null) {
throw new CalculationException("Attempt to split null string");
}
else if (splitter == null || splitter.length == 0) {
throw new CalculationException("Attempt to use null or empty splitter");
}
else {
final int symbol = splitter[0];
int counter = 1;
for (int index = 0, maxIndex = source.length; index < maxIndex; index++) {
if (source[index] == symbol && UnsafedCharUtils.uncheckedCompare(source,index,splitter,0,splitter.length)) {
counter++;
index += splitter.length;
}
}
final char[][] result = new char[counter][];
int start = 0;
counter = 0;
for (int index = 0, maxIndex = source.length; index < maxIndex; index++) {
if (source[index] == symbol && UnsafedCharUtils.uncheckedCompare(source,index,splitter,0,splitter.length)) {
result[counter++] = Arrays.copyOfRange(source,start,index);
start = index += splitter.length;
}
}
result[counter] = Arrays.copyOfRange(source,start,source.length);
return result;
}
}
public static void throwException(final Throwable exc) throws Throwable {
throw exc;
}
}
| 30.457447 | 154 | 0.693853 |
b9e02e93de00405d569a38b9dcb4cf6ae30c05f0 | 5,828 | /*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.tvm;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.util.DateUtils;
import com.amazonaws.util.HttpUtils;
public class Utilities {
protected static final Logger log = TokenVendingMachineLogger.getLogger();
private static String RAW_POLICY_OBJECT = null;
public static String prepareJsonResponseForTokens( Credentials sessionCredentials, String key ) throws Exception {
StringBuilder responseBody = new StringBuilder();
responseBody.append( "{" );
responseBody.append( "\taccessKey: \"" ).append( sessionCredentials.getAccessKeyId() ).append( "\"," );
responseBody.append( "\tsecretKey: \"" ).append( sessionCredentials.getSecretAccessKey() ).append( "\"," );
responseBody.append( "\tsecurityToken: \"" ).append( sessionCredentials.getSessionToken() ).append( "\"," );
responseBody.append( "\texpirationDate: \"" ).append( sessionCredentials.getExpiration().getTime() ).append( "\"" );
responseBody.append( "}" );
// Encrypting the response
return AESEncryption.wrap( responseBody.toString(), key );
}
public static String sign( String content, String key ) {
try {
byte[] data = content.getBytes( Constants.ENCODING_FORMAT );
Mac mac = Mac.getInstance( Constants.SIGNATURE_METHOD );
mac.init( new SecretKeySpec( key.getBytes( Constants.ENCODING_FORMAT ), Constants.SIGNATURE_METHOD ) );
byte[] signature = Base64.encodeBase64( mac.doFinal( data ) );
return new String( signature, Constants.ENCODING_FORMAT );
}
catch ( Exception exception ) {
log.log( Level.SEVERE, "Exception during sign", exception );
}
return null;
}
public static String base64( String data ) throws UnsupportedEncodingException {
byte[] signature = Base64.encodeBase64( data.getBytes( Constants.ENCODING_FORMAT ) );
return new String( signature, Constants.ENCODING_FORMAT );
}
public static String getEndPoint( HttpServletRequest request ) {
if ( null == request ) {
return null;
}
else {
String endpoint = request.getServerName().toLowerCase();
log.info( "Endpoint : " + encode( endpoint ) );
return endpoint;
}
}
/**
* Checks to see if the request has valid timestamp. If given timestamp falls in 30 mins window from current server timestamp
*/
public static boolean isTimestampValid( String timestamp ) {
long timestampLong = 0L;
final long window = 15 * 60 * 1000L;
if ( null == timestamp ) {
return false;
}
try {
timestampLong = new DateUtils().parseIso8601Date( timestamp ).getTime();
}
catch ( ParseException exception ) {
log.warning( "Error parsing timestamp sent from client : " + encode( timestamp ) );
return false;
}
Long now = new Date().getTime();
long before15Mins = new Date( now - window ).getTime();
long after15Mins = new Date( now + window ).getTime();
return ( timestampLong >= before15Mins && timestampLong <= after15Mins );
}
public static boolean isEmpty( String str ) {
if ( null == str || str.trim().length() == 0 )
return true;
return false;
}
public static String encode( String s ) {
if ( null == s )
return s;
return HttpUtils.urlEncode( s, false );
}
public static String getRawPolicyFile() {
if ( RAW_POLICY_OBJECT == null ) {
ByteArrayOutputStream baos = new ByteArrayOutputStream( 8196 );
InputStream in = null;
try {
in = Utilities.class.getResourceAsStream( "/TokenVendingMachinePolicy.json" );
byte[] buffer = new byte[ 1024 ];
int length = 0;
while ( ( length = in.read( buffer ) ) != -1 ) {
baos.write( buffer, 0, length );
}
RAW_POLICY_OBJECT = baos.toString();
}
catch ( Exception exception ) {
log.log( Level.SEVERE, "Unable to load policy object.", exception );
RAW_POLICY_OBJECT = "";
}
finally {
try {
baos.close();
in.close();
}
catch ( Exception exception ) {
log.log( Level.SEVERE, "Unable to close streams.", exception );
}
in = null;
baos = null;
}
}
return RAW_POLICY_OBJECT;
}
public static boolean isValidUID(String uid) {
return ( null == uid || uid.length() < 24) ? false : true ;
}
public static boolean isValidKey(String key) {
return isValidUID(key);
}
/**
* This method is low performance string comparison function. The purpose of this method is to prevent timing attack.
*/
public static boolean slowStringComparison(String givenSignature, String computedSignature) {
if( null == givenSignature || null == computedSignature || givenSignature.length() != computedSignature.length()) return false;
int n = computedSignature.length();
boolean signaturesMatch = true;
for (int i = 0; i < n; i++) {
signaturesMatch &= (computedSignature.charAt(i) == givenSignature.charAt(i));
}
return signaturesMatch;
}
}
| 31.846995 | 129 | 0.69801 |
0227e322266ce8fef3e98c7ef0abe388b01dd25e | 905 | package ChainOfResponsibility.infrastructure;
import ChainOfResponsibility.handlers.JSONHandler;
import ChainOfResponsibility.handlers.MyHttpAddReqHandler;
import ChainOfResponsibility.handlers.RawTextHandler;
import ChainOfResponsibility.handlers.XMLHandler;
/**
* Created by navid on 2/6/18.
*/
public class WebService {
private MyHttpAddReqHandler myChainOfHandlers;
public WebService() {
// creating and chaining handlers
RawTextHandler myRawHandler = new RawTextHandler();
XMLHandler myXmlHandler = new XMLHandler(myRawHandler);
JSONHandler myJsonHandler = new JSONHandler(myXmlHandler);
this.myChainOfHandlers = myJsonHandler;
}
public WebService(MyHttpAddReqHandler chain) {
this.myChainOfHandlers = chain;
}
public String handleRequest(AddRequest addReq) {
return myChainOfHandlers.handle(addReq);
}
}
| 26.617647 | 66 | 0.750276 |
c9459f51a120a531552df378f0e5deb0bab21ae2 | 11,458 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.remoting.management;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import static org.jboss.as.controller.management.BaseNativeInterfaceResourceDefinition.NATIVE_MANAGEMENT_RUNTIME_CAPABILITY;
import static org.jboss.msc.service.ServiceController.Mode.ACTIVE;
import static org.jboss.msc.service.ServiceController.Mode.ON_DEMAND;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import org.jboss.as.controller.ModelController;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.remote.AbstractModelControllerOperationHandlerFactoryService;
import org.jboss.as.controller.remote.ModelControllerClientOperationHandlerFactoryService;
import org.jboss.as.network.SocketBindingManager;
import org.jboss.as.protocol.mgmt.support.ManagementChannelInitialization;
import org.jboss.as.remoting.RemotingServices;
import org.jboss.as.remoting.logging.RemotingLogger;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.remoting3.Endpoint;
import org.xnio.OptionMap;
/**
* Utility class to add remoting services
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author <a href="mailto:kkhan@redhat.com">Kabir Khan</a>
*/
public final class ManagementRemotingServices extends RemotingServices {
private ManagementRemotingServices() {
}
/** The name of the endpoint service used for management */
public static final ServiceName MANAGEMENT_ENDPOINT = RemotingServices.REMOTING_BASE.append("endpoint", "management");
public static final ServiceName SHUTDOWN_EXECUTOR_NAME = MANAGEMENT_ENDPOINT.append("shutdown", "executor");
/** The name of the external management channel */
public static final String MANAGEMENT_CHANNEL = "management";
/** The name of the channel used between slave and master DCs */
public static final String DOMAIN_CHANNEL = "domain";
/** The name of the channel used for Server to HC comms */
public static final String SERVER_CHANNEL = "server";
public static final String MANAGEMENT_CONNECTOR = "management";
public static final String HTTP_CONNECTOR = "http-management";
public static final String HTTPS_CONNECTOR = "https-management";
/**
* Installs a remoting stream server for a domain instance
* @param serviceTarget the service target to install the services into
* @param endpointName the name of the endpoint to install the stream server into
* @param networkInterfaceBinding the network interface binding
* @param port the port
* @param securityRealm the security real name
* @param options the remoting options
*/
public static void installDomainConnectorServices(final OperationContext context,
final ServiceTarget serviceTarget,
final ServiceName endpointName,
final ServiceName networkInterfaceBinding,
final int port,
final OptionMap options,
final ServiceName securityRealm,
final ServiceName saslAuthenticationFactory,
final ServiceName sslContext) {
String sbmCap = "org.wildfly.management.socket-binding-manager";
ServiceName sbmName = context.hasOptionalCapability(sbmCap, NATIVE_MANAGEMENT_RUNTIME_CAPABILITY.getName(), null)
? context.getCapabilityServiceName(sbmCap, SocketBindingManager.class) : null;
installConnectorServicesForNetworkInterfaceBinding(serviceTarget, endpointName, MANAGEMENT_CONNECTOR,
networkInterfaceBinding, port, options, securityRealm, saslAuthenticationFactory, sslContext, sbmName);
}
/**
* Set up the services to create a channel listener. This assumes that an endpoint service called {@code endpointName} exists.
* @param serviceTarget the service target to install the services into
* @param endpointName the name of the endpoint to install a channel listener into
* @param channelName the name of the channel
* @param operationHandlerName the name of the operation handler to handle request for this channel
* @param options the remoting options
* @param onDemand whether to install the services on demand
*/
public static void installManagementChannelOpenListenerService(
final ServiceTarget serviceTarget,
final ServiceName endpointName,
final String channelName,
final ServiceName operationHandlerName,
final OptionMap options,
final boolean onDemand) {
final ManagementChannelOpenListenerService channelOpenListenerService = new ManagementChannelOpenListenerService(channelName, options);
final ServiceBuilder<?> builder = serviceTarget.addService(channelOpenListenerService.getServiceName(endpointName), channelOpenListenerService)
.addDependency(endpointName, Endpoint.class, channelOpenListenerService.getEndpointInjector())
.addDependency(operationHandlerName, ManagementChannelInitialization.class, channelOpenListenerService.getOperationHandlerInjector())
.addDependency(ManagementChannelRegistryService.SERVICE_NAME, ManagementChannelRegistryService.class, channelOpenListenerService.getRegistry())
.addDependency(SHUTDOWN_EXECUTOR_NAME, ExecutorService.class, channelOpenListenerService.getExecutorServiceInjectedValue())
.setInitialMode(onDemand ? ON_DEMAND : ACTIVE);
builder.install();
}
public static void removeManagementChannelOpenListenerService(final OperationContext context, final ServiceName endpointName, final String channelName) {
context.removeService(RemotingServices.channelServiceName(endpointName, channelName));
}
/**
* Set up the services to create a channel listener and operation handler service.
* @param serviceTarget the service target to install the services into
* @param endpointName the endpoint name to install the services into
* @param channelName the name of the channel
* @param executorServiceName service name of the executor service to use in the operation handler service
* @param scheduledExecutorServiceName service name of the scheduled executor service to use in the operation handler service
*/
public static void installManagementChannelServices(
final ServiceTarget serviceTarget,
final ServiceName endpointName,
final AbstractModelControllerOperationHandlerFactoryService operationHandlerService,
final ServiceName modelControllerName,
final String channelName,
final ServiceName executorServiceName,
final ServiceName scheduledExecutorServiceName) {
final OptionMap options = OptionMap.EMPTY;
final ServiceName operationHandlerName = endpointName.append(channelName).append(ModelControllerClientOperationHandlerFactoryService.OPERATION_HANDLER_NAME_SUFFIX);
serviceTarget.addService(operationHandlerName, operationHandlerService)
.addDependency(modelControllerName, ModelController.class, operationHandlerService.getModelControllerInjector())
.addDependency(executorServiceName, ExecutorService.class, operationHandlerService.getExecutorInjector())
.addDependency(scheduledExecutorServiceName, ScheduledExecutorService.class, operationHandlerService.getScheduledExecutorInjector())
.setInitialMode(ACTIVE)
.install();
installManagementChannelOpenListenerService(serviceTarget, endpointName, channelName, operationHandlerName, options, false);
}
public static void removeManagementChannelServices(final OperationContext context, final ServiceName endpointName,
final String channelName) {
removeManagementChannelOpenListenerService(context, endpointName, channelName);
final ServiceName operationHandlerName = endpointName.append(channelName).append(ModelControllerClientOperationHandlerFactoryService.OPERATION_HANDLER_NAME_SUFFIX);
context.removeService(operationHandlerName);
}
private static final String USE_MGMT_ENDPOINT = "use-management-endpoint";
/**
* Manual check because introducing a capability can't be done without a full refactoring.
* This has to go as soon as the management interfaces are redesigned.
* @param context the OperationContext
* @param otherManagementEndpoint : the address to check that may provide an exposed jboss-remoting endpoint.
* @throws OperationFailedException in case we can't remove the management resource.
*/
public static void isManagementResourceRemoveable(OperationContext context, PathAddress otherManagementEndpoint) throws OperationFailedException {
ModelNode remotingConnector;
try {
remotingConnector = context.readResourceFromRoot(
PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, "jmx"), PathElement.pathElement("remoting-connector", "jmx")), false).getModel();
} catch (Resource.NoSuchResourceException ex) {
return;
}
if (!remotingConnector.hasDefined(USE_MGMT_ENDPOINT) ||
(remotingConnector.hasDefined(USE_MGMT_ENDPOINT) && context.resolveExpressions(remotingConnector.get(USE_MGMT_ENDPOINT)).asBoolean(true))) {
try {
context.readResourceFromRoot(otherManagementEndpoint, false);
} catch (NoSuchElementException ex) {
throw RemotingLogger.ROOT_LOGGER.couldNotRemoveResource(context.getCurrentAddress());
}
}
}
}
| 57.004975 | 172 | 0.733985 |
c327d877e4c96a5e0fcca2b6d13d595506254cb8 | 3,556 | /*
* 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.sis.internal.storage.query;
import java.util.stream.Stream;
import org.opengis.util.GenericName;
import org.apache.sis.internal.storage.AbstractFeatureSet;
import org.apache.sis.storage.DataStoreException;
import org.apache.sis.storage.FeatureSet;
// Branch-dependent imports
import org.apache.sis.feature.AbstractFeature;
import org.apache.sis.feature.DefaultFeatureType;
/**
* The result of {@link SimpleQuery#execute(FeatureSet)} executed using Java {@link Stream} methods.
* Queries executed by this class do not benefit from accelerations provided for example by databases.
* This class should be used only as a fallback when the query can not be executed natively by
* {@link FeatureSet#subset(Query)}.
*
* @author Johann Sorel (Geomatys)
* @author Martin Desruisseaux (Geomatys)
* @version 1.0
* @since 1.0
* @module
*/
final class FeatureSubset extends AbstractFeatureSet {
/**
* The set of feature instances to filter, sort or process.
*/
private final FeatureSet source;
/**
* The query for filtering the source set of features.
*/
private final SimpleQuery query;
/**
* The type of features in this set. May or may not be the same as {@link #source}.
* This is computed when first needed.
*/
private DefaultFeatureType resultType;
/**
* Creates a new set of features by filtering the given set using the given query.
*/
FeatureSubset(final FeatureSet source, final SimpleQuery query) {
super(source);
this.source = source;
this.query = query;
}
/**
* Returns {@code null} since this resource is a computation result.
*/
@Override
public GenericName getIdentifier() {
return null;
}
/**
* Returns a description of properties that are common to all features in this dataset.
*/
@Override
public synchronized DefaultFeatureType getType() throws DataStoreException {
if (resultType == null) {
resultType = query.expectedType(source.getType());
}
return resultType;
}
/**
* Returns a stream of all features contained in this dataset.
*/
@Override
public Stream<AbstractFeature> features(final boolean parallel) throws DataStoreException {
Stream<AbstractFeature> stream = source.features(parallel);
/*
* Apply offset.
*/
final long offset = query.getOffset();
if (offset > 0) {
stream = stream.skip(offset);
}
/*
* Apply limit.
*/
final long limit = query.getLimit();
if (limit >= 0) {
stream = stream.limit(limit);
}
return stream;
}
}
| 32.327273 | 102 | 0.675197 |
7a38e81b0a83913ba61ca4b5182555f77349d408 | 11,752 | package com.texastoc.service.calculator;
import com.texastoc.TestConstants;
import com.texastoc.model.game.Game;
import com.texastoc.model.game.GamePlayer;
import com.texastoc.repository.GamePlayerRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
@RunWith(SpringRunner.class)
public class PointsCalculatorTest implements TestConstants {
private PointsCalculator pointsCalculator;
private Random random = new Random(System.currentTimeMillis());
@MockBean
private GamePlayerRepository gamePlayerRepository;
@Before
public void before() {
pointsCalculator = new PointsCalculator(CHOP_TENTH_PLACE_INCR, CHOP_TENTH_PLACE_POINTS, CHOP_MULTIPLIER, gamePlayerRepository);
}
@Test
public void testNoPlayersNoPoints() {
Game game = Game.builder()
.id(1)
.numPlayers(0)
.build();
List<GamePlayer> gamePlayers = pointsCalculator.calculate(game, Collections.EMPTY_LIST);
Assert.assertNotNull("list of game players should not be null", gamePlayers);
Assert.assertEquals("list of game players should be size 0", 0, gamePlayers.size());
}
@Test
public void test1PlayersNoPoints() {
Game game = Game.builder()
.id(1)
.numPlayers(1)
.build();
List<GamePlayer> gamePlayers = new ArrayList<>(1);
gamePlayers.add(GamePlayer.builder()
.build());
gamePlayers = pointsCalculator.calculate(game, gamePlayers);
Assert.assertNotNull("list of game players should not be null", gamePlayers);
Assert.assertEquals("list of game players should be size 1", 1, gamePlayers.size());
Assert.assertNull("game players points should be null", gamePlayers.get(0).getPoints());
Assert.assertNull("game players chop should be null", gamePlayers.get(0).getChop());
}
@Test
public void testUpTo7Players1WithPoints() {
// Create between 1 and 7 players
int numPlayers = 0;
while (numPlayers == 0) {
numPlayers = random.nextInt(8);
}
Game game = Game.builder()
.id(1)
.numPlayers(numPlayers)
.build();
List<GamePlayer> gamePlayers = new ArrayList<>(numPlayers);
for (int i = 0; i < numPlayers; i++) {
gamePlayers.add(GamePlayer.builder()
.build());
}
int pickOnePlayer = random.nextInt(numPlayers);
gamePlayers.get(pickOnePlayer).setPlace(numPlayers);
// Needed in the persistPoints method
Mockito.when(gamePlayerRepository.selectById(Mockito.anyInt()))
.thenReturn(GamePlayer.builder()
.points(1)
.build());
gamePlayers = pointsCalculator.calculate(game, gamePlayers);
Assert.assertNotNull("list of game players should not be null", gamePlayers);
Assert.assertEquals("list of game players should be size " + numPlayers, numPlayers, gamePlayers.size());
int pointsCount = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getPoints() != null) {
++pointsCount;
}
}
int pointsChop = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getChop() != null) {
++pointsChop;
}
}
Assert.assertEquals("only one player should have points", 1, pointsCount);
Assert.assertEquals("no players should have chop points", 0, pointsChop);
}
@Test
public void test10PlayersWith2Finished() {
int numPlayers = 10;
Game game = Game.builder()
.id(1)
.numPlayers(numPlayers)
.build();
List<GamePlayer> gamePlayers = new ArrayList<>(numPlayers);
for (int i = 0; i < numPlayers; i++) {
gamePlayers.add(GamePlayer.builder()
.build());
}
gamePlayers.get(1).setPlace(10);
gamePlayers.get(4).setPlace(9);
// Needed in the persistPoints method
Mockito.when(gamePlayerRepository.selectById(Mockito.anyInt()))
.thenReturn(GamePlayer.builder()
.points(1)
.build());
gamePlayers = pointsCalculator.calculate(game, gamePlayers);
Assert.assertNotNull("list of game players should not be null", gamePlayers);
Assert.assertEquals("list of game players should be size " + numPlayers, numPlayers, gamePlayers.size());
int pointsCount = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getPoints() != null) {
++pointsCount;
}
}
int pointsChop = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getChop() != null) {
++pointsChop;
}
}
Assert.assertEquals("2 players should have points", 2, pointsCount);
Assert.assertEquals("no players should have chop points", 0, pointsChop);
Assert.assertEquals("10th place should have 7 points", 7, (int) gamePlayers.get(1).getPoints());
Assert.assertEquals("9th place should have 9 points", 9, (int) gamePlayers.get(4).getPoints());
}
@Test
public void test17PlayersWith10Finished() {
int numPlayers = 17;
Game game = Game.builder()
.id(1)
.numPlayers(numPlayers)
.build();
List<GamePlayer> gamePlayers = new ArrayList<>(numPlayers);
for (int i = 0; i < numPlayers; i++) {
gamePlayers.add(GamePlayer.builder()
.build());
}
gamePlayers.get(0).setPlace(4);
gamePlayers.get(1).setPlace(6);
gamePlayers.get(2).setPlace(7);
gamePlayers.get(3).setPlace(10);
gamePlayers.get(5).setPlace(9);
gamePlayers.get(8).setPlace(8);
gamePlayers.get(13).setPlace(5);
gamePlayers.get(16).setPlace(3);
gamePlayers.get(7).setPlace(2);
gamePlayers.get(15).setPlace(1);
// Needed in the persistPoints method
Mockito.when(gamePlayerRepository.selectById(Mockito.anyInt()))
.thenReturn(GamePlayer.builder()
.points(1)
.build());
gamePlayers = pointsCalculator.calculate(game, gamePlayers);
Assert.assertNotNull("list of game players should not be null", gamePlayers);
Assert.assertEquals("list of game players should be size " + numPlayers, numPlayers, gamePlayers.size());
int pointsCount = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getPoints() != null) {
++pointsCount;
}
}
int pointsChop = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getChop() != null) {
++pointsChop;
}
}
Assert.assertEquals("ten players should have points", 10, pointsCount);
Assert.assertEquals("no players should have chop points", 0, pointsChop);
Assert.assertEquals("1st place should have 105 points", 105, (int) gamePlayers.get(15).getPoints());
Assert.assertEquals("2nd place should have 81 points", 81, (int) gamePlayers.get(7).getPoints());
Assert.assertEquals("3rh place should have 63 points", 63, (int) gamePlayers.get(16).getPoints());
Assert.assertEquals("4th place should have 49 points", 49, (int) gamePlayers.get(0).getPoints());
Assert.assertEquals("5th place should have 38 points", 38, (int) gamePlayers.get(13).getPoints());
Assert.assertEquals("6th place should have 29 points", 29, (int) gamePlayers.get(1).getPoints());
Assert.assertEquals("7th place should have 23 points", 23, (int) gamePlayers.get(2).getPoints());
Assert.assertEquals("8th place should have 18 points", 18, (int) gamePlayers.get(8).getPoints());
Assert.assertEquals("9th place should have 14 points", 14, (int) gamePlayers.get(5).getPoints());
Assert.assertEquals("10th place should have 11 points", 11, (int) gamePlayers.get(3).getPoints());
}
@Test
public void test17PlayersWith2WayChop() {
int numPlayers = 17;
Game game = Game.builder()
.id(1)
.numPlayers(numPlayers)
.build();
List<GamePlayer> gamePlayers = new ArrayList<>(numPlayers);
for (int i = 0; i < numPlayers; i++) {
gamePlayers.add(GamePlayer.builder()
.build());
}
gamePlayers.get(0).setPlace(4);
gamePlayers.get(1).setPlace(6);
gamePlayers.get(2).setPlace(7);
gamePlayers.get(3).setPlace(10);
gamePlayers.get(5).setPlace(9);
gamePlayers.get(8).setPlace(8);
gamePlayers.get(13).setPlace(5);
gamePlayers.get(16).setPlace(3);
gamePlayers.get(7).setPlace(2);
gamePlayers.get(7).setChop(30000);
gamePlayers.get(15).setPlace(1);
gamePlayers.get(15).setChop(60000);
// Needed in the persistPoints method
Mockito.when(gamePlayerRepository.selectById(Mockito.anyInt()))
.thenReturn(GamePlayer.builder()
.points(1)
.build());
gamePlayers = pointsCalculator.calculate(game, gamePlayers);
Assert.assertNotNull("list of game players should not be null", gamePlayers);
Assert.assertEquals("list of game players should be size " + numPlayers, numPlayers, gamePlayers.size());
int pointsCount = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getPoints() != null) {
++pointsCount;
}
}
int pointsChop = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getChop() != null) {
++pointsChop;
}
}
Assert.assertEquals("ten players should have points", 10, pointsCount);
Assert.assertEquals("2 players should have chop points", 2, pointsChop);
Assert.assertEquals("1st place should have 97 points", 97, (int) gamePlayers.get(15).getPoints());
Assert.assertEquals("2nd place should have 89 points", 89, (int) gamePlayers.get(7).getPoints());
}
@Test
public void test17PlayersWith3WayChop() {
int numPlayers = 17;
Game game = Game.builder()
.id(1)
.numPlayers(numPlayers)
.build();
List<GamePlayer> gamePlayers = new ArrayList<>(numPlayers);
for (int i = 0; i < numPlayers; i++) {
gamePlayers.add(GamePlayer.builder()
.build());
}
gamePlayers.get(0).setPlace(4);
gamePlayers.get(1).setPlace(6);
gamePlayers.get(2).setPlace(7);
gamePlayers.get(3).setPlace(10);
gamePlayers.get(5).setPlace(9);
gamePlayers.get(8).setPlace(8);
gamePlayers.get(13).setPlace(5);
gamePlayers.get(16).setPlace(3);
gamePlayers.get(16).setPlace(3);
gamePlayers.get(16).setChop(25000);
gamePlayers.get(7).setPlace(2);
gamePlayers.get(7).setChop(75000);
gamePlayers.get(15).setPlace(1);
gamePlayers.get(15).setChop(100000);
// Needed in the persistPoints method
Mockito.when(gamePlayerRepository.selectById(Mockito.anyInt()))
.thenReturn(GamePlayer.builder()
.points(1)
.build());
gamePlayers = pointsCalculator.calculate(game, gamePlayers);
Assert.assertNotNull("list of game players should not be null", gamePlayers);
Assert.assertEquals("list of game players should be size " + numPlayers, numPlayers, gamePlayers.size());
int pointsCount = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getPoints() != null) {
++pointsCount;
}
}
int pointsChop = 0;
for (GamePlayer gamePlayer : gamePlayers) {
if (gamePlayer.getChop() != null) {
++pointsChop;
}
}
Assert.assertEquals("ten players should have points", 10, pointsCount);
Assert.assertEquals("3 players should have chop points", 3, pointsChop);
Assert.assertEquals("1st place should have 94 points", 94, (int) gamePlayers.get(15).getPoints());
Assert.assertEquals("2nd place should have 85 points", 85, (int) gamePlayers.get(7).getPoints());
Assert.assertEquals("3rd place should have 70 points", 70, (int) gamePlayers.get(16).getPoints());
}
}
| 31.934783 | 131 | 0.674183 |
8ff9cda67b9f22d94be4050dc376be420ae19a9a | 779 | package pl.ark.chr.buginator.data;
/**
* Created by Arek on 2016-09-29.
*/
public class Credentials {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return new StringBuilder(60)
.append("Credentials{ username:")
.append(username)
.append(", password: ")
.append(password)
.append("}")
.toString();
}
}
| 20.5 | 49 | 0.554557 |
a77a2d69936204f0e5f97000a90cd3d9faf17222 | 85 |
module accounts.util {
exports accounts.util;
requires static java.logging;
}
| 14.166667 | 32 | 0.729412 |
8e01b9577a9807043b75d6016357b7689dae8a6a | 7,634 | package com.etherealscope.requestlogging;
import lombok.Data;
import lombok.experimental.FieldDefaults;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpMethod;
import javax.annotation.PostConstruct;
import static com.etherealscope.requestlogging.StatusCode.SC_ANY;
import static lombok.AccessLevel.PRIVATE;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.APPLICATION_XML_VALUE;
import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;
import static org.springframework.http.MediaType.TEXT_XML_VALUE;
/**
* Configuration properties for request logging
*/
@Data
@FieldDefaults(level = PRIVATE)
@ConfigurationProperties("ethereal.logging")
public class RequestLoggingProperties {
private static final String[] DEFAULT_CONTENT_TYPES = new String[] {
APPLICATION_JSON_VALUE,
APPLICATION_FORM_URLENCODED_VALUE,
TEXT_PLAIN_VALUE,
TEXT_XML_VALUE,
APPLICATION_XML_VALUE
};
/**
* If false, there will be no logging filter registered.
*/
boolean enabled = true;
/**
* If true, at the filter end elapsed time will be logged.
*/
boolean includeTimeElapsed = true;
/**
* Response status codes when to log request and response.
*/
StatusCode[] statusCodes = new StatusCode[] {SC_ANY};
/**
* Request related config.
*/
Request request = new Request();
/**
* Response related config
*/
Response response = new Response();
@Data
@FieldDefaults(level = PRIVATE)
public static class Request {
/**
* If false, no request will be logged.
*/
boolean enabled = true;
/**
* If false, no request headers will be logged.
*/
boolean includeHeaders = true;
/**
* If false, no request payload will be logged.
*/
boolean includePayload = true;
/**
* If false, no request params will be logged.
*/
boolean includeQueryParams = true;
/**
* If true, user ip address will be logged.
*/
boolean includeIpAddress = false;
/**
* Size, where body will be cut.
*/
int maxPayloadSize = 4096;
/**
* White listed content types where to log body.
*/
String[] whiteListedContentTypes = DEFAULT_CONTENT_TYPES;
/**
* Black listed content types where to log body.
*/
String[] blackListedContentTypes = new String[] {};
/**
* White listed servlet paths where to log request.
*/
String[] whiteListedServletPaths = new String[] {};
/**
* Black listed servlet paths where to log request.
*/
String[] blackListedServletPaths = new String[] {};
/**
* Masks to apply for request due to security.
*/
Mask[] masks = new Mask[] {};
}
@Data
@FieldDefaults(level = PRIVATE)
public static class Response {
/**
* If false, no response will be logged.
*/
boolean enabled = true;
/**
* If false, no response headers will be logged.
*/
boolean includeHeaders = true;
/**
* If false, no response payload will be logged.
*/
boolean includePayload = true;
/**
* Size, where body will be cut.
*/
int maxPayloadSize = 4096;
/**
* White listed content types where to log body.
*/
String[] whiteListedContentTypes = DEFAULT_CONTENT_TYPES;
/**
* Black listed content types where to log body.
*/
String[] blackListedContentTypes = new String[] {};
/**
* White listed servlet paths where to log response.
*/
String[] whiteListedServletPaths = new String[] {};
/**
* Black listed servlet paths where to log response.
*/
String[] blackListedServletPaths = new String[] {};
/**
* Masks to apply for response due to security.
*/
Mask[] masks = new Mask[] {};
}
@Data
@FieldDefaults(level = PRIVATE)
public static class Mask {
/**
* Http method to apply for.
*/
HttpMethod method;
/**
* Path matcher like /users/**, /users/*, /users.
*/
String pathMatcher;
/**
* Json field names to mask like password, newPassword, oldPassword.
*/
String[] maskedJsonFields = new String[] {};
/**
* Query params to mask like password, newPassword, oldPassword.
*/
String[] maskedQueryParams = new String[] {};
/**
* Headers to mask like authorization, cookie.
*/
String[] maskedHeaders = new String[] {};
}
@PostConstruct
void init() {
if (statusCodes == null || statusCodes.length == 0) {
throw new IllegalArgumentException("Status codes cannot be null or empty");
}
if (request.maxPayloadSize <= 0 || response.maxPayloadSize <= 0) {
throw new IllegalArgumentException("Max payload size cannot be negative");
}
if (request.blackListedContentTypes == null || response.blackListedContentTypes == null) {
throw new IllegalArgumentException("Black listed content types cannot be null, empty array required");
}
if (request.whiteListedContentTypes == null || response.whiteListedContentTypes == null) {
throw new IllegalArgumentException("White listed content types cannot be null, empty array required");
}
if (request.blackListedServletPaths == null || response.blackListedServletPaths == null) {
throw new IllegalArgumentException("Black listed servlet paths cannot be null, empty array required");
}
if (request.whiteListedServletPaths == null || response.whiteListedServletPaths == null) {
throw new IllegalArgumentException("White listed servlet paths cannot be null, empty array required");
}
if (request.masks == null || response.masks == null) {
throw new IllegalArgumentException("Masks cannot be null, empty array required");
}
if (request.blackListedContentTypes.length > 0 && request.whiteListedContentTypes.length > 0) {
throw new IllegalArgumentException("You cannot set black list together with white list for content types");
}
if (response.blackListedContentTypes.length > 0 && response.whiteListedContentTypes.length > 0) {
throw new IllegalArgumentException("You cannot set black list together with white list for content types");
}
for (Mask mask : request.masks) {
if (mask.maskedQueryParams == null || mask.maskedHeaders == null || mask.maskedJsonFields == null) {
throw new IllegalArgumentException("Mask query params, headers and json fields are not allowed to be null");
}
}
for (Mask mask : response.masks) {
if (mask.maskedQueryParams == null || mask.maskedHeaders == null || mask.maskedJsonFields == null) {
throw new IllegalArgumentException("Mask query params, headers and json fields are not allowed to be null");
}
}
}
}
| 35.506977 | 124 | 0.611213 |
acd02599488a6af242808117559b322f2088273d | 2,877 | package org.apache.lucene.store;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.IOException;
/**
* Simple standalone server that must be running when you
* use {@link VerifyingLockFactory}. This server simply
* verifies at most one process holds the lock at a time.
* Run without any args to see usage.
*
* @see VerifyingLockFactory
* @see LockStressTest
*/
public class LockVerifyServer {
private static String getTime(long startTime) {
return "[" + ((System.currentTimeMillis()-startTime)/1000) + "s] ";
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("\nUsage: java org.apache.lucene.store.LockVerifyServer port\n");
System.exit(1);
}
final int port = Integer.parseInt(args[0]);
ServerSocket s = new ServerSocket(port);
s.setReuseAddress(true);
System.out.println("\nReady on port " + port + "...");
int lockedID = 0;
long startTime = System.currentTimeMillis();
while(true) {
Socket cs = s.accept();
OutputStream out = cs.getOutputStream();
InputStream in = cs.getInputStream();
int id = in.read();
int command = in.read();
boolean err = false;
if (command == 1) {
// Locked
if (lockedID != 0) {
err = true;
System.out.println(getTime(startTime) + " ERROR: id " + id + " got lock, but " + lockedID + " already holds the lock");
}
lockedID = id;
} else if (command == 0) {
if (lockedID != id) {
err = true;
System.out.println(getTime(startTime) + " ERROR: id " + id + " released the lock, but " + lockedID + " is the one holding the lock");
}
lockedID = 0;
} else
throw new RuntimeException("unrecognized command " + command);
System.out.print(".");
if (err)
out.write(1);
else
out.write(0);
out.close();
in.close();
cs.close();
}
}
}
| 29.659794 | 143 | 0.644769 |
12958b961bd279d9b5b5d0ffd00acc9d773a492f | 2,457 | package org.gooru.nucleus.auth.handlers.processors.repositories.activejdbc.dbauth;
import java.util.ResourceBundle;
import org.gooru.nucleus.auth.handlers.app.components.AppConfiguration;
import org.gooru.nucleus.auth.handlers.constants.HelperConstants;
import org.gooru.nucleus.auth.handlers.constants.ParameterConstants;
import org.gooru.nucleus.auth.handlers.processors.ProcessorContext;
import org.gooru.nucleus.auth.handlers.processors.repositories.activejdbc.entities.AJEntityApp;
import org.gooru.nucleus.auth.handlers.processors.responses.ExecutionResult;
import org.gooru.nucleus.auth.handlers.processors.responses.MessageResponse;
import org.gooru.nucleus.auth.handlers.processors.responses.MessageResponseFactory;
import org.gooru.nucleus.auth.handlers.processors.responses.ExecutionResult.ExecutionStatus;
import org.javalite.activejdbc.LazyList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.core.json.JsonObject;
/**
* @author szgooru Created On: 17-May-2017
*/
public class AppAuthorizer implements Authorizer<AJEntityApp> {
private final ProcessorContext context;
private static final Logger LOGGER = LoggerFactory.getLogger(AppAuthorizer.class);
private static final ResourceBundle RESOURCE_BUNDLE =
ResourceBundle.getBundle(HelperConstants.RESOURCE_BUNDLE);
public AppAuthorizer(ProcessorContext context) {
this.context = context;
}
@Override
public ExecutionResult<MessageResponse> authorize(AJEntityApp model) {
if (AppConfiguration.getInstance().isAppIdRequired()) {
String appId = context.requestBody().getString(ParameterConstants.PARAM_APP_ID);
if (appId == null || appId.isEmpty()) {
return new ExecutionResult<>(
MessageResponseFactory
.createValidationErrorResponse(new JsonObject().put(ParameterConstants.PARAM_APP_ID,
RESOURCE_BUNDLE.getString("missing.mandatory.field"))),
ExecutionResult.ExecutionStatus.FAILED);
}
LazyList<AJEntityApp> apps = AJEntityApp.findBySQL(AJEntityApp.VALIDATE_EXISTANCE, appId);
if (apps.isEmpty()) {
LOGGER.warn("app id '{}' not found", appId);
return new ExecutionResult<>(MessageResponseFactory.createForbiddenResponse(
RESOURCE_BUNDLE.getString("appid.not.found")), ExecutionStatus.FAILED);
}
}
return new ExecutionResult<>(null, ExecutionResult.ExecutionStatus.CONTINUE_PROCESSING);
}
}
| 43.875 | 100 | 0.774929 |
3efecec43fa1ca90dfa94dce5b87765f9bc2c92d | 3,446 | package org.zalando.jackson.datatype.money;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import javax.annotation.Nullable;
import javax.money.CurrencyUnit;
import javax.money.MonetaryAmount;
import javax.money.format.MonetaryAmountFormat;
import java.io.IOException;
import java.util.Locale;
final class MonetaryAmountSerializer extends StdSerializer<MonetaryAmount> {
private final FieldNames names;
private final AmountWriter<?> writer;
private final MonetaryAmountFormatFactory factory;
MonetaryAmountSerializer(final FieldNames names, final AmountWriter<?> writer,
final MonetaryAmountFormatFactory factory) {
super(MonetaryAmount.class);
this.writer = writer;
this.factory = factory;
this.names = names;
}
@Override
public void acceptJsonFormatVisitor(final JsonFormatVisitorWrapper wrapper, final JavaType hint)
throws JsonMappingException {
@Nullable final JsonObjectFormatVisitor visitor = wrapper.expectObjectFormat(hint);
if (visitor == null) {
return;
}
final SerializerProvider provider = wrapper.getProvider();
visitor.property(names.getAmount(),
provider.findValueSerializer(writer.getType()),
provider.constructType(writer.getType()));
visitor.property(names.getCurrency(),
provider.findValueSerializer(CurrencyUnit.class),
provider.constructType(CurrencyUnit.class));
visitor.optionalProperty(names.getFormatted(),
provider.findValueSerializer(String.class),
provider.constructType(String.class));
}
@Override
public void serializeWithType(final MonetaryAmount value, final JsonGenerator generator,
final SerializerProvider provider, final TypeSerializer serializer) throws IOException {
// effectively assuming no type information at all
serialize(value, generator, provider);
}
@Override
public void serialize(final MonetaryAmount value, final JsonGenerator json, final SerializerProvider provider)
throws IOException {
final CurrencyUnit currency = value.getCurrency();
@Nullable final String formatted = format(value, provider);
json.writeStartObject();
{
provider.defaultSerializeField(names.getAmount(), writer.write(value), json);
provider.defaultSerializeField(names.getCurrency(), currency, json);
if (formatted != null) {
json.writeStringField(names.getFormatted(), formatted);
}
}
json.writeEndObject();
}
@Nullable
private String format(final MonetaryAmount value, final SerializerProvider provider) {
final Locale locale = provider.getConfig().getLocale();
final MonetaryAmountFormat format = factory.create(locale);
return format == null ? null : format.format(value);
}
}
| 37.053763 | 114 | 0.714452 |
f5df3025a7c1fa5bb6ebe53dbba8093a58adeeca | 7,426 | package com.moebuff.discord.utils.reflect;
import com.moebuff.discord.utils.UnhandledException;
import org.apache.commons.lang3.reflect.FieldUtils;
import java.lang.reflect.Field;
/**
* 字段工具,简化了反射操作,但这并不意味着会提高执行效率,若方法搭配不好反而会降低甚至引发错误。
*
* @author muto
* @see FieldUtils
*/
public class FieldKit {
/**
* 在类中获取已被声明的字段,若字段并非公共成员,则取消 Java 语言访问检查。
*
* @param c 被反射的类,不能为null
* @param fieldName 字段名
* @return 若字段未被声明,则返回null
* @throws IllegalArgumentException if the class is {@code null}, or the field name is blank or empty
*/
public static Field getDeclaredField(Class<?> c, String fieldName) {
return FieldUtils.getDeclaredField(c, fieldName, true);
}
/**
* 移除final修饰符。需要注意的是,对于String和基本类型的静态常量,JVM通常会将代码中对此常量引用的地方替换成相应的值。
*/
public static void removeFinalModifier(Field f) {
Field m = getDeclaredField(Field.class, "modifiers");
if (MemberUtils.isFinal(m)) {
writeField(m, f, f.getModifiers() & MemberUtils.NOT_FINAL);
return;
}
//The "modifiers" is not a field in the Field class on Android.
if (m == null) f.setAccessible(true);
}
// write field
//==========================================================================================
/**
* Writes a {@link Field}.
*
* @param f to write
* @param target the object to call on, may be {@code null} for {@code static} fields
* @param value to set
* @throws IllegalArgumentException if the field is {@code null} or {@code value} is not assignable
* @throws UnhandledException if the field is {@code final}
*/
public static void writeField(Field f, Object target, Object value) {
try {
FieldUtils.writeField(f, target, value, true);
} catch (IllegalAccessException e) {
throw new UnhandledException(e);
}
}
/**
* Writes a {@link Field}. Only the specified class will be considered.
*
* @param fieldName the field name to obtain
* @param target the object to reflect, must not be {@code null}
* @param value to set
* @throws IllegalArgumentException if {@code target} is {@code null},
* {@code fieldName} is blank or empty or could not be found,
* or {@code value} is not assignable
*/
public static void writeField(String fieldName, Object target, Object value) {
try {
FieldUtils.writeDeclaredField(target, fieldName, value, true);
} catch (IllegalAccessException e) {
throw new UnhandledException(e);//理论上这个错误不会出现
}
}
/**
* 修改一个静态字段。该方法与执行 {@code writeField(f, null, value)} 的结果相同。
*
* @param f to write
* @param value to set
* @see #writeField(Field, Object, Object)
*/
public static void writeStaticField(Field f, Object value) {
writeField(f, null, value);
}
/**
* 修改一个静态字段,该字段由 fieldName 指定并在类中已被声明。
*
* @param c 被反射的类,不能为null
* @param fieldName 字段名
* @param value to set
* @see #writeField(Field, Object, Object)
* @see #getDeclaredField(Class, String)
*/
public static void writeStaticField(Class<?> c, String fieldName, Object value) {
writeField(getDeclaredField(c, fieldName), null, value);
}
/**
* 修改常量。在执行 {@link #writeField(Field, Object, Object)} 前移除了final修饰符。
*
* @param f to write
* @param target the object to call on, may be {@code null} for {@code static} fields
* @param value to set
* @see #removeFinalModifier(Field)
*/
public static void writeConstant(Field f, Object target, Object value) {
removeFinalModifier(f);
writeField(f, target, value);
}
/**
* 修改一个在 {@code target} 对象所表示的类中已被声明的常量。
*
* @param fieldName 字段名
* @param target 将被放射的对象,不能为null
* @param value to set
* @see #writeConstant(Field, Object, Object)
* @see #getDeclaredField(Class, String)
*/
public static void writeConstant(String fieldName, Object target, Object value) {
writeConstant(getDeclaredField(target.getClass(), fieldName), target, value);
}
/**
* 修改一个静态常量。该方法与执行 {@code writeConstant(f, null, value)} 的结果相同。
*
* @param f to write
* @param value to set
* @see #writeConstant(Field, Object, Object)
*/
public static void writeStaticConstant(Field f, Object value) {
writeConstant(f, null, value);
}
/**
* 修改一个静态常量,该字段由 fieldName 指定并在类中已被声明。
*
* @param c 被反射的类,不能为null
* @param fieldName 字段名
* @param value to set
* @see #writeConstant(Field, Object, Object)
* @see #getDeclaredField(Class, String)
*/
public static void writeStaticConstant(Class<?> c, String fieldName, Object value) {
writeConstant(getDeclaredField(c, fieldName), null, value);
}
// read field
//==========================================================================================
/**
* Reads a {@link Field}.
*
* @param f the field to use
* @param target the object to call on, may be {@code null} for {@code static} fields
* @return the field value
* @throws IllegalArgumentException if the field is {@code null}
*/
public static Object readField(Field f, Object target) {
try {
return FieldUtils.readField(f, target, true);
} catch (IllegalAccessException e) {
throw new UnhandledException(e);//理论上这个错误不会出现
}
}
/**
* Gets a {@link Field} value by name. Only the class of the specified object will be considered.
*
* @param target the object to reflect, must not be {@code null}
* @param fieldName the field name to obtain
* @return the Field object
* @throws IllegalArgumentException if {@code target} is {@code null},or the field name is blank
* or empty or could not be found
*/
public static Object readField(String fieldName, Object target) {
try {
return FieldUtils.readDeclaredField(target, fieldName, true);
} catch (IllegalAccessException e) {
throw new UnhandledException(e);//理论上这个错误不会出现
}
}
/**
* 获取静态字段的值。该方法与执行 {@code readField(f, null)} 的结果相同。
*
* @param f 将被读取的字段
* @return 静态字段的值
* @see #readField(Field, Object)
*/
public static Object readStaticField(Field f) {
return readField(f, null);
}
/**
* Reads the named {@code static} {@link Field}. Superclasses will be considered.
*
* @param c the {@link Class} to reflect, must not be {@code null}
* @param fieldName the field name to obtain
* @return the Field object
* @throws IllegalArgumentException if the class is {@code null}, or the field name is blank or empty,
* is not {@code static}, or could not be found
*/
public static Object readStaticField(Class<?> c, String fieldName) {
try {
return FieldUtils.readStaticField(c, fieldName, true);
} catch (IllegalAccessException e) {
throw new UnhandledException(e);//理论上这个错误不会出现
}
}
}
| 34.221198 | 106 | 0.590089 |
b9c0c08a46ce3cf3648f1d9cbce7f125b153abe3 | 1,707 | package fundamentos;
public class ConversaoNumeroString {
public static void main(String[] args) {
Integer numW1 = 10000;
Double numW2 = 10000.00;
Float numW3 = 10000.000f;
Short numW4 = 1000;
Byte numW5 = 100;
int num1 = 20000;
double num2 = 20000.00;
float num3 = 200000.00f;
short num4 = 2000;
byte num5 = 127;
/*
* Convertendo Wapper Inteiro para String
* Convertendo inteiro para String
*/
String nums1 = numW1.toString();
System.out.println("\nInteiro Wrapper: "+nums1);
nums1 = Integer.toString(num1);
System.out.println("inteiro primitivo: " +nums1);
/*
* Convertendo Wapper Double para String
* Convertendo Primitivo double para String
*/
String nums2 = numW2.toString();
System.out.println("\nDouble Wrapper: "+nums2);
nums2 = Double.toString(num2);
System.out.println("double primitivo: " +nums2);
/*
* Convertendo Wapper Short para String
* Convertendo Primitivo short para String
*/
String nums3 = numW3.toString();
System.out.println("\nFloat Wrapper: "+nums3);
nums3 = Float.toString(num3);
System.out.println("float primitivo: " +nums3);
/*
* Convertendo Wapper Short para String
* Convertendo Primitivo short para String
*/
String nums4 = numW4.toString();
System.out.println("\nShort Wrapper: " +nums4);
nums4 = Short.toString(num4);
System.out.println("short primitivo: " +nums4);
/*
* Convertendo Wapper Byte para String
* Convertendo Primitivo byte para String
*/
String nums5 = numW5.toString();
System.out.println("\nByte Wrapper: "+nums5);
nums5 = Byte.toString(num5);
System.out.println("byte primitivo: " +nums5);
}
}
| 23.383562 | 51 | 0.66901 |
7f9c2ac1634bcb56bc28648cc51d13801ff03470 | 390 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package config.exclude.packagename;
import io.opentelemetry.extension.annotations.WithSpan;
public class SomeClass implements Runnable {
@WithSpan
@Override
public void run() {}
public static class NestedClass implements Runnable {
@WithSpan
@Override
public void run() {}
}
}
| 16.956522 | 55 | 0.725641 |
9024b625a3ad7924722436a59d9aeca42825b544 | 12,730 | package com.synopsys.integration.alert.database.settings.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Tags;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import com.synopsys.integration.alert.common.descriptor.ProviderDescriptor;
import com.synopsys.integration.alert.common.descriptor.accessor.AuditUtility;
import com.synopsys.integration.alert.common.descriptor.config.ui.ProviderDistributionUIConfig;
import com.synopsys.integration.alert.common.enumeration.ConfigContextEnum;
import com.synopsys.integration.alert.common.enumeration.ItemOperation;
import com.synopsys.integration.alert.common.exception.AlertDatabaseConstraintException;
import com.synopsys.integration.alert.common.exception.AlertException;
import com.synopsys.integration.alert.common.message.model.ComponentItem;
import com.synopsys.integration.alert.common.message.model.MessageContentGroup;
import com.synopsys.integration.alert.common.message.model.ProviderMessageContent;
import com.synopsys.integration.alert.common.persistence.accessor.ConfigurationAccessor;
import com.synopsys.integration.alert.common.persistence.model.ConfigurationFieldModel;
import com.synopsys.integration.alert.common.persistence.model.ConfigurationJobModel;
import com.synopsys.integration.alert.common.persistence.model.ConfigurationModel;
import com.synopsys.integration.alert.database.audit.AuditEntryRepository;
import com.synopsys.integration.alert.database.notification.NotificationContentRepository;
import com.synopsys.integration.alert.database.notification.NotificationEntity;
import com.synopsys.integration.alert.mock.entity.MockNotificationContent;
import com.synopsys.integration.alert.provider.blackduck.BlackDuckProviderKey;
import com.synopsys.integration.alert.provider.blackduck.descriptor.BlackDuckDescriptor;
import com.synopsys.integration.alert.util.AlertIntegrationTest;
import com.synopsys.integration.alert.util.TestTags;
import com.synopsys.integration.rest.RestConstants;
@Transactional
public class NotificationContentRepositoryIT extends AlertIntegrationTest {
@Autowired
private NotificationContentRepository notificationContentRepository;
@Autowired
private AuditEntryRepository auditEntryRepository;
@Autowired
private AuditUtility auditUtility;
@Autowired
private ConfigurationAccessor configurationAccessor;
private ConfigurationModel providerConfigModel = null;
@BeforeEach
public void init() throws AlertDatabaseConstraintException {
notificationContentRepository.deleteAllInBatch();
auditEntryRepository.deleteAllInBatch();
notificationContentRepository.flush();
ConfigurationFieldModel providerConfigEnabled = ConfigurationFieldModel.create(ProviderDescriptor.KEY_PROVIDER_CONFIG_ENABLED);
providerConfigEnabled.setFieldValue("true");
ConfigurationFieldModel providerConfigName = ConfigurationFieldModel.create(ProviderDescriptor.KEY_PROVIDER_CONFIG_NAME);
providerConfigName.setFieldValue("My Black Duck Config");
ConfigurationFieldModel blackduckUrl = ConfigurationFieldModel.create(BlackDuckDescriptor.KEY_BLACKDUCK_URL);
blackduckUrl.setFieldValue("https://a-blackduck-server");
ConfigurationFieldModel blackduckApiKey = ConfigurationFieldModel.create(BlackDuckDescriptor.KEY_BLACKDUCK_API_KEY);
blackduckApiKey.setFieldValue("123456789012345678901234567890123456789012345678901234567890");
ConfigurationFieldModel blackduckTimeout = ConfigurationFieldModel.create(BlackDuckDescriptor.KEY_BLACKDUCK_TIMEOUT);
blackduckTimeout.setFieldValue("300");
List<ConfigurationFieldModel> providerConfigFields = List.of(providerConfigEnabled, providerConfigName, blackduckUrl, blackduckApiKey, blackduckTimeout);
providerConfigModel = configurationAccessor.createConfiguration(new BlackDuckProviderKey(), ConfigContextEnum.GLOBAL, providerConfigFields);
}
@AfterEach
public void cleanup() throws AlertDatabaseConstraintException {
configurationAccessor.deleteConfiguration(providerConfigModel.getConfigurationId());
notificationContentRepository.deleteAllInBatch();
auditEntryRepository.deleteAllInBatch();
}
@Test
public void testSaveEntity() throws Exception {
NotificationEntity entity = createEntity(RestConstants.formatDate(new Date()));
NotificationEntity savedEntity = notificationContentRepository.save(entity);
long count = notificationContentRepository.count();
assertEquals(1, count);
Optional<NotificationEntity> foundEntityOptional = notificationContentRepository.findById(savedEntity.getId());
NotificationEntity foundEntity = foundEntityOptional.get();
assertEquals(entity.getCreatedAt(), foundEntity.getCreatedAt());
assertEquals(entity.getNotificationType(), foundEntity.getNotificationType());
assertEquals(entity.getProvider(), foundEntity.getProvider());
assertEquals(entity.getProviderCreationTime(), foundEntity.getProviderCreationTime());
assertEquals(entity.getContent(), foundEntity.getContent());
}
@Test
public void testFindByDate() throws Exception {
Set<String> validResultDates = new HashSet<>();
NotificationEntity savedEntity = createEntity("2017-10-15T1:00:00.000Z");
validResultDates.add(RestConstants.formatDate(savedEntity.getCreatedAt()));
savedEntity = createEntity("2017-10-21T14:00:00.000Z");
validResultDates.add(RestConstants.formatDate(savedEntity.getCreatedAt()));
savedEntity = createEntity("2017-10-22T14:00:00.000Z");
validResultDates.add(RestConstants.formatDate(savedEntity.getCreatedAt()));
savedEntity = createEntity("2017-10-23T14:00:00.000Z");
validResultDates.add(RestConstants.formatDate(savedEntity.getCreatedAt()));
savedEntity = createEntity("2017-10-30T14:00:00.000Z");
validResultDates.add(RestConstants.formatDate(savedEntity.getCreatedAt()));
createEntity("2017-10-10T16:00:00.000Z");
createEntity("2017-10-31T15:00:00.000Z");
createEntity("2017-10-31T16:00:00.000Z");
createEntity("2017-10-31T17:00:00.000Z");
createEntity("2017-10-31T18:00:00.000Z");
long count = notificationContentRepository.count();
assertEquals(10, count);
Date startDate = RestConstants.parseDateString("2017-10-12T01:30:59.000Z");
Date endDate = RestConstants.parseDateString("2017-10-30T16:59:59.000Z");
List<NotificationEntity> foundEntityList = notificationContentRepository.findByCreatedAtBetween(startDate, endDate);
assertEquals(5, foundEntityList.size());
foundEntityList.forEach(entity -> {
String createdAtString = RestConstants.formatDate(entity.getCreatedAt());
assertTrue(validResultDates.contains(createdAtString));
});
}
// Only re-enable for performance testing
@Test
@Disabled
@Tags(value = {
@Tag(TestTags.DEFAULT_INTEGRATION),
@Tag(TestTags.DEFAULT_PERFORMANCE),
@Tag(TestTags.CUSTOM_DATABASE_CONNECTION)
})
public void findMatchingNotificationTest() throws ParseException, AlertException {
notificationQueryTest(notificationContentRepository::findMatchingNotification);
}
// Only re-enable for performance testing
@Test
@Disabled
@Tags(value = {
@Tag(TestTags.DEFAULT_INTEGRATION),
@Tag(TestTags.DEFAULT_PERFORMANCE),
@Tag(TestTags.CUSTOM_DATABASE_CONNECTION)
})
public void findMatchingSentNotificationTest() throws ParseException, AlertException {
notificationQueryTest(notificationContentRepository::findMatchingSentNotification);
}
public void notificationQueryTest(BiFunction<String, Pageable, Page<NotificationEntity>> queryFunction) throws ParseException, AlertException {
final String searchTerm = "searchTerm";
final int numberToCreate = 1000;
Number numberOfSearchTermMatches = initializeNotificationRepo(searchTerm, numberToCreate);
Instant beforeQueryInstant = Instant.now();
Page<NotificationEntity> matchingNotifications = queryFunction.apply(searchTerm, Pageable.unpaged());
Instant afterQueryInstant = Instant.now();
Duration queryDuration = Duration.between(beforeQueryInstant, afterQueryInstant);
Long durationInSeconds = queryDuration.toSeconds();
System.out.println("Duration (in seconds): " + durationInSeconds);
assertEquals(numberOfSearchTermMatches, matchingNotifications.getTotalElements());
}
private Long initializeNotificationRepo(String searchTerm, int numberToCreate) throws ParseException, AlertException {
List<NotificationEntity> notifications = new ArrayList<>(numberToCreate);
long searchableCount = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(RestConstants.JSON_DATE_FORMAT);
for (int i = 0; i < numberToCreate; i++) {
Date newDate = new Date();
String dateString = simpleDateFormat.format(newDate);
NotificationEntity entity;
if (i % 31 == 0) {
entity = createEntity(dateString, searchTerm);
searchableCount++;
} else {
entity = createEntity(dateString);
}
notifications.add(entity);
}
List<NotificationEntity> savedNotifications = notificationContentRepository.saveAll(notifications);
ConfigurationFieldModel fieldModel = ConfigurationFieldModel.create(ProviderDistributionUIConfig.KEY_FILTER_BY_PROJECT);
fieldModel.setFieldValue("false");
ConfigurationJobModel configJob = configurationAccessor.createJob(Set.of(new BlackDuckProviderKey().getUniversalKey()), Set.of(fieldModel));
for (NotificationEntity notification : savedNotifications) {
MessageContentGroup messageContentGroup = createMessageGroup(notification.getId());
auditUtility.createAuditEntry(Map.of(), configJob.getJobId(), messageContentGroup);
}
auditEntryRepository.flush();
return searchableCount;
}
private NotificationEntity createEntity(String dateString) throws ParseException {
return createEntity(dateString, "NOTIFICATION CONTENT HERE");
}
private NotificationEntity createEntity(String dateString, String content) throws ParseException {
Date createdAt = RestConstants.parseDateString(dateString);
Date providerCreationTime = createdAt;
final String provider = "provider_blackduck";
final String notificationType = "type_1";
NotificationEntity entity = new MockNotificationContent(createdAt, provider, providerCreationTime, notificationType, content, null, providerConfigModel.getConfigurationId()).createEntity();
NotificationEntity savedEntity = notificationContentRepository.save(entity);
return savedEntity;
}
private MessageContentGroup createMessageGroup(Long notificationId) throws AlertException {
ComponentItem componentItem = new ComponentItem.Builder()
.applyComponentData("", "")
.applyOperation(ItemOperation.UPDATE)
.applyNotificationId(notificationId)
.build();
ProviderMessageContent content = new ProviderMessageContent.Builder()
.applyProvider("testProvider", 1L, "testProviderConfig")
.applyTopic("testTopic", "")
.applyAllComponentItems(List.of(componentItem))
.build();
return MessageContentGroup.singleton(content);
}
}
| 51.124498 | 197 | 0.746583 |
b9c7cb8bf42598ea3fc6f847fbfe1b65eab0a4ba | 593 | /* See LICENSE for licensing and NOTICE for copyright. */
package org.ldaptive.extended;
/**
* Provides common implementation for extended responses.
*
* @param <T> type of response value
*
* @author Middleware Services
*/
public abstract class AbstractExtendedResponse<T> implements ExtendedResponse<T>
{
/** Response value. */
private T value;
@Override
public T getValue()
{
return value;
}
/**
* Sets the response value for this extended operation.
*
* @param t response value
*/
protected void setValue(final T t)
{
value = t;
}
}
| 16.942857 | 80 | 0.664418 |
7a3cb62d6cc53d708709d6e3dadeea043f7b3245 | 2,023 | package com.ruoyi.demo.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.DataColumn;
import com.ruoyi.common.annotation.DataPermission;
import com.ruoyi.common.core.mybatisplus.core.BaseMapperPlus;
import com.ruoyi.demo.domain.TestDemo;
import com.ruoyi.demo.domain.vo.TestDemoVo;
import org.apache.ibatis.annotations.Param;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
/**
* 测试单表Mapper接口
*
* @author Lion Li
* @date 2021-07-26
*/
public interface TestDemoMapper extends BaseMapperPlus<TestDemo> {
@DataPermission({
@DataColumn(key = "deptName", value = "dept_id"),
@DataColumn(key = "userName", value = "user_id")
})
Page<TestDemoVo> customPageList(@Param("page") Page<TestDemo> page, @Param("ew") Wrapper<TestDemo> wrapper);
@Override
@DataPermission({
@DataColumn(key = "deptName", value = "dept_id"),
@DataColumn(key = "userName", value = "user_id")
})
<P extends IPage<TestDemo>> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper<TestDemo> queryWrapper);
@Override
@DataPermission({
@DataColumn(key = "deptName", value = "dept_id"),
@DataColumn(key = "userName", value = "user_id")
})
List<TestDemo> selectList(@Param(Constants.WRAPPER) Wrapper<TestDemo> queryWrapper);
@Override
@DataPermission({
@DataColumn(key = "deptName", value = "dept_id"),
@DataColumn(key = "userName", value = "user_id")
})
int updateById(@Param(Constants.ENTITY) TestDemo entity);
@Override
@DataPermission({
@DataColumn(key = "deptName", value = "dept_id"),
@DataColumn(key = "userName", value = "user_id")
})
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
}
| 33.716667 | 112 | 0.701434 |
31f5c6c7b02dc6b0b3fe3ae5284c08618cedc48e | 634 | package com.leacox.sandbox.runtime.simple;
/**
* A runner that attempts to avoid being killed using an iterative approach.
*
* <p>In practice, using Oracle JDK 1.8.0_91, this class sometimes locks up the entire JVM after the
* runtime tries to stop it around 12,000 to 20,000 times. I'm unsure why this is occurring.
*
* @author John Leacox
*/
public class IterativeNeverEndingRunner implements Runnable {
@Override
public void run() {
try {
int i = 0;
while (true) {
try {
i++;
} catch (ThreadDeath td) {
}
}
} catch (ThreadDeath td) {
run();
}
}
}
| 23.481481 | 100 | 0.621451 |
da9881afa08368dc21477ebcdb64432fdce1d664 | 2,033 | package app.printing;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class InConsole {
/**
* Use example : C:\\Users\\<username>\\...\\<filename>
* @param file
* This is a file url on the local disk<br>
*
*/
public static void printLocalFileFromPath(String filePath) {
try {
File file = new File(filePath);
printFile(file);
} catch (Throwable t) {
t.printStackTrace();
}
}
/**
* Use example :
* file://10.70.4.96\\info\\make\\pblack\\.prodpassaccess
* \\credentials.properties
* @param urlstr This is a file url on the local disk
*
*/
public static void printRemoteFileFromPath(String urlstr) {
URL url;
try {
url = new URL(urlstr);
InputStream is;
try {
is = url.openStream();
InputStreamReader isReader = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isReader);
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (IOException e) {
System.err.println("failed to open stream\n" + e.getMessage());
}
} catch (MalformedURLException e) {
System.err.println("url malformed\n" + e.getMessage());
}
}
/**
*
* @param file This is the file to print in the console
*/
public static void printFile(File file) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
do {
sb.append(line);
sb.append(System.lineSeparator());
} while ((line = br.readLine()) != null);
System.out.println(sb.toString());
} catch (Throwable t) {
t.printStackTrace();
} finally {
br.close();
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
| 21.177083 | 69 | 0.631087 |
7b93aa67393f8ee005a0e5b1b9d69a5df6bd86ac | 965 | package net.kaneka.planttech2.blocks.machines;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemGroup;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import javax.annotation.Nullable;
public class EnergySupplierBlock extends MachineBaseBlock
{
public static final BooleanProperty SUPPLYING = BooleanProperty.create("supplying");
public EnergySupplierBlock(String name, ItemGroup group)
{
super(name, group);
setDefaultState(getDefaultState().with(SUPPLYING, false));
}
@Nullable
@Override
public BlockState getStateForPlacement(BlockItemUseContext context)
{
return getDefaultState().with(SUPPLYING, false);
}
@Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder)
{
builder.add(SUPPLYING);
}
}
| 28.382353 | 88 | 0.756477 |
74ef98806aca28c08cc1110b3fc30e5852be07f2 | 107 | package com.nikolafranicevic.classesInterfaces;
public interface Encodable {
public void encode();
}
| 15.285714 | 47 | 0.775701 |
a2eb624c4113bbfffa7822c52174eedac04c380a | 405 | package model.processes;
import java.util.Map;
import level.manager.LevelManager;
public class ExecutableSpecificLevel extends ExecutableLevelChanges {
protected int levelIndex;
public ExecutableSpecificLevel(Map<String, Object> parameters) {
super(parameters);
// TODO Auto-generated constructor stub
}
@Override
public void execute() {
myLevelManager.changeLevelTo(levelIndex);
}
}
| 18.409091 | 69 | 0.780247 |
efe293d84378b3471c0c6c8641deb9943c563952 | 422 | package com.silang.iconfont;
import android.content.Context;
import android.graphics.Typeface;
import android.widget.TextView;
/**
* Created by Administrator on 2017/9/20.
*/
public class IconFontTool {
public static void setTypeface(Context context,String iconPath,TextView tv){
Typeface iconfont1 = Typeface.createFromAsset(context.getAssets(), iconPath);
tv.setTypeface(iconfont1);
}
}
| 21.1 | 85 | 0.739336 |
15374abea66a8d04a10ff8d2c148b3a39b837735 | 252 | package ru.job4j.tictactoo;
/**
* Interface Print - выводит на печать структуры игрового поля.
*
* @author Frolov Sergey (Slevkelebr@yandex.ru)
* @version 0.1
* @since 22.05.2020
*/
public interface Print {
void printStr(String[][] str);
}
| 18 | 63 | 0.68254 |
52fa387a445af3ecc5a57bcf081522a000556028 | 124 | package org.formacion.abstractfactory;
public interface Preguntas {
String preguntaHora();
String preguntaTiempo();
}
| 13.777778 | 38 | 0.774194 |
d5fa229338286a51bff1d291bd51c2a9e8a1f203 | 516 | package com.fengzai.oauth.app.util;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @author rhf30
* @Title: haifeng
* @ProjectName oauth
* @date 2019/5/2917:24
* @Description: 比较密码
*/
public class BCryptPasswordEncoderUtil {
private static BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
public static boolean matches(String password, String encoderPassword){
return bCryptPasswordEncoder.matches(password, encoderPassword);
}
}
| 27.157895 | 93 | 0.767442 |
4eb49195ba29dc7f7de4e514ac66757c789d6b21 | 1,691 | /**
*
*/
package com.example;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import junit.framework.Assert;
/**
* @author rocket
*
*/
public class JsonTest {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonTest.class);
@Test
public void test() throws Exception{
ObjectMapper mapper = new ObjectMapper();
Teacher teacher = new Teacher();
teacher.name = "rocket";
teacher.age = 25;
String str = "{\"person\": {\"name\":\"Bob\", \"age\":13, \"man\": {\"id\": 111, \"school\": {\"level\": 333}}}}";
//Map<String, Object> obj = mapper.readValue(str,new TypeReference<Map<String, Object>>(){});
Object obj = mapper.readValue(str, Class.forName("java.util.Map"));
Object p1 = PropertyUtils.getProperty(obj, "person.man.school.level");
Assert.assertEquals(p1, 333);
Object p2 = PropertyUtils.getProperty(obj, "person.man.school.aa");
Assert.assertEquals(p2, null);
LOGGER.info("hello");
}
public class DynamicBean {
}
public class Teacher {
private String name;
private int age;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
}
| 21.679487 | 116 | 0.659965 |
03d7e0bb8b0bf05411f3afec5065da9addf938f5 | 955 | package org.imaginea.requesttracking.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class Logout
*/
public class Logout extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if(session != null){
session.invalidate();
}
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.sendRedirect("LoginRedirect");
}
}
| 30.806452 | 118 | 0.737173 |
1ef310ac0d7335d43cbbdc5edc9c0be14705bd33 | 8,280 | package com.example.miriyusifli.cardgame;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import com.example.miriyusifli.cardgame.services.AnimatedGifImageView;
import com.example.miriyusifli.cardgame.services.Utils;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import static com.example.miriyusifli.cardgame.services.Utils.hideKeyboard;
public class Choose_language_Fragment extends Fragment {
public Choose_language_Fragment() {
// Required empty public constructor
}
private int i = 1;
private int j = 4;
private AnimatedGifImageView gifImageView_native;
private AnimatedGifImageView gifImageView_foreign;
private String from = null;
private String to = null;
private DatabaseReference databaseReference;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/*SharedPreferences pref = getActivity().getSharedPreferences("MyPref", 0); // 0 - for private mode
from = pref.getString("from", null);
to = pref.getString("to", null);
if (!Utils.isNull(from) && !Utils.isNull(to)) {
if (CardGame.getTopics().size() == 0) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment fragment = new SplashFragment();
fragmentTransaction.replace(R.id.first_activity, fragment);
fragmentTransaction.commit();
return;
}
Intent myIntent = new Intent(getActivity(), MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(myIntent);
return;
}
*/
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
final HashMap<Integer, Integer> flags = new HashMap<>();
flags.put(1, R.drawable.azerbaijan_flag);
flags.put(2, R.drawable.turkey_flag);
flags.put(3, R.drawable.russia_flag);
flags.put(4, R.drawable.united_kingdom_flag);
gifImageView_native = (AnimatedGifImageView) view.findViewById(R.id.GifImageView_native);
gifImageView_native.setAnimatedGif(R.drawable.azerbaijan_flag, AnimatedGifImageView.TYPE.AS_IS);
gifImageView_foreign = (AnimatedGifImageView) view.findViewById(R.id.GifImageView_foreign);
gifImageView_foreign.setAnimatedGif(R.drawable.united_kingdom_flag, AnimatedGifImageView.TYPE.AS_IS);
Button back_native = (Button) view.findViewById(R.id.back_native);
Button next_native = (Button) view.findViewById(R.id.next_native);
Button back_foreign = (Button) view.findViewById(R.id.back_foreign);
Button next_foreign = (Button) view.findViewById(R.id.next_foreign);
back_native.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
i--;
if (i == j) i--;
if (i <= 0) {
i = flags.size();
if (i == j) i--;
}
gifImageView_native.setAnimatedGif(flags.get(i), AnimatedGifImageView.TYPE.FIT_CENTER);
}
});
next_native.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
i++;
if (i == j) i++;
if (i > flags.size()) {
i = 1;
if (i == j) i++;
}
gifImageView_native.setAnimatedGif(flags.get(i), AnimatedGifImageView.TYPE.FIT_CENTER);
}
});
back_foreign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
j--;
if (i == j) j--;
if (j <= 0) {
j = flags.size();
if (i == j) j--;
}
gifImageView_foreign.setAnimatedGif(flags.get(j), AnimatedGifImageView.TYPE.FIT_CENTER);
}
});
next_foreign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
j++;
if (i == j) j++;
if (j > flags.size()) {
j = 1;
if (i == j) j++;
}
gifImageView_foreign.setAnimatedGif(flags.get(j), AnimatedGifImageView.TYPE.FIT_CENTER);
}
});
Button nextPage = (Button) view.findViewById(R.id.next_page);
nextPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (i) {
case 1:
from = "azeri";
break;
case 2:
from = "turkish";
break;
case 3:
from = "russian";
break;
case 4:
from = "english";
break;
}
switch (j) {
case 1:
to = "azeri";
break;
case 2:
to = "turkish";
break;
case 3:
to = "russian";
break;
case 4:
to = "english";
break;
}
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("from", from);
jsonParam.put("to", to);
} catch (JSONException e) {
e.printStackTrace();
}
SharedPreferences pref = getContext().getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
String id = pref.getString("id", null);
DatabaseReference new_user = databaseReference.child(id);
new_user.child("from").setValue(from);
new_user.child("to").setValue(to);
SharedPreferences.Editor editor = pref.edit();
editor.putString("from", from); // Storing string
editor.putString("to", to);
editor.apply(); // commit changes
/* if (CardGame.getTopics().size() == 0) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment fragment = new SplashFragment();
fragmentTransaction.replace(R.id.first_activity, fragment);
fragmentTransaction.commit();
return;
}*/
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment fragment = new SplashFragment();
fragmentTransaction.replace(R.id.main_activity, fragment);
fragmentTransaction.commit();
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View choose_language = inflater.inflate(R.layout.fragment_choose_language_, container, false);
hideKeyboard(getActivity());
return choose_language;
}
} | 31.245283 | 136 | 0.557367 |
ece790b4a4f0e3a302f0d2ca4e7642f7aff4ca84 | 7,441 | /*
* Copyright 2014 OpenNMS Group Inc., Entimoss ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opennms.karaf.licencemgr;
import org.opennms.karaf.licencemgr.LicenceAuthenticator;
import org.opennms.karaf.licencemgr.metadata.jaxb.LicenceMetadata;
import org.osgi.framework.ServiceException;
public class LicenceAuthenticatorImpl implements LicenceAuthenticator {
private String productId;
private String privateKeyEnryptedStr;
private LicenceMetadata licenceMetadata=null;
private String licencewithCRC=null;
private LicenceService licenceService= null;
/**
* Simply authenticates the supplied licencewithCRC string against the local keys without looking up the licence manager service or
* authenticating the systemid
* @param licencewithCRC
* @param productId
* @param privateKeyEnryptedStr
*/
public LicenceAuthenticatorImpl(String licencewithCRC, String productId, String privateKeyEnryptedStr ){
if (licencewithCRC==null) throw new RuntimeException("LicenceAuthenticatoImpl: licencewithCRC cannot be null");
if (productId==null) throw new RuntimeException("LicenceAuthenticatoImpl: productId cannot be null");
if (privateKeyEnryptedStr==null) throw new RuntimeException("LicenceAuthenticatoImpl: privateKeyEnryptedStr cannot be null");
licenceAuthenticatorImpl(licencewithCRC, productId, privateKeyEnryptedStr );
}
/**
* Uses the licence manager service to find an installed licence for the productId and then authenticates it against the
* system id and the local keys
* @param licenceService
* @param productId
* @param privateKeyEnryptedStr
*/
public LicenceAuthenticatorImpl(LicenceService licenceService, String productId, String privateKeyEnryptedStr ){
if (licenceService==null) throw new RuntimeException("LicenceAuthenticatoImpl: licenceService cannot be null");
if (productId==null) throw new RuntimeException("LicenceAuthenticatoImpl: productId cannot be null");
if (privateKeyEnryptedStr==null) throw new RuntimeException("LicenceAuthenticatoImpl: privateKeyEnryptedStr cannot be null");
this.productId=productId;
this.privateKeyEnryptedStr=privateKeyEnryptedStr;
this.licenceService=licenceService;
this.licencewithCRC = licenceService.getLicence(productId);
if (licencewithCRC==null) {
System.out.println("No licence installed for productId:'"+productId+"'");
throw new ServiceException("No licence installed for productId:'"+productId+"'");
}
licenceAuthenticatorImpl(licencewithCRC, productId, privateKeyEnryptedStr );
String systemId =licenceService.getSystemId();
if (systemId==null) throw new ServiceException("systemId cannot be null");
// check system id. If systemID == ALL_SYSTEM_IDS then this test is passed because any systemId is allowed
if (! systemId.equals(licenceMetadata.getSystemId()) && ! "ALL_SYSTEM_IDS".equals(licenceMetadata.getSystemId())) {
System.out.println("licence systemId='"+licenceMetadata.getSystemId()+"' does not match local systemId='"+systemId
+ "' in installed licence for productId='"+productId+"'");
throw new ServiceException("licence systemId='"+licenceMetadata.getSystemId()+"' does not match local systemId='"+systemId
+ "' in installed licence for productId='"+productId+"'");
}
// TODO licenceService.authenticated licence
System.out.println("BundleLicenceAuthenticator authenticated licence for productId="+productId);
System.out.println("Licence Metadata xml="+licenceMetadata.toXml());
}
/**
* checks the encoding of the licence and that the licence productId matches the local product id
* @param licencewithCRC
* @param productId
* @param privateKeyEnryptedStr
*/
private void licenceAuthenticatorImpl(String licencewithCRC, String productId, String privateKeyEnryptedStr ){
if (licencewithCRC==null) throw new RuntimeException("LicenceAuthenticatoImpl: licencewithCRC cannot be null");
if (productId==null) throw new RuntimeException("LicenceAuthenticatoImpl: productId cannot be null");
if (privateKeyEnryptedStr==null) throw new RuntimeException("LicenceAuthenticatoImpl: privateKeyEnryptedStr cannot be null");
// check and remove checksum
StringCrc32Checksum stringCrc32Checksum = new StringCrc32Checksum();
String licenceStr= stringCrc32Checksum.removeCRC(licencewithCRC);
if (licenceStr==null) {
System.out.println("licence checksum incorrect for productId:'"+productId+"'");
throw new ServiceException("licence checksum incorrect for productId:'"+productId+"'");
}
// split components of licence string
String[] components = licenceStr.split(":");
if (components.length!=3) {
System.out.println("incorrectly formatted licence string for productId:'"+productId+"'");
throw new ServiceException("incorrectly formatted licence string for productId:'"+productId+"'");
}
String receivedLicenceMetadataHexStr=components[0];
String receivedEncryptedHashStr=components[1];
String receivedAesSecretKeyStr=components[2];
// decode licence private key before using
AesSymetricKeyCipher aesCipher = new AesSymetricKeyCipher();
aesCipher.setEncodedSecretKeyStr(receivedAesSecretKeyStr);
String decryptedPrivateKeyStr= aesCipher.aesDecryptStr(privateKeyEnryptedStr);
//decrypt encrypted hash of metadata
RsaAsymetricKeyCipher rsaAsymetricKeyCipher = new RsaAsymetricKeyCipher();
rsaAsymetricKeyCipher.setPrivateKeyStr(decryptedPrivateKeyStr);
String decriptedHashStr= rsaAsymetricKeyCipher.rsaDecryptString(receivedEncryptedHashStr);
// verify hash of licence metadata matches decrypted hash
this.licenceMetadata= new LicenceMetadata();
licenceMetadata.fromHexString(receivedLicenceMetadataHexStr);
String sha256Hash = licenceMetadata.sha256Hash();
if (! sha256Hash.equals(decriptedHashStr)) {
System.out.println("licence hash not verified for productId:'"+productId+"'");
throw new ServiceException("licence hash not verified for productId:'"+productId+"'");
}
// check metadata matches expected values
if (! productId.equals(licenceMetadata.getProductId())){
System.out.println("licence productId='"+licenceMetadata.getProductId()+"' does not match expected productId:'"+productId+"'");
throw new ServiceException("licence productId='"+licenceMetadata.getProductId()+"' does not match expected productId:'"+productId+"'");
}
}
/**
* if the class authenticates the licence then the metadata will be available
* @return the licenceMetadata
*/
public LicenceMetadata getLicenceMetadata() {
return licenceMetadata;
}
/**
* If the class authenticates the licence then the licence string will be available
* @return the licencewithCRC
*/
public String getLicencewithCRC() {
return licencewithCRC;
}
}
| 43.51462 | 139 | 0.759575 |
088ef98cbe587e64240bbc73d49b41a55dcbaa94 | 1,126 | /*
* Copyright (c) 2012-2014, John Campbell and other contributors. All rights reserved.
*
* This file is part of Tectonicus. It is subject to the license terms in the LICENSE file found in
* the top-level directory of this distribution. The full list of project contributors is contained
* in the AUTHORS file found in the same location.
*
*/
package tectonicus.world.subset;
import tectonicus.ChunkCoord;
import tectonicus.NullBlockFilter;
import tectonicus.SaveFormat;
import tectonicus.world.World;
import tectonicus.world.filter.BlockFilter;
public class FullWorldSubset implements WorldSubset
{
private final World world;
public FullWorldSubset(World world)
{
this.world = world;
}
@Override
public RegionIterator createRegionIterator(SaveFormat saveFormat)
{
return new AllRegionsIterator(world.getDimensionDir(), saveFormat);
}
@Override
public boolean contains(ChunkCoord coord)
{
return true;
}
@Override
public BlockFilter getBlockFilter(ChunkCoord coord)
{
return new NullBlockFilter();
}
@Override
public String getDescription()
{
return "FullWorldSubset";
}
}
| 22.078431 | 100 | 0.767318 |
38655128cb076f3d71b7b0f8cc0fa7ef17dfaaf9 | 415 | package de.delphi.phi.data;
public class PhiNull extends PhiObject {
public static final PhiNull NULL = new PhiNull();
private PhiNull(){}
@Override
public Type getType() {
return Type.NULL;
}
@Override
public String toString() {
return "NULL";
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| 17.291667 | 61 | 0.621687 |
e2658374888150e4fe6b3085ba0f157aa871b473 | 292 | package com.showcase.securitydemo.exception;
public class ServiceUncheckedException extends SystemUncheckedException {
public ServiceUncheckedException(String message) {
super(message);
}
public ServiceUncheckedException(Throwable cause) {
super(cause);
}
}
| 24.333333 | 73 | 0.743151 |
5b2e92b2ba39275c45c43489a015dd9ef67a1f47 | 726 | package arez.annotations;
import arez.Locator;
import arez.component.Linkable;
/**
* Defines the strategy for loading references from the {@link Locator}.
* The {@link #EAGER} strategy indicates that references should be resolved as early as
* possible while {@link #LAZY} defers loading until required.
*/
public enum LinkType
{
/**
* Defines that the reference can be lazily loaded on access.
*/
LAZY,
/**
* Defines that the reference is loaded via explicit {@link Linkable#link()} call.
* The link() invocation must occur before an attempt is made to access the reference.
*/
EXPLICIT,
/**
* Defines that the reference is eagerly loaded on change or during initialization.
*/
EAGER
}
| 26.888889 | 88 | 0.712121 |
edd11b14fc1e9301eb4919615bc067e1272233e2 | 5,716 | /**
* Main Activity / Splashscreen with buttons.
*
* @author Lars Harmsen
* Copyright (c) <2014> <Lars Harmsen - Quchen>
*/
package com.quchen.flappycow;
import com.google.android.gms.common.SignInButton;
import com.google.example.games.basegameutils.BaseGameActivity;
import android.os.Bundle;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends BaseGameActivity {
/** Name of the SharedPreference that saves the medals */
public static final String medaille_save = "medaille_save";
/** Key that saves the medal */
public static final String medaille_key = "medaille_key";
public static final float DEFAULT_VOLUME = 0.3f;
/** Volume for sound and music */
public static float volume = DEFAULT_VOLUME;
private ImageButton muteButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showOfflineButtons();
((ImageButton)findViewById(R.id.play_button)).setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.play_button), this));
((ImageButton)findViewById(R.id.play_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent("com.quchen.flappycow.Game"));
}
});
((ImageButton)findViewById(R.id.highscore_button)).setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.highscore_button), this));
((ImageButton)findViewById(R.id.highscore_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(MainActivity.this.mHelper.getGamesClient().getLeaderboardIntent(
getResources().getString(R.string.leaderboard_highscore)), 0);
}
});
((ImageButton)findViewById(R.id.achievement_button)).setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.achievement_button), this));
((ImageButton)findViewById(R.id.achievement_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(MainActivity.this.mHelper.getGamesClient().getAchievementsIntent(),0);
}
});
((SignInButton)findViewById(R.id.sign_in_button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
beginUserInitiatedSignIn();
}
});
((Button)findViewById(R.id.sign_out_button)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
signOut();
showOfflineButtons();
}
});
muteButton = ((ImageButton)findViewById(R.id.mute_button));
muteButton.setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.speaker), this));
muteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(volume != 0){
volume = 0;
muteButton.setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.speaker_mute), MainActivity.this));
}else{
volume = DEFAULT_VOLUME;
muteButton.setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.speaker), MainActivity.this));
}
}
});
((Button)findViewById(R.id.about_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent("com.quchen.flappycow.About"));
}
});
setSocket();
}
/**
* Fills the socket with the medals that have already been collected.
*/
private void setSocket(){
SharedPreferences saves = this.getSharedPreferences(medaille_save, 0);
switch(saves.getInt(medaille_key, 0)){
case 1:
((ImageView)findViewById(R.id.medaille_socket)).setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.socket_bronce), this));
break;
case 2:
((ImageView)findViewById(R.id.medaille_socket)).setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.socket_silver), this));
break;
case 3:
((ImageView)findViewById(R.id.medaille_socket)).setImageBitmap(Sprite.createBitmap(getResources().getDrawable(R.drawable.socket_gold), this));
break;
}
}
/**
* Updates the socket for the medals.
*/
@Override
protected void onResume() {
super.onResume();
setSocket();
}
@Override
public void onSignInFailed() {
Toast.makeText(this, "You're not logged in", Toast.LENGTH_SHORT).show();
}
@Override
public void onSignInSucceeded() {
Toast.makeText(this, "You're logged in", Toast.LENGTH_SHORT).show();
showOnlineButtons();
if(AccomplishmentBox.isOnline(this)){
AccomplishmentBox.getLocal(this).submitScore(this, this.mHelper.getGamesClient());
}
}
private void showOnlineButtons(){
findViewById(R.id.achievement_button).setVisibility(View.VISIBLE);
findViewById(R.id.highscore_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
}
private void showOfflineButtons(){
findViewById(R.id.achievement_button).setVisibility(View.GONE);
findViewById(R.id.highscore_button).setVisibility(View.GONE);
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
}
| 34.853659 | 162 | 0.718509 |
c90a9e06eb62ef87efa1cae2562d73a2a77b8529 | 10,628 | /*
Copyright (c) 2016 LinkedIn Corp.
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.linkedin.restli.internal.server.response;
import com.linkedin.data.template.RecordTemplate;
import com.linkedin.restli.common.CollectionMetadata;
import com.linkedin.restli.common.HttpStatus;
import com.linkedin.restli.server.RestLiResponseData;
import com.linkedin.restli.server.RestLiServiceException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This builder utility class is used to build response data for testing filter implementations. Some filters are used
* to modify response data and need to generate response data in tests for those filters.
*
* Each build method will return a response data containing a response envelope. For example, the buildGetResponseData
* method will build a response data containing a GET response envelope. Note that the invariants are maintained for
* both {@link RestLiResponseData} and {@link RestLiResponseEnvelope} - please read their Javadocs for more information.
*
* This class is helpful for creating response data in tests because both the response envelope setter inside response
* data and the response envelope constructors are package private. Without this class, you cannot create response data
* with response envelopes inside of them.
*
* This class is intended to be used as a test utility only.
*
* @author gye
*/
public final class ResponseDataBuilderUtil
{
private ResponseDataBuilderUtil()
{
// private constructor to disable instantiation.
}
public static RestLiResponseData<GetResponseEnvelope> buildGetResponseData(HttpStatus status, RecordTemplate getResponse)
{
return new RestLiResponseDataImpl<>(new GetResponseEnvelope(status, getResponse), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<GetResponseEnvelope> buildGetResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new GetResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<CreateResponseEnvelope> buildCreateResponseData(HttpStatus status, RecordTemplate createResponse)
{
return new RestLiResponseDataImpl<>(new CreateResponseEnvelope(status, createResponse, false), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<CreateResponseEnvelope> buildCreateResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new CreateResponseEnvelope(exception, false), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<ActionResponseEnvelope> buildActionResponseData(HttpStatus status, RecordTemplate actionResponse)
{
return new RestLiResponseDataImpl<>(new ActionResponseEnvelope(status, actionResponse), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<ActionResponseEnvelope> buildActionResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new ActionResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<FinderResponseEnvelope> buildFinderResponseData(HttpStatus status,
List<? extends RecordTemplate> collectionResponse,
CollectionMetadata collectionResponsePaging,
RecordTemplate collectionResponseCustomMetadata)
{
return new RestLiResponseDataImpl<>(new FinderResponseEnvelope(status, collectionResponse, collectionResponsePaging,
collectionResponseCustomMetadata), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<FinderResponseEnvelope> buildFinderResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new FinderResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<GetAllResponseEnvelope> buildGetAllResponseData(HttpStatus status,
List<? extends RecordTemplate> collectionResponse,
CollectionMetadata collectionResponsePaging,
RecordTemplate collectionResponseCustomMetadata)
{
return new RestLiResponseDataImpl<>(new GetAllResponseEnvelope(status, collectionResponse,
collectionResponsePaging, collectionResponseCustomMetadata), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<GetAllResponseEnvelope> buildGetAllResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new GetAllResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<UpdateResponseEnvelope> buildUpdateResponseData(HttpStatus status)
{
return new RestLiResponseDataImpl<>(new UpdateResponseEnvelope(status), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<UpdateResponseEnvelope> buildUpdateResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new UpdateResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<PartialUpdateResponseEnvelope> buildPartialUpdateResponseData(HttpStatus status)
{
return new RestLiResponseDataImpl<>(new PartialUpdateResponseEnvelope(status), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<PartialUpdateResponseEnvelope> buildPartialUpdateResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new PartialUpdateResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<OptionsResponseEnvelope> buildOptionsResponseData(HttpStatus status)
{
return new RestLiResponseDataImpl<>(new OptionsResponseEnvelope(status), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<OptionsResponseEnvelope> buildOptionsResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new OptionsResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<DeleteResponseEnvelope> buildDeleteResponseData(HttpStatus status)
{
return new RestLiResponseDataImpl<>(new DeleteResponseEnvelope(status), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<DeleteResponseEnvelope> buildDeleteResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new DeleteResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<BatchCreateResponseEnvelope> buildBatchCreateResponseData(HttpStatus status,
List<BatchCreateResponseEnvelope.CollectionCreateResponseItem> responseItems)
{
return new RestLiResponseDataImpl<>(new BatchCreateResponseEnvelope(status, responseItems,
false), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<BatchCreateResponseEnvelope> buildBatchCreateResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new BatchCreateResponseEnvelope(exception, false), new HashMap<>(),
new ArrayList<>());
}
public static RestLiResponseData<BatchGetResponseEnvelope> buildBatchGetResponseData(HttpStatus status,
Map<?, BatchResponseEnvelope.BatchResponseEntry> batchResponseMap)
{
return new RestLiResponseDataImpl<>(new BatchGetResponseEnvelope(status, batchResponseMap), new HashMap<>(),
new ArrayList<>());
}
public static RestLiResponseData<BatchGetResponseEnvelope> buildBatchGetResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new BatchGetResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<BatchUpdateResponseEnvelope> buildBatchUpdateResponseData(HttpStatus status,
Map<?, BatchResponseEnvelope.BatchResponseEntry> batchResponseMap)
{
return new RestLiResponseDataImpl<>(new BatchUpdateResponseEnvelope(status, batchResponseMap), new HashMap<>(),
new ArrayList<>());
}
public static RestLiResponseData<BatchUpdateResponseEnvelope> buildBatchUpdateResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new BatchUpdateResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<BatchPartialUpdateResponseEnvelope> buildBatchPartialUpdateResponseData(HttpStatus status,
Map<?, BatchResponseEnvelope.BatchResponseEntry> batchResponseMap)
{
return new RestLiResponseDataImpl<>(new BatchPartialUpdateResponseEnvelope(status, batchResponseMap),
new HashMap<>(), new ArrayList<>());
}
public static RestLiResponseData<BatchPartialUpdateResponseEnvelope> buildBatchPartialUpdateResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new BatchPartialUpdateResponseEnvelope(exception), new HashMap<>(),
new ArrayList<>());
}
public static RestLiResponseData<BatchDeleteResponseEnvelope> buildBatchDeleteResponseData(HttpStatus status,
Map<?, BatchResponseEnvelope.BatchResponseEntry> batchResponseMap)
{
return new RestLiResponseDataImpl<>(new BatchDeleteResponseEnvelope(status, batchResponseMap), new HashMap<>(),
new ArrayList<>());
}
public static RestLiResponseData<BatchDeleteResponseEnvelope> buildBatchDeleteResponseData(RestLiServiceException exception)
{
return new RestLiResponseDataImpl<>(new BatchDeleteResponseEnvelope(exception), new HashMap<>(), new ArrayList<>());
}
}
| 49.432558 | 141 | 0.746142 |
c517a1c53850a51e56cc05e9493193a7e199c855 | 9,509 | package org.zalando.nakadi.webservice.hila;
import org.apache.curator.framework.CuratorFramework;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zalando.nakadi.domain.EventType;
import org.zalando.nakadi.domain.Subscription;
import org.zalando.nakadi.domain.SubscriptionBase;
import org.zalando.nakadi.repository.zookeeper.ZooKeeperHolder;
import org.zalando.nakadi.service.subscription.model.Partition;
import org.zalando.nakadi.service.subscription.zk.NewZkSubscriptionClient;
import org.zalando.nakadi.service.subscription.zk.ZkSubscriptionClient;
import org.zalando.nakadi.utils.RandomSubscriptionBuilder;
import org.zalando.nakadi.utils.TestUtils;
import org.zalando.nakadi.webservice.BaseAT;
import org.zalando.nakadi.webservice.utils.NakadiTestUtils;
import org.zalando.nakadi.webservice.utils.TestStreamingClient;
import org.zalando.nakadi.webservice.utils.ZookeeperTestUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.mockito.ArgumentMatchers.anyLong;
public class HilaRepartitionAT extends BaseAT {
private static final Logger LOG = LoggerFactory.getLogger(HilaRepartitionAT.class);
private static final CuratorFramework CURATOR = ZookeeperTestUtils.createCurator(ZOOKEEPER_URL);
private ZooKeeperHolder zooKeeperHolder;
private final String sid = TestUtils.randomUUID();
private final String subscriptionId = TestUtils.randomUUID();
private final String eventTypeName = "random";
private final String secondEventTypeName = "random_et_2";
@Test
public void testSubscriptionRepartitioningWithSingleEventType() throws Exception {
zooKeeperHolder = Mockito.mock(ZooKeeperHolder.class);
Mockito.when(zooKeeperHolder.get()).thenReturn(CURATOR);
Mockito.when(zooKeeperHolder.getSubscriptionCurator(anyLong()))
.thenReturn(new ZooKeeperHolder.DisposableCuratorFramework(CURATOR));
final ZkSubscriptionClient subscriptionClient = new NewZkSubscriptionClient(
subscriptionId,
zooKeeperHolder,
String.format("%s.%s", subscriptionId, sid),
MAPPER,
30000
);
final Partition[] eventTypePartitions = {new Partition(
eventTypeName, "0", null, null, Partition.State.ASSIGNED)};
setInitialTopology(eventTypePartitions);
subscriptionClient.repartitionTopology(eventTypeName, 2, "001-0001--1");
Assert.assertEquals(subscriptionClient.getTopology().getPartitions().length, 2);
Assert.assertEquals(subscriptionClient.getTopology().getPartitions()[1].getPartition(), "1");
Assert.assertEquals(subscriptionClient.getTopology().getPartitions()[1].getState(), Partition.State.UNASSIGNED);
Assert.assertEquals(subscriptionClient.getTopology().getPartitions()[0].getState(), Partition.State.ASSIGNED);
// test that offset path was created for new partition
Assert.assertNotNull(CURATOR.checkExists().forPath(getOffsetPath(eventTypeName, "1")));
}
@Test
public void testSubscriptionRepartitioningWithMultipleEventTypes() throws Exception {
zooKeeperHolder = Mockito.mock(ZooKeeperHolder.class);
Mockito.when(zooKeeperHolder.get()).thenReturn(CURATOR);
Mockito.when(zooKeeperHolder.getSubscriptionCurator(anyLong()))
.thenReturn(new ZooKeeperHolder.DisposableCuratorFramework(CURATOR));
final ZkSubscriptionClient subscriptionClient = new NewZkSubscriptionClient(
subscriptionId,
zooKeeperHolder,
String.format("%s.%s", subscriptionId, sid),
MAPPER,
30000
);
final Partition[] eventTypePartitions = {
new Partition(eventTypeName, "0", null, null, Partition.State.ASSIGNED),
new Partition(secondEventTypeName, "0", null, null, Partition.State.ASSIGNED)};
setInitialTopology(eventTypePartitions);
subscriptionClient.repartitionTopology(eventTypeName, 2, "001-0001--1");
Assert.assertEquals(subscriptionClient.getTopology().getPartitions().length, 3);
final List<Partition> eTPartitions =
Arrays.stream(subscriptionClient.getTopology().getPartitions())
.filter(p -> p.getEventType().equals(secondEventTypeName)).collect(Collectors.toList());
Assert.assertEquals(eTPartitions.get(0).getState(), Partition.State.ASSIGNED);
}
private String subscriptionPath() {
final String parentPath = "/nakadi/subscriptions";
return String.format("%s/%s", parentPath, subscriptionId);
}
private String getOffsetPath(final String eventTypeName, final String partition) {
return String.format("%s/offsets/%s/%s", subscriptionPath(), eventTypeName, partition);
}
private void setInitialTopology(final Partition[] partitions) throws Exception {
final String topologyPath = subscriptionPath() + "/topology";
final byte[] topologyData = MAPPER.writeValueAsBytes(
new NewZkSubscriptionClient.Topology(partitions, null, 0));
if (null == CURATOR.checkExists().forPath(topologyPath)) {
CURATOR.create().creatingParentsIfNeeded().forPath(topologyPath, topologyData);
} else {
CURATOR.setData().forPath(topologyPath, topologyData);
}
}
@Test(timeout = 30000)
public void whenEventTypeRepartitionedSubscriptionStartsStreamNewPartitions() throws Exception {
final EventType eventType = NakadiTestUtils.createBusinessEventTypeWithPartitions(1);
final Subscription subscription = NakadiTestUtils.createSubscription(
RandomSubscriptionBuilder.builder()
.withEventType(eventType.getName())
.withStartFrom(SubscriptionBase.InitialPosition.BEGIN)
.buildSubscriptionBase());
NakadiTestUtils.publishBusinessEventWithUserDefinedPartition(
eventType.getName(), 1, x -> "{\"foo\":\"bar\"}", p -> "0");
// create session, read from subscription and wait for events to be sent
final TestStreamingClient client = TestStreamingClient
.create(URL, subscription.getId(), "")
.startWithAutocommit(streamBatches -> LOG.info("{}", streamBatches));
TestUtils.waitFor(() -> MatcherAssert.assertThat(client.getBatches(), Matchers.hasSize(1)));
Assert.assertEquals("0", client.getBatches().get(0).getCursor().getPartition());
NakadiTestUtils.repartitionEventType(eventType, 2);
TestUtils.waitFor(() -> MatcherAssert.assertThat(client.isRunning(), Matchers.is(false)));
final TestStreamingClient clientAfterRepartitioning = TestStreamingClient
.create(URL, subscription.getId(), "")
.startWithAutocommit(streamBatches -> LOG.info("{}", streamBatches));
NakadiTestUtils.publishBusinessEventWithUserDefinedPartition(
eventType.getName(), 1, x -> "{\"foo\":\"bar" + x + "\"}", p -> "1");
TestUtils.waitFor(() -> MatcherAssert.assertThat(clientAfterRepartitioning.getBatches(), Matchers.hasSize(1)));
Assert.assertEquals("1", clientAfterRepartitioning.getBatches().get(0).getCursor().getPartition());
}
@Test(timeout = 30000)
public void shouldRepartitionTimelinedEventType() throws Exception {
final EventType eventType = NakadiTestUtils.createBusinessEventTypeWithPartitions(1);
final Subscription subscription = NakadiTestUtils.createSubscription(
RandomSubscriptionBuilder.builder()
.withEventType(eventType.getName())
.withStartFrom(SubscriptionBase.InitialPosition.BEGIN)
.buildSubscriptionBase());
NakadiTestUtils.publishBusinessEventWithUserDefinedPartition(
eventType.getName(), 1, x -> "{\"foo\":\"bar\"}", p -> "0");
// create session, read from subscription and wait for events to be sent
final TestStreamingClient client = TestStreamingClient
.create(URL, subscription.getId(), "")
.startWithAutocommit(streamBatches -> LOG.info("{}", streamBatches));
TestUtils.waitFor(() -> MatcherAssert.assertThat(client.getBatches(), Matchers.hasSize(1)));
Assert.assertEquals("0", client.getBatches().get(0).getCursor().getPartition());
NakadiTestUtils.createTimeline(eventType.getName());
NakadiTestUtils.repartitionEventType(eventType, 2);
TestUtils.waitFor(() -> MatcherAssert.assertThat(client.isRunning(), Matchers.is(false)));
final TestStreamingClient clientAfterRepartitioning = TestStreamingClient
.create(URL, subscription.getId(), "")
.startWithAutocommit(streamBatches -> LOG.info("{}", streamBatches));
NakadiTestUtils.publishBusinessEventWithUserDefinedPartition(
eventType.getName(), 1, x -> "{\"foo\":\"bar" + x + "\"}", p -> "1");
TestUtils.waitFor(() -> MatcherAssert.assertThat(clientAfterRepartitioning.getBatches(), Matchers.hasSize(1)));
Assert.assertEquals("1", clientAfterRepartitioning.getBatches().get(0).getCursor().getPartition());
}
}
| 50.579787 | 120 | 0.698076 |
c618c39120a134d9747b2d7e88b8b322c1552cc5 | 4,569 | /*-
* -\-\-
* Helios Services
* --
* Copyright (C) 2016 Spotify AB
* --
* 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.spotify.helios.servicescommon;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import com.spotify.helios.ZooKeeperTestingServerManager;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient;
import com.spotify.helios.servicescommon.coordination.Paths;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClient;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ZooKeeperRegistrarServiceUtilTest {
private static final String HOSTNAME = "host";
private static final String ID = UUID.randomUUID().toString();
private static final JobId JOB_ID1 =
JobId.newBuilder().setName("job1").setVersion("0.1.0").build();
private ZooKeeperTestingServerManager testingServerManager;
private ZooKeeperClient zkClient;
@Before
public void setUp() throws Exception {
testingServerManager = new ZooKeeperTestingServerManager();
testingServerManager.awaitUp(5, TimeUnit.SECONDS);
zkClient = new DefaultZooKeeperClient(testingServerManager.curatorWithSuperAuth());
}
@After
public void tearDown() throws Exception {
zkClient.close();
if (testingServerManager != null) {
testingServerManager.close();
}
}
@Test
public void testRegisterHost() throws Exception {
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
assertNotNull(zkClient.exists(Paths.configHost(HOSTNAME)));
assertNotNull(zkClient.exists(Paths.configHostJobs(HOSTNAME)));
assertNotNull(zkClient.exists(Paths.configHostPorts(HOSTNAME)));
assertNotNull(zkClient.exists(Paths.statusHost(HOSTNAME)));
assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME)));
assertEquals(ID, new String(zkClient.getData(idPath)));
}
@Test
public void testDeregisterHost() throws Exception {
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
ZooKeeperRegistrarUtil.deregisterHost(zkClient, HOSTNAME);
assertNull(zkClient.exists(Paths.configHost(HOSTNAME)));
assertNull(zkClient.exists(Paths.statusHost(HOSTNAME)));
}
// Verify that the re-registering:
// * does not change the /config/hosts/<host> subtree, except the host-id.
// * deletes everything under /status/hosts/<host> subtree.
@Test
public void testReRegisterHost() throws Exception {
// Register the host & add some fake data to its status & config dirs
final String idPath = Paths.configHostId(HOSTNAME);
ZooKeeperRegistrarUtil.registerHost(zkClient, idPath, HOSTNAME, ID);
zkClient.ensurePath(Paths.statusHostJob(HOSTNAME, JOB_ID1));
zkClient.ensurePath(Paths.configHostJob(HOSTNAME, JOB_ID1));
final Stat jobConfigStat = zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1));
// ... and then re-register it
final String newId = UUID.randomUUID().toString();
ZooKeeperRegistrarUtil.reRegisterHost(zkClient, HOSTNAME, newId);
// Verify that the host-id was updated
assertEquals(newId, new String(zkClient.getData(idPath)));
// Verify that /status/hosts/<host>/jobs exists and is EMPTY
assertNotNull(zkClient.exists(Paths.statusHostJobs(HOSTNAME)));
assertThat(zkClient.listRecursive(Paths.statusHostJobs(HOSTNAME)),
contains(Paths.statusHostJobs(HOSTNAME)));
// Verify that re-registering didn't change the nodes in /config/hosts/<host>/jobs
assertEquals(
jobConfigStat,
zkClient.stat(Paths.configHostJob(HOSTNAME, JOB_ID1))
);
}
}
| 38.075 | 87 | 0.753338 |
b2b3c7c78e694be32859a0498f3b82ff912bb7bc | 7,331 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package ctp.thostapi;
public class CThostFtdcInvestorPositionCombineDetailField {
private long swigCPtr;
protected boolean swigCMemOwn;
protected CThostFtdcInvestorPositionCombineDetailField(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(CThostFtdcInvestorPositionCombineDetailField obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
thosttraderapiJNI.delete_CThostFtdcInvestorPositionCombineDetailField(swigCPtr);
}
swigCPtr = 0;
}
}
public void setTradingDay(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_TradingDay_set(swigCPtr, this, value);
}
public String getTradingDay() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_TradingDay_get(swigCPtr, this);
}
public void setOpenDate(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_OpenDate_set(swigCPtr, this, value);
}
public String getOpenDate() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_OpenDate_get(swigCPtr, this);
}
public void setExchangeID(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_ExchangeID_set(swigCPtr, this, value);
}
public String getExchangeID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_ExchangeID_get(swigCPtr, this);
}
public void setSettlementID(int value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_SettlementID_set(swigCPtr, this, value);
}
public int getSettlementID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_SettlementID_get(swigCPtr, this);
}
public void setBrokerID(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_BrokerID_set(swigCPtr, this, value);
}
public String getBrokerID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_BrokerID_get(swigCPtr, this);
}
public void setInvestorID(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_InvestorID_set(swigCPtr, this, value);
}
public String getInvestorID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_InvestorID_get(swigCPtr, this);
}
public void setComTradeID(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_ComTradeID_set(swigCPtr, this, value);
}
public String getComTradeID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_ComTradeID_get(swigCPtr, this);
}
public void setTradeID(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_TradeID_set(swigCPtr, this, value);
}
public String getTradeID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_TradeID_get(swigCPtr, this);
}
public void setInstrumentID(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_InstrumentID_set(swigCPtr, this, value);
}
public String getInstrumentID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_InstrumentID_get(swigCPtr, this);
}
public void setHedgeFlag(char value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_HedgeFlag_set(swigCPtr, this, value);
}
public char getHedgeFlag() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_HedgeFlag_get(swigCPtr, this);
}
public void setDirection(char value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_Direction_set(swigCPtr, this, value);
}
public char getDirection() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_Direction_get(swigCPtr, this);
}
public void setTotalAmt(int value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_TotalAmt_set(swigCPtr, this, value);
}
public int getTotalAmt() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_TotalAmt_get(swigCPtr, this);
}
public void setMargin(double value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_Margin_set(swigCPtr, this, value);
}
public double getMargin() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_Margin_get(swigCPtr, this);
}
public void setExchMargin(double value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_ExchMargin_set(swigCPtr, this, value);
}
public double getExchMargin() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_ExchMargin_get(swigCPtr, this);
}
public void setMarginRateByMoney(double value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_MarginRateByMoney_set(swigCPtr, this, value);
}
public double getMarginRateByMoney() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_MarginRateByMoney_get(swigCPtr, this);
}
public void setMarginRateByVolume(double value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_MarginRateByVolume_set(swigCPtr, this, value);
}
public double getMarginRateByVolume() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_MarginRateByVolume_get(swigCPtr, this);
}
public void setLegID(int value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_LegID_set(swigCPtr, this, value);
}
public int getLegID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_LegID_get(swigCPtr, this);
}
public void setLegMultiple(int value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_LegMultiple_set(swigCPtr, this, value);
}
public int getLegMultiple() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_LegMultiple_get(swigCPtr, this);
}
public void setCombInstrumentID(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_CombInstrumentID_set(swigCPtr, this, value);
}
public String getCombInstrumentID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_CombInstrumentID_get(swigCPtr, this);
}
public void setTradeGroupID(int value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_TradeGroupID_set(swigCPtr, this, value);
}
public int getTradeGroupID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_TradeGroupID_get(swigCPtr, this);
}
public void setInvestUnitID(String value) {
thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_InvestUnitID_set(swigCPtr, this, value);
}
public String getInvestUnitID() {
return thosttraderapiJNI.CThostFtdcInvestorPositionCombineDetailField_InvestUnitID_get(swigCPtr, this);
}
public CThostFtdcInvestorPositionCombineDetailField() {
this(thosttraderapiJNI.new_CThostFtdcInvestorPositionCombineDetailField(), true);
}
}
| 34.744076 | 111 | 0.811622 |
a0b3055b5ee94e0d5e109d50579361454f616243 | 7,053 | /*
* Copyright 2012-2014 Netherlands eScience Center.
*
* 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 the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.xnattool.ui;
import java.awt.AWTEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import nl.esciencecenter.medim.dicom.DicomProcessingProfile.*;
import nl.esciencecenter.ptk.crypt.Secret;
import nl.esciencecenter.ptk.util.StringUtil;
import nl.esciencecenter.xnattool.DataSetConfig;
public class DatasetSettingsPanelController implements ActionListener, FocusListener
{
private DatasetSettingsPanel settingsPanel;
public DatasetSettingsPanelController(DatasetSettingsPanel settingsPanel)
{
this.settingsPanel = settingsPanel;
}
protected XnatToolPanelController getMasterController()
{
return settingsPanel.getMasterController();
}
protected DataSetConfig getDataSetConfig()
{
XnatToolPanelController mctrl = this.settingsPanel.getMasterController();
if (mctrl == null)
return null;
return mctrl.getDataSetConfig();
}
@Override
public void focusGained(FocusEvent e)
{
}
@Override
public void focusLost(FocusEvent e)
{
handleEvent(e);
}
@Override
public void actionPerformed(ActionEvent event)
{
handleEvent(event);
}
protected void handleEvent(AWTEvent event)
{
Object source = event.getSource();
String actionStr;
boolean modCtrl = false;
boolean temporyFocusEvent = false;
boolean lostFocus = false;
boolean isFocusEvent = false;
if (event instanceof FocusEvent)
{
isFocusEvent = true;
FocusEvent focusEvent = (FocusEvent) event;
temporyFocusEvent = focusEvent.isTemporary();
lostFocus = (focusEvent.getID() == FocusEvent.FOCUS_LOST);
}
else if (event instanceof ActionEvent)
{
actionStr = ((ActionEvent) event).getActionCommand();
modCtrl = ((((ActionEvent) event).getModifiers() & ActionEvent.CTRL_MASK) > 0);
}
DataSetConfig config = getDataSetConfig();
// focus sensitive fields!
// filter for permanent focus lost event only.
if ((isFocusEvent == false) || ((lostFocus) && (temporyFocusEvent == false)))
{
if (source == settingsPanel.sourceIdTF)
{
String newSourceId = settingsPanel.getSourceID();
String oldSourceId = this.getMasterController().getDataSetSourceID();
if (StringUtil.compare(oldSourceId, newSourceId) != 0)
{
doUpdateSourceId(oldSourceId, newSourceId);
}
}
}
// focus ignorant fields:
if (isFocusEvent == false)
{
if (source == settingsPanel.passwordTF)
{
doAuthenticateKey(settingsPanel.getPasswordSecret());
}
else if (source == settingsPanel.subjectIdCB)
{
String valStr = settingsPanel.subjectIdCB.getSelectedItem().toString();
if (config == null)
getMasterController().showError("No DataSet Configuration. Please create one");
else
config.setSubjectKeyType(SubjectKeyType.valueOf(valStr));
}
else if (source == settingsPanel.sessionKeyCB)
{
String valStr = settingsPanel.sessionKeyCB.getSelectedItem().toString();
if (config == null)
getMasterController().showError("No DataSet Configuration. Please create one");
else
config.setSessionKeyType(SessionKeyType.valueOf(valStr));
}
else if (source == settingsPanel.scanUidCB)
{
String valStr = settingsPanel.scanUidCB.getSelectedItem().toString();
if (config == null)
getMasterController().showError("No DataSet Configuration. Please create one");
else
config.setScanKeyType(ScanKeyType.valueOf(valStr));
}
else if (source == settingsPanel.createKeyBut)
{
doCreateNewKey(modCtrl);
}
}
}
protected boolean doCreateNewKey(boolean modCtrl)
{
return this.getMasterController().doCreateNewDatasetKey(modCtrl);
}
protected void doAuthenticateKey(Secret passPhrase)
{
XnatToolPanelController masterCtrl = this.getMasterController();
String sourceId = settingsPanel.getSourceID();
// copy source If from Settings Panel back !
masterCtrl.updateSourceIdFields(sourceId);
try
{
masterCtrl.doAuthenticateDataSetKeys(sourceId, passPhrase);
}
catch (Exception e)
{
masterCtrl.handle("Error authenticating DataSet.", e);
}
DataSetConfig conf = getDataSetConfig();
if (conf == null)
return; // false
}
protected boolean doUpdateSourceId(String oldSourceId, String newSourceId)
{
XnatToolPanelController ctrl = this.getMasterController();
boolean okResult = ctrl.askOkCancel(
"Change Owner ID?",
"Do you want to change the Owner ID ?\n"
+ "If you change the Owner ID you have to create a new Key and Authenticate it with a new Passphrase.\n"
+ "Continuing will invalidate your old key and DataSet!");
if (okResult == false)
{
settingsPanel.setSourceId(oldSourceId);
return false;
}
try
{
// update SourceID -> Delete Keys, will also clear KeyFields!
ctrl.doDeleteDatasetKeys(true);
}
catch (Exception e)
{
ctrl.handle("Couldn't delete Encryption Keys", e);
return false;
}
updateSourceIdFields(newSourceId);
return true;
}
protected void updateSourceIdFields(String newId)
{
// redirect to master controller to update both panel fields!
getMasterController().updateSourceIdFields(newId);
}
}
| 32.205479 | 128 | 0.614632 |
f5342f12b8a950c251e456a332d86c5de6beb0bb | 673 | package net.minecraft.inventory.container;
import net.minecraft.block.Block;
import net.minecraft.block.ShulkerBoxBlock;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public class ShulkerBoxSlot extends Slot {
public ShulkerBoxSlot(IInventory inventoryIn, int slotIndexIn, int xPosition, int yPosition) {
super(inventoryIn, slotIndexIn, xPosition, yPosition);
}
/**
* Check if the stack is allowed to be placed in this slot, used for armor slots as well as furnace fuel.
*/
public boolean isItemValid(ItemStack stack) {
return !(Block.getBlockFromItem(stack.getItem()) instanceof ShulkerBoxBlock);
}
} | 35.421053 | 108 | 0.762259 |
99d5914d985a4a1a87de1b1e9129e689f6d8eb64 | 2,504 | package com.dgsm.accessibilitycoup.Tardigrade;
import android.app.Activity;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import tardigrade.Tardigrade;
import tardigrade.deck.ICard;
import tardigrade.resources.impl.Card;
import tardigrade.resources.impl.Manager;
public class GameTardigrade extends Tardigrade {
protected GameTardigrade(Activity context) {
super(context);
super.CARD_ATTRIBUTES = new String[]{"ATTR_IDIMAGE", "ATTR_PLACE", "ATTR_RULE"};
}
public void startGame(){
if(((Manager)mManager).getObserversIds().size() >= 3){
try {
((WhoState)mState).startGame(new Roles(1));
gameInProgress = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Roles implements Serializable {
private String gameId = "1";
private List<RoleToPlayer> player_roles = new ArrayList<RoleToPlayer>();
public Roles(int gameId) throws IOException {
this.gameId = gameId + "";
mDeck.loadDeck();
List<String> ids = ((Manager)mManager).getObserversIds();
List<ICard> roles = mDeck.getAllCards();
shuffle(ids, 0);
shuffle(roles, 8 - ids.size());
roles.add(Card.Create("0", "Espião", "Descubra onde seus amigos estão",null));
shuffle(roles, 0);
for(int i=0; i< ids.size(); i++){
player_roles.add(new RoleToPlayer(ids.get(i), roles.get(i).getId()));
}
}
public String getMyRole(String id){
for(RoleToPlayer player : player_roles){
if(player.idPlayer.equals(id)){
return player.idRole;
}
}
return "-1";
}
public class RoleToPlayer{
String idPlayer;
String idRole;
public RoleToPlayer(String id, String role){
this.idPlayer = id;
this.idRole = role;
}
}
public void shuffle(List<?> list, int remove){
long seed = System.nanoTime();
if(remove > 1){
while(list.size() > remove){
list.remove(0);
}
}
Collections.shuffle(list, new Random(seed));
}
}
}
| 28.454545 | 90 | 0.555112 |
1860f3450d25071650cfc99d524a8d49ed5e6b9a | 8,327 | package uk.gov.justice.hmpps.datacompliance.events.publishers.deletion.sqs;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import uk.gov.justice.hmpps.datacompliance.dto.OffenderDeletionGrant;
import uk.gov.justice.hmpps.datacompliance.dto.OffenderDeletionReferralRequest;
import uk.gov.justice.hmpps.datacompliance.dto.OffenderNumber;
import uk.gov.justice.hmpps.datacompliance.events.publishers.sqs.DataComplianceAwsEventPusher;
import uk.gov.justice.hmpps.datacompliance.events.publishers.sqs.DataComplianceEventPusher;
import java.time.LocalDate;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class DataComplianceAwsEventPusherTest {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final static OffenderNumber OFFENDER_NUMBER = new OffenderNumber("A1234AA");
private final static long BATCH_ID = 987;
private final static long REFERRAL_ID = 123;
private final static long OFFENDER_ID = 456;
private final static long OFFENDER_BOOK_ID = 789;
private final static LocalDate REFERRAL_WINDOW_START = LocalDate.of(2020, 1, 2);
private final static LocalDate REFERRAL_WINDOW_END = LocalDate.of(2020, 3, 4);
private final static int REFERRAL_LIMIT = 10;
@Mock
private AmazonSQS client;
private DataComplianceEventPusher eventPusher;
@BeforeEach
void setUp() {
eventPusher = new DataComplianceAwsEventPusher(client, "queue.url", OBJECT_MAPPER);
}
@Test
void requestReferral() {
final var request = ArgumentCaptor.forClass(SendMessageRequest.class);
when(client.sendMessage(request.capture()))
.thenReturn(new SendMessageResult().withMessageId("message1"));
eventPusher.requestReferral(OffenderDeletionReferralRequest.builder()
.batchId(BATCH_ID)
.dueForDeletionWindowStart(REFERRAL_WINDOW_START)
.dueForDeletionWindowEnd(REFERRAL_WINDOW_END)
.limit(REFERRAL_LIMIT)
.build());
assertThat(request.getValue().getQueueUrl()).isEqualTo("queue.url");
assertThat(request.getValue().getMessageAttributes().get("eventType").getStringValue())
.isEqualTo("DATA_COMPLIANCE_REFERRAL-REQUEST");
assertThat(request.getValue().getMessageBody()).isEqualTo(
"{" +
"\"batchId\":987," +
"\"dueForDeletionWindowStart\":\"2020-01-02\"," +
"\"dueForDeletionWindowEnd\":\"2020-03-04\"," +
"\"limit\":10" +
"}");
}
@Test
void requestReferralWithoutLimit() {
final var request = ArgumentCaptor.forClass(SendMessageRequest.class);
when(client.sendMessage(request.capture()))
.thenReturn(new SendMessageResult().withMessageId("message1"));
eventPusher.requestReferral(OffenderDeletionReferralRequest.builder()
.batchId(BATCH_ID)
.dueForDeletionWindowStart(REFERRAL_WINDOW_START)
.dueForDeletionWindowEnd(REFERRAL_WINDOW_END)
.build());
assertThat(request.getValue().getQueueUrl()).isEqualTo("queue.url");
assertThat(request.getValue().getMessageAttributes().get("eventType").getStringValue())
.isEqualTo("DATA_COMPLIANCE_REFERRAL-REQUEST");
assertThat(request.getValue().getMessageBody()).isEqualTo(
"{" +
"\"batchId\":987," +
"\"dueForDeletionWindowStart\":\"2020-01-02\"," +
"\"dueForDeletionWindowEnd\":\"2020-03-04\"" +
"}");
}
@Test
void requestAdHocReferral() {
final var request = ArgumentCaptor.forClass(SendMessageRequest.class);
when(client.sendMessage(request.capture()))
.thenReturn(new SendMessageResult().withMessageId("message1"));
eventPusher.requestAdHocReferral(OFFENDER_NUMBER, 123L);
assertThat(request.getValue().getQueueUrl()).isEqualTo("queue.url");
assertThat(request.getValue().getMessageBody()).isEqualTo("{\"offenderIdDisplay\":\"A1234AA\",\"batchId\":123}");
assertThat(request.getValue().getMessageAttributes().get("eventType").getStringValue())
.isEqualTo("DATA_COMPLIANCE_AD-HOC-REFERRAL-REQUEST");
}
@Test
void requestIdDataDuplicateCheck() {
final var request = ArgumentCaptor.forClass(SendMessageRequest.class);
when(client.sendMessage(request.capture()))
.thenReturn(new SendMessageResult().withMessageId("message1"));
eventPusher.requestIdDataDuplicateCheck(OFFENDER_NUMBER, 123L);
assertThat(request.getValue().getQueueUrl()).isEqualTo("queue.url");
assertThat(request.getValue().getMessageBody()).isEqualTo("{\"offenderIdDisplay\":\"A1234AA\",\"retentionCheckId\":123}");
assertThat(request.getValue().getMessageAttributes().get("eventType").getStringValue())
.isEqualTo("DATA_COMPLIANCE_DATA-DUPLICATE-ID-CHECK");
}
@Test
void requestDatabaseDataDuplicateCheck() {
final var request = ArgumentCaptor.forClass(SendMessageRequest.class);
when(client.sendMessage(request.capture()))
.thenReturn(new SendMessageResult().withMessageId("message1"));
eventPusher.requestDatabaseDataDuplicateCheck(OFFENDER_NUMBER, 123L);
assertThat(request.getValue().getQueueUrl()).isEqualTo("queue.url");
assertThat(request.getValue().getMessageBody()).isEqualTo("{\"offenderIdDisplay\":\"A1234AA\",\"retentionCheckId\":123}");
assertThat(request.getValue().getMessageAttributes().get("eventType").getStringValue())
.isEqualTo("DATA_COMPLIANCE_DATA-DUPLICATE-DB-CHECK");
}
@Test
void requestFreeTextMoratoriumCheck() {
final var request = ArgumentCaptor.forClass(SendMessageRequest.class);
when(client.sendMessage(request.capture()))
.thenReturn(new SendMessageResult().withMessageId("message1"));
eventPusher.requestFreeTextMoratoriumCheck(OFFENDER_NUMBER, 123L, List.of("^(regex|1)$","^(regex|2)$"));
assertThat(request.getValue().getQueueUrl()).isEqualTo("queue.url");
assertThat(request.getValue().getMessageBody()).isEqualTo("{\"offenderIdDisplay\":\"A1234AA\",\"retentionCheckId\":123,\"regex\":[\"^(regex|1)$\",\"^(regex|2)$\"]}");
assertThat(request.getValue().getMessageAttributes().get("eventType").getStringValue())
.isEqualTo("DATA_COMPLIANCE_FREE-TEXT-MORATORIUM-CHECK");
}
@Test
void grantDeletion() {
final var request = ArgumentCaptor.forClass(SendMessageRequest.class);
when(client.sendMessage(request.capture()))
.thenReturn(new SendMessageResult().withMessageId("message1"));
eventPusher.grantDeletion(
OffenderDeletionGrant.builder()
.offenderNumber(OFFENDER_NUMBER)
.referralId(REFERRAL_ID)
.offenderId(OFFENDER_ID)
.offenderBookId(OFFENDER_BOOK_ID)
.build());
assertThat(request.getValue().getQueueUrl()).isEqualTo("queue.url");
assertThat(request.getValue().getMessageAttributes().get("eventType").getStringValue())
.isEqualTo("DATA_COMPLIANCE_OFFENDER-DELETION-GRANTED");
assertThat(request.getValue().getMessageBody()).isEqualTo(
"{" +
"\"offenderIdDisplay\":\"A1234AA\"," +
"\"referralId\":123," +
"\"offenderIds\":[456]," +
"\"offenderBookIds\":[789]" +
"}");
}
}
| 43.369792 | 174 | 0.662904 |
a491b5a1ccc535e5a250dc3076c1ad1bef5b4393 | 5,726 | /**
* Copyright © 2013 - 2017 WaveMaker, 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 com.wavemaker.runtime.data.expression;
import java.sql.Date;
import java.sql.Timestamp;
import org.hibernate.type.*;
import com.wavemaker.commons.json.deserializer.WMDateDeSerializer;
import com.wavemaker.commons.json.deserializer.WMLocalDateTimeDeSerializer;
/**
* @author <a href="mailto:sunil.pulugula@wavemaker.com">Sunil Kumar</a>
* @since 17/2/16
*/
public enum AttributeType implements TypeConverter {
BIG_DECIMAL {
@Override
public Object toJavaType(final Object value) {
return BigDecimalType.INSTANCE.fromString(value.toString());
}
},
BIG_INTEGER {
@Override
public Object toJavaType(final Object value) {
return BigIntegerType.INSTANCE.fromString(value.toString());
}
},
BLOB {
@Override
public Object toJavaType(final Object value) {
return BlobType.INSTANCE.fromString(value.toString());
}
},
BOOLEAN {
@Override
public Object toJavaType(final Object value) {
return BooleanType.INSTANCE.fromString(value.toString());
}
},
BYTE {
@Override
public Object toJavaType(final Object value) {
return ByteType.INSTANCE.fromString(value.toString());
}
},
CALENDAR {
@Override
public Object toJavaType(final Object value) {
return new Date(((Number) value).longValue());
}
},
CALENDAR_DATE {
@Override
public Object toJavaType(final Object value) {
return new Date(((Number) value).longValue());
}
},
CHARACTER {
@Override
public Object toJavaType(final Object value) {
return CharacterType.INSTANCE.fromString(value.toString());
}
},
CLOB {
@Override
public Object toJavaType(final Object value) {
return ClobType.INSTANCE.fromString(value.toString());
}
},
CURRENCY {
@Override
public Object toJavaType(final Object value) {
return CurrencyType.INSTANCE.fromString(value.toString());
}
},
DATE {
@Override
public Object toJavaType(final Object value) {
if (value instanceof Number) {
return new Date(((Number) value).longValue());
} else {
return WMDateDeSerializer.getDate(value.toString());
}
}
},
DOUBLE {
@Override
public Object toJavaType(final Object value) {
return DoubleType.INSTANCE.fromString(value.toString());
}
},
FLOAT {
@Override
public Object toJavaType(final Object value) {
return FloatType.INSTANCE.fromString(value.toString());
}
},
INTEGER {
@Override
public Object toJavaType(final Object value) {
return IntegerType.INSTANCE.fromString(value.toString());
}
},
LONG {
@Override
public Object toJavaType(final Object value) {
return LongType.INSTANCE.fromString(value.toString());
}
},
LOCALE {
@Override
public Object toJavaType(final Object value) {
return LocaleType.INSTANCE.fromString(value.toString());
}
},
STRING {
@Override
public Object toJavaType(final Object value) {
return StringType.INSTANCE.fromString(value.toString());
}
},
SHORT {
@Override
public Object toJavaType(final Object value) {
return ShortType.INSTANCE.fromString(value.toString());
}
},
TEXT {
@Override
public Object toJavaType(final Object value) {
return TextType.INSTANCE.fromString(value.toString());
}
},
TIME {
@Override
public Object toJavaType(final Object value) {
if (value instanceof Number) {
return new java.sql.Time(((Number) value).longValue());
} else {
return WMDateDeSerializer.getDate((String) value);
}
}
},
DATETIME {
@Override
public Object toJavaType(final Object value) {
return WMLocalDateTimeDeSerializer.getLocalDateTime((String) value);
}
},
TIMESTAMP {
@Override
public Object toJavaType(final Object value) {
return new Timestamp(((Number) value).longValue());
}
},
TIMEZONE {
@Override
public Object toJavaType(final Object value) {
return TimeZoneType.INSTANCE.fromString(value.toString());
}
},
TRUE_FALSE {
@Override
public Object toJavaType(final Object value) {
return TrueFalseType.INSTANCE.fromString(value.toString());
}
},
YES_NO {
@Override
public Object toJavaType(final Object value) {
return YesNoType.INSTANCE.fromString(value.toString());
}
};
public String getHibernateType() {
return this.name().toLowerCase();
}
}
| 29.364103 | 80 | 0.599546 |
4926c698b2cb7f36d4f56f14133455f68a03963a | 95 | open module modmain { // allow reflective access, currently used in the example_jerry-mouse
} | 47.5 | 93 | 0.778947 |
04642813ad3a3dbd34503a1c6e266a400543e338 | 4,172 | /*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
This software is provided by RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
package rice.persistence.testing;
/*
* @(#) PersistentStorageTest.java
*
* @author Ansley Post
* @author Alan Mislove
*
* @version $Id: GlacierPersistentStorageTest.java 3613 2007-02-15 14:45:14Z jstewart $
*/
import java.io.*;
import java.util.*;
import java.util.zip.*;
import rice.*;
import rice.p2p.commonapi.*;
import rice.p2p.glacier.*;
import rice.p2p.glacier.v2.*;
import rice.p2p.util.*;
import rice.pastry.commonapi.*;
import rice.persistence.*;
/**
* This class is a class which tests the PersistentStorage class
* in the rice.persistence package.
*/
public class GlacierPersistentStorageTest {
File root;
/**
* Builds a MemoryStorageTest
*/
public GlacierPersistentStorageTest(String root) throws IOException {
this.root = new File("FreePastry-Storage-Root/" + root);
}
public void start() throws Exception {
process(root);
}
protected void process(File file) throws Exception {
File[] files = file.listFiles();
for (int i=0; i<files.length; i++) {
/* check each file and recurse into subdirectories */
if (files[i].isFile() && (files[i].getName().length() > 20)) {
ObjectInputStream objin = new XMLObjectInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(files[i]))));
objin.readObject();
Object o = objin.readObject();
if (o instanceof FragmentAndManifest) {
FragmentAndManifest fm = (FragmentAndManifest) o;
int total = fm.fragment.payload.length + 24;
total += fm.manifest.getObjectHash().length + fm.manifest.getSignature().length;
total += fm.manifest.getFragmentHashes().length * fm.manifest.getFragmentHashes()[0].length;
System.out.println(files[i].getName() + "\t" + total + "\t" + files[i].length());
} else {
System.out.println("ERROR: Found class " + o.getClass().getName());
}
objin.close();
} else if (files[i].isDirectory()) {
process(files[i]);
}
}
}
public static void main(String[] args) throws Exception {
GlacierPersistentStorageTest test = new GlacierPersistentStorageTest("sys08.cs.rice.edu-10001-glacier-immutable");
test.start();
}
}
| 36.596491 | 136 | 0.686961 |
638dbda9b60ecdbcbb39b77874841afa8d5aa8f9 | 1,015 | package com.skeqi.mes.mapper.chenj.srm;
import com.skeqi.mes.pojo.chenj.srm.CSrmSupplierR;
import com.skeqi.mes.pojo.chenj.srm.req.CSrmSupplierHRDelReq;
import com.skeqi.mes.pojo.chenj.srm.req.CSrmSupplierHRReq;
import com.skeqi.mes.pojo.chenj.srm.req.CSrmSupplierRReq;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author ChenJ
* @date 2021/7/20
* @Classname CSrmSupplierRMapper
* @Description ${Description}
*/
public interface CSrmSupplierRMapper {
int insertSelective(CSrmSupplierR record);
CSrmSupplierR selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(CSrmSupplierR record);
int updateBatchSelective(List<CSrmSupplierR> list);
int batchInsert(@Param("list") List<CSrmSupplierR> list);
Integer selectRequestCode(String requestCode);
CSrmSupplierR selectFinallyData(String requestCode);
List<CSrmSupplierRReq> selectByPrimaryKeyList(CSrmSupplierHRReq req);
int deleteByPrimaryData(CSrmSupplierHRDelReq delReq);
}
| 26.025641 | 73 | 0.784236 |
c2cc008ee25140dddf249f0269d5daf4330c0f34 | 352 | package cn.orangepoet.omq.broker.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author chengz
* @since 2018/7/17
*/
@RestController
public class HomeController {
@GetMapping("/")
public String index() {
return "broker started";
}
}
| 19.555556 | 62 | 0.71875 |
bc317f4809b806910dfe683d0617c722d0768eb1 | 3,282 | package com.haitang.project.system.clientLoginInfo.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.haitang.framework.aspectj.lang.annotation.Excel;
import com.haitang.framework.web.domain.BaseEntity;
import java.util.Date;
/**
* 【请填写功能名称】对象 client_login_info
*
* @author haitang
* @date 2020-03-19
*/
public class ClientLoginInfo extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** $column.columnComment */
private Long id;
/** pad客户端运行账号 */
@Excel(name = "pad客户端运行账号")
private String account;
/** Pad 设备唯一ID */
@Excel(name = "Pad 设备唯一ID")
private String clientId;
/** pad 临时运行秘钥Token */
@Excel(name = "pad 临时运行秘钥Token")
private String token;
/** token有效时间戳 */
@Excel(name = "token有效时间戳", width = 30, dateFormat = "yyyy-MM-dd")
private Date timestamp;
/** 录音时长,针对本地教学、听诊录音、远程教学都会用到此字段 */
@Excel(name = "录音时长,针对本地教学、听诊录音、远程教学都会用到此字段")
private Integer recordDuration;
/** 状态:1启用、0禁用 */
@Excel(name = "状态:1启用、0禁用")
private Integer enabled;
/** 软删除,1=是 已删除,0=否 未删除 */
@Excel(name = "软删除,1=是 已删除,0=否 未删除")
private Integer isDelete;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setAccount(String account)
{
this.account = account;
}
public String getAccount()
{
return account;
}
public void setClientId(String clientId)
{
this.clientId = clientId;
}
public String getClientId()
{
return clientId;
}
public void setToken(String token)
{
this.token = token;
}
public String getToken()
{
return token;
}
public void setTimestamp(Date timestamp)
{
this.timestamp = timestamp;
}
public Date getTimestamp()
{
return timestamp;
}
public void setRecordDuration(Integer recordDuration)
{
this.recordDuration = recordDuration;
}
public Integer getRecordDuration()
{
return recordDuration;
}
public void setEnabled(Integer enabled)
{
this.enabled = enabled;
}
public Integer getEnabled()
{
return enabled;
}
public void setIsDelete(Integer isDelete)
{
this.isDelete = isDelete;
}
public Integer getIsDelete()
{
return isDelete;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("account", getAccount())
.append("clientId", getClientId())
.append("token", getToken())
.append("timestamp", getTimestamp())
.append("recordDuration", getRecordDuration())
.append("enabled", getEnabled())
.append("createTime", getCreateTime())
.append("updateTime", getUpdateTime())
.append("isDelete", getIsDelete())
.toString();
}
}
| 23.611511 | 72 | 0.577392 |
e2e3cf3804d5ca998022605d09f05cc5c1106ede | 116 | package io.odysz.anson;
public class Ans2dArr extends Anson {
public String[][] strs;
public Ans2dArr() { }
}
| 12.888889 | 37 | 0.689655 |
3c0e957e4201d4d4d2093718e382e3a920f2cedd | 415 | package com.github.sornerol.chess.pubapi.domain.club;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* Wrapper class for returning a list of clubs
*/
@Getter
@Setter
@ToString
public class ClubList {
/**
* List of club PubAPI URLs
*/
@JsonProperty("clubs")
List<String> clubsApiUrls;
}
| 18.043478 | 53 | 0.722892 |
3e29ce385f90c95227b4d705bc422471fc65e6aa | 6,774 | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* com.google.common.collect.Lists
* com.google.common.collect.Maps
*/
package net.minecraft.client.gui;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiOptionButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiSlot;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.resources.Language;
import net.minecraft.client.resources.LanguageManager;
import net.minecraft.client.settings.GameSettings;
public class GuiLanguage
extends GuiScreen {
protected GuiScreen field_146453_a;
private List field_146450_f;
private final GameSettings game_settings_3;
private final LanguageManager field_146454_h;
private GuiOptionButton field_146455_i;
private GuiOptionButton field_146452_r;
private static final String __OBFID = "CL_00000698";
public GuiLanguage(GuiScreen p_i1043_1_, GameSettings p_i1043_2_, LanguageManager p_i1043_3_) {
this.field_146453_a = p_i1043_1_;
this.game_settings_3 = p_i1043_2_;
this.field_146454_h = p_i1043_3_;
}
@Override
public void initGui() {
this.field_146455_i = new GuiOptionButton(100, this.width / 2 - 155, this.height - 38, GameSettings.Options.FORCE_UNICODE_FONT, this.game_settings_3.getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT));
this.buttonList.add(this.field_146455_i);
this.field_146452_r = new GuiOptionButton(6, this.width / 2 - 155 + 160, this.height - 38, I18n.format("gui.done", new Object[0]));
this.buttonList.add(this.field_146452_r);
this.field_146450_f = new List(this.mc);
this.field_146450_f.registerScrollButtons(7, 8);
}
@Override
public void handleMouseInput() throws IOException {
super.handleMouseInput();
this.field_146450_f.handleMouseInput();
}
@Override
protected void actionPerformed(GuiButton button) throws IOException {
if (button.enabled) {
switch (button.id) {
case 5: {
break;
}
case 6: {
this.mc.displayGuiScreen(this.field_146453_a);
break;
}
case 100: {
if (!(button instanceof GuiOptionButton)) break;
this.game_settings_3.setOptionValue(((GuiOptionButton)button).returnEnumOptions(), 1);
button.displayString = this.game_settings_3.getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT);
ScaledResolution var2 = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight);
int var3 = var2.getScaledWidth();
int var4 = var2.getScaledHeight();
this.setWorldAndResolution(this.mc, var3, var4);
break;
}
default: {
this.field_146450_f.actionPerformed(button);
}
}
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
this.field_146450_f.drawScreen(mouseX, mouseY, partialTicks);
this.drawCenteredString(this.fontRendererObj, I18n.format("options.language", new Object[0]), this.width / 2, 16.0f, 0xFFFFFF);
this.drawCenteredString(this.fontRendererObj, "(" + I18n.format("options.languageWarning", new Object[0]) + ")", this.width / 2, this.height - 56, 0x808080);
super.drawScreen(mouseX, mouseY, partialTicks);
}
class List
extends GuiSlot {
private final java.util.List field_148176_l;
private final Map field_148177_m;
private static final String __OBFID = "CL_00000699";
public List(Minecraft mcIn) {
super(mcIn, GuiLanguage.this.width, GuiLanguage.this.height, 32, GuiLanguage.this.height - 65 + 4, 18);
this.field_148176_l = Lists.newArrayList();
this.field_148177_m = Maps.newHashMap();
for (Language var4 : GuiLanguage.this.field_146454_h.getLanguages()) {
this.field_148177_m.put(var4.getLanguageCode(), var4);
this.field_148176_l.add(var4.getLanguageCode());
}
}
@Override
protected int getSize() {
return this.field_148176_l.size();
}
@Override
protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY) {
Language var5 = (Language)this.field_148177_m.get(this.field_148176_l.get(slotIndex));
GuiLanguage.this.field_146454_h.setCurrentLanguage(var5);
((GuiLanguage)GuiLanguage.this).game_settings_3.language = var5.getLanguageCode();
this.mc.refreshResources();
GuiLanguage.this.fontRendererObj.setUnicodeFlag(GuiLanguage.this.field_146454_h.isCurrentLocaleUnicode() || ((GuiLanguage)GuiLanguage.this).game_settings_3.forceUnicodeFont);
GuiLanguage.this.fontRendererObj.setBidiFlag(GuiLanguage.this.field_146454_h.isCurrentLanguageBidirectional());
((GuiLanguage)GuiLanguage.this).field_146452_r.displayString = I18n.format("gui.done", new Object[0]);
((GuiLanguage)GuiLanguage.this).field_146455_i.displayString = GuiLanguage.this.game_settings_3.getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT);
GuiLanguage.this.game_settings_3.saveOptions();
}
@Override
protected boolean isSelected(int slotIndex) {
return ((String)this.field_148176_l.get(slotIndex)).equals(GuiLanguage.this.field_146454_h.getCurrentLanguage().getLanguageCode());
}
@Override
protected int getContentHeight() {
return this.getSize() * 18;
}
@Override
protected void drawBackground() {
GuiLanguage.this.drawDefaultBackground();
}
@Override
protected void drawSlot(int p_180791_1_, int p_180791_2_, int p_180791_3_, int p_180791_4_, int p_180791_5_, int p_180791_6_) {
GuiLanguage.this.fontRendererObj.setBidiFlag(true);
GuiLanguage.this.drawCenteredString(GuiLanguage.this.fontRendererObj, ((Language)this.field_148177_m.get(this.field_148176_l.get(p_180791_1_))).toString(), this.width / 2, p_180791_3_ + 1, 0xFFFFFF);
GuiLanguage.this.fontRendererObj.setBidiFlag(GuiLanguage.this.field_146454_h.getCurrentLanguage().isBidirectional());
}
}
}
| 44.860927 | 213 | 0.675672 |
8be880029fee5d6d3e5381d9433dbb6b2bf0471c | 344 | package com.sp.dao;
import com.sp.domain.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Created by jongwon on 2017. 4. 20..
*/
@Repository("roleRepository")
public interface RoleRepository extends JpaRepository<Role, Integer> {
Role findByRole(String role);
}
| 21.5 | 70 | 0.776163 |
482919fcf39936685cf8e4d552786be69a7fb3ae | 7,149 | /* Copyright 2018 Urban Airship and Contributors */
package com.urbanairship.actions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.urbanairship.BaseTestCase;
import com.urbanairship.CustomShadowService;
import com.urbanairship.UAirship;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication;
import java.util.HashMap;
import java.util.Map;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ActionServiceTest extends BaseTestCase {
ActionService service;
ActionRunRequestFactory actionRunRequestFactory;
private Context context = UAirship.getApplicationContext();
@Before
public void setUp() {
actionRunRequestFactory = Mockito.mock(ActionRunRequestFactory.class);
service = new ActionService(actionRunRequestFactory);
}
/**
* Test that the ActionService.runActions starts the
* action service with the correct intent.
*/
@Test
public void testRunActionsWithString() {
ShadowApplication shadowApplication = Shadows.shadowOf(RuntimeEnvironment.application);
shadowApplication.clearStartedServices();
String actionsPayload = "{ \"actionName\": \"actionValue\" }";
Bundle metadata = new Bundle();
metadata.putString("oh", "hi");
ActionService.runActions(context, actionsPayload, Action.SITUATION_WEB_VIEW_INVOCATION, metadata);
Intent runActionsIntent = shadowApplication.getNextStartedService();
assertNotNull(runActionsIntent);
assertEquals("Should add an intent with action RUN_ACTIONS_ACTION",
runActionsIntent.getAction(), ActionService.ACTION_RUN_ACTIONS);
Bundle actionBundle = runActionsIntent.getBundleExtra(ActionService.EXTRA_ACTIONS_BUNDLE);
assertEquals(actionBundle.getParcelable("actionName"), ActionValue.wrap("actionValue"));
assertEquals("Should add the situation", Action.SITUATION_WEB_VIEW_INVOCATION,
runActionsIntent.getSerializableExtra(ActionService.EXTRA_SITUATION));
}
/**
* Test that the ActionService.runActions starts the
* action service with the correct intent.
*/
@Test
public void testRunActions() {
ShadowApplication shadowApplication = Shadows.shadowOf(RuntimeEnvironment.application);
shadowApplication.clearStartedServices();
Map<String, ActionValue> actions = new HashMap<>();
actions.put("actionName", ActionValue.wrap("actionValue"));
Bundle metadata = new Bundle();
metadata.putString("oh", "hi");
ActionService.runActions(context, actions, Action.SITUATION_PUSH_OPENED, metadata);
Intent runActionsIntent = shadowApplication.getNextStartedService();
assertNotNull(runActionsIntent);
assertEquals("Should add an intent with action RUN_ACTIONS_ACTION",
runActionsIntent.getAction(), ActionService.ACTION_RUN_ACTIONS);
Bundle actionBundle = runActionsIntent.getBundleExtra(ActionService.EXTRA_ACTIONS_BUNDLE);
assertEquals(actionBundle.getParcelable("actionName"), ActionValue.wrap("actionValue"));
assertEquals("Should add the situation", Action.SITUATION_PUSH_OPENED,
runActionsIntent.getSerializableExtra(ActionService.EXTRA_SITUATION));
}
/**
* Test that the ActionService.runActionsPayload does not start
* the service if the actions payload is null or empty
*/
@Test
public void testRunActionsPayloadInvalid() {
ShadowApplication shadowApplication = Shadows.shadowOf(RuntimeEnvironment.application);
shadowApplication.clearStartedServices();
String actionsPayload = null;
ActionService.runActions(context, actionsPayload, Action.SITUATION_WEB_VIEW_INVOCATION, null);
Intent runActionsIntent = shadowApplication.getNextStartedService();
assertNull("Action service should not start with a null actions payload",
runActionsIntent);
Bundle extras = new Bundle();
extras.putString("com.urbanairship.actions", "");
runActionsIntent = shadowApplication.getNextStartedService();
assertNull("Actions service should not start if the actions payload is empty",
runActionsIntent);
}
/**
* Test running actions in the action service actually runs the actions
* and calls stop self once its done.
*/
@Test
@Config(shadows = { CustomShadowService.class })
public void testHandleRunActionIntent() {
ShadowApplication shadowApplication = Shadows.shadowOf(RuntimeEnvironment.application);
CustomShadowService shadowService = (CustomShadowService) Shadows.shadowOf(service);
shadowApplication.clearStartedServices();
ActionRunRequest runRequest = Mockito.mock(StubbedActionRunRequest.class, Mockito.CALLS_REAL_METHODS);
when(actionRunRequestFactory.createActionRequest("actionName")).thenReturn(runRequest);
// Call the request finish callback
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
ActionCompletionCallback callback = (ActionCompletionCallback) args[0];
callback.onFinish(null, ActionResult.newEmptyResult());
return null;
}
}).when(runRequest).run(Mockito.any(ActionCompletionCallback.class));
// Metadata
Bundle metadata = new Bundle();
metadata.putString("oh", "hi");
// Create the intent
ActionService.runActions(context, "{ \"actionName\": \"actionValue\" }", Action.SITUATION_WEB_VIEW_INVOCATION, metadata);
Intent runActionsIntent = shadowApplication.getNextStartedService();
// Start the service
service.onStartCommand(runActionsIntent, 0, 1);
verify(runRequest).setValue(ActionValue.wrap("actionValue"));
verify(runRequest).setSituation(Action.SITUATION_WEB_VIEW_INVOCATION);
verify(runRequest).run(Mockito.any(ActionCompletionCallback.class));
verify(runRequest).setMetadata(argThat(new ArgumentMatcher<Bundle>() {
@Override
public boolean matches(Bundle bundle) {
return bundle.getString("oh").equals("hi");
}
}));
// Verify that the service called stop self with the last start id
assertEquals(1, shadowService.getLastStopSelfId());
}
}
| 39.716667 | 129 | 0.718282 |
41a23f31a36246896fbb166ecdec7426457db6d6 | 3,072 | /*
* This file is part of indra, licensed under the MIT License.
*
* Copyright (c) 2020-2021 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kyori.indra.git.task;
import net.kyori.indra.git.internal.IndraGitService;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
import org.gradle.language.base.plugins.LifecycleBasePlugin;
/**
* Require that the project has no files that are uncommitted to SCM.
*
* <p>This prevents accidentally publishing content that does not match the
* published source.</p>
*
* @since 2.0.0
*/
public abstract class RequireClean extends DefaultTask {
public RequireClean() {
this.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP);
}
@Internal
public abstract Property<IndraGitService> getGit();
@TaskAction
public void check() {
final @Nullable Git git = this.getGit().get().git(this.getProject());
if(git == null) return;
try {
final Status status = git.status().call();
if(!status.isClean()) {
final StringBuilder message = new StringBuilder("Source root must be clean! Make sure your changes are committed. Changed files:");
for(final String changed : status.getUncommittedChanges()) {
message.append(System.lineSeparator())
.append("- ")
.append(changed);
}
for(final String untracked : status.getUntracked()) {
message.append(System.lineSeparator())
.append("- ")
.append(untracked);
}
throw new GradleException(message.toString());
}
} catch(final GitAPIException ex) {
this.getLogger().error("Failed to query clean status of current project repository", ex);
}
}
}
| 37.925926 | 139 | 0.721029 |
904a539290d1baa837ab0c578d582fd16bc24865 | 2,434 | package br.com.zup.mercadolivre.fechamentoCompra;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import br.com.zup.mercadolivre.produto.Produto;
import br.com.zup.mercadolivre.usuario.Usuario;
import br.com.zup.mercadolivre.usuario.UsuarioRepository;
@RestController
@RequestMapping(value = "/compras")
public class FechaCompraController {
@PersistenceContext
EntityManager manager;
@Autowired
UsuarioRepository repository;
@PostMapping
@Transactional
public String criar(@RequestBody @Valid NovaCompraRequest request, UriComponentsBuilder uriComponentsBuilder) throws BindException {
Produto produtoComprado = manager.find(Produto.class, request.getIdProduto());
int quantidade = request.getQuantidade();
boolean abateu = produtoComprado.abateEstoque(quantidade);
Gateway gateway = request.getGateway();
if(abateu) {
Usuario usuarioComprador = repository.findByEmail("mel@gmail.com").get();
Compra novaCompra = new Compra(produtoComprado, quantidade, usuarioComprador,gateway);
manager.persist(novaCompra);
if(gateway.equals(Gateway.PAGSEGURO)) {
UriComponents urlPagSeguro = uriComponentsBuilder.path("/retorno-pagseguro/{id}").
buildAndExpand(novaCompra.getId().toString());
return "pagseguro.com/" + novaCompra.getId() +
"?redirectUrl=" + urlPagSeguro;
}else {
UriComponents urlPayPal = uriComponentsBuilder.path("/retorno-paypal/{id}").
buildAndExpand(novaCompra.getId().toString());
return "paypal.com/" + novaCompra.getId() +
"?redirectUrl=" + urlPayPal;
}
}
//Excelente saída para exceçoes utilizando o próprio framework
BindException erroEstoque = new BindException(request, "novaCompraRequest");
erroEstoque.reject(null, "Houve um erro no estoque!");
throw erroEstoque;
}
}
| 33.805556 | 133 | 0.775267 |
163a72c9d0c9dd828968d8c79a447da194986e50 | 4,951 | /*
* 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.dromara.soul.web.cache;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.dromara.soul.common.dto.convert.DivideHandle;
import org.dromara.soul.common.dto.convert.DivideUpstream;
import org.dromara.soul.common.dto.zk.RuleZkDTO;
import org.dromara.soul.common.utils.GSONUtils;
import org.dromara.soul.common.utils.UrlUtils;
import org.dromara.soul.web.concurrent.SoulThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* this is divide http url upstream.
*
* @author xiaoyu
*/
@Component
@SuppressWarnings("all")
public class UpstreamCacheManager {
private static final Logger LOGGER = LoggerFactory.getLogger(UpstreamCacheManager.class);
private static final BlockingQueue<RuleZkDTO> BLOCKING_QUEUE = new LinkedBlockingQueue<>(1024);
private static final int MAX_THREAD = Runtime.getRuntime().availableProcessors() << 1;
private static final Map<String, List<DivideUpstream>> UPSTREAM_MAP = Maps.newConcurrentMap();
/**
* acquire DivideUpstream list by ruleId.
*
* @param ruleId ruleId
* @return DivideUpstream list {@linkplain DivideUpstream}
*/
public List<DivideUpstream> findUpstreamListByRuleId(final String ruleId) {
return UPSTREAM_MAP.get(ruleId);
}
/**
* Remove by key.
*
* @param key the key
*/
protected static void removeByKey(final String key) {
UPSTREAM_MAP.remove(key);
}
/**
* Init.
*/
@PostConstruct
public void init() {
synchronized (LOGGER) {
ExecutorService executorService = new ThreadPoolExecutor(MAX_THREAD, MAX_THREAD,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
SoulThreadFactory.create("divide-upstream-task",
false));
for (int i = 0; i < MAX_THREAD; i++) {
executorService.execute(new Worker());
}
}
}
/**
* Submit.
*
* @param ruleZkDTO the rule zk dto
*/
public static void submit(final RuleZkDTO ruleZkDTO) {
try {
BLOCKING_QUEUE.put(ruleZkDTO);
} catch (InterruptedException e) {
LOGGER.error(e.getMessage());
}
}
/**
* Execute.
*
* @param ruleZkDTO the rule zk dto
*/
public void execute(final RuleZkDTO ruleZkDTO) {
final DivideHandle divideHandle =
GSONUtils.getInstance().fromJson(ruleZkDTO.getHandle(), DivideHandle.class);
if (Objects.nonNull(divideHandle)) {
final List<DivideUpstream> upstreamList = divideHandle.getUpstreamList();
List<DivideUpstream> resultList = Lists.newArrayListWithCapacity(upstreamList.size());
for (DivideUpstream divideUpstream : upstreamList) {
final boolean pass = UrlUtils.checkUrl(divideUpstream.getUpstreamUrl());
if (pass) {
resultList.add(divideUpstream);
}
}
UPSTREAM_MAP.put(ruleZkDTO.getId(), resultList);
}
}
/**
* The type Worker.
*/
class Worker implements Runnable {
@Override
public void run() {
runTask();
}
private void runTask() {
while (true) {
try {
final RuleZkDTO ruleZkDTO = BLOCKING_QUEUE.take();
Optional.of(ruleZkDTO).ifPresent(UpstreamCacheManager.this::execute);
} catch (Exception e) {
LOGGER.error(" failure ," + e.getMessage());
}
}
}
}
}
| 32.149351 | 99 | 0.647142 |
8a414e11718767bae3d843f2bc521f597e57e310 | 808 | package basic.iteration.lv2;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Exam43275 {
public static boolean isPerfection(int num) {
int sum = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0)
sum += i;
}
return sum == num;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
for (int i = a; i <= b; i++) {
if (isPerfection(i))
System.out.print(i + " ");
}
}
} | 28.857143 | 81 | 0.569307 |
dcb1e5ed75e87bd3985597997d0d3e1ca281ab8d | 216 | /**
* Package for game theory concepts.
*
* @author Kristof Coninx (kristof.coninx AT cs.kuleuven.be)
*/
@NonNullByDefault
package be.kuleuven.cs.gametheory;
import org.eclipse.jdt.annotation.NonNullByDefault;
| 21.6 | 60 | 0.759259 |
e231af16ee377ef1685762dad9bf2872b3e1532b | 221 | package edp.davinci.model;
import lombok.Data;
import java.util.List;
@Data
public class Params {
private Long id;
private String uuid;
private String params;
private List<ParamsDetail> paramDetails;
}
| 15.785714 | 44 | 0.728507 |
058bec62784d10a1ba0c38f7cf36d1e54153e585 | 401 | package br.com.kontulari.kontschedule.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ContadorNotFoundException extends Exception{
private static final long serialVersionUID = 1L;
public ContadorNotFoundException(Long id) {
super("Contador not found with ID " + id);
}
}
| 26.733333 | 62 | 0.812968 |
13a2c89513a237ddcf27a893d9b6e087d563a261 | 4,090 | package dev.tahar.megamock.mocking;
import dev.tahar.megamock.mocking.data.MockInfo;
import dev.tahar.megamock.mocking.storage.MockDocument;
import dev.tahar.megamock.mocking.storage.MockStorageService;
import dev.tahar.megamock.mocking.storage.MocksRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpMethod;
import reactor.core.publisher.Mono;
import java.util.UUID;
@SpringBootTest(classes = {MockStorageService.class})
final class MockStorageServiceTests {
private final static UUID ID = UUID.fromString("00000000-0000-0000-0000-000000000000");
private final static String TITLE = "UnitTestTitle";
private final static String CATEGORY = "UnitTestCategory";
private final static String ENDPOINT = "/unit/test";
private final static HttpMethod HTTP_METHOD = HttpMethod.GET;
@Autowired
private MockStorageService mockStorageService;
@MockBean
private MocksRepository mocksRepository;
@BeforeEach
void init() {
Mockito
.when(mocksRepository.save(Mockito.any()))
.thenReturn(Mono.just(new MockDocument(ID, TITLE, CATEGORY, ENDPOINT, HTTP_METHOD)));
}
@Test
void storeNewMock_saveSuccessful() {
// Mock a database response where no existing mock was not found
Mockito
.when(mocksRepository.findById(Mockito.any(UUID.class)))
.thenReturn(Mono.empty());
Assertions.assertTrue(
mockStorageService
.storeMock(new MockInfo(ID, TITLE, CATEGORY, ENDPOINT, HTTP_METHOD))
.isPresent(),
"Save should succeed when no existing database document was found");
}
@Test
void storeDuplicateMock_saveFailed() {
// Mock a database response where an existing mock was found
Mockito
.when(mocksRepository.findById(Mockito.any(UUID.class)))
.thenReturn(Mono.just(new MockDocument(ID, TITLE, CATEGORY, ENDPOINT, HTTP_METHOD)));
Assertions.assertFalse(
mockStorageService
.storeMock(new MockInfo(ID, TITLE, CATEGORY, ENDPOINT, HTTP_METHOD))
.isPresent(),
"Save should fail when an existing database document was found");
}
@Test
void updateExistingMock_updateSuccessful() {
// Mock a database response where an existing mock was found
Mockito
.when(mocksRepository.findById(Mockito.any(UUID.class)))
.thenReturn(Mono.just(new MockDocument(ID, TITLE, CATEGORY, ENDPOINT, HTTP_METHOD)));
Assertions.assertTrue(mockStorageService
.updateMock(new MockInfo(ID, TITLE, CATEGORY, ENDPOINT, HTTP_METHOD))
.isPresent(),
"Update should succeed when an existing database document was found");
}
@Test
void updateExistingMock_updateFailed() {
// Mock a database response where no existing mock was not found
Mockito
.when(mocksRepository.findById(Mockito.any(UUID.class)))
.thenReturn(Mono.empty());
Assertions.assertFalse(mockStorageService
.updateMock(new MockInfo(ID, TITLE, CATEGORY, ENDPOINT, HTTP_METHOD))
.isPresent(),
"Update should fail when no existing database document was found");
}
@Test
void removeExistingMock_deleteCalled() {
Mockito
.when(mocksRepository.deleteById(Mockito.any(UUID.class)))
.thenReturn(Mono.empty());
mockStorageService.removeMockWithId(ID);
Mockito.verify(mocksRepository, Mockito.times(1)).deleteById(Mockito.any(UUID.class));
}
}
| 38.584906 | 101 | 0.665037 |
a907f2ad551552199814e0aeacf2e6022026950f | 12,465 | /**
* Copyright (C) 2012-14 graphene developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.epics.graphene.rrdtool;
import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import org.epics.graphene.ScatterGraph2DRenderer;
import org.epics.util.array.CollectionNumber;
import org.epics.util.array.IteratorNumber;
import org.epics.util.time.Timestamp;
/**
*
* @author carcassi
*/
public class ScatterPlot extends javax.swing.JFrame {
/**
* Creates new form ScatterPlot
*/
public ScatterPlot() {
initComponents();
}
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
xFilename = new javax.swing.JTextField();
yFilename = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
startDate = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
endDate = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
imagePanel1 = new org.epics.graphene.rrdtool.ImagePanel();
jScrollPane3 = new javax.swing.JScrollPane();
valuesX = new javax.swing.JTextArea();
jScrollPane4 = new javax.swing.JScrollPane();
valuesY = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("x filename:");
jLabel2.setText("y filename:");
xFilename.setText("/media/sf_Shared/dc2-5-17_cpu_system_54823.rrd");
yFilename.setText("/media/sf_Shared/dc2-5-17_cpu_user_54824.rrd");
jLabel3.setText("Start date:");
startDate.setText("01/10/2012");
jLabel4.setText("End date:");
endDate.setText("11/10/2012");
jButton1.setText("Plot");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout imagePanel1Layout = new javax.swing.GroupLayout(imagePanel1);
imagePanel1.setLayout(imagePanel1Layout);
imagePanel1Layout.setHorizontalGroup(
imagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
imagePanel1Layout.setVerticalGroup(
imagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 350, Short.MAX_VALUE)
);
valuesX.setColumns(20);
valuesX.setRows(5);
jScrollPane3.setViewportView(valuesX);
valuesY.setColumns(20);
valuesY.setRows(5);
jScrollPane4.setViewportView(valuesY);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(xFilename, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
.addComponent(yFilename, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(startDate, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(endDate, javax.swing.GroupLayout.Alignment.LEADING)))
.addComponent(imagePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(xFilename, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(yFilename, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(startDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(endDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(imagePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane4)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
RrdToolReader reader = new RrdToolReader();
Timestamp start = Timestamp.of(format.parse(startDate.getText()));
Timestamp end = Timestamp.of(format.parse(endDate.getText()));
TimeSeriesMulti xData = reader.readFile(xFilename.getText(), "AVERAGE", start, end);
TimeSeriesMulti yData = reader.readFile(yFilename.getText(), "AVERAGE", start, end);
// Point2DDataset dataset = Point2DDatasets.lineData(xData.getValues(), yData.getValues());
// valuesX.setText(toText(xData.getValues()));
// valuesY.setText(toText(yData.getValues()));
BufferedImage image = new BufferedImage(imagePanel1.getWidth(), imagePanel1.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
ScatterGraph2DRenderer renderer = new ScatterGraph2DRenderer(imagePanel1.getWidth(), imagePanel1.getHeight());
// renderer.draw(image.createGraphics(), dataset);
imagePanel1.setImage(image);
} catch(Exception ex) {
ex.printStackTrace();
}
}//GEN-LAST:event_jButton1ActionPerformed
private String toText(CollectionNumber coll) {
StringBuilder builder = new StringBuilder();
IteratorNumber iter = coll.iterator();
while (iter.hasNext()) {
builder.append(iter.nextDouble()).append("\n");
}
return builder.toString();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ScatterPlot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ScatterPlot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ScatterPlot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ScatterPlot.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ScatterPlot().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField endDate;
private org.epics.graphene.rrdtool.ImagePanel imagePanel1;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JTextField startDate;
private javax.swing.JTextArea valuesX;
private javax.swing.JTextArea valuesY;
private javax.swing.JTextField xFilename;
private javax.swing.JTextField yFilename;
// End of variables declaration//GEN-END:variables
}
| 51.508264 | 171 | 0.647573 |
1039e942abea001cd5648b5f744dc3d07c4befb2 | 3,905 | /* Copyright (C) 2017 American Printing House for the Blind 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 org.aph.braillejanus;
import org.eclipse.swt.widgets.Display;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Settings
{
static public final String OS_NAME = System.getProperty("os.name").toLowerCase();
private final Display display;
private final File file;
private String version;
Settings(Display display, String fileName)
{
this.display = display;
version = getClass().getPackage().getImplementationVersion();
if(version == null)
{
version = System.getProperty("braillejanus.version");
if(version == null)
{
Log.message(Log.LOG_WARNING, "unable to determine version", false);
version = "development";
}
}
if(fileName == null)
{
fileName = System.getProperty("user.home") + File.separator;
if(OS_NAME.startsWith("windows"))
fileName += "AppData" + File.separator + "Local" + File.separator + "BrailleJanus.conf";
else
fileName += ".braillejanus.conf";
}
file = new File(fileName);
}
public String getVersion()
{
return version;
}
private boolean readLine(String line)
{
if(line.isEmpty())
return true;
int offset = line.indexOf(' ');
if(offset < 0)
return false;
String value = line.substring(offset + 1);
if(value.length() < 1)
return false;
String tokens[];
switch(line.substring(0, offset))
{
case "version":
if(version != null)
if(!version.equals(value))
Log.message(Log.LOG_WARNING, "Version " + value + " from settings file does not match " + version, false);
break;
default: return false;
}
return true;
}
boolean readSettings()
{
if(!file.exists())
{
Log.message(Log.LOG_WARNING, "Settings file not found: " + file.getPath(), false);
return false;
}
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String line;
int lineNumber = 1;
while((line = reader.readLine()) != null)
{
try
{
if(!readLine(line))
Log.message(Log.LOG_ERROR, "Unknown setting, line #" + lineNumber + ": " + line + " -- " + file.getPath(), false);
}
catch(NumberFormatException ignored)
{
Log.message(Log.LOG_ERROR, "Bad setting value, line #" + lineNumber + ": " + line + " -- " + file.getPath(), false);
}
finally
{
lineNumber++;
}
}
}
catch(FileNotFoundException exception)
{
Log.message(Log.LOG_ERROR, exception, false);
}
catch(IOException exception)
{
Log.message(Log.LOG_ERROR, exception, false);
}
finally
{
try
{
if(reader != null)
reader.close();
}
catch(IOException exception)
{
Log.message(Log.LOG_ERROR, exception, false);
}
}
return true;
}
private void writeLines(PrintWriter writer)
{
if(version != null)
writer.println("version " + version);
writer.println();
}
boolean writeSettings()
{
PrintWriter writer = null;
try
{
writer = new PrintWriter(file);
writeLines(writer);
}
catch(FileNotFoundException exception)
{
Log.message(Log.LOG_ERROR, exception, false);
return false;
}
finally
{
if(writer != null)
writer.close();
}
return true;
}
}
| 21.574586 | 122 | 0.663508 |
62d9647242f89a5b24fc2ae3da001b3150bd7149 | 765 | package uk.gov.hmcts.reform.finrem.payments.model.pba;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import uk.gov.hmcts.reform.finrem.payments.model.pba.validation.PBAAccount;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
public class PBAAccountTest {
PBAAccount pba;
@Before
public void setUp() throws Exception {
String json = "{ \"payment_accounts\" : [\"PBA123\", \"PBA456\"]}";
ObjectMapper mapper = new ObjectMapper();
pba = mapper.readValue(json, PBAAccount.class);
}
@Test
public void shouldCreatePaymentFromJson() {
assertThat(pba.getAccountList(), hasItems("PBA123", "PBA456"));
}
} | 30.6 | 75 | 0.715033 |
a05beb44ffc58b680232904cd9f08dc2f8f3c5e8 | 12,526 | package com.example.saar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.saar.About.AboutUsFragment;
import com.example.saar.ChangeCredentials.ChangeCredentialsActivity;
import com.example.saar.Contact.ContactFragment;
import com.example.saar.Donate.DonateFragment;
import com.example.saar.Gallery.GalleryFragment;
import com.example.saar.Home.HomeFragment;
import com.example.saar.Login_SignUp.LoginSignupActivity;
import com.example.saar.Profile.ProfileActivity;
import com.example.saar.Share.ShareFragment;
import com.example.saar.Team.TeamFragment;
import com.example.saar.Timeline_Events.TimelineFragment;
import com.example.saar.Utils.Utils;
import com.example.saar.Video.VideosFragment;
import com.google.firebase.messaging.FirebaseMessaging;
import de.hdodenhof.circleimageview.CircleImageView;
import timber.log.Timber;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//creating fragment object
Fragment fragment = null;
SharedPreferences preferences;
SharedPreferences.Editor editor, notifications;
TextView name, email;
CircleImageView circleImageView;
NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (!preferences.getBoolean(Constant.LOGIN_STATUS, false) && !preferences.getBoolean(Constant.SKIP_LOGIN, false)) {
startActivity(new Intent(this, LoginSignupActivity.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
Menu nav_item = navigationView.getMenu();
if (preferences.getBoolean(Constant.LOGIN_STATUS, false))
nav_item.findItem(R.id.nav_profile).setVisible(true);
else
nav_item.findItem(R.id.nav_profile).setVisible(false);
navigationView.setNavigationItemSelectedListener(this);
showHomeFragment();
View headerview = navigationView.getHeaderView(0);
//Initially HomeFragment will be displayed
displaySelectedScreen(R.id.nav_home);
subscribeForNotification();
LinearLayout header = (LinearLayout) headerview.findViewById(R.id.nav_layout);
name = headerview.findViewById(R.id.nav_header_name);
email = headerview.findViewById(R.id.nav_header_email);
header.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
circleImageView = headerview.findViewById(R.id.nav_header_image);
setHeaderData();
header.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (preferences.getBoolean(Constant.LOGIN_STATUS, false)) {
//user is logged in
Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class);
MainActivity.this.startActivity(intentProfile);
} else {
//user not logged in
Intent intentLogin = new Intent(MainActivity.this, LoginSignupActivity.class);
MainActivity.this.startActivity(intentLogin);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
});
}
private void subscribeForNotification() {
notifications = PreferenceManager.getDefaultSharedPreferences(this).edit();
if (!preferences.getBoolean(Constant.SUBSCRIBE_NOTIFICATION, false)) {
FirebaseMessaging.getInstance().subscribeToTopic("alumnus");
if (preferences.getBoolean(Constant.LOGIN_STATUS, false)) {
String rollno = preferences.getString(Constant.ROLLNO, "");
String batch = Utils.getBatch(rollno);
String department = Utils.getDepartment(rollno);
FirebaseMessaging.getInstance().subscribeToTopic(batch);
FirebaseMessaging.getInstance().subscribeToTopic(department);
}
notifications.putBoolean(Constant.SUBSCRIBE_NOTIFICATION, true);
notifications.apply();
Toast.makeText(MainActivity.this, getString(R.string.msg_subscribed), Toast.LENGTH_SHORT).show();
Timber.d("Subscribed to notification.");
}
}
private void showHomeFragment() {
navigationView.setCheckedItem(R.id.nav_home);
fragment = new HomeFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
@Override
public void onBackPressed() {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.content_frame);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (currentFragment instanceof HomeFragment) {
super.onBackPressed();
} else {
showHomeFragment();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem login = menu.findItem(R.id.action_login_signup);
MenuItem logout = menu.findItem(R.id.action_logout);
MenuItem change_email = menu.findItem(R.id.action_change_email);
MenuItem change_password = menu.findItem(R.id.action_change_password);
if (preferences.getBoolean(Constant.LOGIN_STATUS, false)) {
//user is logged in
login.setVisible(false);
logout.setVisible(true);
change_email.setVisible(true);
change_password.setVisible(true);
} else {
//user is not logged in
login.setVisible(true);
logout.setVisible(false);
change_email.setVisible(false);
change_password.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_login_signup) {
startActivity(new Intent(this, LoginSignupActivity.class));
} else if (id == R.id.action_logout) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage(getString(R.string.logout_confirm_alert)).setCancelable(true)
.setPositiveButton(getString(R.string.alert_positive), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
editor = preferences.edit();
Utils.unsuscribeFromNotification(preferences.getString(Constant.ROLLNO, ""));
Utils.logout(editor, MainActivity.this);
finish();
}
})
.setNegativeButton(getString(R.string.alert_negative), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
} else if (id == R.id.action_change_email) {
Intent intent = new Intent(this, ChangeCredentialsActivity.class);
intent.putExtra("EXTRA", "openChangeEmail");
startActivity(intent);
} else if (id == R.id.action_change_password) {
Intent intent = new Intent(this, ChangeCredentialsActivity.class);
intent.putExtra("EXTRA", "openChangePassword");
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_home:
fragment = new HomeFragment();
break;
case R.id.nav_gallery:
fragment = new GalleryFragment();
break;
case R.id.nav_about_us:
fragment = new AboutUsFragment();
break;
case R.id.nav_timeline:
fragment = new TimelineFragment();
break;
case R.id.nav_team:
fragment = new TeamFragment();
break;
case R.id.nav_donate_now:
fragment = new DonateFragment();
break;
case R.id.nav_share:
fragment = new ShareFragment();
break;
case R.id.nav_videos:
fragment = new VideosFragment();
break;
case R.id.nav_contact_us:
fragment = new ContactFragment();
break;
case R.id.nav_profile:
Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
private void setHeaderData() {
if (preferences.getBoolean(Constant.LOGIN_STATUS, false)) {
//logged in
String full_name = preferences.getString(Constant.FIRST_NAME, "") + " " + preferences.getString(Constant.LAST_NAME, "");
name.setText(full_name);
email.setText(preferences.getString(Constant.EMAIL, ""));
Glide.with(this)
.load(preferences.getString(Constant.IMG_URL, ""))
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.placeholder(R.drawable.ic_account_circle_black_48dp)
.into(circleImageView);
} else {
//Not logged in
name.setText(getResources().getString(R.string.app_name));
email.setText(getResources().getString(R.string.saar_email));
circleImageView.setImageResource(R.drawable.ic_account_circle_black_48dp);
}
}
}
| 41.892977 | 132 | 0.645298 |
89cfd20b66310317114b810609ac332a6403532a | 2,726 | package com.seguetech.zippy.activities;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.seguetech.zippy.R;
public class SplashActivity extends AppCompatActivity {
public static final int DISPLAY_TIME = 3500;
public static final Class ACTION = DashboardActivity.class;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// manually determine the initial layout to use based on orientation.
switch(getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setContentView(R.layout.activity_splash);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setContentView(R.layout.activity_splash_landscape);
break;
}
}
@Override
public void onResume() {
super.onResume();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
go();
}
}, DISPLAY_TIME);
}
private void go() {
startActivity(new Intent(this,ACTION));
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_splash, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
/**
* Manually handle configuration changes to prevent the activity from restarting on rotation,
* which would extend our handler timeout.
*/
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
switch(newConfig.orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
setContentView(R.layout.activity_splash_landscape);
break;
case Configuration.ORIENTATION_PORTRAIT:
setContentView(R.layout.activity_splash);
break;
}
}
}
| 31.333333 | 97 | 0.647836 |
8574526aba56b1c7ac8c814fe68a5a863cfb7496 | 2,465 | /*
* Copyright 2017-2020 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.store.operation.handler;
import uk.gov.gchq.gaffer.commonutil.stream.Streams;
import uk.gov.gchq.gaffer.operation.OperationException;
import uk.gov.gchq.gaffer.operation.impl.Reduce;
import uk.gov.gchq.gaffer.store.Context;
import uk.gov.gchq.gaffer.store.Store;
import java.util.function.BinaryOperator;
/**
* A {@code ReduceHandler} is a handler for the {@link Reduce} {@link uk.gov.gchq.gaffer.operation.Operation}
*
* @param <T> The object type of the input object
*/
public class ReduceHandler<T> implements OutputOperationHandler<Reduce<T>, T> {
/**
* Handles the {@link Reduce} operation. Applies the {@link BinaryOperator}
* function contained within the Reduce operation and returns the resulting
* object.
*
* @param operation the {@link uk.gov.gchq.gaffer.operation.Operation} to be executed
* @param context the operation chain context, containing the user who executed the operation
* @param store the {@link Store} the operation should be run on
* @return the resulting object from the function
* @throws OperationException if execution of the operation fails
*/
@Override
public T doOperation(final Reduce<T> operation, final Context context, final Store store) throws OperationException {
if (null == operation) {
throw new OperationException("Operation cannot be null");
}
Iterable<? extends T> input = operation.getInput();
if (null == input) {
throw new OperationException("Input cannot be null");
}
final T identity = operation.getIdentity();
final BinaryOperator aggregateFunction = operation.getAggregateFunction();
return (T) Streams.toStream(input)
.reduce(identity, aggregateFunction, aggregateFunction);
}
}
| 37.923077 | 121 | 0.707505 |
1c31427d9f3c17cace6faf1977a075b9c1d8bb74 | 1,813 | /*
* Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending
*/
package io.deephaven.db.tables.dbarrays;
import io.deephaven.db.util.LongSizedDataStructure;
import org.jetbrains.annotations.NotNull;
public class DbSubBooleanArray extends DbBooleanArrayDirect.Indirect {
private static final long serialVersionUID = 1L;
private final DbBooleanArray innerArray;
private final long positions[];
public DbSubBooleanArray(@NotNull final DbBooleanArray innerArray, @NotNull final long[] positions) {
this.innerArray = innerArray;
this.positions = positions;
}
@Override
public Boolean get(final long index) {
if (index < 0 || index >= positions.length) {
return null;
}
return innerArray.get(positions[LongSizedDataStructure.intSize("DbSubBooleanArray get", index)]);
}
@Override
public DbBooleanArray subArray(final long fromIndex, final long toIndex) {
return innerArray.subArrayByPositions(DbArrayBase.mapSelectedPositionRange(positions, fromIndex, toIndex));
}
@Override
public DbBooleanArray subArrayByPositions(final long[] positions) {
return innerArray.subArrayByPositions(DbArrayBase.mapSelectedPositions(this.positions, positions));
}
@Override
public Boolean[] toArray() {
final Boolean[] result = new Boolean[positions.length];
for (int ii = 0; ii < positions.length; ++ii) {
result[ii] = get(ii);
}
return result;
}
@Override
public long size() {
return positions.length;
}
@Override
public boolean isEmpty() {
return positions.length == 0;
}
@Override
public DbBooleanArrayDirect getDirect() {
return new DbBooleanArrayDirect(toArray());
}
}
| 28.328125 | 115 | 0.679537 |
19202134240cfe30d76c4a4ea0456681d57b1b57 | 5,098 | package es.uah.repositorioms.domain.entities.users;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.fasterxml.jackson.annotation.JsonIgnore;
import es.uah.repositorioms.utils.Constants;
@Entity
@Table(name = "jhi_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 173991809360011093L;
private Long id;
private String login;
private String password;
private String firstName;
private String lastName;
private String email;
private boolean activated;
private String langKey;
private String imageUrl;
private String activationKey;
private String resetKey;
private Instant resetDate;
private Set<Authority> authorities = new HashSet<>();
private UserApplication userApplication;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash", length = 60, nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Size(max = 50)
@Column(name = "first_name", length = 50)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Size(max = 50)
@Column(name = "last_name", length = 50)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Email
@Size(min = 5, max = 254)
@Column(length = 254, unique = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@NotNull
@Column(nullable = false)
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
@Size(min = 2, max = 10)
@Column(name = "lang_key", length = 10)
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
@Size(max = 256)
@Column(name = "image_url", length = 256)
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
@Size(max = 20)
@Column(name = "reset_key", length = 20)
@JsonIgnore
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
@Column(name = "reset_date")
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") },
inverseJoinColumns = { @JoinColumn(name = "authority_name", referencedColumnName = "name") }
)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
public UserApplication getUserApplication() {
return userApplication;
}
public void setUserApplication(UserApplication userApplication) {
this.userApplication = userApplication;
}
}
| 22.860987 | 100 | 0.712044 |
7795d189bc592158e82bb023ec2975ff735aa8d0 | 2,594 | package com.example.demo.controller;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.bean.Flower;
import com.example.demo.mapper.FlowerMapper;
@RestController
public class FlowerController {
@Autowired
private FlowerMapper flowerMapper;
@RequestMapping(value="/addFlower",method=RequestMethod.POST)
public String addFlower(
@RequestParam("flowername")String flowername,
@RequestParam("description")String description) {
if(flowerMapper.addFlower(flowername, description)>0) {
return "添加成功";
}
else {
return "添加失败";
}
}
@RequestMapping(value="/deleteFlower")
public String deleteFlower(@RequestParam("flowername")String flowername) {
if(flowerMapper.deleteFlower(flowername)>0) {
return "删除成功";
}else {
return "删除失败";
}
}
@RequestMapping(value="/modifyFlower")
public String modifyFlower(
@RequestParam("flowername") String flowername,
@RequestParam("description") String description) {
if(flowerMapper.modifyFlower(flowername,description)>0) {
return "修改成功";
}else {
return "修改失败";
}
}
@RequestMapping(value="/inquireFlower")
public Flower inquierFlower(@RequestParam("flowername")String flowername) {
Flower flower = flowerMapper.inquireFlower(flowername);
if(flower!=null) {
return flower;
}
else {
return null;
}
}
@PostMapping("/upLoadImg")
public String singleFileUpload(@RequestParam("flowername")String flowername,
@RequestParam("file") MultipartFile file) {
if(file.isEmpty()) {
return "请选择文件";
}
try {
byte[] bytes = file.getBytes();
String filePath = "target/classes/static/img/"+file.getOriginalFilename();
Path path = Paths.get(filePath);
Files.write(path,bytes);
flowerMapper.upLoadFlowerImg(flowername, file.getOriginalFilename());
}catch (IOException e) {
e.printStackTrace();
}
return "文件上传成功";
}
}
| 27.892473 | 77 | 0.755975 |
d45ed7941f01958d517bbb171197d00840ab6850 | 385 | package com.wayn.mall.core.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wayn.mall.core.entity.ShopCat;
public interface ShopCatDao extends BaseMapper<ShopCat> {
IPage<ShopCat> selectListPage(Page<ShopCat> page, ShopCat shopCat);
}
| 32.083333 | 71 | 0.815584 |
5dfbd2447839af268d06fc1cc2e64b6c9c1749c8 | 1,884 | package com.github.rschmitt.collider;
import org.junit.jupiter.api.Test;
import static com.github.rschmitt.collider.Collider.clojureMap;
import static com.github.rschmitt.collider.Collider.transientMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class TransientMapTest {
@Test
@SuppressWarnings("unchecked")
public void reuseFails() throws Exception {
TransientMap transientMap = transientMap();
transientMap.toPersistent();
assertThrows(IllegalAccessError.class, () -> transientMap.put(new Object(), new Object()));
}
@Test
public void putOverwrites() throws Exception {
TransientMap transientMap = transientMap();
transientMap.put("a", 1);
assertEquals(transientMap.get("a"), 1);
transientMap.put("a", 2);
assertEquals(transientMap.get("a"), 2);
transientMap.put("b", 3);
assertEquals(transientMap.get("b"), 3);
assertEquals(transientMap.toPersistent(), clojureMap("a", 2, "b", 3));
}
@Test
public void remove() throws Exception {
TransientMap transientMap = transientMap();
assertEquals(transientMap.size(), 0);
transientMap.put("a", 1);
assertEquals(transientMap.size(), 1);
transientMap.remove("a");
assertEquals(transientMap.size(), 0);
transientMap.remove("a");
assertEquals(transientMap.size(), 0);
}
@Test
public void nullValue() throws Exception {
TransientMap transientMap = transientMap();
transientMap.put("key", null);
assertEquals(transientMap.size(), 1);
assertNull(transientMap.get("key"));
assertEquals(transientMap.toPersistent(), clojureMap("key", null));
}
}
| 30.387097 | 99 | 0.668259 |
762b6a5a871477b1da28bc066d3f4f1c279ed985 | 4,311 | /*
* 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.shardingsphere.scaling.core.util;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.scaling.core.api.ScalingClusterAutoSwitchAlgorithm;
import org.apache.shardingsphere.scaling.core.config.HandleConfiguration;
import org.apache.shardingsphere.scaling.core.config.ScalingContext;
import org.apache.shardingsphere.scaling.core.job.position.FinishedPosition;
import org.apache.shardingsphere.scaling.core.job.progress.JobProgress;
import org.apache.shardingsphere.scaling.core.job.task.inventory.InventoryTask;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Scaling task util.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public final class ScalingTaskUtil {
/**
* All inventory tasks is finished and all incremental tasks is almost finished.
*
* @param jobProgressMap job progress map
* @param handleConfig handle configuration
* @return almost finished or not
*/
public static boolean almostFinished(final Map<Integer, JobProgress> jobProgressMap, final HandleConfiguration handleConfig) {
return isProgressCompleted(jobProgressMap, handleConfig)
&& allInventoryTasksFinished(jobProgressMap)
&& allIncrementalTasksAlmostFinished(jobProgressMap);
}
private static boolean isProgressCompleted(final Map<Integer, JobProgress> jobProgressMap, final HandleConfiguration handleConfig) {
return handleConfig.getShardingTotalCount() == jobProgressMap.size()
&& jobProgressMap.values().stream().allMatch(Objects::nonNull);
}
private static boolean allIncrementalTasksAlmostFinished(final Map<Integer, JobProgress> jobProgressMap) {
long currentTimeMillis = System.currentTimeMillis();
Collection<Long> incrementalTaskIdleMinutes = jobProgressMap.values().stream().flatMap(each -> each.getIncrementalTaskProgressMap().values().stream())
.map(each -> {
long latestActiveTimeMillis = each.getIncrementalTaskDelay().getLatestActiveTimeMillis();
return latestActiveTimeMillis > 0 ? TimeUnit.MILLISECONDS.toMinutes(currentTimeMillis - latestActiveTimeMillis) : 0;
})
.collect(Collectors.toList());
ScalingClusterAutoSwitchAlgorithm clusterAutoSwitchAlgorithm = ScalingContext.getInstance().getClusterAutoSwitchAlgorithm();
return clusterAutoSwitchAlgorithm.allIncrementalTasksAlmostFinished(incrementalTaskIdleMinutes);
}
/**
* All inventory tasks is finished.
*
* @param inventoryTasks to check inventory tasks
* @return is finished
*/
public static boolean allInventoryTasksFinished(final List<InventoryTask> inventoryTasks) {
if (inventoryTasks.isEmpty()) {
log.warn("inventoryTasks is empty");
}
return inventoryTasks.stream().allMatch(each -> each.getProgress().getPosition() instanceof FinishedPosition);
}
private static boolean allInventoryTasksFinished(final Map<Integer, JobProgress> jobProgress) {
return jobProgress.values().stream()
.flatMap(each -> each.getInventoryTaskProgressMap().values().stream())
.allMatch(each -> each.getPosition() instanceof FinishedPosition);
}
}
| 46.354839 | 158 | 0.73788 |
14b30e99384e9624b480b008f32168598106dd44 | 1,554 | package mx.gob.municipio.centro.model.gateways.almacen;
import java.util.Date;
import java.util.logging.Logger;
import mx.gob.municipio.centro.model.bases.BaseGatewayAlmacen;
public class GatewayBitacoraAlmacen extends BaseGatewayAlmacen {
private static Logger log = Logger.getLogger(GatewayBitacoraAlmacen.class.getName());
public final static int Nueva_Entrada = 1;
public final static int Actualiza_Entrada = 2;
public final static int Cancela_Entrada = 3;
public final static int Cierra_Entrada = 4;
public final static int Detalle_Entrada = 5;
public GatewayBitacoraAlmacen() {
// TODO Auto-generated constructor stub
}
public void guardarBitacoraAlmacen(int IDMOVTO, Long CVE_DOC, int CVE_PERS, int ID_ALMACEN, int ID_DEPENDENCIA, Long ID_PEDIDO, String TIPO_DOC, int ID_ARTICULO, int ID_PROVEEDOR ,Date FECHA_DOC, String DESCRIPCION, Double MONTO){
Date FECHA = new Date();
String SQL = "INSERT INTO BITACORA_ALMACEN (IDMOVTO,CVE_DOC, CVE_PERS, ID_ALMACEN, ID_DEPENDENCIA, ID_PEDIDO, TIPO_DOC, ID_ARTICULO, ID_PROVEEDOR, FECHA,FECHA_DOC,DESCRIPCION,MONTO)"+
"values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
this.getJdbcTemplate().update(SQL, new Object[]{IDMOVTO,CVE_DOC, CVE_PERS, ID_ALMACEN, ID_DEPENDENCIA, ID_PEDIDO, TIPO_DOC, ID_ARTICULO, ID_PROVEEDOR, FECHA, FECHA_DOC, DESCRIPCION, MONTO} );
}
private Long getNumeroBitacora(Integer ejercicio ){
return this.getJdbcTemplate().queryForLong("select max(cve_movto) as n from ALMACEN_CAT_MOVIMIENTOS_BITACORA where ejercicio=?", new Object[]{ejercicio});
}
}
| 44.4 | 232 | 0.772844 |
12b48add4b117d87bd5a63a0314f309194cabf48 | 3,532 | /*
* @(#)gl_tex_z.java 0.2 99/11/30
*
* jGL 3-D graphics library for Java Copyright (c) 1999 Robin Bing-Yu Chen
* (robin@is.s.u-tokyo.ac.jp)
*
* This library is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or any later version. the GNU Lesser General Public License should be
* included with this distribution in the file LICENSE.
*
* This library 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
* Lesser General Public License for more details.
*/
package jgl.context.render;
import jgl.context.gl_context;
import jgl.context.gl_vertex;
/**
* gl_tex_z is the rendering class for texturing with depth of JavaGL 2.1.
*
* @version 0.2, 30 Nov 1999
* @author Robin Bing-Yu Chen
*/
public class gl_tex_z extends gl_tex {
protected void init(gl_vertex v1, gl_vertex v2) {
super.init(v1, v2);
init_z(v1, v2);
}
protected void set_first_point() {
super.set_first_point();
set_first_z();
}
protected void init_dx(int dx) {
super.init_dx(dx);
init_z_dx(dx);
}
protected void init_dy(int dy) {
super.init_dy(dy);
init_z_dy(dy);
}
protected void inc_x() {
super.inc_x();
z_inc_x();
}
protected void dec_x() {
super.dec_x();
z_dec_x();
}
protected void inc_y() {
super.inc_y();
z_inc_y();
}
protected void inc_x_inc_y() {
super.inc_x_inc_y();
z_inc_x();
}
protected void dec_x_inc_y() {
super.dec_x_inc_y();
z_dec_x();
}
protected void put_pixel() {
if (CC.Lighting.Enable) {
pixel.put_pixel(x, y, z, w, s / w, t / w, r / w, dsdx, dsdy, dtdx, dtdy, drdx, drdy, color);
} else {
pixel.put_pixel(x, y, z, w, s / w, t / w, r / w, dsdx, dsdy, dtdx, dtdy, drdx, drdy);
}
}
protected void put_pixel_by_index() {
if (CC.Lighting.Enable) {
pixel.put_pixel_by_index(x, z, w, s / w, t / w, r / w, dsdx, dsdy, dtdx, dtdy, drdx, drdy,
color);
} else {
pixel.put_pixel_by_index(x, z, w, s / w, t / w, r / w, dsdx, dsdy, dtdx, dtdy, drdx, drdy);
}
}
/**
* Draw a flat horizontal line in the Color Buffer with depth value, assume that x1 is in the left
* side of x2
*/
private void draw_horizontal_line(int x1, int x2, int y, float z1, float w1, float s1, float t1,
float r1) {
this.LineZ[0] = z1;
draw_horizontal_line(x1, x2, y, w1, s1, t1, r1);
}
protected void init(gl_vertex v1, gl_vertex v2, gl_vertex v3) {
super.init(v1, v2, v3);
init_z(v1, v2, v3);
}
protected void set_left(int pos) {
super.set_left(pos);
set_left_z(pos);
}
protected void init_dx_dy(int area, int left, int right, int top) {
super.init_dx_dy(area, left, right, top);
init_z_dx_dy(area, left, right, top);
}
protected void init_other(boolean delta, int dy) {
super.init_other(delta, dy);
init_z_other(delta, dy);
}
protected void inc_y_once() {
super.inc_y_once();
z_inc_y_once();
}
protected void inc_y_more() {
super.inc_y_more();
z_inc_y_more();
}
protected void draw_horizontal_line(int y) {
draw_horizontal_line(LeftPoint, RightPoint, y, LeftPointZ, LeftPointW, LeftPointS, LeftPointT,
LeftPointR);
}
public gl_tex_z(gl_context cc) {
super(cc);
}
}
| 24.699301 | 100 | 0.649207 |
56efa1940919e68f96c12608c0b9a6855608bdac | 2,618 | package com.github.ele115.tello_wrapper;
import com.github.ele115.tello_wrapper.tello4j.api.drone.WifiDroneFactory;
public final class Tello {
private Tello() {
// static class
}
/**
* Connect to a Tello drone.
*
* @param droneId If it is "simulator", then a fake drone is connected;
* otherwise, it should be the 6-letter ID of the drone.
* @return Controller of the drone.
*/
public static ITelloDrone Connect(String droneId) {
var env = System.getenv("TELLO_SIMULATOR");
if (env != null && env.equals("TRUE"))
return new TelloSimulator(true);
if (droneId == null)
throw new RuntimeException("Please specify your Drone ID");
if (droneId.equals("simulator")) {
var sim = new TelloSimulator(false);
Tello3D.getInstance().addSimulator(sim);
return sim;
}
if (droneId.equals("simulator-simple"))
return new TelloSimulator(false);
if (droneId.equals("default")) {
var drone = WifiDroneFactory.build();
drone.connect();
return drone;
}
if (!droneId.matches("[0-9A-F]{6}"))
throw new RuntimeException("Drone ID incorrect, please double check");
var id = droneId.toLowerCase();
var mac = "60:60:1f:" + id.substring(0, 2) + ":" + id.substring(2, 4) + ":" + id.substring(4);
var res = com.github.b1f6c1c4.mac_to_ip.Facade.Execute(mac, "192\\.168\\..*");
if (res.isEmpty())
throw new RuntimeException("Drone with ID " + mac + " not found, please double check");
if (res.size() > 1)
throw new RuntimeException("More than one drones with ID " + mac + " found");
{
var ip = res.get(0);
var drone = WifiDroneFactory.build();
drone.connect(ip);
return drone;
}
}
public static ITelloDrone Connect(String droneId, double rX, double rY, double rAngle) {
if (!droneId.equals("simulator"))
throw new RuntimeException("Please use Tello::Connect(String droneId)");
var init = new TelloMicroState();
init.rX = rX;
init.rY = rY;
init.rZ = 0;
init.rAngle = rAngle;
var sim = new TelloSimulator(false, init);
Tello3D.getInstance().addSimulator(sim);
return sim;
}
public static Tello3D getSimulator() {
return Tello3D.getInstance();
}
public static void setWindowSize(int w, int h) {
Tello3D.setWindowSize(w, h);
}
}
| 34.906667 | 102 | 0.577158 |
d00fca7bc902f6dc68bcaffd89d3c481f8a2dd5e | 139 | package com.scraping.spider;
import java.util.Set;
public interface Mp3Spider extends Spider{
public Set<String> getAllMp3Links();
}
| 13.9 | 42 | 0.769784 |
da3468fb605a92902a032ddb653e2e2ea28bf7e5 | 604 | package ftb.lib.mod.config;
import ftb.lib.FTBLib;
import ftb.lib.api.config.*;
import java.io.File;
public class FTBLibConfig
{
public static final ConfigFile configFile = new ConfigFile("ftblib");
public static void load()
{
configFile.setFile(new File(FTBLib.folderLocal, "ftblib.json"));
configFile.setDisplayName("FTBLib");
configFile.add(new ConfigGroup("commands").addAll(FTBLibConfigCmd.class, null, false), false);
configFile.add(new ConfigGroup("command_names").addAll(FTBLibConfigCmdNames.class, null, false), false);
ConfigRegistry.add(configFile);
configFile.load();
}
} | 28.761905 | 106 | 0.758278 |
75384b77129904780b20c486276e62391e7e77dc | 2,685 | package org.apache.syncope.core.provisioning.api.mytests.testcases;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.syncope.core.provisioning.api.utils.RealmUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class NormalizingAddToTest {
String realmContext;
Set<String> realmsSet;
String newRealm;
public static final String VALID_NEW_REALM = "vnr";
public static final String CONTAINED_NEW_REALM = "cnr";
public static final String CONTAINED_REALMS = "cr";
@Before
public void configureParameters() {
realmsSet = new HashSet<>();
switch (realmContext) {
case (VALID_NEW_REALM):
realmsSet.add("RealmA");
realmsSet.add("RealmB");
newRealm = "AnotherRealm";
break;
case (CONTAINED_NEW_REALM):
realmsSet.add("RealmA");
realmsSet.add("RealmB");
newRealm = "RealmA_something";
break;
case (CONTAINED_REALMS):
realmsSet.add("RealmA_something");
realmsSet.add("RealmA_somethingElse");
newRealm = "RealmA";
break;
}
}
@Parameters
public static List<TestParameters> getData() {
List<TestParameters> testInputs = new ArrayList<>();
testInputs.add(new TestParameters(VALID_NEW_REALM));
testInputs.add(new TestParameters(CONTAINED_NEW_REALM));
testInputs.add(new TestParameters(CONTAINED_REALMS));
return testInputs;
}
/*
* Se newRealm inizia per realm ==> non aggiungere newRealm a realmsSet
* Se realm inizia per newRealm ==> aggiungi newRealm e rimuovi realm da realmsSet
*/
public NormalizingAddToTest(TestParameters input) {
this.realmContext = input.getRealmContext();
}
@Test
public void test() {
switch (realmContext) {
case (VALID_NEW_REALM):
assertTrue(RealmUtils.normalizingAddTo(realmsSet, newRealm));
assertEquals(3, realmsSet.size());
break;
case (CONTAINED_NEW_REALM):
assertFalse(RealmUtils.normalizingAddTo(realmsSet, newRealm));
assertEquals(2, realmsSet.size());
break;
case (CONTAINED_REALMS):
assertTrue(RealmUtils.normalizingAddTo(realmsSet, newRealm));
assertEquals(1, realmsSet.size());
break;
}
}
private static class TestParameters {
String realmContext;
public TestParameters(String realmContext) {
this.realmContext = realmContext;
}
public String getRealmContext() {
return realmContext;
}
}
}
| 25.093458 | 83 | 0.735196 |
51148777ec4ab7f7d794c278145c28148a9b234b | 1,004 | /*
* Copyright (c) 2016 Yahoo Inc.
* Licensed under the terms of the Apache version 2.0 license.
* See LICENSE file for terms.
*/
package com.yahoo.yqlplus.engine.internal.java.functions;
import com.yahoo.yqlplus.language.parser.ProgramCompileException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public final class MethodHandleHelper {
private MethodHandleHelper() {
}
public static MethodHandle uncheckedLookup(Class<?> clazz, String name, Class<?> rval, Class[] argumentTypes) {
try {
return MethodHandles.lookup().findVirtual(clazz, name, MethodType.methodType(rval, argumentTypes));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new ProgramCompileException(e);
}
}
public static MethodHandle uncheckedLookup(Class<?> clazz, String name, Class<?> rval) {
return uncheckedLookup(clazz, name, rval, new Class<?>[0]);
}
}
| 32.387097 | 115 | 0.713147 |
2d77b458a7ef0546f2e8a02925acc8f083de3239 | 1,169 | package org.monarchinitiative.phenol.formats.hpo;
import org.monarchinitiative.phenol.ontology.data.TermId;
/**
* Utility class with {@link TermId} constants for the sub ontologies.
*
* @author <a href="mailto:manuel.holtgrewe@bihealth.de">Manuel Holtgrewe</a>
* @author <a href="mailto:sebastian.koehler@charite.de">Sebastian Koehler</a>
*/
public final class HpoSubOntologyRootTermIds {
/** {@link TermId} of sub ontology "phenotypic abnormality". */
public static final TermId PHENOTYPIC_ABNORMALITY =
TermId.constructWithPrefix("HP:0000118");
/** {@link TermId} of sub ontology "clinical modifier". */
public static final TermId CLINICAL_MODIFIER = TermId.constructWithPrefix("HP:0012823");
/** {@link TermId} of sub ontology "mortality/aging". */
public static final TermId MORTALITY_AGING = TermId.constructWithPrefix("HP:0040006");
/** {@link TermId} of sub ontology "frequency". */
public static final TermId FREQUENCY = TermId.constructWithPrefix("HP:0040279");
/** {@link TermId} of sub ontology "mode of inheritance". */
public static final TermId MODE_OF_INHERITANCE =
TermId.constructWithPrefix("HP:0000005");
}
| 38.966667 | 90 | 0.739093 |
3cd3f9e872bd853d48fab1b0b25fe9c715894dec | 1,142 | package com.sjf.security;
import com.sjf.dto.MyJson;
import com.sjf.entity.SysRole;
import org.json.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by SJF on 2017/2/17.
*/
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException e) throws IOException, ServletException {
MyJson myJson = new MyJson();
myJson.setCode(0);
myJson.setMessage("登陆失败");
myJson.setData(null);
JSONObject json = new JSONObject(myJson);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(json.toString());
}
}
| 33.588235 | 105 | 0.748687 |
2cda58c8be6a4ec371ed5e78c8a8db26846a6dcf | 673 | package com.yarwest.guice_demo.calculator;
import com.google.inject.Guice;
import com.google.inject.Injector;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
* Hello world!
*
*/
public class App extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
final Injector injector = Guice.createInjector(new BootstrapModule());
FXMLLoader loader = new FXMLLoader(getClass().getResource("/calculator.fxml"));
loader.setControllerFactory(injector::getInstance);
primaryStage.setScene(new Scene(loader.load(), 1000, 800));
primaryStage.show();
}
}
| 24.925926 | 81 | 0.771174 |
bcfcbc3fc548a1bec9a888732f95c712f5700bcd | 4,701 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.iso.dashboard.dao;
import com.iso.dashboard.dto.CTaskAssignee;
import com.iso.dashboard.dto.CTaskAssigneePK;
import com.iso.dashboard.dto.ResultDTO;
import com.iso.dashboard.utils.Constants;
import com.iso.dashboard.utils.DataUtil;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
/**
*
* @author VIET_BROTHER
*/
public class TaskAssigneeDAO extends BaseDAO {
private static TaskAssigneeDAO dao;
public static TaskAssigneeDAO getInstance() {
if (dao == null) {
dao = new TaskAssigneeDAO();
}
return dao;
}
public List<CTaskAssignee> getAssignee(String taskId, String assignId) {
List<CTaskAssignee> assignees = new ArrayList<>();
Session session = null;
try {
session = getSession();
List<String> params = new ArrayList<>();
String sql = "FROM CTaskAssignee where 1=1 ";
if (!DataUtil.isNullOrEmpty(taskId)) {
sql += " and id.taskId = ? ";
params.add(taskId);
}
if (!DataUtil.isNullOrEmpty(assignId)) {
sql += " and assignedId = ? ";
params.add(assignId);
}
Query query = session.createQuery(sql);
for (int i = 0; i < params.size(); i++) {
query.setParameter(i, Integer.valueOf(params.get(i)));
}
assignees = (List<CTaskAssignee>) query.list();
session.getTransaction().commit();
} catch (Exception e) {
if (session != null && session.isOpen()) {
session.getTransaction().rollback();
}
e.printStackTrace();
}
return assignees;
}
public ResultDTO addAssignee(CTaskAssignee p) {
ResultDTO res = new ResultDTO(Constants.FAIL, "");
Session session = null;
try {
session = getSession();
session.save(p);
session.getTransaction().commit();
res.setKey(Constants.SUCCESS);
} catch (Exception e) {
if (session != null && session.isOpen()) {
session.getTransaction().rollback();
}
e.printStackTrace();
res.setMessage(e.getMessage());
}
return res;
}
public ResultDTO updateAssignee(CTaskAssignee newData) {
ResultDTO res = new ResultDTO(Constants.FAIL, "");
Session session = null;
try {
session = getSession();
CTaskAssignee u = (CTaskAssignee) session.get(CTaskAssignee.class, newData.getId());
u.setAssignedId(newData.getAssignedId());
u.setIsMain(newData.getIsMain());
session.update(u);
session.getTransaction().commit();
res.setKey(Constants.SUCCESS);
} catch (Exception e) {
if (session != null && session.isOpen()) {
session.getTransaction().rollback();
}
e.printStackTrace();
res.setMessage(e.getMessage());
}
return res;
}
public ResultDTO removeAssignee(CTaskAssigneePK id) {
ResultDTO res = new ResultDTO(Constants.FAIL, "");
Session session = null;
try {
session = getSession();
CTaskAssignee u = (CTaskAssignee) session.get(CTaskAssignee.class, id);
session.delete(u);
session.getTransaction().commit();
res.setKey(Constants.SUCCESS);
} catch (Exception e) {
if (session != null && session.isOpen()) {
session.getTransaction().rollback();
}
res.setMessage(e.getMessage());
e.printStackTrace();
}
return res;
}
public CTaskAssignee getAssigneeById(CTaskAssigneePK id) {
ResultDTO res = new ResultDTO(Constants.FAIL, "");
Session session = null;
CTaskAssignee assignee = null;
try {
session = getSession();
assignee = (CTaskAssignee) session.get(CTaskAssignee.class, id);
session.getTransaction().commit();
res.setKey(Constants.SUCCESS);
} catch (Exception e) {
if (session != null && session.isOpen()) {
session.getTransaction().rollback();
}
e.printStackTrace();
res.setMessage(e.getMessage());
}
return assignee;
}
}
| 33.105634 | 96 | 0.562646 |
bec7c4ea87eee683196fcc8bf8b1d11e015bd8a5 | 4,136 | /**
* jspice is distributed under the GNU General Public License version 3
* and is also available under alternative licenses negotiated directly
* with Knowm, Inc.
*
* Copyright (c) 2016-2017 Knowm Inc. www.knowm.org
*
* Knowm, Inc. holds copyright
* and/or sufficient licenses to all components of the jspice
* package, and therefore can grant, at its sole discretion, the ability
* for companies, individuals, or organizations to create proprietary or
* open source (even if not GPL) modules which may be dynamically linked at
* runtime with the portions of jspice which fall under our
* copyright/license umbrella, or are distributed under more flexible
* licenses than GPL.
*
* The 'Knowm' name and logos are trademarks owned by Knowm, Inc.
*
* If you have any questions regarding our licensing policy, please
* contact us at `contact@knowm.org`.
*/
package org.knowm.jspice.netlist;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.knowm.jspice.component.element.memristor.MMSSMemristor;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class NetlistMMSSMemristor extends NetlistComponent {
@Valid
@NotNull
@JsonProperty("r_init")
private double rInit;
@Valid
@NotNull
@JsonProperty("r_on")
private double rOn;
@Valid
@NotNull
@JsonProperty("r_off")
private double rOff;
@Valid
@NotNull
@JsonProperty("tau")
private double tau;
@Valid
@NotNull
@JsonProperty("v_on")
private double vOn;
@Valid
@NotNull
@JsonProperty("v_off")
private double vOff;
@Valid
@NotNull
@JsonProperty("phi")
private double phi;
@Valid
@NotNull
@JsonProperty("schottky_forward_alpha")
private double schottkyForwardAlpha;
@Valid
@NotNull
@JsonProperty("schottky_forward_beta")
private double schottkyForwardBeta;
@Valid
@NotNull
@JsonProperty("schottky_reverse_alpha")
private double schottkyReverseAlpha;
@Valid
@NotNull
@JsonProperty("schottky_reverse_beta")
private double schottkyReverseBeta;
public NetlistMMSSMemristor(String id, double rInit, double rOn, double rOff, double tau, double vOn, double vOff, double phi,
double schottkyForwardAlpha, double schottkyForwardBeta, double schottkyReverseAlpha, double schottkyReverseBeta, String... nodes) {
super(new MMSSMemristor(id, rInit, rOn, rOff, tau, vOn, vOff, phi, schottkyForwardAlpha, schottkyForwardBeta, schottkyReverseAlpha,
schottkyReverseBeta), nodes);
this.rInit = rInit;
this.rOn = rOn;
this.rOff = rOff;
this.tau = tau;
this.vOn = vOn;
this.vOff = vOff;
this.phi = phi;
this.schottkyForwardAlpha = schottkyForwardAlpha;
this.schottkyForwardBeta = schottkyForwardBeta;
this.schottkyReverseAlpha = schottkyReverseAlpha;
this.schottkyReverseBeta = schottkyReverseBeta;
}
@JsonCreator
public NetlistMMSSMemristor(@JsonProperty("id") String id, @JsonProperty("r_init") double rInit, @JsonProperty("r_on") double rOn,
@JsonProperty("r_off") double rOff, @JsonProperty("n") double n, @JsonProperty("tau") double tau, @JsonProperty("v_on") double vOn,
@JsonProperty("v_off") double vOff, @JsonProperty("phi") double phi, @JsonProperty("schottky_forward_alpha") double schottkyForwardAlpha,
@JsonProperty("schottky_forward_beta") double schottkyForwardBeta, @JsonProperty("schottky_reverse_alpha") double schottkyReverseAlpha,
@JsonProperty("schottky_reverse_beta") double schottkyReverseBeta, @JsonProperty("nodes") String nodes) {
super(new MMSSMemristor(id, rInit, rOn, rOff, tau, vOn, vOff, phi, schottkyForwardAlpha, schottkyForwardBeta, schottkyReverseAlpha,
schottkyReverseBeta), nodes);
this.rInit = rInit;
this.rOn = rOn;
this.rOff = rOff;
this.tau = tau;
this.vOn = vOn;
this.vOff = vOff;
this.phi = phi;
this.schottkyForwardAlpha = schottkyForwardAlpha;
this.schottkyForwardBeta = schottkyForwardBeta;
this.schottkyReverseAlpha = schottkyReverseAlpha;
this.schottkyReverseBeta = schottkyReverseBeta;
}
}
| 32.3125 | 143 | 0.745164 |
51a1a32ea1733e79dcf21efa5c61ab6fbb3c145e | 3,633 | /**
* GnucashJobImpl.java
* License: GPLv3 or later
* Created on 14.05.2005
* (c) 2005 by "Wolschon Softwaredesign und Beratung".
*
*
* -----------------------------------------------------------
* major Changes:
* 14.05.2005 - initial version
* ...
*
*/
package biz.wolschon.fileformats.gnucash.jwsdpimpl;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import biz.wolschon.fileformats.gnucash.GnucashCustomer;
import biz.wolschon.fileformats.gnucash.GnucashFile;
import biz.wolschon.fileformats.gnucash.GnucashInvoice;
import biz.wolschon.fileformats.gnucash.GnucashJob;
import biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncGncJobType;
/**
* created: 14.05.2005 <br/>
* Implementation of GnucashJob that uses JWSDP.
* @author <a href="mailto:Marcus@Wolschon.biz">Marcus Wolschon</a>
* @see biz.wolschon.fileformats.gnucash.GnucashJob
*/
public class GnucashJobImpl implements GnucashJob {
/**
* the JWSDP-object we are facading.
*/
private final GncGncJobType jwsdpPeer;
/**
* The file we belong to.
*/
private final GnucashFile file;
/**
* @param peer the JWSDP-object we are facading.
* @see #jwsdpPeer
* @param gncFile the file to register under
*/
public GnucashJobImpl(
final GncGncJobType peer,
final GnucashFile gncFile) {
super();
jwsdpPeer = peer;
file = gncFile;
}
/**
* The gnucash-file is the top-level class to contain everything.
* @return the file we are associated with
*/
public GnucashFile getFile() {
return file;
}
/**
*
* @return The JWSDP-Object we are wrapping.
*/
public GncGncJobType getJwsdpPeer() {
return jwsdpPeer;
}
/**
* @return the unique-id to identify this object with across name- and hirarchy-changes
*/
public String getId() {
assert jwsdpPeer.getJobGuid().getType().equals("guid");
String guid = jwsdpPeer.getJobGuid().getValue();
if (guid == null) {
throw new IllegalStateException(
"job has a null guid-value! guid-type="
+ jwsdpPeer.getJobGuid().getType());
}
return guid;
}
/**
* @return all invoices that refer to this job.
* @see GnucashJob#getInvoices()
*/
public Collection<? extends GnucashInvoice> getInvoices() {
List<GnucashInvoice> retval = new LinkedList<GnucashInvoice>();
for (GnucashInvoice invoice : getFile().getInvoices()) {
if (invoice.getJobID().equals(getId())) {
retval.add(invoice);
}
}
return retval;
}
/**
* @return true if the job is still active
*/
public boolean isJobActive() {
return getJwsdpPeer().getJobActive() == 1;
}
/**
* {@inheritDoc}
*/
public String getCustomerType() {
return jwsdpPeer.getJobOwner().getOwnerType();
}
/**
* {@inheritDoc}
*/
public String getCustomerId() {
assert jwsdpPeer.getJobOwner().getOwnerId().getType().equals("guid");
return jwsdpPeer.getJobOwner().getOwnerId().getValue();
}
/**
* {@inheritDoc}
*/
public GnucashCustomer getCustomer() {
return file.getCustomerByID(getCustomerId());
}
/**
* {@inheritDoc}
*/
public String getJobNumber() {
return jwsdpPeer.getJobId();
}
/**
* {@inheritDoc}
*/
public String getName() {
return jwsdpPeer.getJobName();
}
}
| 24.22 | 91 | 0.597853 |
7b1a467d95dbe043a85e2cd9278fb6285c100b7a | 1,378 | package com.example.activityandintents;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SecondActitity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_actitity);
Intent myIntent = getIntent();
Button b = findViewById(R.id.SecondActivityBtn);
TextView tv = findViewById(R.id.textView);
String str1= myIntent.getStringExtra("FirstKey");
String str2= myIntent.getStringExtra("SecondKey");
tv.setText(str1+str2);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent navigateToNextPage = new Intent(v.getContext(),MainActivity.class);
navigateToNextPage.putExtra("FirstKey","This message is from SecondActivity");
navigateToNextPage.putExtra("SecondKey","Hello Om");
startActivity(navigateToNextPage);
}
});
}
}
| 32.809524 | 94 | 0.70029 |
09fad854468b0ff2feaaea9d86a9c523c9f66412 | 5,067 | /**
*
* Copyright the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.omemo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.File;
import org.jivesoftware.smackx.omemo.OmemoConfiguration;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Test the OmemoConfiguration class.
*/
public class OmemoConfigurationTest {
@Test
public void omemoConfigurationTest() {
@SuppressWarnings("unused") OmemoConfiguration configuration = new OmemoConfiguration();
// Default Store Path
File storePath = new File("test");
assertNull("getFileBasedOmemoStoreDefaultPath MUST return null at this point.",
OmemoConfiguration.getFileBasedOmemoStoreDefaultPath());
OmemoConfiguration.setFileBasedOmemoStoreDefaultPath(storePath);
assertEquals("FileBasedOmemoStoreDefaultPath must equal the one we set.", storePath.getAbsolutePath(),
OmemoConfiguration.getFileBasedOmemoStoreDefaultPath().getAbsolutePath());
// EME
OmemoConfiguration.setAddEmeEncryptionHint(false);
assertEquals(false, OmemoConfiguration.getAddEmeEncryptionHint());
OmemoConfiguration.setAddEmeEncryptionHint(true);
assertEquals(true, OmemoConfiguration.getAddEmeEncryptionHint());
// MAM
OmemoConfiguration.setAddMAMStorageProcessingHint(false);
assertEquals(false, OmemoConfiguration.getAddMAMStorageProcessingHint());
OmemoConfiguration.setAddMAMStorageProcessingHint(true);
assertEquals(true, OmemoConfiguration.getAddMAMStorageProcessingHint());
// Body hint
OmemoConfiguration.setAddOmemoHintBody(false);
assertEquals(false, OmemoConfiguration.getAddOmemoHintBody());
OmemoConfiguration.setAddOmemoHintBody(true);
assertEquals(true, OmemoConfiguration.getAddOmemoHintBody());
// Delete stale devices
OmemoConfiguration.setDeleteStaleDevices(false);
assertEquals(false, OmemoConfiguration.getDeleteStaleDevices());
OmemoConfiguration.setDeleteStaleDevices(true);
assertEquals(true, OmemoConfiguration.getDeleteStaleDevices());
OmemoConfiguration.setDeleteStaleDevicesAfterHours(25);
assertEquals(25, OmemoConfiguration.getDeleteStaleDevicesAfterHours());
try {
OmemoConfiguration.setDeleteStaleDevicesAfterHours(-3);
TestCase.fail("OmemoConfiguration.setDeleteStaleDevicesAfterHours should not accept values <= 0.");
} catch (IllegalArgumentException e) {
// Expected.
}
// Ignore stale device
OmemoConfiguration.setIgnoreStaleDevices(false);
assertEquals(false, OmemoConfiguration.getIgnoreStaleDevices());
OmemoConfiguration.setIgnoreStaleDevices(true);
assertEquals(true, OmemoConfiguration.getIgnoreStaleDevices());
OmemoConfiguration.setIgnoreStaleDevicesAfterHours(44);
assertEquals(44, OmemoConfiguration.getIgnoreStaleDevicesAfterHours());
try {
OmemoConfiguration.setIgnoreStaleDevicesAfterHours(-5);
TestCase.fail("OmemoConfiguration.setIgnoreStaleDevicesAfterHours should not accept values <= 0.");
} catch (IllegalArgumentException e) {
// Expected
}
// Renew signedPreKeys
OmemoConfiguration.setRenewOldSignedPreKeys(false);
assertEquals(false, OmemoConfiguration.getRenewOldSignedPreKeys());
OmemoConfiguration.setRenewOldSignedPreKeys(true);
assertEquals(true, OmemoConfiguration.getRenewOldSignedPreKeys());
OmemoConfiguration.setRenewOldSignedPreKeysAfterHours(77);
assertEquals(77, OmemoConfiguration.getRenewOldSignedPreKeysAfterHours());
try {
OmemoConfiguration.setRenewOldSignedPreKeysAfterHours(0);
TestCase.fail("OmemoConfiguration.setRenewOldSignedPreKeysAfterHours should not accept values <= 0");
} catch (IllegalArgumentException e) {
// Expected
}
OmemoConfiguration.setMaxNumberOfStoredSignedPreKeys(6);
assertEquals(6, OmemoConfiguration.getMaxNumberOfStoredSignedPreKeys());
try {
OmemoConfiguration.setMaxNumberOfStoredSignedPreKeys(0);
TestCase.fail("OmemoConfiguration.setMaxNumberOfStoredSignedPreKeys should not accept values <= 0");
} catch (IllegalArgumentException e) {
//Expected
}
}
}
| 44.447368 | 113 | 0.727452 |
4b166e0193afb5f3e539ffe8eb879f14abdd1242 | 264 | package com.project.world.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
@Configuration
@EnableRedisRepositories
public class SpringDataRedisConfig {
}
| 26.4 | 87 | 0.867424 |
5b77a384d55d120d22704baadafe6a6ea4eb07ce | 10,020 | package seedu.scheduler.testutil;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_DEPARTMENT_AMY;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_DEPARTMENT_BOB;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_FACULTY_BOB;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_NAME_AMY;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_NAME_BOB;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_NUS_WORK_EMAIL_AMY;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_NUS_WORK_EMAIL_BOB;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_PERSONAL_EMAIL_BOB;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_PHONE_AMY;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_PHONE_BOB;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_SLOT_AMY;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_SLOT_BOB;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_TAG_FRIEND;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND;
import static seedu.scheduler.logic.commands.CommandTestUtil.VALID_YEAR_OF_STUDY_BOB;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import seedu.scheduler.model.IntervieweeList;
import seedu.scheduler.model.InterviewerList;
import seedu.scheduler.model.person.Interviewee;
import seedu.scheduler.model.person.Interviewer;
import seedu.scheduler.model.person.Person;
/**
* A utility class containing a list of {@code Person} objects to be used in tests.
*/
public class TypicalPersons {
// Persons
public static final Person ALICE = new PersonBuilder().withName("Alice Pauline")
.withPhone("94351253").withTags("friends").build();
public static final Person BENSON = new PersonBuilder().withName("Benson Meier")
.withPhone("98765432").withTags("owesMoney", "friends").build();
public static final Person CARL = new PersonBuilder().withName("Carl Kurz").withPhone("95352563").build();
public static final Person DANIEL = new PersonBuilder().withName("Daniel Meier").withPhone("87652533")
.withTags("friends").build();
public static final Person ELLE = new PersonBuilder().withName("Elle Meyer").withPhone("9482224").build();
public static final Person FIONA = new PersonBuilder().withName("Fiona Kunz").withPhone("9482427").build();
public static final Person GEORGE = new PersonBuilder().withName("George Best").withPhone("9482442").build();
public static final Person HOON = new PersonBuilder().withName("Hoon Meier").withPhone("8482424").build();
public static final Person IDA = new PersonBuilder().withName("Ida Mueller").withPhone("8482131").build();
// Typical Interviewees
public static final Interviewee ALICE_INTERVIEWEE = new IntervieweeBuilder(ALICE).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HeyThere@gmail.com")
.withNusWorkEmail("HeyoAlice@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
public static final Interviewee BENSON_INTERVIEWEE = new IntervieweeBuilder(BENSON).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HiThere@gmail.com")
.withNusWorkEmail("HeyoBenson@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
public static final Interviewee CARL_INTERVIEWEE = new IntervieweeBuilder(CARL).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HiThere@gmail.com")
.withNusWorkEmail("HeyoCarl@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
public static final Interviewee DANIEL_INTERVIEWEE = new IntervieweeBuilder(DANIEL).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HiThere@gmail.com")
.withNusWorkEmail("HeyoDaniel@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
public static final Interviewee ELLE_INTERVIEWEE = new IntervieweeBuilder(ELLE).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HiThere@gmail.com")
.withNusWorkEmail("HeyoElle@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
public static final Interviewee FIONA_INTERVIEWEE = new IntervieweeBuilder(FIONA).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HiThere@gmail.com")
.withNusWorkEmail("HeyoFiona@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
public static final Interviewee GEORGE_INTERVIEWEE = new IntervieweeBuilder(GEORGE).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HiThere@gmail.com")
.withNusWorkEmail("HeyoGeorge@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
public static final Interviewee HOON_INTERVIEWEE = new IntervieweeBuilder(HOON).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HiThere@gmail.com")
.withNusWorkEmail("HeyoHoon@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
public static final Interviewee IDA_INTERVIEWEE = new IntervieweeBuilder(IDA).withFaculty("Engineering")
.withYearOfStudy("1").withDepartmentChoices("Logistics").withPersonalEmail("HiThere@gmail.com")
.withNusWorkEmail("HeyoIda@u.nus.edu").withTimeslots("03/03/2019 16:00-17:00").build();
// Typical Interviewers
public static final Interviewer ALICE_INTERVIEWER = new InterviewerBuilder(ALICE).withDepartment("Logistics")
.withEmail("interviewerAlice@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
public static final Interviewer BENSON_INTERVIEWER = new InterviewerBuilder(BENSON).withDepartment("Logistics")
.withEmail("interviewerBenson@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
public static final Interviewer CARL_INTERVIEWER = new InterviewerBuilder(CARL).withDepartment("Logistics")
.withEmail("interviewerCarl@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
public static final Interviewer DANIEL_INTERVIEWER = new InterviewerBuilder(DANIEL).withDepartment("Logistics")
.withEmail("interviewerDaniel@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
public static final Interviewer ELLE_INTERVIEWER = new InterviewerBuilder(ELLE).withDepartment("Logistics")
.withEmail("interviewerElle@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
public static final Interviewer FIONA_INTERVIEWER = new InterviewerBuilder(FIONA).withDepartment("Logistics")
.withEmail("interviewerFiona@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
public static final Interviewer GEORGE_INTERVIEWER = new InterviewerBuilder(GEORGE).withDepartment("Logistics")
.withEmail("interviewerGeorge@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
public static final Interviewer HOON_INTERVIEWER = new InterviewerBuilder(HOON).withDepartment("Marketing")
.withEmail("interviewerHoon@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
public static final Interviewer IDA_INTERVIEWER = new InterviewerBuilder(IDA).withDepartment("Marketing")
.withEmail("interviewerIda@gmail.com").withAvailabilities("05/05/2019 16:00-17:00").build();
// Manually added - Person's details found in {@code CommandTestUtil}
public static final Person AMY_PERSON_MANUAL = new PersonBuilder().withName(VALID_NAME_AMY)
.withPhone(VALID_PHONE_AMY).withTags(VALID_TAG_FRIEND).build();
public static final Interviewer AMY_INTERVIEWER_MANUAL = new InterviewerBuilder(AMY_PERSON_MANUAL)
.withDepartment(VALID_DEPARTMENT_AMY).withAvailabilities(VALID_SLOT_AMY)
.withEmail(VALID_NUS_WORK_EMAIL_AMY).build();
public static final Person BOB_PERSON_MANUAL = new PersonBuilder().withName(VALID_NAME_BOB)
.withPhone(VALID_PHONE_BOB).withTags(VALID_TAG_HUSBAND, VALID_TAG_FRIEND).build();
public static final Interviewee BOB_INTERVIEWEE_MANUAL = new IntervieweeBuilder(BOB_PERSON_MANUAL)
.withFaculty(VALID_FACULTY_BOB).withYearOfStudy(VALID_YEAR_OF_STUDY_BOB)
.withDepartmentChoices(VALID_DEPARTMENT_BOB).withTimeslots(VALID_SLOT_BOB)
.withPersonalEmail(VALID_PERSONAL_EMAIL_BOB).withNusWorkEmail(VALID_NUS_WORK_EMAIL_BOB).build();
private TypicalPersons() {} // prevents instantiation
/**
* Returns an {@code IntervieweeList} with all the typical interviewees.
* @return
*/
public static IntervieweeList getTypicalIntervieweeList() {
IntervieweeList ib = new IntervieweeList();
for (Interviewee i: getTypicalInterviewees()) {
ib.addEntity(i);
}
return ib;
}
public static List<Interviewee> getTypicalInterviewees() {
return new ArrayList<>(Arrays.asList(ALICE_INTERVIEWEE, BENSON_INTERVIEWEE, CARL_INTERVIEWEE,
DANIEL_INTERVIEWEE, ELLE_INTERVIEWEE, FIONA_INTERVIEWEE, GEORGE_INTERVIEWEE));
}
public static InterviewerList getTypicalInterviewerList() {
InterviewerList ib = new InterviewerList();
for (Interviewer i: getTypicalInterviewers()) {
ib.addEntity(i);
}
return ib;
}
public static List<Interviewer> getTypicalInterviewers() {
return new ArrayList<>(Arrays.asList(ALICE_INTERVIEWER, BENSON_INTERVIEWER, CARL_INTERVIEWER,
DANIEL_INTERVIEWER, ELLE_INTERVIEWER, FIONA_INTERVIEWER, GEORGE_INTERVIEWER));
}
}
| 70.56338 | 115 | 0.752994 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.