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
|
---|---|---|---|---|---|
e98c2dbc5c5468f3d91b1284a44a2a145176a283
| 6,459 |
/**
* (c) Copyright 2012 WibiData, Inc.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.kiji.schema;
import java.io.IOException;
import java.util.List;
import org.kiji.annotations.ApiAudience;
import org.kiji.annotations.ApiStability;
import org.kiji.annotations.Inheritance;
import org.kiji.schema.layout.KijiTableLayout;
import org.kiji.schema.util.ReferenceCountable;
/**
* The KijiTable interface provides operations on KijiTables. To perform reads to and
* writes from a Kiji table use a {@link KijiTableReader} or {@link KijiTableWriter}.
* Instances of these classes can be obtained by using the {@link #openTableReader()}
* and {@link #openTableWriter()} methods. {@link EntityId}s, which identify particular
* rows within a Kiji table are also generated from its components.
*
* <h2>KijiTable instance lifecycle:</h2>
* <p>
* To open a connection to a KijiTable, use {@link Kiji#openTable(String)}. A KijiTable
* contains an open connection to an HBase cluster. Because of this, KijiTable objects
* must be released using {@link #release()} when finished using it:
* </p>
* <pre>
* <code>
* final KijiTable table = myKiji.openTable("tableName");
* // Do some magic
* table.release();
* </code>
* </pre>
*
* <h2>Reading & Writing from a KijiTable:</h2>
* <p>
* The KijiTable interface does not directly provide methods to perform I/O on a Kiji
* table. Read and write operations can be performed using either a {@link KijiTableReader}
* or a {@link KijiTableWriter}:
* </p>
* <pre>
* <code>
* final KijiTable table = myKiji.openTable("tableName");
*
* final EntityId myId = table.getEntityId("myRowKey");
*
* final KijiTableReader reader = table.openTableReader();
* final KijiTableWriter writer = table.openTableWriter();
*
* // Read some data from a Kiji table using an existing EntityId and KijiDataRequest.
* final KijiRowData row = reader.get(myId, myDataRequest);
*
* // Do things with the row...
*
* // Write some data to a new column in the same row.
* writer.put(myId, "info", "newcolumn", "newvalue");
*
* // Close open connections.
* reader.close();
* writer.close();
* table.release();
* </code>
* </pre>
*
* @see KijiTableReader for more information about reading data from a Kiji table.
* @see KijiTableWriter for more information about writing data to a Kiji table.
* @see EntityId for more information about identifying rows with entity ids.
* @see Kiji for more information about opening a KijiTable instance.
*/
@ApiAudience.Public
@ApiStability.Stable
@Inheritance.Sealed
public interface KijiTable extends ReferenceCountable<KijiTable> {
/** @return the Kiji instance this table belongs to. */
Kiji getKiji();
/** @return the name of this table. */
String getName();
/** @return the URI for this table, trimmed at the table path component. */
KijiURI getURI();
/** @return the layout of this table. */
KijiTableLayout getLayout();
/**
* Creates an entity id from a list of components.
*
* @param kijiRowKey This can be one of the following depending on row key encoding:
* <ul>
* <li>
* Raw, Hash, Hash-Prefix EntityId: A single String or byte array
* component.
* </li>
* <li>
* Formatted EntityId: The primitive row key components (string, int,
* long) either passed in their expected order in the key or as an ordered
* list of components.
* </li>
* </ul>
* @return a new EntityId with the specified Kiji row key.
*/
EntityId getEntityId(Object... kijiRowKey);
/**
* Opens a KijiTableReader for this table.
*
* <p> The caller of this method is responsible for closing the returned reader.
* <p> The reader returned by this method does not provide any isolation guarantee.
* In particular, you should assume that the underlying resources (connections, buffers, etc)
* are used concurrently for other purposes.
*
* @return A KijiTableReader for this table.
* @throws KijiIOException Future implementations may throw unchecked KijiIOException.
*/
KijiTableReader openTableReader();
/**
* Gets a KijiReaderFactory for this table.
*
* <p> The returned reader factory is valid as long as the caller retains the table. </p>
*
* @throws IOException in case of an error.
* @return A KijiReaderFactory.
*/
KijiReaderFactory getReaderFactory() throws IOException;
/**
* Opens a KijiTableWriter for this table.
*
* <p> The caller of this method is responsible for closing the returned writer.
* <p> The writer returned by this method does not provide any isolation guarantee.
* In particular, you should assume that the underlying resources (connections, buffers, etc)
* are used concurrently for other purposes.
* <p> If you have specific resource requirements, such as buffering, timeouts, dedicated
* connection, etc, use {@link #getWriterFactory()}.
*
* @return A KijiTableWriter for this table.
* @throws KijiIOException Future implementations may throw unchecked KijiIOException.
*/
KijiTableWriter openTableWriter();
/**
* Gets a KijiWriterFactory for this table.
*
* <p> The returned writer factory is valid as long as the caller retains the table. </p>
*
* @throws IOException in case of an error.
* @return A KijiWriterFactory.
*/
KijiWriterFactory getWriterFactory() throws IOException;
/**
* Return the regions in this table as an ordered list.
*
* @return An ordered list of the table regions.
* @throws IOException If there is an error retrieving the regions of this table.
*/
List<KijiRegion> getRegions() throws IOException;
}
| 36.286517 | 99 | 0.694535 |
93b94f49a3f211a7205eae6bc269568d0adad8a2
| 3,149 |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package sql.trigger;
import java.sql.*;
import java.util.List;
import com.gemstone.gemfire.cache.CacheWriterException;
import com.gemstone.gemfire.cache.EntryEvent;
import com.pivotal.gemfirexd.callbacks.Event;
import com.pivotal.gemfirexd.callbacks.EventCallback;
import com.pivotal.gemfirexd.callbacks.Event.Type;
import hydra.*;
import sql.SQLHelper;
import sql.SQLTest;
public class TriggerWriter extends SQLTest implements EventCallback {
public static TriggerWriter getTriggerCallback() {
return new TriggerWriter();
}
public void close() throws SQLException {
Log.getLogWriter().info("close writer");
}
public void init(String initStr) throws SQLException {
Log.getLogWriter().info("init writer : " + initStr);
}
/* Tests simulate before trigger behaviors , not after trigger behaviors */
public void onEvent(Event event) throws SQLException {
Log.getLogWriter().info("onEvent , Event Type : " + event.getType());
Connection conn = getGFEConnection();
String sql = null;
List<Object> row;
PreparedStatement stmt;
try{
if ((event.getType()).equals(Type.BEFORE_INSERT)){
row = event.getNewRow();
sql = "insert into trade.customers_audit values(?,?,?,?,?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, ((Integer)row.get(0)).intValue());
stmt.setString(2, (String)row.get(1));
stmt.setDate(3, (Date)row.get(2));
stmt.setString(4, (String)row.get(3));
stmt.setInt(5, ((Integer)row.get(4)).intValue());
} else if ((event.getType()).equals(Type.BEFORE_DELETE)){
row = event.getOldRow();
sql = "delete from trade.customers_audit where cid = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, ((Integer)row.get(0)).intValue());
} else if ((event.getType()).equals(Type.BEFORE_UPDATE)){
row = event.getNewRow();
sql = "update trade.customers_audit set addr = ? where cid = 1";
stmt = conn.prepareStatement(sql);
stmt.setString(1,(String)row.get(3));
} else {
throw new IllegalArgumentException ("Unknown Event Type " + event.getType());
}
int numRow = stmt.executeUpdate();
Log.getLogWriter().info("SZHU modified " + numRow + " row to audit table");
stmt.close();
commit(conn);
conn.commit();
closeGFEConnection(conn);
}catch(SQLException se){
SQLHelper.handleSQLException(se);
}
}
}
| 36.616279 | 83 | 0.675135 |
f5a54f2cf2f551aac0bf5668000e6716f4a4a0bb
| 809 |
package com.ycbjie.ycscrollpager;
import android.content.Context;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class ImageUtils {
/**
* 加载图片
* @param resId
* @param target 控件
*/
public static void loadImgByPicasso(Context context , int path , int resId, ImageView target) {
if(target==null){
return;
}
if(path!=0){
Picasso.with(context)
.load(path)
.placeholder(resId)
.error(resId)
.into(target);
}else {
Picasso.with(context)
.load(resId)
.placeholder(resId)
.error(resId)
.into(target);
}
}
}
| 22.472222 | 99 | 0.485785 |
6fda39765d57c042642694a02630ebe7543996cb
| 1,738 |
package io.napadlek.graphapi.rest;
import io.napadlek.graphapi.business.service.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity handleBusinessException(BusinessException businessException) {
ErrorResponse errorResponse = convertToErrorResponse(businessException);
errorResponse.setBusinessException(true);
return ResponseEntity.badRequest()
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(errorResponse);
}
@ExceptionHandler
public ResponseEntity handleAllExceptions(Exception exception) {
ErrorResponse errorResponse = convertToErrorResponse(exception);
errorResponse.setBusinessException(false);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(errorResponse);
}
private ErrorResponse convertToErrorResponse(Exception exception) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setMessage(exception.getMessage());
errorResponse.setExceptionClass(exception.getClass().toString());
errorResponse.setStackTrace(Stream.of(exception.getStackTrace()).map(StackTraceElement::toString).collect(Collectors.toList()));
return errorResponse;
}
}
| 41.380952 | 136 | 0.766398 |
bf5d9b586d41fb11660862714574eb04326b477c
| 45,516 |
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.commonservices.ocf.metadatamanagement.server;
import org.odpi.openmetadata.commonservices.ffdc.RESTExceptionHandler;
import org.odpi.openmetadata.commonservices.multitenant.OCFOMASServiceInstance;
import org.odpi.openmetadata.commonservices.ocf.metadatamanagement.handlers.*;
import org.odpi.openmetadata.commonservices.ocf.metadatamanagement.rest.*;
import org.odpi.openmetadata.frameworks.connectors.ffdc.InvalidParameterException;
import org.odpi.openmetadata.frameworks.connectors.ffdc.PropertyServerException;
import org.odpi.openmetadata.frameworks.connectors.ffdc.UserNotAuthorizedException;
import org.odpi.openmetadata.frameworks.connectors.properties.beans.Comment;
import org.odpi.openmetadata.frameworks.connectors.properties.beans.NoteLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* The ConnectedAssetRESTServices is the server-side implementation of the Connected Asset OMAS REST interface.
*/
public class OCFMetadataRESTServices
{
static private OCFMetadataInstanceHandler instanceHandler = new OCFMetadataInstanceHandler();
private static final Logger log = LoggerFactory.getLogger(OCFMetadataRESTServices.class);
private RESTExceptionHandler restExceptionHandler = new RESTExceptionHandler();
/**
* Default constructor
*/
public OCFMetadataRESTServices()
{
}
/**
* Returns the basic information about the asset. The connection guid allows the short description for the
* asset to be filled out.
*
* @param serverName name of the server.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param connectionGUID unique id for connection used to access asset.
*
* @return a bean with the basic properties about the asset or
* InvalidParameterException - the asset GUID is null or invalid or
* UnrecognizedAssetGUIDException - the asset GUID is not recognized by the property server or
* UnrecognizedConnectionGUIDException - the connection GUID is not recognized by the property server or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException the requesting user is not authorized to issue this request.
*/
private AssetResponse getAssetResponse(String serverName,
String userId,
String assetGUID,
String connectionGUID,
String methodName)
{
log.debug("Calling method: " + methodName + " for server " + serverName);
AssetResponse response = new AssetResponse();
try
{
AssetHandler assetHandler = instanceHandler.getAssetHandler(userId, serverName);
if (connectionGUID != null)
{
response.setAsset(assetHandler.getAsset(userId, assetGUID, connectionGUID));
}
else
{
response.setAsset(assetHandler.getAsset(userId, assetGUID));
}
response.setCertificationCount(assetHandler.getCertificationCount(userId, assetGUID, methodName));
response.setCommentCount(assetHandler.getCommentCount(userId, assetGUID, methodName));
response.setConnectionCount(assetHandler.getConnectionCount(userId, assetGUID, methodName));
response.setExternalIdentifierCount(assetHandler.getExternalIdentifierCount(userId, assetGUID, methodName));
response.setExternalReferencesCount(assetHandler.getExternalReferencesCount(userId, assetGUID, methodName));
response.setInformalTagCount(assetHandler.getInformalTagCount(userId, assetGUID, methodName));
response.setLicenseCount(assetHandler.getLicenseCount(userId, assetGUID, methodName));
response.setLikeCount(assetHandler.getLikeCount(userId, assetGUID, methodName));
response.setKnownLocationsCount(assetHandler.getKnownLocationsCount(userId, assetGUID, methodName));
response.setNoteLogsCount(assetHandler.getNoteLogsCount(userId, assetGUID, methodName));
response.setRatingsCount(assetHandler.getRatingsCount(userId, assetGUID, methodName));
response.setRelatedAssetCount(assetHandler.getRelatedAssetCount(userId, assetGUID, methodName));
response.setRelatedMediaReferenceCount(assetHandler.getRelatedMediaReferenceCount(userId, assetGUID, methodName));
response.setSchemaType(assetHandler.getSchemaType(userId, assetGUID, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the basic information about the asset. The connection guid allows the short description for the
* asset to be filled out.
*
* @param serverName name of the server.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param connectionGUID unique id for connection used to access asset.
*
* @return a bean with the basic properties about the asset or
* InvalidParameterException - the asset GUID is null or invalid or
* UnrecognizedAssetGUIDException - the asset GUID is not recognized by the property server or
* UnrecognizedConnectionGUIDException - the connection GUID is not recognized by the property server or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException the requesting user is not authorized to issue this request.
*/
public AssetResponse getConnectedAssetSummary(String serverName,
String userId,
String assetGUID,
String connectionGUID)
{
final String methodName = "getConnectedAssetSummary";
return this.getAssetResponse(serverName, userId, assetGUID, connectionGUID, methodName);
}
/**
* Returns the basic information about the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
*
* @return a bean with the basic properties about the asset or
* InvalidParameterException - the userId is null or invalid or
* UnrecognizedAssetGUIDException - the GUID is null or invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public AssetResponse getAssetSummary(String serverName,
String userId,
String assetGUID)
{
final String methodName = "getAssetSummary";
return this.getAssetResponse(serverName, userId, assetGUID, null, methodName);
}
/**
* Returns the list of certifications for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of certifications or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public CertificationsResponse getCertifications(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getCertifications";
log.debug("Calling method: " + methodName + " for server " + serverName);
CertificationsResponse response = new CertificationsResponse();
try
{
CertificationHandler handler = instanceHandler.getCertificationHandler(userId, serverName);
response.setList(handler.getCertifications(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of comments for the requested anchor.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param anchorGUID String unique id for anchor object.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
* @param methodName String name of calling method.
*
* @return a list of comments or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
private CommentsResponse getAttachedComments(String serverName,
String userId,
String anchorGUID,
int elementStart,
int maxElements,
String methodName)
{
log.debug("Calling method: " + methodName + " for server " + serverName);
CommentsResponse response = new CommentsResponse();
try
{
CommentHandler handler = instanceHandler.getCommentHandler(userId, serverName);
List<Comment> attachedComments = handler.getComments(userId, anchorGUID, elementStart, maxElements, methodName);
List<CommentResponse> results = new ArrayList<>();
if (attachedComments != null)
{
for (Comment comment : attachedComments)
{
if (comment != null)
{
CommentResponse commentResponse = new CommentResponse();
commentResponse.setComment(comment);
commentResponse.setReplyCount(handler.countAttachedComments(userId, comment.getGUID(), methodName));
results.add(commentResponse);
}
}
}
if (results.isEmpty())
{
response.setList(null);
}
else
{
response.setList(results);
}
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of comments for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of comments or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public CommentsResponse getComments(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getComments";
return getAttachedComments(serverName, userId, assetGUID, elementStart, maxElements, methodName);
}
/**
* Returns the list of replies to a comment.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param commentGUID String unique id for root comment.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of comments or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public CommentsResponse getCommentReplies(String serverName,
String userId,
String commentGUID,
int elementStart,
int maxElements)
{
final String methodName = "getCommentReplies";
return getAttachedComments(serverName, userId, commentGUID, elementStart, maxElements, methodName);
}
/**
* Returns the list of connections for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of connections or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public ConnectionsResponse getConnections(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getConnections";
log.debug("Calling method: " + methodName + " for server " + serverName);
ConnectionsResponse response = new ConnectionsResponse();
try
{
ConnectionHandler handler = instanceHandler.getConnectionHandler(userId, serverName);
response.setList(handler.getConnections(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of external identifiers for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of external identifiers or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public ExternalIdentifiersResponse getExternalIdentifiers(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getExternalIdentifiers";
log.debug("Calling method: " + methodName + " for server " + serverName);
ExternalIdentifiersResponse response = new ExternalIdentifiersResponse();
try
{
ExternalIdentifierHandler handler = instanceHandler.getExternalIdentifierHandler(userId, serverName);
response.setList(handler.getExternalIdentifiers(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of external references for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of external references or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public ExternalReferencesResponse getExternalReferences(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getExternalReferences";
log.debug("Calling method: " + methodName + " for server " + serverName);
ExternalReferencesResponse response = new ExternalReferencesResponse();
try
{
ExternalReferenceHandler handler = instanceHandler.getExternalReferenceHandler(userId, serverName);
response.setList(handler.getExternalReferences(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of informal tags for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of informal tags or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public InformalTagsResponse getInformalTags(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getInformalTags";
log.debug("Calling method: " + methodName + " for server " + serverName);
InformalTagsResponse response = new InformalTagsResponse();
try
{
InformalTagHandler handler = instanceHandler.getInformalTagHandler(userId, serverName);
response.setList(handler.getAttachedTags(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of licenses for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of licenses or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public LicensesResponse getLicenses(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getLicenses";
log.debug("Calling method: " + methodName + " for server " + serverName);
LicensesResponse response = new LicensesResponse();
try
{
LicenseHandler handler = instanceHandler.getLicenseHandler(userId, serverName);
response.setList(handler.getLicenses(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of likes for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of likes or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public LikesResponse getLikes(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getLikes";
log.debug("Calling method: " + methodName + " for server " + serverName);
LikesResponse response = new LikesResponse();
try
{
LikeHandler handler = instanceHandler.getLikeHandler(userId, serverName);
response.setList(handler.getLikes(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of known locations for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of known locations or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public LocationsResponse getKnownLocations(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getKnownLocations";
log.debug("Calling method: " + methodName + " for server " + serverName);
LocationsResponse response = new LocationsResponse();
try
{
LocationHandler handler = instanceHandler.getLocationHandler(userId, serverName);
response.setList(handler.getLocations(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of note logs for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of note logs or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public NoteLogsResponse getNoteLogs(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getNoteLogs";
log.debug("Calling method: " + methodName + " for server " + serverName);
NoteLogsResponse response = new NoteLogsResponse();
try
{
NoteLogHandler handler = instanceHandler.getNoteLogHandler(userId, serverName);
List<NoteLog> noteLogs = handler.getAttachedNoteLogs(userId, assetGUID, elementStart, maxElements, methodName);
List<NoteLogResponse> results = new ArrayList<>();
for (NoteLog noteLog : noteLogs)
{
if (noteLog != null)
{
NoteLogResponse noteLogResponse = new NoteLogResponse();
noteLogResponse.setNoteLog(noteLog);
noteLogResponse.setNoteCount(handler.countAttachedNoteLogs(userId, noteLog.getGUID(), methodName));
results.add(noteLogResponse);
}
}
if (results.isEmpty())
{
response.setList(null);
}
else
{
response.setList(results);
}
response.setList(results);
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of notes for a note log.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param noteLogGUID String unique id for the note log.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of notes or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public NotesResponse getNotes(String serverName,
String userId,
String noteLogGUID,
int elementStart,
int maxElements)
{
final String methodName = "getNotes";
log.debug("Calling method: " + methodName + " for server " + serverName);
NotesResponse response = new NotesResponse();
try
{
NoteHandler handler = instanceHandler.getNoteHandler(userId, serverName);
response.setList(handler.getNotes(userId, noteLogGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of ratings for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of ratings or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public RatingsResponse getRatings(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getRatings";
log.debug("Calling method: " + methodName + " for server " + serverName);
RatingsResponse response = new RatingsResponse();
try
{
RatingHandler handler = instanceHandler.getRatingHandler(userId, serverName);
response.setList(handler.getRatings(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of related assets for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of assets or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public RelatedAssetsResponse getRelatedAssets(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getRelatedAssets";
log.debug("Calling method: " + methodName + " for server " + serverName);
RelatedAssetsResponse response = new RelatedAssetsResponse();
try
{
AssetHandler handler = instanceHandler.getAssetHandler(userId, serverName);
response.setList(handler.getRelatedAssets(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns the list of related media references for the asset.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param assetGUID String unique id for asset.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a list of related media references or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public RelatedMediaReferencesResponse getRelatedMediaReferences(String serverName,
String userId,
String assetGUID,
int elementStart,
int maxElements)
{
final String methodName = "getRelatedMediaReferences";
log.debug("Calling method: " + methodName + " for server " + serverName);
RelatedMediaReferencesResponse response = new RelatedMediaReferencesResponse();
try
{
RelatedMediaHandler handler = instanceHandler.getRelatedMediaHandler(userId, serverName);
response.setList(handler.getRelatedMedia(userId, assetGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
/**
* Returns a list of schema attributes for a schema type.
*
* @param serverName String name of server instance to call.
* @param userId String userId of user making request.
* @param schemaTypeGUID String unique id for containing schema type.
* @param elementStart int starting position for fist returned element.
* @param maxElements int maximum number of elements to return on the call.
*
* @return a schema attributes response or
* InvalidParameterException - the GUID is not recognized or the paging values are invalid or
* PropertyServerException - there is a problem retrieving the asset properties from the property server or
* UserNotAuthorizedException - the requesting user is not authorized to issue this request.
*/
public SchemaAttributesResponse getSchemaAttributes(String serverName,
String userId,
String schemaTypeGUID,
int elementStart,
int maxElements)
{
final String methodName = "getSchemaAttributes";
log.debug("Calling method: " + methodName + " for server " + serverName);
SchemaAttributesResponse response = new SchemaAttributesResponse();
try
{
SchemaTypeHandler handler = instanceHandler.getSchemaTypeHandler(userId, serverName);
response.setList(handler.getSchemaAttributes(userId, schemaTypeGUID, elementStart, maxElements, methodName));
}
catch (InvalidParameterException error)
{
restExceptionHandler.captureInvalidParameterException(response, error);
}
catch (PropertyServerException error)
{
restExceptionHandler.capturePropertyServerException(response, error);
}
catch (UserNotAuthorizedException error)
{
restExceptionHandler.captureUserNotAuthorizedException(response, error);
}
log.debug("Returning from method: " + methodName + " for server " + serverName + " with response: " + response.toString());
return response;
}
}
| 44.233236 | 132 | 0.61965 |
6605df3d780618b74f5d2f89d7b995efe017ac19
| 8,636 |
/*
* (C) Copyright IBM Corp. 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.watson.health.iml.v1.model;
import java.util.ArrayList;
import java.util.List;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* The getDocumentCategories options.
*/
public class GetDocumentCategoriesOptions extends GenericModel {
/**
* Select concepts belonging to disorders, drugs or genes.
*/
public interface Category {
/** disorders. */
String DISORDERS = "disorders";
/** drugs. */
String DRUGS = "drugs";
/** genes. */
String GENES = "genes";
}
protected String corpus;
protected String documentId;
protected String highlightTagBegin;
protected String highlightTagEnd;
protected List<String> types;
protected String category;
protected Boolean onlyNegatedConcepts;
protected String fields;
protected Long limit;
/**
* Builder.
*/
public static class Builder {
private String corpus;
private String documentId;
private String highlightTagBegin;
private String highlightTagEnd;
private List<String> types;
private String category;
private Boolean onlyNegatedConcepts = false;
private String fields;
private Long limit = 50L;
private Builder(GetDocumentCategoriesOptions getDocumentCategoriesOptions) {
this.corpus = getDocumentCategoriesOptions.corpus;
this.documentId = getDocumentCategoriesOptions.documentId;
this.highlightTagBegin = getDocumentCategoriesOptions.highlightTagBegin;
this.highlightTagEnd = getDocumentCategoriesOptions.highlightTagEnd;
this.types = getDocumentCategoriesOptions.types;
this.category = getDocumentCategoriesOptions.category;
if (getDocumentCategoriesOptions.onlyNegatedConcepts() != null) {
this.onlyNegatedConcepts = getDocumentCategoriesOptions.onlyNegatedConcepts;
}
this.fields = getDocumentCategoriesOptions.fields;
this.limit = getDocumentCategoriesOptions.limit;
}
/**
* Instantiates a new builder.
*/
public Builder() {
}
/**
* Instantiates a new builder with required properties.
*
* @param corpus the corpus
* @param documentId the documentId
*/
public Builder(String corpus, String documentId) {
this.corpus = corpus;
this.documentId = documentId;
}
/**
* Builds a GetDocumentCategoriesOptions.
*
* @return the new GetDocumentCategoriesOptions instance
*/
public GetDocumentCategoriesOptions build() {
return new GetDocumentCategoriesOptions(this);
}
/**
* Adds an types to types.
*
* @param types the new types
* @return the GetDocumentCategoriesOptions builder
*/
public Builder addTypes(String types) {
com.ibm.cloud.sdk.core.util.Validator.notNull(types,
"types cannot be null");
if (this.types == null) {
this.types = new ArrayList<String>();
}
this.types.add(types);
return this;
}
/**
* Set the corpus.
*
* @param corpus the corpus
* @return the GetDocumentCategoriesOptions builder
*/
public Builder corpus(String corpus) {
this.corpus = corpus;
return this;
}
/**
* Set the documentId.
*
* @param documentId the documentId
* @return the GetDocumentCategoriesOptions builder
*/
public Builder documentId(String documentId) {
this.documentId = documentId;
return this;
}
/**
* Set the highlightTagBegin.
*
* @param highlightTagBegin the highlightTagBegin
* @return the GetDocumentCategoriesOptions builder
*/
public Builder highlightTagBegin(String highlightTagBegin) {
this.highlightTagBegin = highlightTagBegin;
return this;
}
/**
* Set the highlightTagEnd.
*
* @param highlightTagEnd the highlightTagEnd
* @return the GetDocumentCategoriesOptions builder
*/
public Builder highlightTagEnd(String highlightTagEnd) {
this.highlightTagEnd = highlightTagEnd;
return this;
}
/**
* Set the types.
* Existing types will be replaced.
*
* @param types the types
* @return the GetDocumentCategoriesOptions builder
*/
public Builder types(List<String> types) {
this.types = types;
return this;
}
/**
* Set the category.
*
* @param category the category
* @return the GetDocumentCategoriesOptions builder
*/
public Builder category(String category) {
this.category = category;
return this;
}
/**
* Set the onlyNegatedConcepts.
*
* @param onlyNegatedConcepts the onlyNegatedConcepts
* @return the GetDocumentCategoriesOptions builder
*/
public Builder onlyNegatedConcepts(Boolean onlyNegatedConcepts) {
this.onlyNegatedConcepts = onlyNegatedConcepts;
return this;
}
/**
* Set the fields.
*
* @param fields the fields
* @return the GetDocumentCategoriesOptions builder
*/
public Builder fields(String fields) {
this.fields = fields;
return this;
}
/**
* Set the limit.
*
* @param limit the limit
* @return the GetDocumentCategoriesOptions builder
*/
public Builder limit(long limit) {
this.limit = limit;
return this;
}
}
protected GetDocumentCategoriesOptions(Builder builder) {
com.ibm.cloud.sdk.core.util.Validator.notEmpty(builder.corpus,
"corpus cannot be empty");
com.ibm.cloud.sdk.core.util.Validator.notEmpty(builder.documentId,
"documentId cannot be empty");
corpus = builder.corpus;
documentId = builder.documentId;
highlightTagBegin = builder.highlightTagBegin;
highlightTagEnd = builder.highlightTagEnd;
types = builder.types;
category = builder.category;
onlyNegatedConcepts = builder.onlyNegatedConcepts;
fields = builder.fields;
limit = builder.limit;
}
/**
* New builder.
*
* @return a GetDocumentCategoriesOptions builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the corpus.
*
* Corpus name.
*
* @return the corpus
*/
public String corpus() {
return corpus;
}
/**
* Gets the documentId.
*
* Document ID.
*
* @return the documentId
*/
public String documentId() {
return documentId;
}
/**
* Gets the highlightTagBegin.
*
* HTML tag used to highlight concepts found in the text. Default is '&ltb&gt'.
*
* @return the highlightTagBegin
*/
public String highlightTagBegin() {
return highlightTagBegin;
}
/**
* Gets the highlightTagEnd.
*
* HTML tag used to highlight concepts found in the text. Default is '&lt/b&gt'.
*
* @return the highlightTagEnd
*/
public String highlightTagEnd() {
return highlightTagEnd;
}
/**
* Gets the types.
*
* Select concepts belonging to these semantic types to return. Semantic types for the corpus can be found using the
* /v1/corpora/{corpus}/types method.Defaults to 'all'.
*
* @return the types
*/
public List<String> types() {
return types;
}
/**
* Gets the category.
*
* Select concepts belonging to disorders, drugs or genes.
*
* @return the category
*/
public String category() {
return category;
}
/**
* Gets the onlyNegatedConcepts.
*
* Only return negated concepts?.
*
* @return the onlyNegatedConcepts
*/
public Boolean onlyNegatedConcepts() {
return onlyNegatedConcepts;
}
/**
* Gets the fields.
*
* Comma separated list of fields to return: passages, annotations, highlightedTitle, highlightedAbstract,
* highlightedBody, highlightedSections.
*
* @return the fields
*/
public String fields() {
return fields;
}
/**
* Gets the limit.
*
* Limit the number of passages per search concept (1 to 250). Default is 50.
*
* @return the limit
*/
public Long limit() {
return limit;
}
}
| 25.031884 | 118 | 0.661649 |
6cb7c5ecf41bc3425b07e1204f59cbb2e476e02d
| 718 |
package org.jeecg.modules.project.service.impl;
import org.jeecg.modules.project.entity.Papers;
import org.jeecg.modules.project.mapper.PapersMapper;
import org.jeecg.modules.project.service.IPapersService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;
/**
* @Description: 文件
* @Author: jeecg-boot
* @Date: 2019-11-18
* @Version: V1.0
*/
@Service
public class PapersServiceImpl extends ServiceImpl<PapersMapper, Papers> implements IPapersService {
@Override
public void uploadFile(MultipartFile[] fileList, String projectLocal, String parentId) throws Exception {
}
}
| 28.72 | 109 | 0.786908 |
379b0ff4b087e0841d7cc0dd6f8561a45bffbbc2
| 1,297 |
/*
* Copyright (C) 2017, Megatron King
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.megatronking.svg.generator.xml;
import org.dom4j.DocumentException;
import org.dom4j.Element;
/**
* We convert xml to tree elements by dom4j framework.
* The next step is parsing the elements to model objects.
* An element can have declared namespaces, attributes, child nodes and textual content.
*
* @author Megatron King
* @since 2016/9/1 9:37
*/
public interface IElementParser<T> {
/**
* Parse an element to a model object, one element, one object.
*
* @param element the dom element.
* @param t the object.
* @throws DocumentException an exception when parsing xml.
*/
void parse(Element element, T t) throws DocumentException;
}
| 32.425 | 100 | 0.724749 |
61cc40bbf773d37ca4c2ff544ecdf893b908fffd
| 19,464 |
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.repositories;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.gradle.api.Action;
import org.gradle.api.artifacts.ModuleIdentifier;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.attributes.Attribute;
import org.gradle.api.attributes.AttributeContainer;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.DefaultVersionComparator;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.DefaultVersionSelectorScheme;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.VersionParser;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.VersionSelector;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.VersionSelectorScheme;
import org.gradle.internal.Actions;
import org.gradle.internal.Cast;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.regex.Pattern;
class DefaultRepositoryContentDescriptor implements RepositoryContentDescriptorInternal {
private Set<String> includedConfigurations;
private Set<String> excludedConfigurations;
private Set<ContentSpec> includeSpecs;
private Set<ContentSpec> excludeSpecs;
private Map<Attribute<Object>, Set<Object>> requiredAttributes;
private boolean locked;
private Action<? super ArtifactResolutionDetails> cachedAction;
private final Supplier<String> repositoryNameSupplier;
private final VersionSelectorScheme versionSelectorScheme;
private final ConcurrentHashMap<String, VersionSelector> versionSelectors = new ConcurrentHashMap<>();
private final VersionParser versionParser;
public DefaultRepositoryContentDescriptor(Supplier<String> repositoryNameSupplier, VersionParser versionParser) {
this.versionSelectorScheme = new DefaultVersionSelectorScheme(new DefaultVersionComparator(), versionParser);
this.repositoryNameSupplier = repositoryNameSupplier;
this.versionParser = versionParser;
}
protected VersionParser getVersionParser() {
return versionParser;
}
private void assertMutable() {
if (locked) {
throw new IllegalStateException("Cannot mutate content repository descriptor '" +
repositoryNameSupplier.get() +
"' after repository has been used");
}
}
@Override
public Action<? super ArtifactResolutionDetails> toContentFilter() {
if (cachedAction != null) {
return cachedAction;
}
locked = true;
if (includedConfigurations == null &&
excludedConfigurations == null &&
includeSpecs == null &&
excludeSpecs == null &&
requiredAttributes == null) {
// no filtering in place
return Actions.doNothing();
}
cachedAction = new RepositoryFilterAction(createSpecMatchers(includeSpecs), createSpecMatchers(excludeSpecs));
return cachedAction;
}
@Override
public RepositoryContentDescriptorInternal asMutableCopy() {
DefaultRepositoryContentDescriptor copy = new DefaultRepositoryContentDescriptor(repositoryNameSupplier, getVersionParser());
if (includedConfigurations != null) {
copy.includedConfigurations = Sets.newHashSet(includedConfigurations);
}
if (excludedConfigurations != null) {
copy.excludedConfigurations = Sets.newHashSet(excludedConfigurations);
}
if (includeSpecs != null) {
copy.includeSpecs = Sets.newHashSet(includeSpecs);
}
if (excludeSpecs != null) {
copy.excludeSpecs = Sets.newHashSet(excludeSpecs);
}
if (requiredAttributes != null) {
copy.requiredAttributes = Maps.newHashMap(requiredAttributes);
}
return copy;
}
@Nullable
private static ImmutableList<SpecMatcher> createSpecMatchers(@Nullable Set<ContentSpec> specs) {
ImmutableList<SpecMatcher> matchers = null;
if (specs != null) {
ImmutableList.Builder<SpecMatcher> builder = ImmutableList.builderWithExpectedSize(specs.size());
for (ContentSpec spec : specs) {
builder.add(spec.toMatcher());
}
matchers = builder.build();
}
return matchers;
}
@Override
public void includeGroup(String group) {
checkNotNull(group, "Group cannot be null");
addInclude(group, null, null, false);
}
private static void checkNotNull(@Nullable String value, String message) {
if (value == null) {
throw new IllegalArgumentException(message);
}
}
@Override
public void includeGroupByRegex(String groupRegex) {
checkNotNull(groupRegex, "Group cannot be null");
addInclude(groupRegex, null, null, true);
}
@Override
public void includeModule(String group, String moduleName) {
checkNotNull(group, "Group cannot be null");
checkNotNull(moduleName, "Module name cannot be null");
addInclude(group, moduleName, null, false);
}
@Override
public void includeModuleByRegex(String groupRegex, String moduleNameRegex) {
checkNotNull(groupRegex, "Group cannot be null");
checkNotNull(moduleNameRegex, "Module name cannot be null");
addInclude(groupRegex, moduleNameRegex, null, true);
}
@Override
public void includeVersion(String group, String moduleName, String version) {
checkNotNull(group, "Group cannot be null");
checkNotNull(moduleName, "Module name cannot be null");
checkNotNull(version, "Version cannot be null");
addInclude(group, moduleName, version, false);
}
@Override
public void includeVersionByRegex(String groupRegex, String moduleNameRegex, String versionRegex) {
checkNotNull(groupRegex, "Group cannot be null");
checkNotNull(moduleNameRegex, "Module name cannot be null");
checkNotNull(versionRegex, "Version cannot be null");
addInclude(groupRegex, moduleNameRegex, versionRegex, true);
}
private void addInclude(String group, @Nullable String moduleName, @Nullable String version, boolean regex) {
assertMutable();
if (includeSpecs == null) {
includeSpecs = Sets.newHashSet();
}
includeSpecs.add(new ContentSpec(regex, group, moduleName, version, versionSelectorScheme, versionSelectors, true));
}
@Override
public void excludeGroup(String group) {
checkNotNull(group, "Group cannot be null");
addExclude(group, null, null, false);
}
@Override
public void excludeGroupByRegex(String groupRegex) {
checkNotNull(groupRegex, "Group cannot be null");
addExclude(groupRegex, null, null, true);
}
@Override
public void excludeModule(String group, String moduleName) {
checkNotNull(group, "Group cannot be null");
checkNotNull(moduleName, "Module name cannot be null");
addExclude(group, moduleName, null, false);
}
@Override
public void excludeModuleByRegex(String groupRegex, String moduleNameRegex) {
checkNotNull(groupRegex, "Group cannot be null");
checkNotNull(moduleNameRegex, "Module name cannot be null");
addExclude(groupRegex, moduleNameRegex, null, true);
}
@Override
public void excludeVersion(String group, String moduleName, String version) {
checkNotNull(group, "Group cannot be null");
checkNotNull(moduleName, "Module name cannot be null");
checkNotNull(version, "Version cannot be null");
addExclude(group, moduleName, version, false);
}
@Override
public void excludeVersionByRegex(String groupRegex, String moduleNameRegex, String versionRegex) {
checkNotNull(groupRegex, "Group cannot be null");
checkNotNull(moduleNameRegex, "Module name cannot be null");
checkNotNull(versionRegex, "Version cannot be null");
addExclude(groupRegex, moduleNameRegex, versionRegex, true);
}
private void addExclude(String group, @Nullable String moduleName, @Nullable String version, boolean regex) {
assertMutable();
if (excludeSpecs == null) {
excludeSpecs = Sets.newHashSet();
}
excludeSpecs.add(new ContentSpec(regex, group, moduleName, version, versionSelectorScheme, versionSelectors, false));
}
@Override
public void onlyForConfigurations(String... configurationNames) {
if (includedConfigurations == null) {
includedConfigurations = Sets.newHashSet();
}
Collections.addAll(includedConfigurations, configurationNames);
}
@Override
public void notForConfigurations(String... configurationNames) {
if (excludedConfigurations == null) {
excludedConfigurations = Sets.newHashSet();
}
Collections.addAll(excludedConfigurations, configurationNames);
}
@Override
@SuppressWarnings("unchecked")
public <T> void onlyForAttribute(Attribute<T> attribute, T... validValues) {
if (requiredAttributes == null) {
requiredAttributes = Maps.newHashMap();
}
requiredAttributes.put(Cast.uncheckedCast(attribute), ImmutableSet.copyOf(validValues));
}
Supplier<String> getRepositoryNameSupplier() {
return repositoryNameSupplier;
}
@Nullable
Set<String> getIncludedConfigurations() {
return includedConfigurations;
}
void setIncludedConfigurations(@Nullable Set<String> includedConfigurations) {
this.includedConfigurations = includedConfigurations;
}
@Nullable
Set<String> getExcludedConfigurations() {
return excludedConfigurations;
}
void setExcludedConfigurations(@Nullable Set<String> excludedConfigurations) {
this.excludedConfigurations = excludedConfigurations;
}
@Nullable
Set<ContentSpec> getIncludeSpecs() {
return includeSpecs;
}
void setIncludeSpecs(@Nullable Set<ContentSpec> includeSpecs) {
this.includeSpecs = includeSpecs;
}
@Nullable
Set<ContentSpec> getExcludeSpecs() {
return excludeSpecs;
}
void setExcludeSpecs(@Nullable Set<ContentSpec> excludeSpecs) {
this.excludeSpecs = excludeSpecs;
}
@Nullable
Map<Attribute<Object>, Set<Object>> getRequiredAttributes() {
return requiredAttributes;
}
void setRequiredAttributes(@Nullable Map<Attribute<Object>, Set<Object>> requiredAttributes) {
this.requiredAttributes = requiredAttributes;
}
private static class ContentSpec {
private final boolean regex;
private final String group;
private final String module;
private final String version;
private final VersionSelectorScheme versionSelectorScheme;
private final ConcurrentHashMap<String, VersionSelector> versionSelectors;
private final boolean inclusive;
private final int hashCode;
private ContentSpec(boolean regex, String group, @Nullable String module, @Nullable String version, VersionSelectorScheme versionSelectorScheme, ConcurrentHashMap<String, VersionSelector> versionSelectors, boolean inclusive) {
this.regex = regex;
this.group = group;
this.module = module;
this.version = version;
this.versionSelectorScheme = versionSelectorScheme;
this.versionSelectors = versionSelectors;
this.inclusive = inclusive;
this.hashCode = Objects.hashCode(regex, group, module, version, inclusive);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ContentSpec that = (ContentSpec) o;
return regex == that.regex &&
hashCode == that.hashCode &&
Objects.equal(group, that.group) &&
Objects.equal(module, that.module) &&
Objects.equal(version, that.version) &&
Objects.equal(inclusive, that.inclusive);
}
@Override
public int hashCode() {
return hashCode;
}
SpecMatcher toMatcher() {
if (regex) {
return new PatternSpecMatcher(group, module, version, inclusive);
}
return new SimpleSpecMatcher(group, module, version, versionSelectorScheme, versionSelectors, inclusive);
}
}
private interface SpecMatcher {
boolean matches(ModuleIdentifier id);
boolean matches(ModuleComponentIdentifier id);
}
private static class SimpleSpecMatcher implements SpecMatcher {
private final String group;
private final String module;
private final String version;
private final VersionSelector versionSelector;
private final boolean inclusive;
private SimpleSpecMatcher(String group, @Nullable String module, @Nullable String version, VersionSelectorScheme versionSelectorScheme, ConcurrentHashMap<String, VersionSelector> versionSelectors, boolean inclusive) {
this.group = group;
this.module = module;
this.version = version;
this.inclusive = inclusive;
this.versionSelector = getVersionSelector(versionSelectors, versionSelectorScheme, version);
}
@Override
public boolean matches(ModuleIdentifier id) {
return group.equals(id.getGroup())
&& (module == null || module.equals(id.getName()))
&& (inclusive || version == null);
}
@Override
public boolean matches(ModuleComponentIdentifier id) {
return group.equals(id.getGroup())
&& (module == null || module.equals(id.getModule()))
&& (version == null || version.equals(id.getVersion()) || versionSelector.accept(id.getVersion()));
}
@Nullable
private VersionSelector getVersionSelector(ConcurrentHashMap<String, VersionSelector> versionSelectors, VersionSelectorScheme versionSelectorScheme, @Nullable String version) {
return version != null ? versionSelectors.computeIfAbsent(version, s -> versionSelectorScheme.parseSelector(version)) : null;
}
}
private static class PatternSpecMatcher implements SpecMatcher {
private final Pattern groupPattern;
private final Pattern modulePattern;
private final Pattern versionPattern;
private final boolean inclusive;
private PatternSpecMatcher(String group, @Nullable String module, @Nullable String version, boolean inclusive) {
this.groupPattern = Pattern.compile(group);
this.modulePattern = module == null ? null : Pattern.compile(module);
this.versionPattern = version == null ? null : Pattern.compile(version);
this.inclusive = inclusive;
}
@Override
public boolean matches(ModuleIdentifier id) {
return groupPattern.matcher(id.getGroup()).matches()
&& (modulePattern == null || modulePattern.matcher(id.getName()).matches())
&& (inclusive || versionPattern == null);
}
@Override
public boolean matches(ModuleComponentIdentifier id) {
return groupPattern.matcher(id.getGroup()).matches()
&& (modulePattern == null || modulePattern.matcher(id.getModule()).matches())
&& (versionPattern == null || versionPattern.matcher(id.getVersion()).matches());
}
}
private class RepositoryFilterAction implements Action<ArtifactResolutionDetails> {
private final ImmutableList<SpecMatcher> includeMatchers;
private final ImmutableList<SpecMatcher> excludeMatchers;
public RepositoryFilterAction(@Nullable ImmutableList<SpecMatcher> includeMatchers, @Nullable ImmutableList<SpecMatcher> excludeMatchers) {
this.includeMatchers = includeMatchers;
this.excludeMatchers = excludeMatchers;
}
@Override
public void execute(ArtifactResolutionDetails details) {
if (includedConfigurations != null && !includedConfigurations.contains(details.getConsumerName())) {
details.notFound();
return;
}
if (excludedConfigurations != null && excludedConfigurations.contains(details.getConsumerName())) {
details.notFound();
return;
}
if (includeMatchers != null && !anyMatch(includeMatchers, details)) {
details.notFound();
return;
}
if (excludeMatchers != null && anyMatch(excludeMatchers, details)) {
details.notFound();
return;
}
if (anyAttributesExcludes(details)) {
details.notFound();
}
}
private boolean anyAttributesExcludes(ArtifactResolutionDetails details) {
if (requiredAttributes != null) {
AttributeContainer consumerAttributes = details.getConsumerAttributes();
for (Map.Entry<Attribute<Object>, Set<Object>> entry : requiredAttributes.entrySet()) {
Attribute<Object> key = entry.getKey();
Set<Object> allowedValues = entry.getValue();
Object value = consumerAttributes.getAttribute(key);
if (!allowedValues.contains(value)) {
return true;
}
}
}
return false;
}
private boolean anyMatch(ImmutableList<SpecMatcher> matchers, ArtifactResolutionDetails details) {
for (SpecMatcher matcher : matchers) {
boolean matches;
if (details.isVersionListing()) {
matches = matcher.matches(details.getModuleId());
} else {
matches = matcher.matches(details.getComponentId());
}
if (matches) {
return true;
}
}
return false;
}
}
}
| 39.48073 | 234 | 0.659525 |
716a03329474c1a66a5a36473fb4d163159a8dc0
| 3,267 |
//This package contains all the libraries we need to program the FTC Robot Controller
package org.firstinspires.ftc.teamcode;
//Import all the classes we will need
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;/*
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DigitalChannel;
import com.qualcomm.robotcore.hardware.Servo;*/
//TeleOp stands for the driver controlled portion of the robot game
//@TeleOp adds the program to the TeleOp section of the Robot Controller App with the name "DemoTeleOp"
@TeleOp(name = "DemoTeleOp")
//There are two types of OpModes, OpMode and LinearOpMode. We use LinearOpMode.
public class DemoTeleOp extends LinearOpMode {
//Here, we initialize the motors we are using in the demonstration
private DcMotor motorOne;
private DcMotor motorTwo;
/*private DcMotor motorThree;
private DcMotor motorFour;
//Initialize a servo
private Servo servoOne;
//Initialize a Continuous Rotation Servo. CRServos behave similar to motors
private CRServo servoTwo;
//Initialize a touch sensor. Touch sensors are DigitalChannel devices
private DigitalChannel touchSensor;*/
//Overrides the method runOpMode from superclass LinearOpMode
@Override
//runOpMode() is the function that is run when the program is initialized by the user
//InterruptedException allows for the program to stop when stop is pressed
public void runOpMode()throws InterruptedException{
//Define all our motors, servos, and sensors using the hardware map created by our configuration
motorOne = hardwareMap.dcMotor.get("motorOne");
motorTwo = hardwareMap.dcMotor.get("motorTwo");
/*motorThree = hardwareMap.dcMotor.get("motorThree");
motorFour = hardwareMap.dcMotor.get("motorFour");
servoOne = hardwareMap.servo.get("servoOne");
servoTwo = hardwareMap.crservo.get("servoTwo");
touchSensor = hardwareMap.digitalChannel.get("touchSensor");
//Reverse motorThree
motorThree.setDirection(DcMotor.Direction.REVERSE);
//Motors can run to a position using the motor encoders. First, set the motor to run to position mode
//and then reset the encoder for accuracy
motorFour.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motorFour.setMode(DcMotor.RunMode.RUN_TO_POSITION);*/
//Telemetry is useful for adding information to the printout on the app
//First, data must be added to the telemetry log
telemetry.addData("Status", "Ready");
//Push telemetry data to be displayed
telemetry.update();
//Wait until start is pressed by the user
waitForStart();/*
//Set the power motorFour will run at and keep it in the start position
motorFour.setPower(1);
motorFour.setTargetPosition(0);*/
//This loop will keep running until stop is pressed. Everything that happens during the run will be in this loop
while(opModeIsActive()){
motorOne.setPower(gamepad1.left_stick_y);
motorTwo.setPower(gamepad1.right_stick_y);
}
}
}
| 41.35443 | 120 | 0.725742 |
dfbf46adeb8ca8a2105f473394f1ee3157f7c2f0
| 1,662 |
package com.github.gianlucanitti.javaexpreval;
import junit.framework.TestCase;
public class ExpressionListTest extends TestCase{
public void testAdd(){
ExpressionList expList = new ExpressionList();
try{
expList.addItem(new ConstExpression(1));
}catch(Exception ex){
fail(ex.getMessage());
}
try{
expList.addOperator('+');
}catch(Exception ex){
fail(ex.getMessage());
}
try{
expList.addItem(new ConstExpression(2));
}catch(Exception ex){
fail(ex.getMessage());
}
try{
expList.addItem(new ConstExpression(1));
fail("ExpressionList.addItem is allowing insertion of invalid tokens");
}catch(Exception ex){
assertTrue(ex instanceof UnexpectedTokenException);
}
}
public void testSimplify(){
try{
ExpressionList expList = new ExpressionList();
expList.addItem(new ConstExpression(5));
expList.addOperator('+');
expList.addItem(new ConstExpression(3));
expList.addOperator('*');
expList.addItem(new ConstExpression(2));
expList.addOperator('^');
expList.addItem(new BinaryOpExpression(new ConstExpression(3), '+', new ConstExpression(1)));
assertEquals(53.0, expList.simplify().eval());
}catch(Exception ex){
fail(ex.getMessage());
}
try{
ExpressionList expList = new ExpressionList();
expList.addItem(new ConstExpression(1));
expList.addOperator('/');
expList.simplify();
fail("An invalid expression list doesn't throw an exception when simplified.");
}catch(Exception ex){
assertTrue(ex instanceof ExpressionException);
}
}
}
| 28.655172 | 99 | 0.659446 |
1ce63714aa75d67b0f95076c26fb5e91973c4b06
| 1,455 |
package net.gudenau.minecraft.redstoneplus.client;
import net.minecraft.block.BlockState;
import net.minecraft.block.RedstoneWireBlock;
import net.minecraft.client.color.block.BlockColorProvider;
import net.minecraft.util.DyeColor;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.ExtendedBlockView;
public class RedstoneWireColor implements BlockColorProvider{
private final float red;
private final float green;
private final float blue;
public RedstoneWireColor(DyeColor color){
float[] rgb = color.getColorComponents();
this.red = rgb[0];
this.green = rgb[1];
this.blue = rgb[2];
}
@Override
public int getColor(BlockState state, ExtendedBlockView blockView, BlockPos position, int tintIndex){
if(!(state.getBlock() instanceof RedstoneWireBlock)){
return 0;
}
int powerLevel = state.get(RedstoneWireBlock.POWER);
float powerPercentage = powerLevel / 15.0F;
float colorIntensity = powerPercentage * 0.6F + 0.4F;
if(powerLevel == 0){
colorIntensity = 0.3F;
}
return 0xff000000 |
MathHelper.clamp((int)(red * colorIntensity * 255.0F), 0, 255) << 16 |
MathHelper.clamp((int)(green * colorIntensity * 255.0F), 0, 255) << 8 |
MathHelper.clamp((int)(blue * colorIntensity * 255.0F), 0, 255);
}
}
| 34.642857 | 105 | 0.670103 |
472db83c5a059aff50644190e59844d4ab766f4c
| 643 |
package com.example.playground.monadic.parser.combinators;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class SeqParserTest {
@Test
public void shouldParseSequenceOfLetters() {
Parser parser = Parsers.seq(Parsers.letter());
assertThat(parser.parse("world"), is(equalTo(Parser.result("world", ""))));
assertThat(parser.parse("World"), is(equalTo(Parser.result("World", ""))));
assertThat(parser.parse("1world"), is(equalTo(Parser.error("Predicate is not satisfied with '1'"))));
}
}
| 33.842105 | 109 | 0.709176 |
83abf1f5c943c9d3d217337f553bdb529213056c
| 292 |
package org.multiverse.stms.gamma.transactions.fat;
public class FatVariableLengthGammaTxn_initTest extends FatGammaTxn_initTest<FatVariableLengthGammaTxn> {
@Override
protected FatVariableLengthGammaTxn newTransaction() {
return new FatVariableLengthGammaTxn(stm);
}
}
| 29.2 | 105 | 0.80137 |
9085cbdc61f125a9541fef6db9f15e4d7663e80f
| 449 |
package ua.com.zno.online.domain.question;
/**
* Created by quento on 02.04.17.
*/
public enum QuestionType {
//radio button question
QUESTION_WITH_ONE_CORRECT_ANSWER,
//checkbox question
QUESTION_WITH_MULTIPLY_CORRECT_ANSWERS,
//question with sub_questions (radio button or checkbox) e.g. many-to-many questions-answers
QUESTION_WITH_SUB_QUESTIONS,
//question type where user must type answer
QUESTION_OPEN
}
| 22.45 | 96 | 0.743875 |
239d6dfea7df2a438f3e490da75e40f91febb6ea
| 305 |
package example2;
import org.noear.solon.SolonBuilder;
/**
* @author noear 2021/7/30 created
*/
public class Example2App {
public static void main(String[] args) {
new SolonBuilder()
.onError(e->e.printStackTrace())
.start(Example2App.class, args);
}
}
| 20.333333 | 48 | 0.613115 |
8eded4e3e7556abc49bfae4d6c0afe59e05257e9
| 3,136 |
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.am.common.event;
/**
* @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
public abstract class Event {
public static Enum valueOf(Type type, Action action) {
Enum event1 = null;
switch (type) {
case DOMAIN:
event1 = DomainEvent.actionOf(action);
break;
case APPLICATION:
event1 = ApplicationEvent.actionOf(action);
break;
case CERTIFICATE:
event1 = CertificateEvent.actionOf(action);
break;
case EXTENSION_GRANT:
event1 = ExtensionGrantEvent.actionOf(action);
break;
case IDENTITY_PROVIDER:
event1 = IdentityProviderEvent.actionOf(action);
break;
case ROLE:
event1 = RoleEvent.actionOf(action);
break;
case SCOPE:
event1 = ScopeEvent.actionOf(action);
break;
case FORM:
event1 = FormEvent.actionOf(action);
break;
case EMAIL:
event1 = EmailEvent.actionOf(action);
break;
case REPORTER:
event1 = ReporterEvent.actionOf(action);
break;
case POLICY:
event1 = PolicyEvent.actionOf(action);
break;
case USER:
event1 = UserEvent.actionOf(action);
break;
case GROUP:
event1 = GroupEvent.actionOf(action);
break;
case MEMBERSHIP:
event1 = MembershipEvent.actionOf(action);
break;
case FACTOR:
event1 = FactorEvent.actionOf(action);
break;
case FLOW:
event1 = FlowEvent.actionOf(action);
break;
case ALERT_TRIGGER:
event1 = AlertTriggerEvent.actionOf(action);
break;
case ALERT_NOTIFIER:
event1 = AlertNotifierEvent.actionOf(action);
break;
case RESOURCE:
event1 = ResourceEvent.actionOf(action);
break;
case BOT_DETECTION:
event1 = BotDetectionEvent.actionOf(action);
break;
}
return event1;
}
}
| 34.086957 | 75 | 0.537628 |
000f85347a1d26fae03d9e757ecacc796cbe969f
| 700 |
package lee.code.code_820__Short_Encoding_of_Words;
import java.util.*;
import lee.util.*;
/**
*
*
* 820.Short Encoding of Words
*
* difficulty: Medium
* @see https://leetcode.com/problems/short-encoding-of-words/description/
* @see description_820.md
* @Similiar Topics
* @Similiar Problems
* Run solution from Unit Test:
* @see lee.codetest.code_820__Short_Encoding_of_Words.CodeTest
* Run solution from Main Judge Class:
* @see lee.code.code_820__Short_Encoding_of_Words.C820_MainClass
*
*/
/**
testcase:["time", "me", "bell"]
*/
public class MainTest {
public static void main(String[] args) {
//new Solution().minimumLengthEncoding(String[]words);
}
}
| 20.588235 | 73 | 0.707143 |
949173538c315e9ffdbea6fd2ab5c3dbbffd702a
| 2,869 |
package jvm;
/**********************************************************************
* <p>文件名:StrIntern.java </p>
* <p>文件描述:(描述该文件做什么)
* @project_name:test
* @author zengshunyaojava
* @create 2020/3/17 0:55
* @history
* @department:政务事业部
* Copyright ChengDu Funi Cloud Code Technology Development CO.,LTD 2014
* All Rights Reserved.
*/
public class StrIntern {
public static void main(String[] args) {
//一次放开一个多行注释运行
//false,true,true
// String s = new String("1");
// s.intern();//
// String s2 = "1";//常量池中
// System.out.println(s == s2);
// String s3 = new String("1") + new String("1");
// new StringBuilder().append("").toString();
// s3.intern();//
// String s4 = "11";
// System.out.println(s3.intern() == s4);
// System.out.println(s3 == s4);
//false,false,true
// String s = new String("1");
// String s2 = "1";
// s.intern();
// System.out.println(s == s2);
// String s3 = new String("1") + new String("1");
// String s4 = "11";
// s3.intern();
// System.out.println(s3 == s4);
// System.out.println(s3.intern() == s4);
//+连接但编译器不优化
//true,true
// String s1 = new String("xy") + "z";
// String s2 = s1.intern();
// System.out.println(s1 == s1.intern());
// System.out.println(s1 + "-----" + s2);
// System.out.println(s2 == s1.intern());
// 一般情况
//false,false,true
// String s1 = new String("xyz");
// String s2 = s1.intern();
// System.out.println(s1 == s2);
// System.out.println(s1 == s1.intern());
// System.out.println(s1 + " " + s2);
// System.out.println(s2 == s1.intern());
//编译器优化
//true,true
// String s1 = "xy" + "z";
// String s2 = s1.intern();
// System.out.println(s1 == s1.intern());
// System.out.println(s1 + " " + s2);
// System.out.println(s2 == s1.intern());
String str1 = new StringBuilder("i'm").append(" T").toString();
System.out.println(str1.intern() == str1);
//
String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern() == str2);
// 这段代码在JDK1.6中运行,会得到两个false,而在JDK1.7和1.8中运行会得到一个true和一个false。这个差异的原因是:
//
// 在JDK1.6中,intern()方法会把首次遇到的字符串实例复制到永久代中,返回的也是永久代中这个字符串实例的引用,
// 而由StringBuilder创建的字符串实例在Java堆上,所以必然不是同一个引用。
// 而JDK1.7中已经将运行时常量池从永久代移除,在Java 堆(Heap)中开辟了一块区域存放运行时常量池。
// 因此intern()返回的引用和由StringBuilder创建的那个字符串实例是同一个。
// 对 str2的比较返回false是因为“java”这个字符串在执行 StringBuilder.toString()之前已经出现过,
// 字符串常量池中已经有它的引用了,不符合“首次出现”的原则,而“i'm T”这个字符串则是首次出现的,因此返回true。
//
// 链接:https://www.jianshu.com/p/5fdf752efc06
}
}
| 32.235955 | 78 | 0.533287 |
d1dd25158a541480b0c509a763ff09f7a041f235
| 203 |
package me.batizhao.dp.domain;
import lombok.Data;
/**
* @author batizhao
* @date 2021/4/12
*/
@Data
public class Props {
private String value = "value";
private String label = "label";
}
| 12.6875 | 35 | 0.650246 |
d623d7138474088b72e3afd2c245b89d133d2f9f
| 7,480 |
package model.beans;
// Generated 23/11/2020 16:41:25 by Hibernate Tools 4.3.1
import java.util.Date;
/**
* Leituras generated by hbm2java
*/
public class Leituras implements java.io.Serializable {
private Long id;
private Clientes clientes;
private Medidores medidores;
private Date mesAno;
private long anterior;
private Long atual;
private double constante;
private Double residuo;
private Long medido;
private Long faturado;
private double tarifaSemTributos;
private double tarifaComTributos;
private long media12meses;
private Date dataVencimento;
private Date dataAnterior;
private Date dataAtual;
private Date dataEmissao;
private Date dataApresentacao;
private Date dataProxima;
private Integer diasConsumo;
private Double total;
private Long consumo;
private Date createdAt;
private Date updatedAt;
public Leituras() {
}
public Leituras(Clientes clientes, Medidores medidores, Date mesAno, long anterior, double constante, double tarifaSemTributos, double tarifaComTributos, long media12meses, Date dataAnterior) {
this.clientes = clientes;
this.medidores = medidores;
this.mesAno = mesAno;
this.anterior = anterior;
this.constante = constante;
this.tarifaSemTributos = tarifaSemTributos;
this.tarifaComTributos = tarifaComTributos;
this.media12meses = media12meses;
this.dataAnterior = dataAnterior;
}
public Leituras(Clientes clientes, Medidores medidores, Date mesAno, long anterior, Long atual, double constante, Double residuo, Long medido, Long faturado, double tarifaSemTributos, double tarifaComTributos, long media12meses, Date dataVencimento, Date dataAnterior, Date dataAtual, Date dataEmissao, Date dataApresentacao, Date dataProxima, Integer diasConsumo, Double total, Long consumo, Date createdAt, Date updatedAt) {
this.clientes = clientes;
this.medidores = medidores;
this.mesAno = mesAno;
this.anterior = anterior;
this.atual = atual;
this.constante = constante;
this.residuo = residuo;
this.medido = medido;
this.faturado = faturado;
this.tarifaSemTributos = tarifaSemTributos;
this.tarifaComTributos = tarifaComTributos;
this.media12meses = media12meses;
this.dataVencimento = dataVencimento;
this.dataAnterior = dataAnterior;
this.dataAtual = dataAtual;
this.dataEmissao = dataEmissao;
this.dataApresentacao = dataApresentacao;
this.dataProxima = dataProxima;
this.diasConsumo = diasConsumo;
this.total = total;
this.consumo = consumo;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public Leituras(Clientes cliente, Medidores medidor, Date mesAno, long anterior, double constante, double residuo, double tarifaSemTributos, double tarifaComTributos, long media12Meses, Date dataAnterior) {
this.clientes = cliente;
this.medidores = medidor;
this.mesAno = mesAno;
this.anterior = anterior;
this.constante = constante;
this.residuo = residuo;
this.tarifaSemTributos = tarifaSemTributos;
this.tarifaComTributos = tarifaComTributos;
this.media12meses= media12Meses;
this.dataAnterior = dataAnterior;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Clientes getClientes() {
return this.clientes;
}
public void setClientes(Clientes clientes) {
this.clientes = clientes;
}
public Medidores getMedidores() {
return this.medidores;
}
public void setMedidores(Medidores medidores) {
this.medidores = medidores;
}
public Date getMesAno() {
return this.mesAno;
}
public void setMesAno(Date mesAno) {
this.mesAno = mesAno;
}
public long getAnterior() {
return this.anterior;
}
public void setAnterior(long anterior) {
this.anterior = anterior;
}
public Long getAtual() {
return this.atual;
}
public void setAtual(Long atual) {
this.atual = atual;
}
public double getConstante() {
return this.constante;
}
public void setConstante(double constante) {
this.constante = constante;
}
public Double getResiduo() {
return this.residuo;
}
public void setResiduo(Double residuo) {
this.residuo = residuo;
}
public Long getMedido() {
return this.medido;
}
public void setMedido(Long medido) {
this.medido = medido;
}
public Long getFaturado() {
return this.faturado;
}
public void setFaturado(Long faturado) {
this.faturado = faturado;
}
public double getTarifaSemTributos() {
return this.tarifaSemTributos;
}
public void setTarifaSemTributos(double tarifaSemTributos) {
this.tarifaSemTributos = tarifaSemTributos;
}
public double getTarifaComTributos() {
return this.tarifaComTributos;
}
public void setTarifaComTributos(double tarifaComTributos) {
this.tarifaComTributos = tarifaComTributos;
}
public long getMedia12meses() {
return this.media12meses;
}
public void setMedia12meses(long media12meses) {
this.media12meses = media12meses;
}
public Date getDataVencimento() {
return this.dataVencimento;
}
public void setDataVencimento(Date dataVencimento) {
this.dataVencimento = dataVencimento;
}
public Date getDataAnterior() {
return this.dataAnterior;
}
public void setDataAnterior(Date dataAnterior) {
this.dataAnterior = dataAnterior;
}
public Date getDataAtual() {
return this.dataAtual;
}
public void setDataAtual(Date dataAtual) {
this.dataAtual = dataAtual;
}
public Date getDataEmissao() {
return this.dataEmissao;
}
public void setDataEmissao(Date dataEmissao) {
this.dataEmissao = dataEmissao;
}
public Date getDataApresentacao() {
return this.dataApresentacao;
}
public void setDataApresentacao(Date dataApresentacao) {
this.dataApresentacao = dataApresentacao;
}
public Date getDataProxima() {
return this.dataProxima;
}
public void setDataProxima(Date dataProxima) {
this.dataProxima = dataProxima;
}
public Integer getDiasConsumo() {
return this.diasConsumo;
}
public void setDiasConsumo(Integer diasConsumo) {
this.diasConsumo = diasConsumo;
}
public Double getTotal() {
return this.total;
}
public void setTotal(Double total) {
this.total = total;
}
public Long getConsumo() {
return this.consumo;
}
public void setConsumo(Long consumo) {
this.consumo = consumo;
}
public Date getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return this.updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
| 28.014981 | 430 | 0.649733 |
08a3c47ee33f7f43a0140d63ac6fb433ae80b05b
| 3,992 |
/*
* Copyright 2019-2020 StreamThoughts.
*
* 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 io.streamthoughts.kafka.connect.filepulse.filter;
import io.streamthoughts.kafka.connect.filepulse.config.DateFilterConfig;
import io.streamthoughts.kafka.connect.filepulse.data.TypedStruct;
import io.streamthoughts.kafka.connect.filepulse.source.FileRecordOffset;
import io.streamthoughts.kafka.connect.filepulse.source.SourceMetadata;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DateFilterTest {
private DateFilter filter;
private FilterContext context;
private Map<String, Object> configs;
@Before
public void setUp() {
filter = new DateFilter();
configs = new HashMap<>();
context = FilterContextBuilder.newBuilder()
.withMetadata(new SourceMetadata("", "", 0L, 0L, 0L, -1L))
.withOffset(FileRecordOffset.invalid())
.build();
}
@Test
public void shouldConvertToEpochTimeGivenNoTimezoneAndNoLocale() {
configs.put(DateFilterConfig.DATE_FIELD_CONFIG, "$.date");
configs.put(DateFilterConfig.DATE_TARGET_CONFIG, "$.timestamp");
configs.put(DateFilterConfig.DATE_FORMATS_CONFIG, Collections.singletonList("yyyy-MM-dd'T'HH:mm:ss"));
filter.configure(configs);
TypedStruct struct = TypedStruct.create().put("date", "2001-07-04T12:08:56");
List<TypedStruct> results = filter.apply(context, struct, false).collect();
TypedStruct record = results.get(0);
Assert.assertEquals(994248536000L, record.getLong("timestamp").longValue());
}
@Test
public void shouldConvertToEpochTimeGivenTimezone() {
configs.put(DateFilterConfig.DATE_FIELD_CONFIG, "$.date");
configs.put(DateFilterConfig.DATE_TARGET_CONFIG, "$.timestamp");
configs.put(DateFilterConfig.DATE_TIMEZONE_CONFIG, "Europe/Paris");
configs.put(DateFilterConfig.DATE_FORMATS_CONFIG, Collections.singletonList("yyyy-MM-dd'T'HH:mm:ss"));
filter.configure(configs);
TypedStruct struct = TypedStruct.create().put("date", "2001-07-04T14:08:56");
List<TypedStruct> results = filter.apply(context, struct, false).collect();
TypedStruct record = results.get(0);
Assert.assertEquals(994248536000L, record.getLong("timestamp").longValue());
}
@Test
public void shouldConvertToEpochTimeGivenLocale() {
configs.put(DateFilterConfig.DATE_FIELD_CONFIG, "$.date");
configs.put(DateFilterConfig.DATE_TARGET_CONFIG, "$.timestamp");
configs.put(DateFilterConfig.DATE_LOCALE_CONFIG, "fr_FR");
configs.put(DateFilterConfig.DATE_FORMATS_CONFIG, Collections.singletonList("EEEE, d MMMM yyyy HH:mm:ss"));
filter.configure(configs);
TypedStruct struct = TypedStruct.create().put("date", "mercredi, 4 juillet 2001 12:08:56");
List<TypedStruct> results = filter.apply(context, struct, false).collect();
TypedStruct record = results.get(0);
Assert.assertEquals(994248536000L, record.getLong("timestamp").longValue());
}
}
| 41.154639 | 115 | 0.717936 |
50e12adbdb4e1edcc7d311ee5d1f7eb24d16d9b0
| 3,075 |
/*
* 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.vishnu.Calc.IO;
/**
* Easily manipulate the XML by the functions
*
* @author Vishnu
* @version 1.0
*
*/
public class XmlData {
private String xmlDatas = "";
private String xmlVariables = "";
/**
* Used to insert the value
*
* @param variable the value to set the value
* @param value the value for value
*
*/
public void putXMLData(String variable, String value) {
xmlDatas = xmlDatas + "<" + variable + ">" + value + "</" + variable + ">" + "\n";
xmlVariables = xmlVariables + variable + "~";
}
/**
* Used to insert the value for multiple variable
*
* @param variable the value to set the value in array
* @param value the value for value
*
*/
public void putXMLData(String[] variable, String value) {
for (String variable1 : variable) {
putXMLData(variable1, value);
}
}
/**
* used to get the particular data in the element
*
* @param variable get the data of variable
* @return the value as string
*/
public String getXMLData(String variable) {
if (xmlDatas.contains("<" + variable + ">")) {
return xmlDatas.substring(xmlDatas.lastIndexOf("<" + variable + ">") + variable.length() + 2, xmlDatas.lastIndexOf("</" + variable + ">"));
}
return "";
}
/**
* check whether the data is present
*
* @param variable is the element name to find
* @return isPresent or not
*/
public boolean isXMLPresent(String variable) {
if (xmlDatas.contains("<" + variable + ">")) {
return true;
}
return false;
}
/**
*
* @return the XML datas
*/
public String printXML() {
return xmlDatas.trim();
}
/**
*
* @return the XMl elements
*/
public String[] getXMLVariables() {
return xmlVariables.split("~");
}
/**
*
* @return count the XML element number
*/
public int getXMLCount() {
return xmlVariables.split("~").length;
}
/**
* Returns the value present in the elements
*
* @param value the input to get elements
* @return the elements
*
*/
public String[] getValuesInElement(String value) {
String values[] = xmlDatas.split("\n"), temps = "";
for (int i = 0; i < values.length; i++) {
if (values[i].contains(">" + value + "</")) {
temps = temps + values[i] + "~";
}
}
return temps.split("~");
}
/**
* Returns the count of the value present in the elements
*
* @param value the input to get elements
* @return the elements count
*
*/
public int getValuesInElementCount(String value) {
return getValuesInElement(value).length;
}
}
| 24.798387 | 151 | 0.556098 |
1f49e60ddcee2c9c534ed8b0f5e60c39b4858b57
| 1,561 |
package com.github.marivaldosena.casadocodigo.autores;
import com.github.marivaldosena.casadocodigo.livros.Livro;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "autores")
public class Autor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 120)
private String nome;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false, length = 400)
private String descricao;
@Column(nullable = false)
private LocalDateTime instante;
@OneToMany(mappedBy = "autor")
private List<Livro> livros;
/**
* @deprecated Hibernate only.
*/
public Autor() {
}
/**
*
* @param nome Nome do autor.
* @param email E-mail principal.
* @param descricao Breve descrição.
*/
public Autor(String nome, String email, String descricao) {
this.nome = nome;
this.email = email;
this.descricao = descricao;
this.instante = LocalDateTime.now();
this.livros = new ArrayList<>();
}
public Long getId() {
return id;
}
public String getNome() {
return nome;
}
public String getEmail() {
return email;
}
public String getDescricao() {
return descricao;
}
public LocalDateTime getInstante() {
return instante;
}
public List<Livro> getLivros() {
return livros;
}
}
| 20.539474 | 63 | 0.622678 |
a7539b6794810f8166bde1b862bc47d9cca1176b
| 602 |
package com.br.zup.academy.lais.proposta.SistemFinanceiro;
public class AvaliacaoRespose {
public String documento;
public String nome;
public String idProposta;
public StatusAnalise resultadoSolicitacao;
public AvaliacaoRespose(String documento, String nome, String idProposta, StatusAnalise resultadoSolicitacao) {
this.documento = documento;
this.nome = nome;
this.idProposta = idProposta;
this.resultadoSolicitacao = resultadoSolicitacao;
}
public StatusAnalise getResultadoSolicitacao() {
return resultadoSolicitacao;
}
}
| 30.1 | 115 | 0.732558 |
d0255f3572f7926285ad2fab0adf85bc46fbe213
| 40,035 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.admin.cts;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.UserManager;
import android.provider.Settings;
import android.test.AndroidTestCase;
import android.util.Log;
import java.util.List;
import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
/**
* Test that exercises {@link DevicePolicyManager}. The test requires that the
* CtsDeviceAdminReceiver be installed via the CtsDeviceAdmin.apk and be
* activated via "Settings > Location & security > Select device administrators".
*/
public class DevicePolicyManagerTest extends AndroidTestCase {
private static final String TAG = DevicePolicyManagerTest.class.getSimpleName();
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mComponent;
private ComponentName mSecondComponent;
private boolean mDeviceAdmin;
private static final String TEST_CA_STRING1 =
"-----BEGIN CERTIFICATE-----\n" +
"MIICVzCCAgGgAwIBAgIJAMvnLHnnfO/IMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
"VQQGEwJJTjELMAkGA1UECAwCQVAxDDAKBgNVBAcMA0hZRDEVMBMGA1UECgwMSU1G\n" +
"TCBQVlQgTFREMRAwDgYDVQQLDAdJTUZMIE9VMRIwEAYDVQQDDAlJTUZMLklORk8x\n" +
"HzAdBgkqhkiG9w0BCQEWEHJhbWVzaEBpbWZsLmluZm8wHhcNMTMwODI4MDk0NDA5\n" +
"WhcNMjMwODI2MDk0NDA5WjCBhjELMAkGA1UEBhMCSU4xCzAJBgNVBAgMAkFQMQww\n" +
"CgYDVQQHDANIWUQxFTATBgNVBAoMDElNRkwgUFZUIExURDEQMA4GA1UECwwHSU1G\n" +
"TCBPVTESMBAGA1UEAwwJSU1GTC5JTkZPMR8wHQYJKoZIhvcNAQkBFhByYW1lc2hA\n" +
"aW1mbC5pbmZvMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ738cbTQlNIO7O6nV/f\n" +
"DJTMvWbPkyHYX8CQ7yXiAzEiZ5bzKJjDJmpRAkUrVinljKns2l6C4++l/5A7pFOO\n" +
"33kCAwEAAaNQME4wHQYDVR0OBBYEFOdbZP7LaMbgeZYPuds2CeSonmYxMB8GA1Ud\n" +
"IwQYMBaAFOdbZP7LaMbgeZYPuds2CeSonmYxMAwGA1UdEwQFMAMBAf8wDQYJKoZI\n" +
"hvcNAQEFBQADQQBdrk6J9koyylMtl/zRfiMAc2zgeC825fgP6421NTxs1rjLs1HG\n" +
"VcUyQ1/e7WQgOaBHi9TefUJi+4PSVSluOXon\n" +
"-----END CERTIFICATE-----";
@Override
protected void setUp() throws Exception {
super.setUp();
mDevicePolicyManager = (DevicePolicyManager)
mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
mComponent = DeviceAdminInfoTest.getReceiverComponent();
mSecondComponent = DeviceAdminInfoTest.getSecondReceiverComponent();
mDeviceAdmin =
mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
setBlankPassword();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
setBlankPassword();
}
private void setBlankPassword() {
if (!mDeviceAdmin) {
return;
}
// Reset the password to nothing for future tests...
mDevicePolicyManager.setPasswordQuality(mComponent,
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 0);
assertTrue(mDevicePolicyManager.resetPassword("", 0));
}
public void testGetActiveAdmins() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testGetActiveAdmins");
return;
}
List<ComponentName> activeAdmins = mDevicePolicyManager.getActiveAdmins();
assertFalse(activeAdmins.isEmpty());
assertTrue(activeAdmins.contains(mComponent));
assertTrue(mDevicePolicyManager.isAdminActive(mComponent));
}
public void testGetMaximumFailedPasswordsForWipe() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testGetMaximumFailedPasswordsForWipe");
return;
}
mDevicePolicyManager.setMaximumFailedPasswordsForWipe(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getMaximumFailedPasswordsForWipe(mComponent));
mDevicePolicyManager.setMaximumFailedPasswordsForWipe(mComponent, 5);
assertEquals(5, mDevicePolicyManager.getMaximumFailedPasswordsForWipe(mComponent));
}
public void testPasswordQuality_something() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_something");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent,
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
assertEquals(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING,
mDevicePolicyManager.getPasswordQuality(mComponent));
assertFalse(mDevicePolicyManager.isActivePasswordSufficient());
assertTrue(mDevicePolicyManager.resetPassword("123", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 10);
assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(mComponent));
assertFalse(mDevicePolicyManager.isActivePasswordSufficient());
assertFalse(mDevicePolicyManager.resetPassword("123", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd123", 0));
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumLength(mComponent));
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
assertTrue(mDevicePolicyManager.resetPassword("123", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
}
public void testPasswordQuality_numeric() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_numeric");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent,
DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
assertEquals(DevicePolicyManager.PASSWORD_QUALITY_NUMERIC,
mDevicePolicyManager.getPasswordQuality(mComponent));
assertFalse(mDevicePolicyManager.isActivePasswordSufficient());
assertTrue(mDevicePolicyManager.resetPassword("123", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 10);
assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(mComponent));
assertFalse(mDevicePolicyManager.isActivePasswordSufficient());
assertFalse(mDevicePolicyManager.resetPassword("123", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd123", 0));
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumLength(mComponent));
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
assertTrue(mDevicePolicyManager.resetPassword("123", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
}
public void testPasswordQuality_alphabetic() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_alphabetic");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent,
DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
assertEquals(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC,
mDevicePolicyManager.getPasswordQuality(mComponent));
assertFalse(mDevicePolicyManager.isActivePasswordSufficient());
assertFalse(mDevicePolicyManager.resetPassword("123", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 10);
assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(mComponent));
assertFalse(mDevicePolicyManager.isActivePasswordSufficient());
assertFalse(mDevicePolicyManager.resetPassword("123", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd123", 0));
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumLength(mComponent));
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
assertFalse(mDevicePolicyManager.resetPassword("123", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
}
public void testPasswordQuality_alphanumeric() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_alphanumeric");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent,
DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC);
assertEquals(DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC,
mDevicePolicyManager.getPasswordQuality(mComponent));
assertFalse(mDevicePolicyManager.isActivePasswordSufficient());
assertFalse(mDevicePolicyManager.resetPassword("123", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 10);
assertEquals(10, mDevicePolicyManager.getPasswordMinimumLength(mComponent));
assertFalse(mDevicePolicyManager.isActivePasswordSufficient());
assertFalse(mDevicePolicyManager.resetPassword("123", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd123", 0));
mDevicePolicyManager.setPasswordMinimumLength(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumLength(mComponent));
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
assertFalse(mDevicePolicyManager.resetPassword("123", 0));
assertFalse(mDevicePolicyManager.resetPassword("abcd", 0));
assertTrue(mDevicePolicyManager.resetPassword("abcd123", 0));
}
public void testPasswordQuality_complexUpperCase() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_complexUpperCase");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
resetComplexPasswordRestrictions();
String caseDescription = "minimum UpperCase=0";
assertPasswordSucceeds("abc", caseDescription);
assertPasswordSucceeds("aBc", caseDescription);
assertPasswordSucceeds("ABC", caseDescription);
assertPasswordSucceeds("ABCD", caseDescription);
mDevicePolicyManager.setPasswordMinimumUpperCase(mComponent, 1);
assertEquals(1, mDevicePolicyManager.getPasswordMinimumUpperCase(mComponent));
caseDescription = "minimum UpperCase=1";
assertPasswordFails("abc", caseDescription);
assertPasswordSucceeds("aBc", caseDescription);
assertPasswordSucceeds("ABC", caseDescription);
assertPasswordSucceeds("ABCD", caseDescription);
mDevicePolicyManager.setPasswordMinimumUpperCase(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumUpperCase(mComponent));
caseDescription = "minimum UpperCase=3";
assertPasswordFails("abc", caseDescription);
assertPasswordFails("aBC", caseDescription);
assertPasswordSucceeds("ABC", caseDescription);
assertPasswordSucceeds("ABCD", caseDescription);
}
public void testPasswordQuality_complexLowerCase() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_complexLowerCase");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
resetComplexPasswordRestrictions();
String caseDescription = "minimum LowerCase=0";
assertPasswordSucceeds("ABCD", caseDescription);
assertPasswordSucceeds("aBC", caseDescription);
assertPasswordSucceeds("abc", caseDescription);
assertPasswordSucceeds("abcd", caseDescription);
mDevicePolicyManager.setPasswordMinimumLowerCase(mComponent, 1);
assertEquals(1, mDevicePolicyManager.getPasswordMinimumLowerCase(mComponent));
caseDescription = "minimum LowerCase=1";
assertPasswordFails("ABCD", caseDescription);
assertPasswordSucceeds("aBC", caseDescription);
assertPasswordSucceeds("abc", caseDescription);
assertPasswordSucceeds("abcd", caseDescription);
mDevicePolicyManager.setPasswordMinimumLowerCase(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumLowerCase(mComponent));
caseDescription = "minimum LowerCase=3";
assertPasswordFails("ABCD", caseDescription);
assertPasswordFails("aBC", caseDescription);
assertPasswordSucceeds("abc", caseDescription);
assertPasswordSucceeds("abcd", caseDescription);
}
public void testPasswordQuality_complexLetters() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_complexLetters");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
resetComplexPasswordRestrictions();
String caseDescription = "minimum Letters=0";
assertPasswordSucceeds("1234", caseDescription);
assertPasswordSucceeds("a23", caseDescription);
assertPasswordSucceeds("abc", caseDescription);
assertPasswordSucceeds("abcd", caseDescription);
mDevicePolicyManager.setPasswordMinimumLetters(mComponent, 1);
assertEquals(1, mDevicePolicyManager.getPasswordMinimumLetters(mComponent));
caseDescription = "minimum Letters=1";
assertPasswordFails("1234", caseDescription);
assertPasswordSucceeds("a23", caseDescription);
assertPasswordSucceeds("abc", caseDescription);
assertPasswordSucceeds("abcd", caseDescription);
mDevicePolicyManager.setPasswordMinimumLetters(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumLetters(mComponent));
caseDescription = "minimum Letters=3";
assertPasswordFails("1234", caseDescription);
assertPasswordFails("a23", caseDescription);
assertPasswordSucceeds("abc", caseDescription);
assertPasswordSucceeds("abcd", caseDescription);
}
public void testPasswordQuality_complexNumeric() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_complexNumeric");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
resetComplexPasswordRestrictions();
String caseDescription = "minimum Numeric=0";
assertPasswordSucceeds("abcd", caseDescription);
assertPasswordSucceeds("1bc", caseDescription);
assertPasswordSucceeds("123", caseDescription);
assertPasswordSucceeds("1234", caseDescription);
mDevicePolicyManager.setPasswordMinimumNumeric(mComponent, 1);
assertEquals(1, mDevicePolicyManager.getPasswordMinimumNumeric(mComponent));
caseDescription = "minimum Numeric=1";
assertPasswordFails("abcd", caseDescription);
assertPasswordSucceeds("1bc", caseDescription);
assertPasswordSucceeds("123", caseDescription);
assertPasswordSucceeds("1234", caseDescription);
mDevicePolicyManager.setPasswordMinimumNumeric(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumNumeric(mComponent));
caseDescription = "minimum Numeric=3";
assertPasswordFails("abcd", caseDescription);
assertPasswordFails("1bc", caseDescription);
assertPasswordSucceeds("123", caseDescription);
assertPasswordSucceeds("1234", caseDescription);
}
public void testPasswordQuality_complexSymbols() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_complexSymbols");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
resetComplexPasswordRestrictions();
String caseDescription = "minimum Symbols=0";
assertPasswordSucceeds("abcd", caseDescription);
assertPasswordSucceeds("_bc", caseDescription);
assertPasswordSucceeds("@#!", caseDescription);
assertPasswordSucceeds("_@#!", caseDescription);
mDevicePolicyManager.setPasswordMinimumSymbols(mComponent, 1);
assertEquals(1, mDevicePolicyManager.getPasswordMinimumSymbols(mComponent));
caseDescription = "minimum Symbols=1";
assertPasswordFails("abcd", caseDescription);
assertPasswordSucceeds("_bc", caseDescription);
assertPasswordSucceeds("@#!", caseDescription);
assertPasswordSucceeds("_@#!", caseDescription);
mDevicePolicyManager.setPasswordMinimumSymbols(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumSymbols(mComponent));
caseDescription = "minimum Symbols=3";
assertPasswordFails("abcd", caseDescription);
assertPasswordFails("_bc", caseDescription);
assertPasswordSucceeds("@#!", caseDescription);
assertPasswordSucceeds("_@#!", caseDescription);
}
public void testPasswordQuality_complexNonLetter() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordQuality_complexNonLetter");
return;
}
mDevicePolicyManager.setPasswordQuality(mComponent, PASSWORD_QUALITY_COMPLEX);
assertEquals(PASSWORD_QUALITY_COMPLEX, mDevicePolicyManager.getPasswordQuality(mComponent));
resetComplexPasswordRestrictions();
String caseDescription = "minimum NonLetter=0";
assertPasswordSucceeds("Abcd", caseDescription);
assertPasswordSucceeds("_bcd", caseDescription);
assertPasswordSucceeds("3bcd", caseDescription);
assertPasswordSucceeds("_@3c", caseDescription);
assertPasswordSucceeds("_25!", caseDescription);
mDevicePolicyManager.setPasswordMinimumNonLetter(mComponent, 1);
assertEquals(1, mDevicePolicyManager.getPasswordMinimumNonLetter(mComponent));
caseDescription = "minimum NonLetter=1";
assertPasswordFails("Abcd", caseDescription);
assertPasswordSucceeds("_bcd", caseDescription);
assertPasswordSucceeds("3bcd", caseDescription);
assertPasswordSucceeds("_@3c", caseDescription);
assertPasswordSucceeds("_25!", caseDescription);
mDevicePolicyManager.setPasswordMinimumNonLetter(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordMinimumNonLetter(mComponent));
caseDescription = "minimum NonLetter=3";
assertPasswordFails("Abcd", caseDescription);
assertPasswordFails("_bcd", caseDescription);
assertPasswordFails("3bcd", caseDescription);
assertPasswordSucceeds("c_@3c", caseDescription);
assertPasswordSucceeds("_25!", caseDescription);
}
public void testPasswordHistoryLength() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordHistoryLength");
return;
}
// Password history length restriction is only imposed if password quality is at least
// numeric.
mDevicePolicyManager.setPasswordQuality(mComponent,
DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
int originalValue = mDevicePolicyManager.getPasswordHistoryLength(mComponent);
try {
mDevicePolicyManager.setPasswordHistoryLength(mComponent, 3);
assertEquals(3, mDevicePolicyManager.getPasswordHistoryLength(mComponent));
// Although it would make sense we cannot test if password history restrictions
// are enforced as DevicePolicyManagerService.resetPassword fails to do so at the
// moment. See b/17707820
} finally {
mDevicePolicyManager.setPasswordHistoryLength(mComponent, originalValue);
}
}
public void testPasswordExpirationTimeout() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testPasswordExpirationTimeout");
return;
}
long originalValue = mDevicePolicyManager.getPasswordExpirationTimeout(mComponent);
try {
for (long testLength : new long[] {
0L, 864000000L /* ten days */, 8640000000L /* 100 days */}) {
mDevicePolicyManager.setPasswordExpirationTimeout(mComponent, testLength);
assertEquals(testLength,
mDevicePolicyManager.getPasswordExpirationTimeout(mComponent));
}
} finally {
mDevicePolicyManager.setPasswordExpirationTimeout(mComponent, originalValue);
}
}
public void testMaximumTimeToLock() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testMaximumTimeToLock");
return;
}
long originalValue = mDevicePolicyManager.getMaximumTimeToLock(mComponent);
try {
for (long testLength : new long[] {
5000L /* 5 sec */, 60000L /* 1 min */, 1800000 /* 30 min */}) {
mDevicePolicyManager.setMaximumTimeToLock(mComponent, testLength);
assertEquals(testLength,
mDevicePolicyManager.getMaximumTimeToLock(mComponent));
}
} finally {
mDevicePolicyManager.setMaximumTimeToLock(mComponent, originalValue);
}
}
public void testCreateUser_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testCreateUser_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.createUser(mComponent, "user name");
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertDeviceOwnerMessage(e.getMessage());
}
}
public void testRemoveUser_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testRemoveUser_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.removeUser(mComponent, null);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertDeviceOwnerMessage(e.getMessage());
}
}
public void testSetApplicationHidden_failIfNotDeviceOrProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetApplicationHidden_failIfNotDeviceOrProfileOwner");
return;
}
try {
mDevicePolicyManager.setApplicationHidden(mComponent, "com.google.anything", true);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testIsApplicationHidden_failIfNotDeviceOrProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testIsApplicationHidden_failIfNotDeviceOrProfileOwner");
return;
}
try {
mDevicePolicyManager.isApplicationHidden(mComponent, "com.google.anything");
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetGlobalSetting_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetGlobalSetting_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.setGlobalSetting(mComponent,
Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, "1");
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertDeviceOwnerMessage(e.getMessage());
}
}
public void testSetSecureSetting_failIfNotDeviceOrProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetSecureSetting_failIfNotDeviceOrProfileOwner");
return;
}
try {
mDevicePolicyManager.setSecureSetting(mComponent,
Settings.Secure.INSTALL_NON_MARKET_APPS, "1");
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetMasterVolumeMuted_failIfNotDeviceOrProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetMasterVolumeMuted_failIfNotDeviceOrProfileOwner");
return;
}
try {
mDevicePolicyManager.setMasterVolumeMuted(mComponent, true);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testIsMasterVolumeMuted_failIfNotDeviceOrProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetMasterVolumeMuted_failIfNotDeviceOrProfileOwner");
return;
}
try {
mDevicePolicyManager.isMasterVolumeMuted(mComponent);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetRecommendedGlobalProxy_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetRecommendedGlobalProxy_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.setRecommendedGlobalProxy(mComponent, null);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertDeviceOwnerMessage(e.getMessage());
}
}
public void testSetLockTaskPackages_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetLockTaskPackages_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.setLockTaskPackages(mComponent, new String[] {"package"});
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
}
}
public void testClearDeviceOwnerApp_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testClearDeviceOwnerApp_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.clearDeviceOwnerApp("android.deviceadmin.cts");
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertDeviceOwnerMessage(e.getMessage());
}
}
public void testSwitchUser_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSwitchUser_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.switchUser(mComponent, null);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertDeviceOwnerMessage(e.getMessage());
}
}
public void testCreateAndInitializeUser_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testCreateAndInitializeUser_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.createAndInitializeUser(mComponent, "name", "admin name",
mComponent, null);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertDeviceOwnerMessage(e.getMessage());
}
}
public void testInstallCaCert_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testInstallCaCert_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.installCaCert(mComponent,
TEST_CA_STRING1.getBytes());
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testUninstallCaCert_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testUninstallCaCert_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.uninstallCaCert(mComponent,
TEST_CA_STRING1.getBytes());
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testGetInstalledCaCerts_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testGetInstalledCaCerts_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.getInstalledCaCerts(mComponent);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testHasCaCertInstalled_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testHasCaCertInstalled_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.hasCaCertInstalled(mComponent,
TEST_CA_STRING1.getBytes());
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testUninstallAllUserCaCerts_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testUninstallAllUserCaCerts_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.uninstallAllUserCaCerts(mComponent);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetScreenCaptureDisabled_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetScreenCaptureDisabled_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.setScreenCaptureDisabled(mComponent, true);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetAutoTimeRequired_failIfNotDeviceOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetAutoTimeRequired_failIfNotDeviceOwner");
return;
}
try {
mDevicePolicyManager.setAutoTimeRequired(mComponent, true);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertDeviceOwnerMessage(e.getMessage());
}
}
public void testAddPersistentPreferredActivity_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testAddPersistentPreferredActivity_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.addPersistentPreferredActivity(mComponent,
new IntentFilter(Intent.ACTION_MAIN),
new ComponentName("android.admin.cts", "dummy"));
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testClearPackagePersistentPreferredActivities_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testClearPackagePersistentPreferredActivities_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.clearPackagePersistentPreferredActivities(mComponent,
"android.admin.cts");
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetApplicationRestrictions_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetApplicationRestrictions_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.setApplicationRestrictions(mComponent,
"android.admin.cts", null);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testAddUserRestriction_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testAddUserRestriction_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.addUserRestriction(mComponent,
UserManager.DISALLOW_SMS);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetAccountManagementDisabled_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetAccountManagementDisabled_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.setAccountManagementDisabled(mComponent,
"dummy", true);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetRestrictionsProvider_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetRestrictionsProvider_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.setRestrictionsProvider(mComponent,
new ComponentName("android.admin.cts", "dummy"));
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetUninstallBlocked_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetUninstallBlocked_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.setUninstallBlocked(mComponent,
"android.admin.cts", true);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetPermittedAccessibilityServices_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetPermittedAccessibilityServices_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.setPermittedAccessibilityServices(mComponent, null);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
public void testSetPermittedInputMethods_failIfNotProfileOwner() {
if (!mDeviceAdmin) {
Log.w(TAG, "Skipping testSetPermittedInputMethods_failIfNotProfileOwner");
return;
}
try {
mDevicePolicyManager.setPermittedInputMethods(mComponent, null);
fail("did not throw expected SecurityException");
} catch (SecurityException e) {
assertProfileOwnerMessage(e.getMessage());
}
}
private void assertDeviceOwnerMessage(String message) {
assertTrue("message is: "+ message, message.contains("does not own the device")
|| message.contains("can only be called by the device owner"));
}
private void assertProfileOwnerMessage(String message) {
assertTrue("message is: "+ message,
message.contains("does not own the profile"));
}
private void resetComplexPasswordRestrictions() {
/**
* Not enough to reset only mComponent as
* {@link DevicePolicyManager#resetPassword(String, int)} checks restrictions across all
* admin components.
*/
for (ComponentName adminComponent : new ComponentName[] {mComponent, mSecondComponent}) {
mDevicePolicyManager.setPasswordMinimumLength(adminComponent, 0);
mDevicePolicyManager.setPasswordMinimumUpperCase(adminComponent, 0);
mDevicePolicyManager.setPasswordMinimumLowerCase(adminComponent, 0);
mDevicePolicyManager.setPasswordMinimumLetters(adminComponent, 0);
mDevicePolicyManager.setPasswordMinimumNumeric(adminComponent, 0);
mDevicePolicyManager.setPasswordMinimumSymbols(adminComponent, 0);
mDevicePolicyManager.setPasswordMinimumNonLetter(adminComponent, 0);
}
}
private void assertPasswordFails(String password, String restriction) {
boolean passwordResetResult = mDevicePolicyManager.resetPassword(password, /* flags= */0);
assertFalse("Password '" + password + "' should have failed on " + restriction,
passwordResetResult);
}
private void assertPasswordSucceeds(String password, String restriction) {
boolean passwordResetResult = mDevicePolicyManager.resetPassword(password, /* flags= */0);
assertTrue("Password '" + password + "' failed on " + restriction, passwordResetResult);
assertTrue(mDevicePolicyManager.isActivePasswordSufficient());
}
}
| 42.772436 | 103 | 0.679855 |
7b372b98b346bf955a2d6c77991f02f7d7305a7f
| 333 |
package ru.otus.hw1.dao;
import org.springframework.core.io.Resource;
import ru.otus.hw1.utils.DataValidationException;
import java.util.List;
public interface Dao<T> {
List<T> getAll();
T getById(int id) throws DataValidationException;
int getCount();
void reloadData(Resource resource);
}
| 17.526316 | 54 | 0.693694 |
af5fc937a675062e5f8a966133ba97eca2750d32
| 43 |
package gr.helix.lab.web.controller.action;
| 43 | 43 | 0.837209 |
d83f332ea5786be463e365a8f5f1099e19e2ed5a
| 3,526 |
/*
* ====================================================================
* StreamEPS Platform
*
* Distributed under the Modified BSD License.
* Copyright notice: The copyright for this software and a full listing
* of individual contributors are as shown in the packaged copyright.txt
* file.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the ORGANIZATION nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* =============================================================================
*/
package org.streameps.aggregation;
import org.streameps.aggregation.collection.HashMapCounter;
import java.util.HashSet;
import java.util.Set;
/**
* It aggregates the most frequent occurring numeric value from a stream of events
* via producers, channels or event processing network.
*
* @author Frank Appiah
*/
public class ModeAggregation implements IAggregation<HashMapCounter, Double> {
private HashMapCounter counter = new HashMapCounter();
private Set<Double> values = new HashSet<Double>();
/**
* It aggregates the value from the stream.
*
* @param cv Value aggregate counter
* @param value Value being aggregated.
*/
public void process(HashMapCounter cv, Double value) {
cv.incrementAt(value);
counter = cv;
values.add(value);
}
/**
* It returns the mode of the aggregation.
*
* @return the mode value
*/
public Double getValue() {
double mode = 0;
long freq = 0;
for (Object v : counter.getMap().keySet()) {
if (Math.max(counter.totalCountByKey(v), freq) > freq) {
freq = Math.max(counter.totalCountByKey(v), freq);
mode = (Double) v;
}
}
return mode;
}
/**
* It resets the aggregated values.
*/
public void reset() {
counter = new HashMapCounter();
values = new HashSet<Double>();
}
public HashMapCounter getBuffer() {
return this.counter;
}
@Override
public String toString() {
return "mode";
}
}
| 35.26 | 82 | 0.658253 |
0c94cea035a4851571f2248d0be6b487df702616
| 343 |
package com.gerenciador.bovino.exception;
public class LoteNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public LoteNotFoundException(String mensagem) {
super(mensagem);
}
public LoteNotFoundException(String mensagem, Throwable causa) {
super(mensagem, causa);
}
}
| 19.055556 | 65 | 0.752187 |
0796421edcf34c3a0cb548dbfa886073be379cc3
| 349 |
package com.lenovo.compass.sys.mapper;
import com.lenovo.compass.sys.entity.SysUserRole;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author suozq
* @since 2021-08-24
*/
@Mapper
public interface SysUserRoleMapper extends BaseMapper<SysUserRole> {
}
| 19.388889 | 68 | 0.744986 |
3c7f2193163ae34811cdee0882c09dbd276c8857
| 595 |
package mage.abilities.mana;
import mage.Mana;
import mage.abilities.effects.mana.BasicManaEffect;
import mage.constants.ColoredManaSymbol;
/**
*
* @author BetaSteward_at_googlemail.com
*/
public class BlackManaAbility extends BasicManaAbility {
public BlackManaAbility() {
super(new BasicManaEffect(Mana.BlackMana(1)));
this.netMana.add(new Mana(ColoredManaSymbol.B));
}
public BlackManaAbility(BlackManaAbility ability) {
super(ability);
}
@Override
public BlackManaAbility copy() {
return new BlackManaAbility(this);
}
}
| 19.833333 | 56 | 0.707563 |
3742630836ad71c766efbf14ba9bec0bf3a87a8f
| 1,749 |
/*-
* ========================LICENSE_START=================================
* JSoagger
* %%
* Copyright (C) 2019 JSOAGGER
* %%
* 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.
* =========================LICENSE_END==================================
*/
package io.github.jsoagger.jfxcore.engine.components.presenter.impl;
import io.github.jsoagger.core.utils.StringUtils;
import io.github.jsoagger.jfxcore.api.IJSoaggerController;
import io.github.jsoagger.jfxcore.api.presenter.ModelEnumeratedValueTranslater;
import io.github.jsoagger.jfxcore.viewdef.json.xml.model.VLViewComponentXML;
/**
* @author Ramilafananana Vonjisoa
* @mailTo yvonjisoa@nexitia.com
* @date 16 févr. 2018
*/
public class DefaultEnumeratedValueTranslater implements ModelEnumeratedValueTranslater {
// needs a translater CoreGeneralMessageSource
// private ResourceBundleMessageSource coreGeneralMessageSource;
/**
* @{inheritedDoc}
*/
@Override
public String translate(IJSoaggerController controller, VLViewComponentXML config, String token) {
if (StringUtils.isNotBlank(token)) {
// return coreGeneralMessageSource.getMessage(token, null, Locale.ENGLISH);
return "Needs translater";
}
return token;
}
}
| 32.388889 | 100 | 0.705546 |
3ea3fc4d320fd4e9b2aa2d830e362c6e4705cdc8
| 11,763 |
/*
* Copyright (C) 1999-2011 University of Connecticut Health Center
*
* Licensed under the MIT License (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.opensource.org/licenses/mit-license.php
*/
package cbit.vcell.VirtualMicroscopy.importer;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
import org.vcell.util.Issue;
import cbit.image.ImageException;
import cbit.vcell.VirtualMicroscopy.ImageDataset;
import cbit.vcell.VirtualMicroscopy.ROI;
import cbit.vcell.VirtualMicroscopy.UShortImage;
/**
*/
public class AnnotatedImageDataset {
private ImageDataset imageDataset = null;
private ArrayList<ROI> rois = new ArrayList<ROI>();
private transient ROI currentlyDisplayedROI = null;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
private String PROPERTY_CHANGE_CURRENTLY_DISPLAYED_ROI_WITH_SAVE = "PROPERTY_CHANGE_CURRENTLY_DISPLAYED_ROI_WITH_SAVE";
private String PROPERTY_CHANGE_CURRENTLY_DISPLAYED_ROI_WITHOUT_SAVE = "PROPERTY_CHANGE_CURRENTLY_DISPLAYED_ROI_WITHOUT_SAVE";
public static enum VFRAP_ROI_ENUM {
ROI_BLEACHED,
ROI_BACKGROUND,
ROI_CELL,
ROI_BLEACHED_RING1,
ROI_BLEACHED_RING2,
ROI_BLEACHED_RING3,
ROI_BLEACHED_RING4,
ROI_BLEACHED_RING5,
ROI_BLEACHED_RING6,
ROI_BLEACHED_RING7,
ROI_BLEACHED_RING8
}
/**
* Constructor for AnnotatedImageDataset.
* @param argImageDataset ImageDataset
* @param argROIs ROI[]
*/
public AnnotatedImageDataset(ImageDataset argImageDataset, ROI[] argROIs) {
// Error checking
if (argImageDataset.getAllImages().length == 0) {
throw new RuntimeException("image dataset is empty");
}
// Now initialize
this.imageDataset = argImageDataset;
rois = new ArrayList<ROI>(Arrays.asList(argROIs));
verifyROIdimensions(imageDataset,rois);
if (rois.size()>0){
setCurrentlyDisplayedROI(rois.get(0));
}
}
/**
* Constructor for AnnotatedImageDataset.
* @param argImageDataset ImageDataset
* @param argROITypes ROI.RoiType[]
*/
public AnnotatedImageDataset(ImageDataset argImageDataset, String[] argROINames) {
// Error checking
if (argImageDataset.getAllImages().length == 0) {
throw new RuntimeException("image dataset is empty");
}
// Now initialize
this.imageDataset = argImageDataset;
rois = new ArrayList<ROI>();
for (int i = 0;argROINames!=null && i < argROINames.length; i++) {
UShortImage[] roiImages = new UShortImage[imageDataset.getSizeZ()];
try {
for (int j = 0; j < roiImages.length; j++) {
roiImages[j] = new UShortImage(imageDataset.getImage(j,0,0));//getImage(z,c,t), it gets a 2D image at z=j
java.util.Arrays.fill(roiImages[j].getPixels(),(short)0);
}
} catch (ImageException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
//comment added in Feb, 2008. Each roi contains images, whoes size equals to size of z slices.
ROI roi = new ROI(roiImages,argROINames[i]);
rois.add(roi);//rois contains different types of roi, 11 types. 3 primary + 8 generated.
}
verifyROIdimensions(imageDataset, rois);
if (rois.size()>0){
setCurrentlyDisplayedROI(rois.get(0));
}
}
/**
* Method verifyROIdimensions.
* @param argImageDataset ImageDataset
* @param argROIs ArrayList<ROI>
*/
private void verifyROIdimensions(ImageDataset argImageDataset, ArrayList<ROI> argROIs){
if (rois!=null){
int imgNumX = argImageDataset.getImage(0,0,0).getNumX();
int imgNumY = argImageDataset.getImage(0,0,0).getNumY();
int imgNumZ = argImageDataset.getSizeZ();
for (int i = 0; i < argROIs.size(); i++) {
UShortImage firstROIImage = argROIs.get(i).getRoiImages()[0];
int roiNumX = firstROIImage.getNumX();
int roiNumY = firstROIImage.getNumY();
int roiNumZ = argROIs.get(i).getRoiImages().length;
if (roiNumX!=imgNumX || roiNumY!=imgNumY || roiNumZ!=imgNumZ){
throw new RuntimeException("ROI size ("+roiNumX+","+roiNumY+","+roiNumZ+") doesn't match image size ("+imgNumX+","+imgNumY+","+imgNumZ+")");
}
}
}
}
/**
* Method getRoi.
* @param roiType RoiType
* @return ROI
*/
public ROI getRoi(String roiName) {
for (int i = 0;i<rois.size(); i++) {
if (rois.get(i).getROIName().equals(roiName)){
return rois.get(i);
}
}
return null;
}
public static short[] collectAllZAtOneTimepointIntoOneArray(ImageDataset sourceImageDataSet,int timeIndex){
short[] collectedPixels = new short[sourceImageDataSet.getISize().getXYZ()];
int pixelIndex = 0;
for (int z = 0; z < sourceImageDataSet.getSizeZ(); z++) {
short[] slicePixels = sourceImageDataSet.getImage(z, 0, timeIndex).getPixels();
System.arraycopy(slicePixels, 0, collectedPixels, pixelIndex, slicePixels.length);
pixelIndex+= slicePixels.length;
}
return collectedPixels;
}
//reorder ROIs according to the order of FRAPData.VFRAP_ROI_ENUM
public static ROI[] reorderROIs(ROI[] origROIs)
{
ROI[] resultROIs = new ROI[origROIs.length];
for(int i=0; i<VFRAP_ROI_ENUM.values().length; i++)
{
for(int j=0; j<origROIs.length; j++)
{
if(VFRAP_ROI_ENUM.values()[i].name().equals(origROIs[j].getROIName()))
{
resultROIs[i] = origROIs[j];
break;
}
}
}
return resultROIs;
}
/**
* Method getAverageUnderROI.
* @param channelIndex int
* @param timeIndex int
* @param roi ROI
* @return double
*/
//average under roi at each time point
public double getAverageUnderROI(int timeIndex, ROI roi,double[] normalizeFactorXYZ,double preNormalizeOffset){
short[] dataArray = AnnotatedImageDataset.collectAllZAtOneTimepointIntoOneArray(imageDataset, timeIndex);
short[] roiArray = roi.getPixelsXYZ();
return AnnotatedImageDataset.getAverageUnderROI(dataArray,roiArray,normalizeFactorXYZ,preNormalizeOffset);
}
//NOTE: the normalized fractor (prebleachaverage) should have background subtracted.
public static double getAverageUnderROI(Object dataArray,short[] roi,double[] normalizeFactorXYZ,double preNormalizeOffset){
if(!(dataArray instanceof short[]) && !(dataArray instanceof double[])){
throw new IllegalArgumentException("getAverageUnderROI: Only short[] and double[] implemented");
}
if(normalizeFactorXYZ == null && preNormalizeOffset != 0){
throw new IllegalArgumentException("preNormalizeOffset must be 0 if normalizeFactorXYZ is null");
}
int arrayLength = Array.getLength(dataArray);
if(normalizeFactorXYZ != null && arrayLength != normalizeFactorXYZ.length){
throw new IllegalArgumentException("Data array length and normalize length do not match");
}
if(roi != null && roi.length != arrayLength){
throw new IllegalArgumentException("Data array length and roi length do not match");
}
double intensityVal = 0.0;
long numPixelsInMask = 0;
// System.out.println("prenormalizeoffset="+preNormalizeOffset);
for (int i = 0; i < arrayLength; i++) {
double imagePixel = (dataArray instanceof short[]?(((short[])dataArray)[i]) & 0x0000FFFF:((double[])dataArray)[i]);
if (roi == null || roi[i] != 0){
if(normalizeFactorXYZ == null){
intensityVal += imagePixel;
}else{
//if pixel value after background subtraction is <=0, clamp it to 0
//the whole image add up 1 after background subtraction
if(((double)imagePixel-preNormalizeOffset) > 0)
{
intensityVal += ((double)imagePixel+1-preNormalizeOffset)/(normalizeFactorXYZ[i]);
}
else
{
intensityVal += 1/(normalizeFactorXYZ[i]);
}
}
numPixelsInMask++;
}
}
if (numPixelsInMask==0){
return 0.0;
}
return intensityVal/numPixelsInMask;
}
/**
* Method getNumRois.
* @return int
*/
public int getNumRois() {
return rois.size();
}
/**
* Method addRoi.
* @param roi ROI
*/
public void addReplaceRoi(ROI roi) {
ROI[] oldROIs = getRois();
rois = new ArrayList<ROI>();
boolean isCurrentlyDisplayed = false;
for (int i = 0; i < oldROIs.length; i++) {
if(!oldROIs[i].getROIName().equals(roi.getROIName())){
rois.add(oldROIs[i]);
}else{
if(currentlyDisplayedROI == oldROIs[i]){
isCurrentlyDisplayed = true;
}
}
}
rois.add(roi);
if(isCurrentlyDisplayed){
setCurrentlyDisplayedROI(roi);
}
//property is not being listened anywhere, commented on 15 Setp, 2009
// propertyChangeSupport.firePropertyChange("rois", oldROIs, newROIs);
}
/**
* Method addPropertyChangeListener.
* @param listener PropertyChangeListener
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
/**
* Method removePropertyChangeListener.
* @param listener PropertyChangeListener
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
/**
* Method getImageDataset.
* @return ImageDataset
*/
public ImageDataset getImageDataset() {
return imageDataset;
}
/**
* Method gatherIssues.
* @param issueList Vector<Issue>
*/
public void gatherIssues(Vector<Issue> issueList) {
}
/**
* This method returns a ROI array of rois.
* In this method, we loop through rois to put rois according to the order of FRAPData.VFRAP_ROI_ENUM
* Please note : Use getROILength() method if simply need the length of rois.
* Create a local variable if need to use getRois() multiple times.
*/
public ROI[] getRois()
{
ROI[] oldROIs = rois.toArray(new ROI[rois.size()]);
return reorderROIs(oldROIs);
}
public int getROILength()
{
return rois.size();
}
/**
* Method getCurrentlyDisplayedROI.
* @return ROI
*/
public ROI getCurrentlyDisplayedROI() {
return currentlyDisplayedROI;
}
/**
* Method setCurrentlyDisplayedROI.
* @param argCurrentlyDisplayedROI ROI
*/
public void setCurrentlyDisplayedROI(ROI argCurrentlyDisplayedROI) {
setCurrentlyDisplayedROI(argCurrentlyDisplayedROI, true);
}
public void setCurrentlyDisplayedROI(ROI argCurrentlyDisplayedROI, boolean bSave) {
ROI oldDisplayedROI = this.currentlyDisplayedROI;
this.currentlyDisplayedROI = argCurrentlyDisplayedROI;
if(bSave)
{
propertyChangeSupport.firePropertyChange(PROPERTY_CHANGE_CURRENTLY_DISPLAYED_ROI_WITH_SAVE, oldDisplayedROI, currentlyDisplayedROI);
}
else
{
propertyChangeSupport.firePropertyChange(PROPERTY_CHANGE_CURRENTLY_DISPLAYED_ROI_WITHOUT_SAVE, oldDisplayedROI, currentlyDisplayedROI);
}
}
//have to use this method, because the when switching between different frapStudies,
//the old and current displayedROI are the same(e.g study1@cellROI --> study2@cellROI --> study1@cellROI),it will not fire property change.
//however, we want to change the image when shift from one frapStudy to another.
public void setCurrentlyDisplayedROIForBatchRun(ROI argCurrentlyDisplayedROI)
{
this.currentlyDisplayedROI = argCurrentlyDisplayedROI;
propertyChangeSupport.firePropertyChange(PROPERTY_CHANGE_CURRENTLY_DISPLAYED_ROI_WITHOUT_SAVE, null, currentlyDisplayedROI);
}
public void setImageDataset(ImageDataset newImgDataset)
{
imageDataset = newImgDataset;
}
}
| 32.766017 | 146 | 0.701182 |
01777496882cb9ed26381f7a6ce7ded0613a80e1
| 862 |
package implementation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
*
* @author minchoba
* 백준 1448번: 삼각형 만들기
*
* @see https://www.acmicpc.net/problem/1448/
*
*/
public class Boj1448 {
public static void main(String[] args) throws Exception {
// 버퍼를 통한 값 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] edge = new int[N];
for (int i = 0; i < N; i++) {
edge[i] = Integer.parseInt(br.readLine());
}
Arrays.sort(edge); // 정렬
int res = -1;
for (int i = N - 3; i >= 0; i--) { // 뒤에서부터 인접한 길이를 탐색하며
int a = edge[i];
int b = edge[i + 1];
int c = edge[i + 2];
if (c < b + a) { // 삼각형의 조건에 맞는지 확인
res = a + b + c;
break;
}
}
System.out.println(res); // 삼각형이면 둘레를 아니면 -1 출력
}
}
| 20.52381 | 75 | 0.592807 |
1498e2874af41ae7f3619362c3f662c8b27e1952
| 355 |
package com.stevesoltys.movieglu.net;
import com.stevesoltys.movieglu.model.nowshowing.NowShowingResponse;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* @author Steve Soltys
*/
public interface MoviegluService {
@GET("filmsNowShowing/")
Call<NowShowingResponse> getNowShowing(@Query("n") int count);
}
| 20.882353 | 68 | 0.766197 |
516187c95768a73198de13e34e57a50ac562566d
| 10,810 |
package tech.coinbub.daemon.testutils.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.LogContainerResultCallback;
import com.googlecode.jsonrpc4j.IJsonRpcClient;
import com.googlecode.jsonrpc4j.JsonRpcClient;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Optional;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.coinbub.daemon.normalized.Normalized;
import tech.coinbub.daemon.proxy.ProxyUtil;
import tech.coinbub.daemon.testutils.Util;
import static tech.coinbub.daemon.testutils.docker.DockerUtils.*;
public class Dockerized implements BeforeAllCallback,
AfterAllCallback,
BeforeEachCallback,
AfterEachCallback,
ParameterResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(Dockerized.class);
private static final String RAW_INTERFACE_KEY = "raw-interface";
private static final String NORMALIZED_INTERFACE_KEY = "normalized-interface";
private static Thread shutdownHook = null;
@Override
public void beforeAll(final ExtensionContext context) throws Exception {
final Configuration config = getConfiguration(context);
if (!config.getReconfigurePerTest() && !config.getRebuildPerTest()) {
setup(context);
}
}
@Override
public void afterAll(final ExtensionContext context) throws Exception {
final Configuration config = getConfiguration(context);
if (!config.getReconfigurePerTest() && !config.getRebuildPerTest()) {
teardown(context);
}
}
@Override
public void beforeEach(final ExtensionContext context) throws Exception {
final Configuration config = getConfiguration(context);
if (config.getReconfigurePerTest() || config.getRebuildPerTest()) {
setup(context);
}
}
@Override
public void afterEach(final ExtensionContext context) throws InterruptedException {
final Configuration config = getConfiguration(context);
if (config.getReconfigurePerTest() || config.getRebuildPerTest()) {
teardown(context);
}
}
@Override
public boolean supportsParameter(final ParameterContext parameterContext,
final ExtensionContext extensionContext)
throws ParameterResolutionException {
if (!isDockerized(extensionContext)) {
return false;
}
final ExtensionContext.Store store = extensionContext.getStore(ExtensionContext.Namespace.GLOBAL);
final Configuration config = store.get(Configuration.class, Configuration.class);
return parameterContext.getParameter().getType().equals(config.getRawInterface())
|| parameterContext.getParameter().getType().equals(config.getNormalizedInterface())
|| parameterContext.getParameter().getType().equals(Normalized.class);
}
@Override
public Object resolveParameter(final ParameterContext parameterContext,
final ExtensionContext extensionContext)
throws ParameterResolutionException {
final ExtensionContext.Store store = extensionContext.getStore(ExtensionContext.Namespace.GLOBAL);
final Configuration config = store.get(Configuration.class, Configuration.class);
if (parameterContext.getParameter().getType().equals(config.getRawInterface())) {
return store.get(RAW_INTERFACE_KEY, config.getRawInterface());
}
if (parameterContext.getParameter().getType().equals(config.getNormalizedInterface())
|| parameterContext.getParameter().getType().equals(Normalized.class)) {
return store.get(NORMALIZED_INTERFACE_KEY, config.getNormalizedInterface());
}
return null;
}
//
// Core Helpers
//
/**
* Determines whether or not the current execution context has at least one @Dockerize annotation.
* @param context The current execution context
* @return True if dockerized, false otherwise
*/
private static boolean isDockerized(final ExtensionContext context) {
return getTestClassDockerizeAnnotation(context) != null
|| getTestMethodDockerizeAnnotation(context) != null;
}
private static Dockerize getTestClassDockerizeAnnotation(final ExtensionContext context) {
final Optional<Class<?>> testClass = context.getTestClass();
if (testClass.isPresent()) {
return Util.getAnnotation(testClass.get(), Dockerize.class);
}
return null;
}
private static Dockerize getTestMethodDockerizeAnnotation(final ExtensionContext context) {
final Optional<Method> testMethod = context.getTestMethod();
if (testMethod.isPresent()) {
return Util.getAnnotation(testMethod.get(), Dockerize.class);
}
return null;
}
private Configuration getConfiguration(final ExtensionContext context) {
final ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.GLOBAL);
if (store.get(Configuration.class) == null) {
final Dockerize dockerizedClass = getTestClassDockerizeAnnotation(context);
final Dockerize dockerizedMethod = getTestMethodDockerizeAnnotation(context);
final Configuration config = new Configuration(dockerizedClass, dockerizedMethod);
store.put(Configuration.class, config);
return config;
}
return store.get(Configuration.class, Configuration.class);
}
private void setup(final ExtensionContext context) throws Exception {
if (!isDockerized(context)) {
return;
}
final Dockerize dockerizedClass = getTestClassDockerizeAnnotation(context);
final Dockerize dockerizedMethod = getTestMethodDockerizeAnnotation(context);
final Configuration config = new Configuration(dockerizedClass, dockerizedMethod);
final ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.GLOBAL);
final DockerClient dockerClient = DockerClientBuilder.getInstance().build();
// Determine whether or not we need to run setup
LOGGER.debug("Setup");
if (config.getContainerLocation() == null) {
boolean rebuild = false;
if (config.getRebuildPerTest()) {
LOGGER.debug(" > Rebuild per test");
rebuild = true;
}
if (!containerExists(dockerClient, config)) {
LOGGER.debug(" > Container does not exist");
rebuild = true;
}
if (rebuild) {
LOGGER.debug(" > Rebuild");
terminateContainer(dockerClient, config);
pullImage(dockerClient, config);
createContainer(dockerClient, config);
}
if (rebuild || config.getReconfigurePerTest()) {
LOGGER.debug(" > Reconfigure");
stopContainer(dockerClient, config);
copyConfiguration(dockerClient, config);
}
LOGGER.debug(" > Prepare for test");
startContainer(dockerClient, config);
getHostPortBinding(dockerClient, config);
registerShutdownHook(dockerClient, config);
}
final URL url = config.getURL();
LOGGER.info("Using URL {}", url.toString());
final JsonRpcClient rpcClient = new JsonRpcHttpClient(url, Util.headers(config.getUser(), config.getPass()));
final Object raw = ProxyUtil.createClientProxy(
this.getClass().getClassLoader(),
config.getRawInterface(),
(IJsonRpcClient) rpcClient);
final Normalized normalized = (Normalized) config.getNormalizedInterface()
.getConstructor(config.getRawInterface())
.newInstance(raw);
try {
normalized.waitForDaemon();
} catch (Exception ex) {
LOGGER.debug("Container logs:");
dockerClient.logContainerCmd(config.getName())
.withTail(100)
.withStdOut(true)
.withStdErr(true)
.exec(new LogContainerResultCallback() {
@Override
public void onNext(Frame item) {
LOGGER.debug(item.toString());
}
})
.awaitCompletion();
if (config.getPersistentOnError()) {
stopContainer(dockerClient, config);
renameContainer(dockerClient, config, context);
removeShutdownHook();
}
throw new IllegalStateException(ex);
}
store.put(Configuration.class, config);
store.put(DockerClient.class, dockerClient);
store.put(JsonRpcClient.class, rpcClient);
store.put(RAW_INTERFACE_KEY, raw);
store.put(NORMALIZED_INTERFACE_KEY, normalized);
}
private void teardown(final ExtensionContext context) throws InterruptedException {
if (!isDockerized(context)) {
return;
}
final ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.GLOBAL);
store.remove(Configuration.class);
store.remove(DockerClient.class);
store.remove(JsonRpcClient.class);
store.remove(RAW_INTERFACE_KEY);
store.remove(NORMALIZED_INTERFACE_KEY);
}
private static void removeShutdownHook() {
if (shutdownHook != null) {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
shutdownHook = null;
}
}
private static void registerShutdownHook(final DockerClient client, final Configuration config) {
removeShutdownHook();
shutdownHook = new Thread(() -> {
try {
terminateContainer(client, config);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
| 42.062257 | 117 | 0.662997 |
59c8b0c74626e8969312b650526441be30d5e405
| 279 |
package commons.model;
public class Authentication {
private String secret;
private String pem;
private String password;
public String getSecret() {
return secret;
}
public String getPem() {
return pem;
}
public String getPassword() {
return password;
}
}
| 11.625 | 30 | 0.706093 |
1fb07733c706f7a22c9cdf1c7ab4ce146aa9f3b0
| 989 |
package com.home.commonClient.net.sceneBaseResponse.unit;
import com.home.commonClient.constlist.generate.GameResponseType;
import com.home.commonClient.constlist.generate.SceneBaseResponseType;
import com.home.commonClient.net.sceneBaseResponse.base.UnitSResponse;
import com.home.shine.bytes.BytesReadStream;
/** 单位复活消息(generated by shine) */
public class UnitReviveResponse extends UnitSResponse
{
/** 数据类型ID */
public static final int dataID=SceneBaseResponseType.UnitRevive;
public UnitReviveResponse()
{
_dataID=SceneBaseResponseType.UnitRevive;
}
/** 执行 */
protected void execute()
{
scene.getFightUnitAbs(instanceID).fight.onRevive();
}
/** 获取数据类名 */
@Override
public String getDataClassName()
{
return "UnitReviveResponse";
}
/** 读取字节流(完整版) */
@Override
protected void toReadBytesFull(BytesReadStream stream)
{
super.toReadBytesFull(stream);
stream.startReadObj();
stream.endReadObj();
}
}
| 23 | 71 | 0.731041 |
ef82d9c53b3565bcb4823fb9db01f9e1ac2f2f4e
| 613 |
package ru.job4j;
/**
* Created by Anton on 25.05.2017.
*/
public class EasyHash {
/**
* Hashsum.
*/
private int hash;
/**
* Number.
*/
private int number;
/**
* Constructor.
* @param hash
* @param number
*/
public EasyHash(int hash, int number) {
this.hash = hash;
this.number = number;
}
/**
* Getter.
* @return hash
*/
@Override
public int hashCode() {
return hash;
}
/**
* Getter.
* @return number
*/
public int getNumber() {
return number;
}
}
| 14.255814 | 43 | 0.469821 |
0b7bb4b5d7bbd9a7da51adb9cea948a92e94f277
| 268 |
package de.adesso.gitstalker.core.resources.member_Resources;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
@Data
@NoArgsConstructor
public class RepositoriesContributedTo {
private ArrayList<NodesRepoContributedTo> nodes;
}
| 19.142857 | 61 | 0.828358 |
46f59bbfafb29b582b00fbf664c57d5178e9c57c
| 1,628 |
package cs132.vapor.ast;
import cs132.util.SourcePos;
/**
* A function definition.
*/
public class VFunction extends VTarget
{
/**
* All functions in a single program are assigned an index contiguously, starting
* from zero.
*/
public final int index;
/**
* The function's parameter list.
*/
public final VVarRef.Local[] params;
/**
* The function's list of code labels. This array keeps the labels in the same order
* they appear in the code.
*/
public VCodeLabel[] labels;
/**
* The function's stack declaration. Ex: <code>[in 1, out 2, local 0]</code>.
*/
public final Stack stack;
/**
* The function body is just a list of instructions. The code labels appear separately
* in the {@link #labels} array.
*/
public VInstr[] body;
/**
* The full list of local variables used in this function. {@link VVarRef.Local} nodes
* have an index that point into this array.
*/
public String[] vars;
public VFunction(SourcePos sourcePos, String ident, int index, VVarRef.Local[] params, Stack stack)
{
super(sourcePos, ident);
this.index = index;
this.params = params;
this.stack = stack;
}
/**
* The details of a function's stack space declaration.
*/
public static final class Stack
{
/** The number of words in the "in" part of the stack. */
public final int in;
/** The number of words in the "out" part of the stack. */
public final int out;
/** The number of words in the "local" part of the stack. */
public final int local;
public Stack(int in, int out, int local)
{
this.in = in;
this.out = out;
this.local = local;
}
}
}
| 22.611111 | 100 | 0.665848 |
25a76d7de6c11f4ab355cf46a6bd869c27477748
| 947 |
package pub.gordon.dg.maven.bean;
/**
* @author Gordon
* @date 2017-11-03 11:26
*/
public class MavenNode {
private String groupId;
private String artifactId;
private String version;
public MavenNode(String groupId, String artifactId, String version) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("MavenNode{");
sb.append("groupId='").append(groupId).append('\'');
sb.append(", artifactId='").append(artifactId).append('\'');
sb.append(", version='").append(version).append('\'');
sb.append('}');
return sb.toString();
}
}
| 22.547619 | 73 | 0.600845 |
fc4f45e933cf244176ae0d0c08d1fd13465fb60e
| 1,166 |
package com.jstfs.practice.designpattern.creational.factorymethod;
import com.jstfs.practice.designpattern.creational.factorymethod.factory.AppleGardener;
import com.jstfs.practice.designpattern.creational.factorymethod.factory.FruitGardener;
import com.jstfs.practice.designpattern.creational.factorymethod.factory.GrapeGardener;
import com.jstfs.practice.designpattern.creational.factorymethod.factory.StrawberryGardener;
/**
* 工厂方法,每种工厂生产不同类的产品
* 二维:每个工厂和自己生产的产品构成线条,然后多个这样的线条在同一个平面内相互平行
*
* JDK中:
* Iterable(迭代器工厂接口) Iterator(迭代器产品接口)
* | |
* v v
* 各种集合类(生产迭代器的具体工厂) 各种集合类中的iterator()方法返回的迭代器(具体迭代器产品)
*
* @createBy jstfs
* @createTime 2018-10-25 上午10:56:40
*/
public class Client {
public static void main(String[] args) {
fruitPlant(new StrawberryGardener());
fruitGrow(new AppleGardener());
fruitHarvest(new GrapeGardener());
}
private static void fruitPlant(FruitGardener gardener) {
gardener.produce().plant();
}
private static void fruitGrow(FruitGardener gardener) {
gardener.produce().grow();
}
private static void fruitHarvest(FruitGardener gardener) {
gardener.produce().harvest();
}
}
| 29.897436 | 92 | 0.76072 |
6a1f7bed851faa569939e6e53c8d1a5e3fd9d449
| 1,812 |
package com.ihealthink.ks.system.webapi;
import com.ihealthink.ks.common.redis.service.RedisService;
import com.ihealthink.ks.core.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @author wangwb5
* EngineFlowInstance表相关操作
*/
@Slf4j
@Api(value = "用戶管理", tags = {"查询用户列表请求"})
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("user")
public class SysUserController extends BaseController {
@Autowired
private final RedisService redisService;
@ApiOperation(value = "获取用户信息", notes = "根据条件查询用户信息列表", httpMethod = "GET")
@GetMapping(value = "/list")
public Map<String, Object> queryFlowInstanceList() {
redisService.setCacheObject("aaa", "wowowoowoww");
Map<String, Object> map = new HashMap<>();
Object o = redisService.getCacheObject("aaa");
map.put("aaa", o);
return map;
}
// @ApiOperation(value = "根据id查询流程实例信息", notes = "根据id查询流程实例信息", httpMethod = "GET")
// @ApiImplicitParam(name = "flowInstanceId", value = "流程实例主键", required = true, paramType = "path")
// @GetMapping(value = "/queryFlowInstanceById/{flowInstanceId}")
// public R<EngineFlowInstance> queryFlowInstanceById(@PathVariable("flowInstanceId") String flowInstanceId) {
//
// return engineFlowInstanceService.queryFlowInstanceById(Long.parseLong(flowInstanceId));
// }
}
| 33.555556 | 113 | 0.742826 |
2d6f4ba04c8593190732507ac7a2005b34564cb7
| 600 |
package me.roitgrund.chess.stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.stream.Collectors;
import static com.google.common.truth.Truth.assertThat;
import static me.roitgrund.chess.stream.Streams.reverseIntStream;
public class StreamsTest {
@Test
public void testReverseIntStream() {
assertThat(
reverseIntStream(10, 0).boxed()
.collect(Collectors.toList()))
.containsExactlyElementsIn(
Arrays.asList(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
.inOrder();
}
}
| 26.086957 | 72 | 0.616667 |
d20a2acfefc8688bba8272885f9857bf76e98a61
| 85 |
package com.myhome.domain;
public enum SecurityTokenType {
RESET, EMAIL_CONFIRM
}
| 14.166667 | 31 | 0.788235 |
17dbb8dfd48229296bb22db5b26adf0c2785cf5c
| 497 |
package com.lh.learning.leetcode.no61_70.no70;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @auther: loneyfall
* @date: 2021/4/23
* @description:
*/
public class Question70Test {
private static Question70 question70;
@BeforeClass
public static void beforeClass() {
question70 = new Question70();
}
@Test
public void test() {
System.out.println(question70.climbStairs(2));
System.out.println(question70.climbStairs(3));
}
}
| 19.88 | 54 | 0.668008 |
b1d0b800d05b701d9dbe8a2c696137902343b60f
| 738 |
package asset.core;
import asset.util.Asset;
public class Skill extends Asset {
private Attributes att;
private Trait[] trts;
private boolean avail;
private boolean debugAvail;
public Skill(String name, String desc) {
super(name, desc);
}
public void setConditions(Attributes att, Trait[] trts) {
this.att = att;
this.trts = trts;
}
public void setAttributeConditions(Attributes att) {
this.att = att;
}
public void setTraitConditions(Trait[] trts) {
this.trts = trts;
}
public boolean isAvailable() {
return avail;
}
public boolean DEBUG_Availability() {
return debugAvail;
}
public Attributes getAttributeConditions() {
return att;
}
public Trait[] getTraitConditions() {
return trts;
}
}
| 17.162791 | 58 | 0.712737 |
cb84e45aacb5187a56957515630489c6b7f2e766
| 931 |
package ru.job4j.search;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**Модель справочника.
*@author IvanPJF (teaching-light@yandex.ru)
*@since 14.10.2018
*@version 0.1
*/
public class PhoneDictionary {
private List<Person> persons = new ArrayList<>();
public void add(Person person) {
this.persons.add(person);
}
/**
* Вернуть список всех пользователей, который содержат key в любых полях.
* @param key Ключ поиска.
* @return Список подощедщих пользователей.
*/
public List<Person> find(String key) {
return this.persons.stream().filter(
values -> values.getName().contains(key)
|| values.getSurname().contains(key)
|| values.getAddress().contains(key)
|| values.getPhone().contains(key)
).collect(Collectors.toList());
}
}
| 29.09375 | 77 | 0.615467 |
a054758f21ee1d7e67cabe7484f6d73e2cc3148e
| 444 |
package android.support.v7.view.menu;
import android.widget.ListView;
public abstract interface r
{
public abstract void dismiss();
public abstract ListView getListView();
public abstract boolean isShowing();
public abstract void show();
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/android/support/v7/view/menu/r.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 22.2 | 112 | 0.698198 |
060b16e35a98c754c67d14b05637f627cb3b507f
| 9,589 |
/*
* Project Sc2gears
*
* Copyright (c) 2010 Andras Belicza <iczaaa@gmail.com>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the authors permission
* is prohibited and protected by Law.
*/
package hu.belicza.andras.sc2gearsdb;
import static hu.belicza.andras.sc2gearsdbapi.ServletApi.PARAM_OPERATION;
import static hu.belicza.andras.sc2gearsdbapi.ServletApi.PARAM_PROTOCOL_VERSION;
import hu.belicza.andras.sc2gearsdbapi.ServletApi;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A base servlet with request processing and response building utilities.
*
* @author Andras Belicza
*/
@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {
private static final Logger LOGGER = Logger.getLogger( BaseServlet.class.getName() );
/** Google Analytics code to be included immediately before the closing <code></head></code> tag. */
protected static final String GA_TRACKER_HTML_SCRIPT = "<script type=\"text/javascript\">"
+ "var _gaq = _gaq || [];"
+ "_gaq.push(['_setAccount', 'UA-4884955-25']);"
+ "_gaq.push(['_trackPageview']);"
+ "(function() {"
+ "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;"
+ "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';"
+ "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);"
+ "})();"
+ "</script>";
/** Google Adsense code, Header ad 728x90. */
protected static final String HEADER_AD_728_90_HTML_SCRIPT = "<script type=\"text/javascript\">"
+ "google_ad_client = \"ca-pub-4479321142068297\";"
+ "google_ad_slot = \"4124263936\";"
+ "google_ad_width = 728;"
+ "google_ad_height = 90;"
+ "</script>"
+ "<script type=\"text/javascript\""
+ "src=\"https://pagead2.googlesyndication.com/pagead/show_ads.js\">"
+ "</script>";
/** Footer copyright HTML code. */
protected static final String FOOTER_COPYRIGHT_HTML = "<hr/><div style=\"text-align:right;font-style:italic\">© András Belicza, 2010-2014</div>";
/** Default CSS HTML code. */
protected static String DEFAULT_CSS_HTML;
@Override
public void init() throws ServletException {
if ( DEFAULT_CSS_HTML == null ) {
final StringBuilder cssBuilder = new StringBuilder( "<style type=\"text/css\">" );
try ( final InputStreamReader cssReader = new InputStreamReader( getServletConfig().getServletContext().getResourceAsStream( "/sc2gearsdb.css" ), "UTF-8" ) ) {
final char[] buffer = new char[ 256 ];
int charsRead;
while ( ( charsRead = cssReader.read( buffer ) ) >= 0 )
cssBuilder.append( buffer, 0, charsRead );
} catch ( final IOException ie ) {
LOGGER.log( Level.SEVERE, "Failed to load sc2gearsdb.css!", ie );
} finally {
cssBuilder.append( "</style>" );
DEFAULT_CSS_HTML = cssBuilder.toString();
}
}
}
/**
* Checks the protocol version supplied as a request parameter ({@link ServletApi#PARAM_PROTOCOL_VERSION})
* and returns the operation supplied as a request parameter ({@link ServletApi#PARAM_OPERATION}).
*
* <p>{@link HttpServletResponse#SC_BAD_REQUEST} is sent back if the protocol version is missing or invalid, or if the operation is missing.</p>
*
* @param validProtocolVersion valid protocol version to accept
* @param request the HTTP servlet request
* @param response the HTTP servlet response
* @return the operation, or <code>null</code> if the protocol version is missing or invalid or the operation is missing
* @throws IOException
*/
protected static String checkProtVerAndGetOperation( final String validProtocolVersion, final HttpServletRequest request, final HttpServletResponse response ) throws IOException {
final String protocolVersion = request.getParameter( PARAM_PROTOCOL_VERSION );
if ( protocolVersion == null ) {
LOGGER.warning( "Missing Protocol version!" );
response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Missing Protocol version!" );
return null;
}
if ( !validProtocolVersion.equals( protocolVersion ) ) {
LOGGER.warning( "Invalid Protocol version: " + protocolVersion + " (valid: " + validProtocolVersion + ")" );
response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid Protocol version! (Must be: " + validProtocolVersion + ")" );
return null;
}
final String operation = request.getParameter( PARAM_OPERATION );
if ( operation == null ) {
LOGGER.warning( "Missing Operation!" );
response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Missing Operation!" );
return null;
}
LOGGER.fine( "Operation: " + operation );
return operation;
}
/**
* Returns the value of a parameter as a {@link Boolean}.
*/
protected static Boolean getBooleanParam( final HttpServletRequest request, final String paramName ) {
try {
return Boolean.valueOf( request.getParameter( paramName ) );
} catch ( final Exception e ) {
return null;
}
}
/**
* Returns the value of a parameter as a {@link Short}.
*/
protected static Short getShortParam( final HttpServletRequest request, final String paramName ) {
try {
return Short.valueOf( request.getParameter( paramName ) );
} catch ( final Exception e ) {
return null;
}
}
/**
* Returns the value of a parameter as an {@link Integer}.
*/
protected static Integer getIntParam( final HttpServletRequest request, final String paramName ) {
try {
return Integer.valueOf( request.getParameter( paramName ) );
} catch ( final Exception e ) {
return null;
}
}
/**
* Returns the value of a parameter as an {@link Long}.
*/
protected static Long getLongParam( final HttpServletRequest request, final String paramName ) {
try {
return Long.valueOf( request.getParameter( paramName ) );
} catch ( final Exception e ) {
return null;
}
}
/**
* Returns the value of a parameter as a {@link Float}.
*/
protected static Float getFloatParam( final HttpServletRequest request, final String paramName ) {
try {
return Float.valueOf( request.getParameter( paramName ) );
} catch ( final Exception e ) {
return null;
}
}
/**
* Returns the value of a parameter as a {@link Date}.
*/
protected static Date getDateParam( final HttpServletRequest request, final String paramName ) {
try {
return new Date( Long.valueOf( request.getParameter( paramName ) ) );
} catch ( final Exception e ) {
return null;
}
}
/**
* Returns a String list parsed from the value of the specified parameter.<br>
* The value is treated as a comma separated list of strings.
* Elements of this comma separated lists are trimmed by {@link String#trim()}.
*/
protected static List< String > getStringListParam( final HttpServletRequest request, final String paramName ) {
try {
final String[] values = request.getParameter( paramName ).split( "," );
final List< String > valueList = new ArrayList< String >();
for ( String value : values ) {
value = value.trim();
if ( value.length() > 0 )
valueList.add( value );
}
return valueList;
} catch ( final Exception e ) {
return null;
}
}
/**
* Returns an integer list parsed from the value of the specified parameter.<br>
* The value is treated as a comma separated list of integers.
* Elements of this comma separated lists are trimmed by {@link String#trim()}.
*/
protected static List< Integer > getIntListParam( final HttpServletRequest request, final String paramName ) {
try {
final String[] values = request.getParameter( paramName ).split( "," );
final List< Integer > valueList = new ArrayList< Integer >();
for ( String value : values ) {
value = value.trim();
if ( value.length() > 0 )
valueList.add( Integer.valueOf( value ) );
}
return valueList;
} catch ( final Exception e ) {
return null;
}
}
/**
* Configures the response never to cache the data.
* @param response reference to the response
*/
protected static void setNoCache( final HttpServletResponse response ) {
response.setHeader ( "Cache-Control", "no-cache" ); // For HTTP 1.1
response.setHeader ( "Pragma" , "no-cache" ); // For HTTP 1.0
response.setDateHeader( "Expires" , 0 ); // For proxies
}
/**
* Included the default CSS into the specified output writer.
* <p>This method is to be called when the output HTML document is inside the <code><head></code> tag.
* This method will insert a <code><style></code> tag and inlines the CSS content.</p>
* @param out writer to write the default CSS code
*/
protected static void includeDefaultCss( final PrintWriter out ) {
out.println( DEFAULT_CSS_HTML );
}
}
| 36.880769 | 181 | 0.667223 |
0cebd5944154b8081872bf91944d8709804aa8ea
| 2,877 |
package com.trivadis.plsql.formatter.settings.tests.grammar.plsql;
import com.trivadis.plsql.formatter.settings.ConfiguredTestFormatter;
import oracle.dbtools.app.Format;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class Sqlcode_function extends ConfiguredTestFormatter {
@BeforeEach
public void setup() {
getFormatter().options.put(getFormatter().idCase, Format.Case.lower);
}
@Test
public void example_12_23() throws IOException {
var input = """
CREATE OR REPLACE PROCEDURE p AUTHID DEFINER AS
name EMPLOYEES.LAST_NAME%TYPE;
v_code NUMBER;
v_errm VARCHAR2(64);
BEGIN
SELECT last_name INTO name
FROM EMPLOYEES
WHERE EMPLOYEE_ID = -1;
EXCEPTION
WHEN OTHERS THEN
v_code := SQLCODE;
v_errm := SUBSTR(SQLERRM, 1, 64);
DBMS_OUTPUT.PUT_LINE
('Error code ' || v_code || ': ' || v_errm);
/* Invoke another procedure,
declared with PRAGMA AUTONOMOUS_TRANSACTION,
to insert information about errors. */
INSERT INTO errors (code, message)
VALUES (v_code, v_errm);
RAISE;
END;
/
""";
var actual = formatter.format(input);
var expected = """
create or replace procedure p
authid definer
as
name employees.last_name%type;
v_code number;
v_errm varchar2(64);
begin
select last_name into name
from employees
where employee_id = - 1;
exception
when others then
v_code := sqlcode;
v_errm := substr(sqlerrm, 1, 64);
dbms_output.put_line('Error code '
|| v_code
|| ': '
|| v_errm);
/* Invoke another procedure,
declared with PRAGMA AUTONOMOUS_TRANSACTION,
to insert information about errors. */
insert into errors (code, message)
values (v_code, v_errm);
raise;
end;
/
""";
assertEquals(expected, actual);
}
}
| 35.518519 | 77 | 0.443865 |
ca77b5d55a9490fcec8ffa8da51f604e6ef045d4
| 1,148 |
package br.com.marcosatanaka.easypoi.demo;
import br.com.marcosatanaka.easypoi.excel.ExcelColumn;
import br.com.marcosatanaka.easypoi.util.StringToBigDecimal;
import com.google.common.base.MoreObjects;
import java.math.BigDecimal;
import java.util.Objects;
public class ImportacaoDTO {
@ExcelColumn(name = "NOME")
private String nome;
@ExcelColumn(name = "CPF")
private String cpf;
@ExcelColumn(name = "RENDA")
private String renda;
@Override
public boolean equals(Object obj) {
if (obj instanceof ImportacaoDTO) {
ImportacaoDTO that = (ImportacaoDTO) obj;
return Objects.equals(nome, that.nome) &&
Objects.equals(cpf, that.cpf) &&
Objects.equals(renda, that.renda);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(nome, cpf, renda);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("nome", nome)
.add("cpf", cpf)
.add("renda", renda)
.toString();
}
public String getNome() {
return nome;
}
public String getCpf() {
return cpf;
}
public BigDecimal getRenda() {
return StringToBigDecimal.convert(renda);
}
}
| 19.457627 | 60 | 0.707317 |
f8d9318cb25c238236be77596388eaca53bead99
| 961 |
package org.radargun.service;
import org.infinispan.protostream.SerializationContext;
import org.radargun.Service;
import org.radargun.traits.ProvidesTrait;
/**
* @author Vojtech Juranek <vjuranek@redhat.com>
*/
@Service(doc = JDG66HotrodService.SERVICE_DESCRIPTION)
public class JDG66HotrodService extends Infinispan71HotrodService {
@ProvidesTrait
public JDGHotrodContinuousQuery createContinuousQuery() {
return new JDGHotrodContinuousQuery(this);
}
@Override
protected JDG66HotrodQueryable createQueryable() {
return new JDG66HotrodQueryable(this);
}
@Override
protected void registerMarshallers(SerializationContext context) {
for (RegisteredClass rc : classes) {
try {
context.registerMarshaller(rc.getMarshaller());
} catch (Exception e) {
throw new IllegalArgumentException("Could not instantiate marshaller for " + rc.clazz, e);
}
}
}
}
| 28.264706 | 102 | 0.722164 |
089e9eea1923ff53e9aa288ba208ba9ddcdc2cf6
| 677 |
package g_BuiltInQueryMethodsStreamAPIExercises;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class p05_FilterByEmail {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<String> students = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if ("END".equals(input)) {
break;
}
students.add(input);
}
students.stream()
.filter(a -> a.contains("@gmail.com"))
.forEach(s -> System.out.println(s.substring(0, s.lastIndexOf(" "))));
}
}
| 24.178571 | 86 | 0.568685 |
87039819442fb85796c499dbfd9aba9b9ee6126d
| 371 |
package com.itdr.mapper;
import com.itdr.pojo.GameDetail;
public interface GameDetailMapper {
int deleteByPrimaryKey(Integer id);
int insert(GameDetail record);
int insertSelective(GameDetail record);
GameDetail selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(GameDetail record);
int updateByPrimaryKey(GameDetail record);
}
| 21.823529 | 55 | 0.773585 |
61f1468ae2ca908a9477db71a2581f413b24fbac
| 351 |
package exceptions.publix;
import play.mvc.Http;
/**
* It causes the request to return with an HTTP status 403 (Forbidden).
*
* @author Kristian Lange
*/
@SuppressWarnings("serial")
public class ForbiddenPublixException extends PublixException {
public ForbiddenPublixException(String message) {
super(message, Http.Status.FORBIDDEN);
}
}
| 19.5 | 71 | 0.757835 |
99b0f49b60b24f3e8f7ea4655b71c6a6ab03b320
| 1,532 |
package com.skewpixel.rltut2019.ecs;
import com.skewpixel.rltut2019.ecs.components.Component;
import java.util.HashMap;
import java.util.Map;
public class Entity {
private Map<String, Component> componentMap = new HashMap<>();
public Entity(){}
public Entity(Component... components){
for(Component component :components) {
addComponent(component);
}
}
public void addComponent(Component component) {
componentMap.put(component.getName(), component);
}
public boolean hasComponent(String componentName) {
return componentMap.containsKey(componentName);
}
public <T extends Component> boolean hasComponent(Class<T> clazz) {
for(Map.Entry<String, Component> es : componentMap.entrySet()){
if(clazz.isInstance(es.getValue())) {
return true;
}
}
return false;
}
public <T extends Component> T getComponentByName(String componentName, Class<T> clazz) {
if(hasComponent(componentName)){
Component c = componentMap.get(componentName);
if(clazz.isInstance(c)) {
return clazz.cast(c);
}
}
return null;
}
public <T extends Component> T getComponent(Class<T> clazz) {
for(Map.Entry<String, Component> es : componentMap.entrySet()){
if(clazz.isInstance(es.getValue())) {
return clazz.cast(es.getValue());
}
}
return null;
}
}
| 25.966102 | 93 | 0.60705 |
d58c1ac4ebce1bdf0f138c3190a47eaa4278dd48
| 1,071 |
package ru.stqa.dmiv.mantis.appmanager;
import org.openqa.selenium.By;
import ru.stqa.dmiv.mantis.model.UserData;
public class AdminHelper extends HelperBase {
public AdminHelper(ApplicationManager app) {
super(app);
}
public void resetPassword(UserData user) {
adminLogin();
wd.get(app.getProperty("web.baseUrl") + "manage_user_edit_page.php?user_id=" + user.getId());
click(By.cssSelector("input[value='Сбросить пароль']"));
}
private void adminLogin() {
wd.get(app.getProperty("web.baseUrl") + "login.php");
type(By.name("username"), app.getProperty("web.adminLogin"));
click(By.cssSelector("input[type='submit']"));
type(By.name("password"), app.getProperty("web.adminPassword"));
click(By.cssSelector("input[type='submit']"));
}
public void changePassword(String confirmationLink, String password) {
wd.get(confirmationLink);
type(By.name("password"), password);
type(By.name("password_confirm"), password);
click(By.cssSelector("button[type='submit']"));
}
}
| 32.454545 | 98 | 0.677871 |
4ef27644b7aa1bcd781ec5796011dd327eeed9dc
| 573 |
package br.jus.tst.tstunit;
import org.junit.*;
/**
* Testes unitários da {@link Configuracao}.
*
* @author Thiago Miranda
* @since 26 de jan de 2017
*/
public class ConfiguracaoTeste {
private Configuracao configuracao;
@Before
public void setUp() {
configuracao = Configuracao.getInstance();
}
@Test(expected = TestUnitException.class)
public void deveriaLancarExcecaoCasoArquivoNaoExista() throws TestUnitException {
configuracao.setNomeArquivoPropriedades("teste.properties");
configuracao.carregar();
}
}
| 22.038462 | 85 | 0.699825 |
afe96121642b37a0ff57d317b1286fdb5e062801
| 263 |
/*
* Copyright Anatoly Starostin (c) 2017.
*/
package treeton.gui.trnedit;
import treeton.core.IntFeatureMap;
public interface IntFeatureMapEditorListener {
public void imapEdited(IntFeatureMap source, IntFeatureMap attrs, IntFeatureMap inducedAttrs);
}
| 21.916667 | 98 | 0.790875 |
cdb079689262f63b2b0e109b7d8bfdb29c4a4a76
| 632 |
package org.krash.jpinba.servlet;
import org.krash.jpinba.data.JPinbaRequest;
import javax.servlet.ServletRequest;
/**
* Helper, attaching and extracting JPinbaRequest from Servlet, via custom attribute
*/
abstract public class Helper {
public static final String ATTRIBUTE_NAME = "org.krash.jpinba.servlet.REQUEST";
public static void attachRequest(ServletRequest request, JPinbaRequest jpRequest)
{
request.setAttribute(ATTRIBUTE_NAME, jpRequest);
}
public static JPinbaRequest extract(ServletRequest request)
{
return (JPinbaRequest) request.getAttribute(ATTRIBUTE_NAME);
}
}
| 25.28 | 85 | 0.753165 |
2dc208fcadd0d75262d1572cf517422100ea4ddc
| 655 |
package com.demo.schoolregistration.service;
import com.demo.schoolregistration.model.Course;
import com.demo.schoolregistration.repository.CourseRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class CourseService {
private final CourseRepository courseRepository;
public CourseService(CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
public Long addCourse(Course course) {
course = courseRepository.save(course);
log.info("Course {} has been successfully added : " , course.getCourseId());
return course.getCourseId();
}
}
| 27.291667 | 80 | 0.784733 |
16981bbdfc212844384062750b6bf8a51ffaf078
| 180 |
package com.github.kolorobot.mockito.annotations;
class ConsolePrinter implements Printer {
@Override
public void print(String s) {
System.out.println(s);
}
}
| 20 | 49 | 0.7 |
6bf3b2eaa6d379060979480af84779490333302c
| 540 |
package me.jugal.cabs.repositories;
import me.jugal.cabs.entities.Driver;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface IDriverRepository extends CrudRepository<Driver, Integer> {
List<Driver> findByOrderNull();
@Modifying
@Query("update Driver d set d.order = null")
void freeAllDrivers();
}
| 28.421053 | 76 | 0.796296 |
93ddda4be93c860162d6d984f147ebd5fbfcbc8f
| 412 |
/**
* Copyright (C) 2017, TP-LINK TECHNOLOGIES CO., LTD.
*
* SimpleAppInfo.java
*
* description
*
* Author Deng Xinliang Created at 3/30/17.
*
* Ver 1.0, 3/30/17, Deng Xinliang, Create file
*/
package com.mx.dxinl.quicklauncher.model;
import android.graphics.drawable.Drawable;
public final class SimpleAppInfo {
public String mName;
public String mPkgName;
public Drawable mDrawable;
}
| 18.727273 | 53 | 0.703883 |
8db8e21a95aadcf0f32b17a36e5b903f8cc34540
| 3,443 |
package net.minecraft.data.worldgen.placement;
import java.util.Random;
import net.minecraft.SystemUtils;
import net.minecraft.core.IRegistry;
import net.minecraft.data.RegistryGeneration;
import net.minecraft.util.random.SimpleWeightedRandomList;
import net.minecraft.util.valueproviders.ConstantInt;
import net.minecraft.util.valueproviders.IntProvider;
import net.minecraft.util.valueproviders.WeightedListInt;
import net.minecraft.world.level.levelgen.HeightMap;
import net.minecraft.world.level.levelgen.VerticalAnchor;
import net.minecraft.world.level.levelgen.placement.CountPlacement;
import net.minecraft.world.level.levelgen.placement.HeightRangePlacement;
import net.minecraft.world.level.levelgen.placement.HeightmapPlacement;
import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import net.minecraft.world.level.levelgen.placement.PlacementModifier;
public class PlacementUtils {
public static final PlacementModifier HEIGHTMAP = HeightmapPlacement.onHeightmap(HeightMap.Type.MOTION_BLOCKING);
public static final PlacementModifier HEIGHTMAP_TOP_SOLID = HeightmapPlacement.onHeightmap(HeightMap.Type.OCEAN_FLOOR_WG);
public static final PlacementModifier HEIGHTMAP_WORLD_SURFACE = HeightmapPlacement.onHeightmap(HeightMap.Type.WORLD_SURFACE_WG);
public static final PlacementModifier HEIGHTMAP_OCEAN_FLOOR = HeightmapPlacement.onHeightmap(HeightMap.Type.OCEAN_FLOOR);
public static final PlacementModifier FULL_RANGE = HeightRangePlacement.uniform(VerticalAnchor.bottom(), VerticalAnchor.top());
public static final PlacementModifier RANGE_10_10 = HeightRangePlacement.uniform(VerticalAnchor.aboveBottom(10), VerticalAnchor.belowTop(10));
public static final PlacementModifier RANGE_8_8 = HeightRangePlacement.uniform(VerticalAnchor.aboveBottom(8), VerticalAnchor.belowTop(8));
public static final PlacementModifier RANGE_4_4 = HeightRangePlacement.uniform(VerticalAnchor.aboveBottom(4), VerticalAnchor.belowTop(4));
public static final PlacementModifier RANGE_BOTTOM_TO_MAX_TERRAIN_HEIGHT = HeightRangePlacement.uniform(VerticalAnchor.bottom(), VerticalAnchor.absolute(256));
public PlacementUtils() {}
public static PlacedFeature bootstrap() {
PlacedFeature[] aplacedfeature = new PlacedFeature[]{AquaticPlacements.KELP_COLD, CavePlacements.CAVE_VINES, EndPlacements.CHORUS_PLANT, MiscOverworldPlacements.BLUE_ICE, NetherPlacements.BASALT_BLOBS, OrePlacements.ORE_ANCIENT_DEBRIS_LARGE, TreePlacements.ACACIA_CHECKED, VegetationPlacements.BAMBOO_VEGETATION, VillagePlacements.PILE_HAY_VILLAGE};
return (PlacedFeature) SystemUtils.getRandom((Object[]) aplacedfeature, new Random());
}
public static PlacedFeature register(String s, PlacedFeature placedfeature) {
return (PlacedFeature) IRegistry.register(RegistryGeneration.PLACED_FEATURE, s, placedfeature);
}
public static PlacementModifier countExtra(int i, float f, int j) {
float f1 = 1.0F / f;
if (Math.abs(f1 - (float) ((int) f1)) > 1.0E-5F) {
throw new IllegalStateException("Chance data cannot be represented as list weight");
} else {
SimpleWeightedRandomList<IntProvider> simpleweightedrandomlist = SimpleWeightedRandomList.builder().add(ConstantInt.of(i), (int) f1 - 1).add(ConstantInt.of(i + j), 1).build();
return CountPlacement.of(new WeightedListInt(simpleweightedrandomlist));
}
}
}
| 62.6 | 357 | 0.805112 |
a19b6c3caee6c106d999e1c0abc2ad19f76775e8
| 8,775 |
package com.avira.antivirusimplementation;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
/**
* @author ovidiu.buleandra
*
* main activity presented to the user
* uses an antivirus object to scan an application that the user chooses from the list of installed non-system apps
*
* for the purpose of testing install EICAR Antivirus test from the playstore (harmless app that holds a test virus signature)
*
*/
public class AntivirusActivity extends ActionBarActivity implements View.OnClickListener{
private static final String TAG = AntivirusActivity.class.getSimpleName();
private ScanResultsReceiver scanResultsReceiver;
private ProgressBar progress;
private Button btnSelect, btnSelectFolder;
private TextView txtSelectedApp, txtVersion, warning;
private ListView resultsList;
private List<AppInfo> listOfApplications;
private ScanFolderTask scanFolderTask;
private ScanResultsAdapter resultsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_antivirus);
// ui stuff
btnSelect = (Button) findViewById(R.id.btn_select_app);
btnSelectFolder = (Button) findViewById(R.id.btn_select_folder);
txtSelectedApp = (TextView) findViewById(R.id.scan_target);
resultsList = (ListView) findViewById(R.id.results);
warning = (TextView) findViewById(R.id.warning);
txtVersion = (TextView) findViewById(R.id.txt_version);
progress = (ProgressBar) findViewById(R.id.progress);
btnSelect.setOnClickListener(this);
btnSelectFolder.setOnClickListener(this);
txtSelectedApp.setText("");
listOfApplications = new ArrayList<>();
// display some info about the scan engine and virus definitions
txtVersion.setText(String.format("Virus Definitions %s\nEngine version %s",
Antivirus.getInstance().getVDFVersion(),
Antivirus.getInstance().getEngineVersion()));
resultsAdapter = new ScanResultsAdapter(this, warning);
resultsList.setAdapter(resultsAdapter);
scanResultsReceiver = new ScanResultsReceiver();
scanFolderTask = new ScanFolderTask();
}
@Override
protected void onResume() {
super.onResume();
listOfApplications.clear();
new LoadApplicationsTask(this, listOfApplications).execute();
LocalBroadcastManager.getInstance(this).registerReceiver(scanResultsReceiver,
new IntentFilter(Antivirus.ACTION_SCAN_FINISHED));
}
@Override
protected void onPause() {
super.onPause();
if(scanFolderTask != null) {
scanFolderTask.cancel(true);
}
LocalBroadcastManager.getInstance(this).unregisterReceiver(scanResultsReceiver);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_select_app:
final ListAdapter adapter = new ApplicationsAdapter(this, listOfApplications);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
AppInfo selectedApp = (AppInfo)adapter.getItem(which);
txtSelectedApp.setText(selectedApp.displayName);
resultsAdapter.clear();
startScan(selectedApp.sourceDir);
}
});
builder.create().show();
break;
case R.id.btn_select_folder:
new SelectFolderDialog().show(getSupportFragmentManager(), new SelectFolderDialog.SelectFolderInterface() {
@Override
public void onPathSelected(String path) {
txtSelectedApp.setText(path);
scanFolderTask = new ScanFolderTask();
resultsAdapter.clear();
scanFolderTask.execute(path);
}
});
break;
}
}
private void startScan(String targetDir) {
Antivirus.getInstance().scanPath(targetDir);
}
private class ScanResultsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String scannedPath = intent.getStringExtra(Antivirus.EXTRA_PATH);
ScannerCallback callbackData = intent.getParcelableExtra(Antivirus.EXTRA_SCAN_RESULT);
Log.i(TAG, "AV:ScanResultsReceiver " + scannedPath + " > " + callbackData);
resultsAdapter.addDetection(scannedPath, callbackData);
}
}
private static class ScanFolderTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String path = params[0];
LinkedList<String> dirs = new LinkedList<>();
dirs.push(path);
while(dirs.size() > 0) {
String currentDirPath = dirs.pop();
File currentDir = new File(currentDirPath);
String[] files = currentDir.list();
if(files == null)
continue;
for(String file: files) {
if(isCancelled()) {
return null;
}
File currentFile = new File(currentDirPath, file);
if(currentFile.isFile()) {
Antivirus.getInstance().scanPath(currentFile.getPath());
} else if(currentFile.isDirectory()) {
dirs.push(currentFile.getPath());
} // ignore all others
}
}
return null;
}
}
private static class LoadApplicationsTask extends AsyncTask<Void, AppInfo, Void> {
private WeakReference<List<AppInfo>> weakRefList;
private PackageManager packageManager;
public LoadApplicationsTask(Context ctx, List<AppInfo> list) {
weakRefList = new WeakReference<>(list);
packageManager = ctx.getPackageManager();
}
@Override
protected Void doInBackground(Void... params) {
List<ApplicationInfo> listOfApplications = packageManager.getInstalledApplications(0);
for(ApplicationInfo info : listOfApplications) {
try {
if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
String name = info.loadLabel(packageManager).toString();
publishProgress(new AppInfo(name, info.packageName, info.publicSourceDir));
}
} catch(Resources.NotFoundException e) {
Log.e(TAG, "error loading label " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
return null;
}
@Override
protected void onProgressUpdate(AppInfo... values) {
List<AppInfo> list = weakRefList.get();
if(list != null) {
list.add(values[0]);
}
}
@Override
protected void onPostExecute(Void aVoid) {
List<AppInfo> list = weakRefList.get();
if(list != null) {
Collections.sort(list, new Comparator<AppInfo>() {
@Override
public int compare(AppInfo lhs, AppInfo rhs) {
return lhs.displayName.compareTo(rhs.displayName);
}
});
}
}
}
}
| 36.869748 | 126 | 0.615954 |
547ee36007cc9be1c2e7f8466c5e2d298737835a
| 2,400 |
package at.crimsonbit.nodesystem.examples.customnode;
import java.util.logging.Level;
import com.google.common.collect.Sets.SetView;
import at.crimsonbit.nodesystem.gui.GNodeGraph;
import at.crimsonbit.nodesystem.gui.animation.Animator;
import at.crimsonbit.nodesystem.gui.node.GNode;
import at.crimsonbit.nodesystem.gui.widget.toast.JFXToast;
import at.crimsonbit.nodesystem.gui.widget.toast.ToastPosition;
import at.crimsonbit.nodesystem.gui.widget.toast.ToastTime;
import at.crimsonbit.nodesystem.nodebackend.api.INodeType;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
/**
*
* Example of how to use your custom node together with a custom node class.
* Please note, that if you don't want to react to custom messages your don't
* need to use a custom class. By Default every node uses the standard GNode
* class.
*
* @author Florian Wagner
*
*/
public class CustomNodeClassExample extends GNode {
public CustomNodeClassExample() {
super();
}
// This constructor HAS TO BE in your custom node class.
public CustomNodeClassExample(String name, int id, boolean draw, GNodeGraph graph) {
super(name, id, draw, graph);
addPopUpItem(5, "Make Toast"); // Adds a custom pop-up menu item.
addPopUpItem(6, "Animate"); // Adds a custom pop-up menu item.
addPopUpItem(7, "Append Log"); // Adds a custom pop-up menu item.
}
public CustomNodeClassExample(String name, INodeType type, boolean draw, GNodeGraph graph, double x, double y) {
super(name, type, draw, graph, x, y);
addPopUpItem(5, "Make Toast"); // Adds a custom pop-up menu item.
addPopUpItem(6, "Animate"); // Adds a custom pop-up menu item.
addPopUpItem(7, "Append Log"); // Adds a custom pop-up menu item.
}
/**
* Every pop-up message id that is above getInternalIDCounter() will be consumed
* by the method below. You can react to your custom id's here.
*/
@Override
public void consumeCustomMessage(int id) {
if (id == 5) {
//Creates a new Toast Message.
JFXToast.makeToast((Stage) getScene().getWindow(), "Sample Text!", ToastTime.TIME_SHORT, ToastPosition.BOTTOM);
}
if (id == 6) {
//Animates the opacity property of this node.
Animator.animateProperty(opacityProperty(), 500, 200, 200, 0, 1);
}
if (id == 7) {
// the log function is located in the nodegraph.
getNodeGraph().log(Level.WARNING, "This is a custom log warning!");
}
}
}
| 34.285714 | 114 | 0.728333 |
b23bfe7b0c66ffe55e9c583a1747368476a3aa59
| 2,680 |
package name.mjw.jquante.math.interpolater;
/**
* Same as @class TriLinearInterpolater but use a specified sub interpolater to
* perform individual point interpolation.
*
* @author V.Ganesh
* @version 2.0 (Part of MeTA v2.0)
*/
public class ThreePointInterpolater extends Interpolater {
/** Creates a new instance of ThreePointInterpolater */
public ThreePointInterpolater() {
subInterpolater = new LinearInterpolater();
}
private double i1;
private double i2;
private double j1;
private double j2;
private double w1;
private double w2;
private double[] x1 = new double[9];
private double[] y1 = new double[8];
private double[] delta = new double[3];
/**
* Interpolate value at X depending upon value at Y. Same as @class
* TriLinearInterpolater but use a specified sub interpolater to perform
* individual point interpolation. Default sub-interpolater is Linear
* interpolater.
*
* Note: It is the responsibility of the caller to ensure that only one point
* interpolater(s) are set as sub-interpolater. Else this routine will fail to
* operate.
*
* @param y
* the Y values (results of fuction evaluation)
* @param x
* the X values at fuction evaluation is performed or is expected
* @return the interpolated value depending upon the interpolation formula
*/
@Override
public double interpolate(double[] y, double[] x) {
delta[0] = (x[3] - x[0]) / x[6];
delta[1] = (x[4] - x[1]) / x[7];
delta[2] = (x[5] - x[2]) / x[8];
y1[0] = y[0];
y1[1] = y[1];
y1[2] = y[2];
y1[3] = y[3];
x1[0] = delta[2];
i1 = subInterpolater.interpolate(y1, x1);
y1[0] = y[2];
y1[1] = y[3];
y1[2] = y[4];
y1[3] = y[5];
i2 = subInterpolater.interpolate(y1, x1);
y1[0] = y[4];
y1[1] = y[5];
y1[2] = y[6];
y1[3] = y[7];
j1 = subInterpolater.interpolate(y1, x1);
y1[0] = y[6];
y1[1] = y[7];
y1[2] = y[4];
y1[3] = y[5];
j2 = subInterpolater.interpolate(y1, x1);
y1[0] = i1;
y1[1] = i2;
y1[2] = j1;
y1[3] = j2;
x1[0] = delta[1];
w1 = subInterpolater.interpolate(y1, x1);
y1[0] = j1;
y1[1] = j2;
y1[2] = i1;
y1[3] = i2;
w2 = subInterpolater.interpolate(y1, x1);
y1[0] = w1;
y1[1] = w2;
y1[2] = w1;
y1[3] = w2;
x1[0] = delta[0];
return (subInterpolater.interpolate(y1, x1));
}
/**
* Return number of Y arguments required for this Interpolater
*
* @return number of Y arguments
*/
@Override
public int getNumberOfRequiredYArgs() {
return 8;
}
/**
* Return number of X arguments required for this Interpolater
*
* @return number of X arguments
*/
@Override
public int getNumberOfRequiredXArgs() {
return 9;
}
}
| 23.304348 | 79 | 0.631716 |
b592d5a59d2d1bf805fdf24ff3a52343ab8cb050
| 3,534 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.core.clients.versioncontrol.soapextensions.internal;
import com.microsoft.tfs.core.clients.versioncontrol.VersionControlConstants;
/**
* This class does not implement the "compression" done in the VS
* implementation, only parsing for file ID and destroy detection.
*
* @threadsafety thread-safe
*/
public class DownloadURL {
/**
* The string "&fid=" to search for in the download URL.
*/
private final static String FILE_ID_SEARCH_STRING = "&fid="; //$NON-NLS-1$
/**
* The download URL's path part.
*/
private final String queryString;
/**
* The file ID parsed from the query arguments.
*/
private final int fileID;
/**
* Creates a new {@link DownloadURL} instance from the query string part of
* a TFS download URL.
*
* @param queryString
* the query string to parse (may be <code>null</code> or empty)
*/
public DownloadURL(final String queryString) {
// Query string is always saved untouched
this.queryString = queryString;
if (queryString == null || queryString.length() == 0) {
this.fileID = 0;
return;
}
// Parse the file ID
// Find the first character of the file ID (number).
int pos;
/*
* Look for the "fid=" part of "&fid=" at the beginning of the string,
* since there is no & separator at the beginning.
*/
if (queryString.startsWith(FILE_ID_SEARCH_STRING.substring(1))) {
pos = FILE_ID_SEARCH_STRING.length() - 1;
} else {
// Look "&fid=" in the entire url
pos = queryString.indexOf(FILE_ID_SEARCH_STRING);
if (pos < 0) {
// String did not contain a fid= key/value pair.
this.fileID = 0;
return;
}
pos += FILE_ID_SEARCH_STRING.length();
}
if (pos == queryString.length()) {
// String ended in "fid=".
this.fileID = 0;
return;
}
/*
* Find the first character after the file ID. It is legal for the index
* to be just off the end of the string.
*/
int endPos = queryString.indexOf('&', pos);
if (endPos < 0) {
endPos = queryString.length();
}
// Get and store the file ID.
final String fileIdString = queryString.substring(pos, endPos);
if (fileIdString == null || fileIdString.length() == 0) {
// Value of fid= key/value pair was not a number.
this.fileID = 0;
return;
}
int id = 0;
try {
id = Integer.parseInt(fileIdString);
} catch (final NumberFormatException e) {
id = 0;
}
this.fileID = id;
}
/**
* @return true if the content represented by this download url has been
* destroyed.
*/
public boolean isContentDestroyed() {
return (null != queryString && fileID == VersionControlConstants.DESTROYED_FILE_ID /* 1023 */);
}
public int getFileID() {
return fileID;
}
/**
* Returns a string representation of the download URL which is equal to the
* one provided at construction.
*/
public String getURL() {
return queryString;
}
}
| 28.272 | 103 | 0.56961 |
f41df8bdba42335bbe0b74b69b553783dbb7cf44
| 6,444 |
package org.dc.penguin.core.utils;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.dc.jdbc.core.ConnectionManager;
import org.dc.jdbc.core.DbHelper;
import org.dc.penguin.core.NodeConfigInfo;
import org.dc.penguin.core.pojo.Message;
import org.dc.penguin.core.pojo.MessageQueue;
import org.dc.penguin.core.pojo.MsgType;
import org.dc.penguin.core.pojo.RoleType;
import org.dc.penguin.core.raft.NodeInfo;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
public class RaftUtils {
/**
* 获取本机所有IP
* @throws Exception
*/
//private static Set<String> ipSet = new HashSet<String>();
public static Set<String> getAllLocalHostIP() throws Exception {
Set<String> ipSet = new HashSet<String>();
Enumeration<NetworkInterface> netInterfaces;
netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration<InetAddress> ni_enum = ni.getInetAddresses();
while (ni_enum.hasMoreElements()) {
ip = (InetAddress) ni_enum.nextElement();
if (ip.getHostAddress().indexOf(":") == -1) {
ipSet.add(ip.getHostAddress());
}
}
}
return ipSet;
}
private static Map<String,SocketPool> socketPoolMap = new ConcurrentHashMap<String,SocketPool>();
private static Lock lock = new ReentrantLock();
public static SocketPool getSocketPool(String host , int port) {
String key = host+":"+port;
SocketPool pool = socketPoolMap.get(key);
if(pool==null) {
lock.lock();
pool = socketPoolMap.get(key);
if(pool==null) {
pool = new SocketPool(host,port);
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(10);
GenericObjectPool<SocketConnection> objectPool = new GenericObjectPool<SocketConnection>(pool,poolConfig);
pool.setObjectPool(objectPool);
socketPoolMap.put(key, pool);
}
lock.unlock();
}
return pool;
}
private static Map<String,DbHelper> dbHelperMap = new ConcurrentHashMap<String,DbHelper>();
public static DbHelper getDBHelper(String host , int port) {
String key = host+":"+port;
DbHelper dbHelper = dbHelperMap.get(key);
if(dbHelper==null) {
lock.lock();
dbHelper = dbHelperMap.get(key);
if(dbHelper==null) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:h2:file:"+NodeConfigInfo.dataDir+"raftdb_"+port+"");
dataSource.setFailFast(true);
dataSource.setInitialSize(10);
dataSource.setLoginTimeout(5);
dataSource.setMaxActive(200);
dataSource.setMinIdle(1);
dataSource.setMaxWait(20000);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(true);
dataSource.setTestWhileIdle(true);
dataSource.setPoolPreparedStatements(false);
dbHelper = new DbHelper(dataSource);
dbHelperMap.put(key, dbHelper);
}
lock.unlock();
}
return dbHelper;
}
public static String createLeaderKey(NodeInfo nodeInfo) {
return nodeInfo.getHost()+":"+nodeInfo.getDataServerPort()+":"+nodeInfo.getElectionServerPort()+":"+nodeInfo.getTerm().get()+":"+nodeInfo.getDataIndex();
}
public static int getTerm(String leaderKey) {
return Integer.parseInt(leaderKey.split(":")[3]);
}
public static void initNodeInfo(NodeInfo nodeInfo) throws Throwable {
DbHelper dbHelper = RaftUtils.getDBHelper(nodeInfo.getHost(),nodeInfo.getDataServerPort());
ConnectionManager.setReadOnly(true);//设置数据库查询只读事务
Map<String, Object> rt_map = dbHelper.selectOne("select table_name from INFORMATION_SCHEMA.TABLES where table_name = 'RAFT_TABLE'");
if(rt_map==null) {
dbHelper.excuteSql("create table RAFT_TABLE(id bigInt PRIMARY KEY,key varchar(1000),value BLOB,data_index bigInt,term int)");
}else {
Message msgData = dbHelper.selectOne("select * from RAFT_TABLE order by data_index desc limit 1",Message.class);
if(msgData!=null) {
nodeInfo.setDataIndex(new AtomicLong(msgData.getDataIndex()));
nodeInfo.setTerm(new AtomicInteger(msgData.getTerm()));
}
}
}
public static Message sendMessage(String host,int port,String data) throws Exception {
SocketPool pool = RaftUtils.getSocketPool(host, port);
SocketConnection conn = null;
try {
conn = pool.getSocketConnection();
return JSON.parseObject(conn.sendMessage(data), Message.class);
}catch (Exception e) {
throw e;
}finally {
if(conn!=null) {
conn.close();
}
}
}
public static NodeInfo getLeaderNodeInfo() {
for (NodeInfo nodeInfo : NodeConfigInfo.nodeVector) {
if(nodeInfo.getRole()==RoleType.LEADER) {
return nodeInfo;
}
}
return null;
}
public static void dataSync(NodeInfo leaderNode, NodeInfo node) throws Exception {
//1.获取领导dataIndex
Message msg = new Message();
msg.setMsgCode(MsgType.GET_LEADER_LAST_DATAINDEX_POS);
Message mm = RaftUtils.sendMessage(leaderNode.getHost(), leaderNode.getElectionServerPort(), msg.toJSONString());
AtomicLong leaderIndex = new AtomicLong(Long.parseLong(new String(mm.getValue())));
//2.批量同步数据
//return true;
}
public static boolean dataSave(MessageQueue msgQue) throws Throwable {
DbHelper dbHelper = RaftUtils.getDBHelper(msgQue.getNodeInfo().getHost(), msgQue.getNodeInfo().getDataServerPort());
Long max_dataIndex = dbHelper.selectOne("select CAST(IFNULL(max(data_index),0) as bigInt) from RAFT_TABLE",Long.class);
if(max_dataIndex.longValue()==msgQue.getMessage().getDataIndex().longValue()-1) {
dbHelper.insertEntity(msgQue.getNodeInfo());//插入本地
Message msg_succ = new Message();
msg_succ.setMsgCode(MsgType.SUCCESS);
msgQue.getHandlerContext().channel().writeAndFlush(msg_succ.toJSONString());
return true;
}else {
return false;
}
}
}
| 36.613636 | 156 | 0.719274 |
359bd643e2a4f86a87d936232db46f0c0fb2dfea
| 90 |
package p;
class A{
int m(int i){
}
}
class B extends A{
int m(int i){
int o= i;
}
}
| 9 | 18 | 0.544444 |
60faaaf032726d0029604c9f67c80af2c65a0419
| 4,807 |
package hudson.util;
import hudson.Functions;
import hudson.os.PosixAPI;
import hudson.os.PosixException;
import java.io.*;
import java.util.regex.Pattern;
/**
* Adds more to commons-io.
*
* @author Kohsuke Kawaguchi
* @since 1.337
*/
public class IOUtils extends org.apache.commons.io.IOUtils {
/**
* Drains the input stream and closes it.
*/
public static void drain(InputStream in) throws IOException {
copy(in,new NullStream());
in.close();
}
public static void copy(File src, OutputStream out) throws IOException {
FileInputStream in = new FileInputStream(src);
try {
copy(in,out);
} finally {
closeQuietly(in);
}
}
public static void copy(InputStream in, File out) throws IOException {
FileOutputStream fos = new FileOutputStream(out);
try {
copy(in,fos);
} finally {
closeQuietly(fos);
}
}
/**
* Ensures that the given directory exists (if not, it's created, including all the parent directories.)
*
* @return
* This method returns the 'dir' parameter so that the method call flows better.
*/
public static File mkdirs(File dir) throws IOException {
if(dir.mkdirs() || dir.exists())
return dir;
// following Ant <mkdir> task to avoid possible race condition.
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// ignore
}
if (dir.mkdirs() || dir.exists())
return dir;
throw new IOException("Failed to create a directory at "+dir);
}
/**
* Fully skips the specified size from the given input stream.
*
* <p>
* {@link InputStream#skip(long)} has two problems. One is that
* it doesn't let us reliably differentiate "hit EOF" case vs "inpustream just returning 0 since there's no data
* currently available at hand", and some subtypes (such as {@link FileInputStream#skip(long)} returning -1.
*
* <p>
* So to reliably skip just the N bytes, we'll actually read all those bytes.
*
* @since 1.349
*/
public static InputStream skip(InputStream in, long size) throws IOException {
DataInputStream di = new DataInputStream(in);
while (size>0) {
int chunk = (int)Math.min(SKIP_BUFFER.length,size);
di.readFully(SKIP_BUFFER,0,chunk);
size -= chunk;
}
return in;
}
/**
* Resolves the given path with respect to given base. If the path represents an absolute path, a file representing
* it is returned, otherwise a file representing a path relative to base is returned.
* <p>
* It would be nice if File#File(File, String) were doing this.
* @param base File that represents the parent, may be null if path is absolute
* @param path Path of the file, may not be null
* @return new File(name) if name represents an absolute path, new File(base, name) otherwise
* @see hudson.FilePath#absolutize()
*/
public static File absolutize(File base, String path) {
if (isAbsolute(path))
return new File(path);
return new File(base, path);
}
/**
* See {@link hudson.FilePath#isAbsolute(String)}.
* @param path String representing <code> Platform Specific </code> (unlike FilePath, which may get Platform agnostic paths), may not be null
* @return true if String represents absolute path on this platform, false otherwise
*/
public static boolean isAbsolute(String path) {
Pattern DRIVE_PATTERN = Pattern.compile("[A-Za-z]:[\\\\/].*");
return path.startsWith("/") || DRIVE_PATTERN.matcher(path).matches();
}
/**
* Gets the mode of a file/directory, if appropriate.
* @return a file mode, or -1 if not on Unix
* @throws PosixException if the file could not be statted, e.g. broken symlink
*/
public static int mode(File f) throws PosixException {
if(Functions.isWindows()) return -1;
return PosixAPI.jnr().stat(f.getPath()).mode();
}
/**
* Read the first line of the given stream, close it, and return that line.
*
* @param encoding
* If null, use the platform default encoding.
* @since 1.422
*/
public static String readFirstLine(InputStream is, String encoding) throws IOException {
BufferedReader reader = new BufferedReader(
encoding==null ? new InputStreamReader(is) : new InputStreamReader(is,encoding));
try {
return reader.readLine();
} finally {
reader.close();
}
}
private static final byte[] SKIP_BUFFER = new byte[8192];
}
| 32.70068 | 145 | 0.617849 |
0d38cc21f8ed6a596391bbee6cbaa1b3b0f72d33
| 4,145 |
package com.epam.brest.service.impl;
import com.epam.brest.model.Car;
import com.epam.brest.service.config.ServiceTestConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith({SpringExtension.class})
@Import({ServiceTestConfig.class})
@Transactional
class CarServiceImplTestIT {
public static final Logger LOG = LogManager.getLogger(CarServiceImplTestIT.class);
@Autowired
CarServiceImpl carService;
@Test
void findAllCars() {
LOG.info("Method started: findAllCars() of {}", getClass().getName());
assertNotNull(carService);
assertNotNull(carService.findAllCars());
LOG.info("{}", carService.findAllCars());
}
@Test
void findCarById() {
LOG.info("Method started: findCarById() of {}", getClass().getName());
assertNotNull(carService);
List<Car> cars = carService.findAllCars();
if(cars.size() == 0) {
carService.saveCar(new Car("ZILOK", 2));
cars = carService.findAllCars();
}
Car carSrc = cars.get(0);
Car carDst = carService.findCarById(carSrc.getCarId());
assertEquals(carSrc.getCarModel(), carDst.getCarModel());
LOG.info("Car's name first from list: {} equals car's name after finding by id {}: {}",
carSrc.getCarModel(), carSrc.getCarId(), carDst.getCarModel());
}
@Test
void saveCar() {
LOG.info("Method started: saveCar() of {}", getClass().getName());
assertNotNull(carService);
Integer countCarBeforeSave = carService.count();
Integer countCarAfterSave = carService.saveCar(new Car("LADA", 1));
assertNotNull(countCarAfterSave);
assertEquals(countCarBeforeSave, carService.count() - 1);
LOG.info("Size driver's list before save():{} equals after save minus one {}", countCarBeforeSave, carService.count() - 1);
}
@Test
void updateCarById() {
LOG.info("Method started: updateCarById() of {}", getClass().getName());
assertNotNull(carService);
List<Car> cars = carService.findAllCars();
if(cars.size() == 0) {
carService.saveCar(new Car("AUDI", 1));
cars = carService.findAllCars();
}
Car carSrc = cars.get(0);
carSrc.setCarModel(carSrc.getCarModel() + "_TEST");
carService.updateCarById(carSrc.getCarId(), carSrc);
Car carDst = carService.findCarById(carSrc.getCarId());
assertEquals(carSrc.getCarModel(), carDst.getCarModel());
LOG.info("Car's name first from list: {} equals car's name after updating: {}", carSrc.getCarModel(), carDst.getCarModel());
}
@Test
void deleteCarById() {
LOG.info("Method started: deleteCarById() of {}", getClass().getName());
assertNotNull(carService);
carService.saveCar(new Car("MUSTANG", 1));
Integer countRecordsBeforeDelete = carService.count();
List<Car> cars = carService.findAllCars();
Car carSrc = cars.get(cars.size() - 1);
carService.deleteCarById(carSrc.getCarId());
assertEquals(countRecordsBeforeDelete - 1, carService.findAllCars().size());
LOG.info("Count records before deleting minus one: {} equals car's size list after deleting {}", countRecordsBeforeDelete - 1, carService.findAllCars().size());
}
@Test
void count() {
LOG.info("Method started: count() of {}", getClass().getName());
assertNotNull(carService);
List<Car> cars = carService.findAllCars();
assertEquals(cars.size(), carService.count());
LOG.info("Quantity of records {} equals size of car's list {}", carService.count(), cars.size());
}
}
| 40.242718 | 168 | 0.662002 |
dc1f2f70571fac3cdca2fa55ec4387df66b5b84c
| 964 |
package com.zackratos.ultimatebarx.sample;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.zackratos.ultimatebarx.library.UltimateBarX;
/**
* @Author : Zackratos
* @Date : 2020/7/11 4:10
* @email : 869649338@qq.com
* @Describe :
*/
public class DrawerFragment extends Fragment {
DrawerFragment() {
super(R.layout.fragment_drawer);
}
public static DrawerFragment newInstance() {
return new DrawerFragment();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// UltimateBarX.create(UltimateBarX.STATUS_BAR)
// .transparent()
// .apply(this);
UltimateBarX.with(this)
.transparent()
.applyStatusBar();
}
}
| 24.717949 | 88 | 0.66805 |
65e5fa9a377d1254580b34aa524d7906486ee54d
| 723 |
package rlbotexample.app.physics.state_setter;
import rlbot.gamestate.*;
import rlbotexample.dynamic_objects.car.ExtendedCarData;
import util.game_constants.RlConstants;
import util.game_situation.GameSituation;
import util.math.vector.Vector3;
public class CarStateSetter {
public static void applyPhysics(PhysicsState alternativePhysics, ExtendedCarData carData) {
GameState gameState = GameSituation.getCurrentGameState();
final CarState defaultCarState = new CarState();
final CarState alternativeCarState = defaultCarState.withPhysics(alternativePhysics);
gameState.withCarState(carData.playerIndex, alternativeCarState);
GameSituation.applyGameState(gameState);
}
}
| 38.052632 | 95 | 0.795297 |
bd74bf3e91273b9870085d7c3bbad0096aba1acf
| 9,773 |
package io.github.jhipster.sample.repository;
import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.PagingIterable;
import com.datastax.oss.driver.api.core.cql.BatchStatement;
import com.datastax.oss.driver.api.core.cql.BatchStatementBuilder;
import com.datastax.oss.driver.api.core.cql.BoundStatement;
import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder;
import com.datastax.oss.driver.api.core.cql.DefaultBatchType;
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.mapper.annotations.Dao;
import com.datastax.oss.driver.api.mapper.annotations.DaoFactory;
import com.datastax.oss.driver.api.mapper.annotations.DaoKeyspace;
import com.datastax.oss.driver.api.mapper.annotations.Delete;
import com.datastax.oss.driver.api.mapper.annotations.Insert;
import com.datastax.oss.driver.api.mapper.annotations.Mapper;
import com.datastax.oss.driver.api.mapper.annotations.Select;
import io.github.jhipster.sample.domain.User;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import org.springframework.boot.autoconfigure.cassandra.CassandraProperties;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
/**
* Spring Data Cassandra repository for the {@link User} entity.
*/
@Repository
public class UserRepository {
private final CqlSession session;
private final Validator validator;
private UserDao userDao;
private PreparedStatement findOneByActivationKeyStmt;
private PreparedStatement findOneByResetKeyStmt;
private PreparedStatement insertByActivationKeyStmt;
private PreparedStatement insertByResetKeyStmt;
private PreparedStatement deleteByActivationKeyStmt;
private PreparedStatement deleteByResetKeyStmt;
private PreparedStatement findOneByLoginStmt;
private PreparedStatement insertByLoginStmt;
private PreparedStatement deleteByLoginStmt;
private PreparedStatement findOneByEmailStmt;
private PreparedStatement insertByEmailStmt;
private PreparedStatement deleteByEmailStmt;
private PreparedStatement truncateStmt;
private PreparedStatement truncateByResetKeyStmt;
private PreparedStatement truncateByLoginStmt;
private PreparedStatement truncateByEmailStmt;
public UserRepository(CqlSession session, Validator validator, CassandraProperties cassandraProperties) {
this.session = session;
this.validator = validator;
UserTokenMapper userTokenMapper = new UserTokenMapperBuilder(session).build();
userDao = userTokenMapper.userTokenDao(CqlIdentifier.fromCql(cassandraProperties.getKeyspaceName()));
findOneByActivationKeyStmt =
session.prepare("SELECT id " + "FROM user_by_activation_key " + "WHERE activation_key = :activation_key");
findOneByResetKeyStmt = session.prepare("SELECT id " + "FROM user_by_reset_key " + "WHERE reset_key = :reset_key");
insertByActivationKeyStmt =
session.prepare("INSERT INTO user_by_activation_key (activation_key, id) " + "VALUES (:activation_key, :id)");
insertByResetKeyStmt = session.prepare("INSERT INTO user_by_reset_key (reset_key, id) " + "VALUES (:reset_key, :id)");
deleteByActivationKeyStmt = session.prepare("DELETE FROM user_by_activation_key " + "WHERE activation_key = :activation_key");
deleteByResetKeyStmt = session.prepare("DELETE FROM user_by_reset_key " + "WHERE reset_key = :reset_key");
findOneByLoginStmt = session.prepare("SELECT id " + "FROM user_by_login " + "WHERE login = :login");
insertByLoginStmt = session.prepare("INSERT INTO user_by_login (login, id) " + "VALUES (:login, :id)");
deleteByLoginStmt = session.prepare("DELETE FROM user_by_login " + "WHERE login = :login");
findOneByEmailStmt = session.prepare("SELECT id " + "FROM user_by_email " + "WHERE email = :email");
insertByEmailStmt = session.prepare("INSERT INTO user_by_email (email, id) " + "VALUES (:email, :id)");
deleteByEmailStmt = session.prepare("DELETE FROM user_by_email " + "WHERE email = :email");
truncateStmt = session.prepare("TRUNCATE user");
truncateByResetKeyStmt = session.prepare("TRUNCATE user_by_reset_key");
truncateByLoginStmt = session.prepare("TRUNCATE user_by_login");
truncateByEmailStmt = session.prepare("TRUNCATE user_by_email");
}
public Optional<User> findById(String id) {
return userDao.get(id);
}
public Optional<User> findOneByActivationKey(String activationKey) {
BoundStatement stmt = findOneByActivationKeyStmt.bind().setString("activation_key", activationKey);
return findOneFromIndex(stmt);
}
public Optional<User> findOneByResetKey(String resetKey) {
BoundStatement stmt = findOneByResetKeyStmt.bind().setString("reset_key", resetKey);
return findOneFromIndex(stmt);
}
public Optional<User> findOneByEmailIgnoreCase(String email) {
BoundStatement stmt = findOneByEmailStmt.bind().setString("email", email.toLowerCase());
return findOneFromIndex(stmt);
}
public Optional<User> findOneByLogin(String login) {
BoundStatement stmt = findOneByLoginStmt.bind().setString("login", login);
return findOneFromIndex(stmt);
}
public List<User> findAll() {
return userDao.findAll().all();
}
public User save(User user) {
Set<ConstraintViolation<User>> violations = validator.validate(user);
if (violations != null && !violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
User oldUser = userDao.get(user.getId()).orElse(null);
if (oldUser != null) {
if (!StringUtils.isEmpty(oldUser.getActivationKey()) && !oldUser.getActivationKey().equals(user.getActivationKey())) {
session.execute(deleteByActivationKeyStmt.bind().setString("activation_key", oldUser.getActivationKey()));
}
if (!StringUtils.isEmpty(oldUser.getResetKey()) && !oldUser.getResetKey().equals(user.getResetKey())) {
session.execute(deleteByResetKeyStmt.bind().setString("reset_key", oldUser.getResetKey()));
}
if (!StringUtils.isEmpty(oldUser.getLogin()) && !oldUser.getLogin().equals(user.getLogin())) {
session.execute(deleteByLoginStmt.bind().setString("login", oldUser.getLogin()));
}
if (!StringUtils.isEmpty(oldUser.getEmail()) && !oldUser.getEmail().equalsIgnoreCase(user.getEmail())) {
session.execute(deleteByEmailStmt.bind().setString("email", oldUser.getEmail().toLowerCase()));
}
}
BatchStatementBuilder batch = BatchStatement.builder(DefaultBatchType.LOGGED);
batch.addStatement(userDao.saveQuery(user));
if (!StringUtils.isEmpty(user.getActivationKey())) {
batch.addStatement(
insertByActivationKeyStmt.bind().setString("activation_key", user.getActivationKey()).setString("id", user.getId())
);
}
if (!StringUtils.isEmpty(user.getResetKey())) {
batch.addStatement(insertByResetKeyStmt.bind().setString("reset_key", user.getResetKey()).setString("id", user.getId()));
}
batch.addStatement(insertByLoginStmt.bind().setString("login", user.getLogin()).setString("id", user.getId()));
batch.addStatement(insertByEmailStmt.bind().setString("email", user.getEmail().toLowerCase()).setString("id", user.getId()));
session.execute(batch.build());
return user;
}
public void delete(User user) {
BatchStatementBuilder batch = BatchStatement.builder(DefaultBatchType.LOGGED);
batch.addStatement(userDao.deleteQuery(user));
if (!StringUtils.isEmpty(user.getActivationKey())) {
batch.addStatement(deleteByActivationKeyStmt.bind().setString("activation_key", user.getActivationKey()));
}
if (!StringUtils.isEmpty(user.getResetKey())) {
batch.addStatement(deleteByResetKeyStmt.bind().setString("reset_key", user.getResetKey()));
}
batch.addStatement(deleteByLoginStmt.bind().setString("login", user.getLogin()));
batch.addStatement(deleteByEmailStmt.bind().setString("email", user.getEmail().toLowerCase()));
session.execute(batch.build());
}
private Optional<User> findOneFromIndex(BoundStatement stmt) {
ResultSet rs = session.execute(stmt);
return Optional.ofNullable(rs.one()).map(row -> row.getString("id")).flatMap(id -> userDao.get(id));
}
public void deleteAll() {
BoundStatement truncate = truncateStmt.bind();
session.execute(truncate);
BoundStatement truncateByEmail = truncateByEmailStmt.bind();
session.execute(truncateByEmail);
BoundStatement truncateByLogin = truncateByLoginStmt.bind();
session.execute(truncateByLogin);
BoundStatement truncateByResetKey = truncateByResetKeyStmt.bind();
session.execute(truncateByResetKey);
}
}
@Dao
interface UserDao {
@Select
Optional<User> get(String id);
@Select
PagingIterable<User> findAll();
@Insert
BoundStatement saveQuery(User user);
@Delete
BoundStatement deleteQuery(User user);
}
@Mapper
interface UserTokenMapper {
@DaoFactory
UserDao userTokenDao(@DaoKeyspace CqlIdentifier keyspace);
}
| 41.764957 | 134 | 0.717692 |
04bddbbeb3ac5a9d7550d0ce119b5ad1ba3950b2
| 1,227 |
package edu.rafat.tushar.onlinestore;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.craftman.cardform.Card;
import com.craftman.cardform.CardForm;
import com.craftman.cardform.OnPayBtnClickListner;
import com.google.android.gms.common.internal.Objects;
public class Payment_form extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_form);
CardForm cardForm = (CardForm)findViewById(R.id.cardform);
TextView textDes = (TextView)findViewById(R.id.payment_amount);
Button btnPay = (Button)findViewById(R.id.btn_pay);
textDes.setText("$1999");
btnPay.setText(String.format("payer %s",textDes.getText()));
cardForm.setPayBtnClickListner(new OnPayBtnClickListner() {
@Override
public void onClick(Card card) {
Toast.makeText(Payment_form.this, "Name:"+card.getName()+" Last 4 digits:"+card.getLast4(), Toast.LENGTH_SHORT).show();
}
});
}
}
| 31.461538 | 135 | 0.711491 |
e8f94defd4e00efadcc01a03ee47c813eb603d89
| 215 |
package io.girirajvyas.gof.designpatterns.structural.bridge.shapewithbridge;
public class BlueColour implements Colour {
@Override
public void applyColour() {
System.out.println("Applying Blue Colour");
}
}
| 19.545455 | 76 | 0.781395 |
8e87eb4dfd210ca9f917c49f2f1774bac53bac25
| 863 |
package com.example.librx.rx.http;
import com.example.librx.rx.BaseResult;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.functions.Function;
/**
* @author 李栋杰
* @time 2017/7/29 10:25
* @desc 用于处理操作成功(data为空,又需要提示的情况)的情况
*/
public class ServerResultWithDataFunc <T extends BaseResult> implements Function<T, T> {
//将不是对应的code抛出ServerException处理
@Override
public T apply(T baseResult) throws Exception {
List<String> codes = getStayCode();
//通过请求码判断是否请求成功
if (codes.contains(baseResult.code)) {
return baseResult;
}
throw new ServerException(baseResult);
}
//将需要的保留的信息留在onNext中
public List<String> getStayCode() {
List<String> list = new ArrayList<>();
//请求成功返回码(该天气API的请求成功返回码是200)
list.add("200");
return list;
}
}
| 23.972222 | 88 | 0.660487 |
85777684954ce2a9a6b4268cf9009d69a1ffa1a7
| 1,758 |
package sonia.scm.schedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Singleton
public class CronScheduler implements Scheduler {
private static final Logger LOG = LoggerFactory.getLogger(CronScheduler.class);
private final ScheduledExecutorService executorService;
private final CronTaskFactory taskFactory;
private final CronThreadFactory threadFactory;
@Inject
public CronScheduler(CronTaskFactory taskFactory) {
this.taskFactory = taskFactory;
this.threadFactory = new CronThreadFactory();
this.executorService = createExecutor();
}
private ScheduledExecutorService createExecutor() {
return Executors.newScheduledThreadPool(2, threadFactory);
}
@Override
public CronTask schedule(String expression, Runnable runnable) {
return schedule(taskFactory.create(expression, runnable));
}
@Override
public CronTask schedule(String expression, Class<? extends Runnable> runnable) {
return schedule(taskFactory.create(expression, runnable));
}
private CronTask schedule(CronTask task) {
if (task.hasNextRun()) {
LOG.debug("schedule task {}", task);
Future<?> future = executorService.scheduleAtFixedRate(task, 0L, 1L, TimeUnit.SECONDS);
task.setFuture(future);
} else {
LOG.debug("skip scheduling, because task {} has no next run", task);
}
return task;
}
@Override
public void close() {
LOG.debug("shutdown underlying executor service");
threadFactory.close();
executorService.shutdown();
}
}
| 28.819672 | 93 | 0.750853 |
b5ca34dc905744ccf302e1895be4e991d38c9e56
| 2,131 |
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.events;
import java.util.regex.Pattern;
/**
* An output filter for warnings.
*/
public interface OutputFilter {
/** An output filter that matches everything. */
public static final OutputFilter OUTPUT_EVERYTHING = new OutputFilter() {
@Override
public boolean showOutput(String tag) {
return true;
}
};
/** An output filter that matches nothing. */
public static final OutputFilter OUTPUT_NOTHING = new OutputFilter() {
@Override
public boolean showOutput(String tag) {
return false;
}
};
/**
* Returns true iff the given tag matches the output filter.
*/
boolean showOutput(String tag);
/**
* An output filter using regular expression matching.
*/
public static final class RegexOutputFilter implements OutputFilter {
/** Returns an output filter for the given regex (by compiling it). */
public static OutputFilter forRegex(String regex) {
return new RegexOutputFilter(Pattern.compile(regex));
}
/** Returns an output filter for the given pattern. */
public static OutputFilter forPattern(Pattern pattern) {
return new RegexOutputFilter(pattern);
}
private final Pattern pattern;
private RegexOutputFilter(Pattern pattern) {
this.pattern = pattern;
}
@Override
public boolean showOutput(String tag) {
return pattern.matcher(tag).find();
}
@Override
public String toString() {
return pattern.toString();
}
}
}
| 28.039474 | 75 | 0.700141 |
1026f63924b328d34fb8582c9bf248ad98c630dc
| 220 |
package com.semihshn.passengerservice.adapter.jpa.contactInfo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ContactInfoJpaRepository extends JpaRepository<ContactInfoEntity, Long> {
}
| 31.428571 | 90 | 0.859091 |
3d3bee6b9a3397f1bc845b69c229a9bf70f84016
| 4,001 |
/*
* Copyright (c) 2010-2018 Nathan Rajlich
*
* 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 org.java_websocket.issues;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.java_websocket.util.SocketUtil;
import org.java_websocket.util.ThreadCheck;
import org.junit.Rule;
import org.junit.Test;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class Issue661Test {
@Rule
public ThreadCheck zombies = new ThreadCheck();
private CountDownLatch countServerDownLatch = new CountDownLatch( 1 );
private boolean wasError = false;
class TestPrintStream extends PrintStream {
public TestPrintStream( OutputStream out ) {
super( out );
}
@Override
public void println( Object o ) {
wasError = true;
super.println( o );
}
}
//@Test(timeout = 2000)
public void testIssue() throws Exception {
System.setErr( new TestPrintStream( System.err ) );
int port = SocketUtil.getAvailablePort();
WebSocketServer server0 = new WebSocketServer( new InetSocketAddress( port ) ) {
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
fail( "There should be no onOpen" );
}
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
fail( "There should be no onClose" );
}
@Override
public void onMessage( WebSocket conn, String message ) {
fail( "There should be no onMessage" );
}
@Override
public void onError( WebSocket conn, Exception ex ) {
fail( "There should be no onError!" );
}
@Override
public void onStart() {
countServerDownLatch.countDown();
}
};
server0.start();
try {
countServerDownLatch.await();
} catch ( InterruptedException e ) {
//
}
WebSocketServer server1 = new WebSocketServer( new InetSocketAddress( port ) ) {
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
fail( "There should be no onOpen" );
}
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
fail( "There should be no onClose" );
}
@Override
public void onMessage( WebSocket conn, String message ) {
fail( "There should be no onMessage" );
}
@Override
public void onError( WebSocket conn, Exception ex ) {
if( !( ex instanceof BindException ) ) {
fail( "There should be no onError" );
}
}
@Override
public void onStart() {
fail( "There should be no onStart!" );
}
};
server1.start();
Thread.sleep( 1000 );
server1.stop();
server0.stop();
Thread.sleep( 100 );
assertTrue( "There was an error using System.err", !wasError );
}
}
| 28.992754 | 83 | 0.712572 |
9b491cc29ebf731fb6c4cb07e3ecf3455f345b55
| 8,154 |
package org.apache.maven.shared.release;
/*
* 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 static org.junit.Assert.fail;
import java.io.File;
import java.io.InputStream;
import org.codehaus.plexus.ContainerConfiguration;
import org.codehaus.plexus.DefaultContainerConfiguration;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.PlexusContainerException;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.DefaultContext;
import org.junit.After;
import org.junit.Before;
/**
* Based on PlexusTestCase from org.sonatype.sisu:sisu-inject-plexus
*
* @author Robert Scholte
*/
public abstract class PlexusJUnit4TestCase
{
private PlexusContainer container;
private static String basedir;
@Before
public void setUp()
throws Exception
{
basedir = getBasedir();
}
protected void setupContainer()
{
// ----------------------------------------------------------------------------
// Context Setup
// ----------------------------------------------------------------------------
final DefaultContext context = new DefaultContext();
context.put( "basedir", getBasedir() );
customizeContext( context );
final boolean hasPlexusHome = context.contains( "plexus.home" );
if ( !hasPlexusHome )
{
final File f = getTestFile( "target/plexus-home" );
if ( !f.isDirectory() )
{
f.mkdir();
}
context.put( "plexus.home", f.getAbsolutePath() );
}
// ----------------------------------------------------------------------------
// Configuration
// ----------------------------------------------------------------------------
final String config = getCustomConfigurationName();
final ContainerConfiguration containerConfiguration =
new DefaultContainerConfiguration().setName( "test" ).setContext( context.getContextData() ).setClassPathCaching( true );
if ( config != null )
{
containerConfiguration.setContainerConfiguration( config );
}
else
{
final String resource = getConfigurationName( null );
containerConfiguration.setContainerConfiguration( resource );
}
customizeContainerConfiguration( containerConfiguration );
try
{
container = new DefaultPlexusContainer( containerConfiguration );
}
catch ( final PlexusContainerException e )
{
e.printStackTrace();
fail( "Failed to create plexus container." );
}
}
/**
* Allow custom test case implementations do augment the default container configuration before executing tests.
*
* @param containerConfiguration
*/
protected void customizeContainerConfiguration( final ContainerConfiguration containerConfiguration )
{
}
protected void customizeContext( final Context context )
{
}
protected PlexusConfiguration customizeComponentConfiguration()
{
return null;
}
@After
public void tearDown()
throws Exception
{
if ( container != null )
{
container.dispose();
container = null;
}
}
protected PlexusContainer getContainer()
{
if ( container == null )
{
setupContainer();
}
return container;
}
protected InputStream getConfiguration()
throws Exception
{
return getConfiguration( null );
}
@SuppressWarnings( "unused" )
protected InputStream getConfiguration( final String subname )
throws Exception
{
return getResourceAsStream( getConfigurationName( subname ) );
}
protected String getCustomConfigurationName()
{
return null;
}
/**
* Allow the retrieval of a container configuration that is based on the name of the test class being run. So if you
* have a test class called org.foo.FunTest, then this will produce a resource name of org/foo/FunTest.xml which
* would be used to configure the Plexus container before running your test.
*
* @param subname
* @return
*/
protected String getConfigurationName( final String subname )
{
return getClass().getName().replace( '.', '/' ) + ".xml";
}
protected InputStream getResourceAsStream( final String resource )
{
return getClass().getResourceAsStream( resource );
}
protected ClassLoader getClassLoader()
{
return getClass().getClassLoader();
}
// ----------------------------------------------------------------------
// Container access
// ----------------------------------------------------------------------
protected Object lookup( final String componentKey )
throws Exception
{
return getContainer().lookup( componentKey );
}
protected Object lookup( final String role, final String roleHint )
throws Exception
{
return getContainer().lookup( role, roleHint );
}
protected <T> T lookup( final Class<T> componentClass )
throws Exception
{
return getContainer().lookup( componentClass );
}
protected <T> T lookup( final Class<T> componentClass, final String roleHint )
throws Exception
{
return getContainer().lookup( componentClass, roleHint );
}
protected void release( final Object component )
throws Exception
{
getContainer().release( component );
}
// ----------------------------------------------------------------------
// Helper methods for sub classes
// ----------------------------------------------------------------------
public static File getTestFile( final String path )
{
return new File( getBasedir(), path );
}
@SuppressWarnings( "hiding" )
public static File getTestFile( final String basedir, final String path )
{
File basedirFile = new File( basedir );
if ( !basedirFile.isAbsolute() )
{
basedirFile = getTestFile( basedir );
}
return new File( basedirFile, path );
}
public static String getTestPath( final String path )
{
return getTestFile( path ).getAbsolutePath();
}
@SuppressWarnings( "hiding" )
public static String getTestPath( final String basedir, final String path )
{
return getTestFile( basedir, path ).getAbsolutePath();
}
public static String getBasedir()
{
if ( basedir != null )
{
return basedir;
}
basedir = System.getProperty( "basedir" );
if ( basedir == null )
{
basedir = new File( "" ).getAbsolutePath();
}
return basedir;
}
public String getTestConfiguration()
{
return getTestConfiguration( getClass() );
}
public static String getTestConfiguration( final Class<?> clazz )
{
final String s = clazz.getName().replace( '.', '/' );
return s.substring( 0, s.indexOf( "$" ) ) + ".xml";
}
}
| 27.924658 | 133 | 0.586951 |
fe879097595f22e87fcaf05ae61dc96b3d7e6147
| 2,900 |
package com.blogpessoal.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.Size;
import javax.validation.groups.ConvertGroup;
import javax.validation.groups.Default;
import com.blogpessoal.validations.ValidationsGroups.ValidationAtualizacaoPostagem;
import com.blogpessoal.validations.ValidationsGroups.ValidationId;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
@Entity
public class Postagem implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull(groups = ValidationAtualizacaoPostagem.class)
@Null
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(groups = {Default.class, ValidationAtualizacaoPostagem.class})
@Size(groups = {Default.class, ValidationAtualizacaoPostagem.class}, min = 5, max = 100)
private String titulo;
@NotBlank(groups = {Default.class, ValidationAtualizacaoPostagem.class})
@Size(groups = {Default.class, ValidationAtualizacaoPostagem.class}, min = 10, max = 500)
private String texto;
@Temporal(TemporalType.TIMESTAMP)
private Date data = new java.sql.Date(System.currentTimeMillis());
@Valid
@ConvertGroup(from = Default.class, to = ValidationId.class)
@ConvertGroup(from = ValidationAtualizacaoPostagem.class, to = ValidationId.class)
@NotNull(groups = {Default.class, ValidationAtualizacaoPostagem.class})
@ManyToOne
@JsonIgnoreProperties("postagens")
private Tema tema;
@ManyToOne
@JsonIgnoreProperties("postagens")
private Usuario usuario;
public Postagem() {}
public Postagem(String titulo, String texto, Tema tema) {
this.titulo = titulo;
this.texto = texto;
this.tema = tema;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getTexto() {
return texto;
}
public void setTexto(String texto) {
this.texto = texto;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public Tema getTema() {
return tema;
}
public void setTema(Tema tema) {
this.tema = tema;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
}
| 24.576271 | 90 | 0.771379 |
6fcc26262e5ddc9171487bc2f7483f722c514f31
| 734 |
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import gnu.io.*;
public class Test
{
static public void main(String[] args) throws IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException
{
CommPortIdentifier id = CommPortIdentifier.getPortIdentifier(args[0]);
SerialPort port = (SerialPort) id.open("reader", 1000);
port.setSerialPortParams(19200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
InputStream in = port.getInputStream();
OutputStream out = port.getOutputStream();
out.write(0xFD);
}
}
| 30.583333 | 136 | 0.652589 |
49f14b420dbd2f9124449e90df1fe6ab3a71fec5
| 1,636 |
package cn.com.tsjx.infomation.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import cn.com.tsjx.common.dao.BaseDaoImpl;
import cn.com.tsjx.common.enums.Deleted;
import cn.com.tsjx.common.web.model.Pager;
import cn.com.tsjx.common.web.model.Params;
import cn.com.tsjx.infomation.dao.InfomationDao;
import cn.com.tsjx.infomation.entity.Infomation;
import cn.com.tsjx.infomation.entity.InfomationDto;
import cn.com.tsjx.user.entity.User;
@Repository("infomationDao")
public class InfomationDaoImpl extends BaseDaoImpl<Infomation, Long> implements InfomationDao {
@Override
public List<Infomation> getInfomationsByParam(User user, Infomation infomation) {
Params params = Params.create();
params.add("deleted", Deleted.NO.value);
params.add("userId", user.getId());
return this.selectList(this.getMethodName(), params);
}
@Override
public Pager<InfomationDto> getPagerCollections(Params map, Pager<InfomationDto> pager) {
return this.selectPage(this.getMethodName(),map,pager);
}
public Pager<InfomationDto> getInfoPagerWithImg(Params map, Pager<InfomationDto> pager) {
return this.selectPage(this.getMethodName(),map,pager);
}
public Pager<InfomationDto> getInfoPagerWithImgNoUser(Params map, Pager<InfomationDto> pager) {
return this.selectPage(this.getMethodName(),map,pager);
}
public void autoDown() {
Params param = Params.create();
this.update(this.getMethodName(),param);
}
}
| 32.078431 | 100 | 0.695599 |
b10996ef049cfbf36ce93ea0ca0e1ac7af84bac5
| 3,200 |
package com.taoerxue.manager.service;
import com.taoerxue.common.bean.Result;
import com.taoerxue.common.cache.redis.JedisClient;
import com.taoerxue.common.exception.SQLException;
import com.taoerxue.mapper.AdminUserMapper;
import com.taoerxue.pojo.AdminUser;
import com.taoerxue.pojo.AdminUserExample;
import com.taoerxue.util.JsonUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* Created by lizhihui on 2017-04-17 11:47.
*/
@Service
public class UserService {
@Resource
private JedisClient jedisClient;
@Resource
private AdminUserMapper adminUserMapper;
public String generateToken(AdminUser adminUser) {
String oldToken = jedisClient.get("manager:user:phone:" + adminUser.getPhone());
if (oldToken != null) {
jedisClient.del(oldToken);
}
//6.向 redis 中添加登录成功凭证
String token = UUID.randomUUID().toString().replace("-", "");
jedisClient.set("manager:user:phone:" + adminUser.getPhone(), token);
jedisClient.set(token, JsonUtils.objectToJson(adminUser));
return token;
}
public Result check(String phone, String password) {
AdminUserExample adminUserExample = new AdminUserExample();
adminUserExample.createCriteria().andPhoneEqualTo(phone);
List<AdminUser> adminUsers = adminUserMapper.selectByExample(adminUserExample);
if (adminUsers.size() < 1)
return Result.build(500, "帐号不存在");
AdminUser adminUser = adminUsers.get(0);
if (adminUser == null || !DigestUtils.md5DigestAsHex(password.trim().getBytes()).equals(adminUser.getPassword()))
return Result.build(500, "帐号不存在或密码错误");
if (adminUser.getStatus().equals(false))
return Result.build(500, "该帐号已经被禁用,请联系管理员");
//修改登录信息
changeLoginTime(phone);
//返回管理员信息
return Result.ok(adminUser);
}
private void changeLoginTime(String phone) {
AdminUserExample adminUserExample = new AdminUserExample();
adminUserExample.createCriteria().andPhoneEqualTo(phone);
AdminUser adminUser = new AdminUser();
adminUser.setLoginTime(new Date());
adminUserMapper.updateByExampleSelective(adminUser, adminUserExample);
}
public void resetPassword(String phone, String password) {
AdminUserExample adminUserExample = new AdminUserExample();
adminUserExample.createCriteria().andPhoneEqualTo(phone);
List<AdminUser> adminUsers = adminUserMapper.selectByExample(adminUserExample);
if (adminUsers.size() == 0)
throw new SQLException("帐号不存在");
AdminUser adminUser = adminUsers.get(0);
String newPassword = DigestUtils.md5DigestAsHex(password.trim().getBytes());
Integer id = adminUser.getId();
adminUser = new AdminUser();
adminUser.setId(id);
adminUser.setPassword(newPassword);
int i = adminUserMapper.updateByPrimaryKeySelective(adminUser);
if (i != 1)
throw new SQLException("重置密码失败");
}
}
| 35.955056 | 121 | 0.691875 |
032138e9a05a5b07a6d89933fc8ac9adb681fda8
| 1,128 |
/*
* */
package com.synectiks.process.server.shared.plugins;
import javax.inject.Inject;
import com.synectiks.process.server.plugin.rest.PluginRestResource;
import java.util.Map;
import java.util.Set;
/**
* This class provides the map of {@link PluginRestResource} classes that are available through the Guice mapbinder.
*
* We need this wrapper class to be able to inject the {@literal Set<Class<? extends PluginRestResource>>} into
* a Jersey REST resource. HK2 does not allow to inject this directly into the resource class.
*/
public class PluginRestResourceClasses {
private final Map<String, Set<Class<? extends PluginRestResource>>> pluginRestResources;
@Inject
public PluginRestResourceClasses(final Map<String, Set<Class<? extends PluginRestResource>>> pluginRestResources) {
this.pluginRestResources = pluginRestResources;
}
/**
* Returns a map of plugin packge names to Sets of {@link PluginRestResource} classes.
*
* @return the map
*/
public Map<String, Set<Class<? extends PluginRestResource>>> getMap() {
return pluginRestResources;
}
}
| 32.228571 | 119 | 0.73227 |
6ac1758968fcc7baebf901ca7ead246abe061abc
| 3,823 |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.0. You may not use this file
* except in compliance with the Zeebe Community License 1.0.
*/
package io.zeebe.util.collection;
import static org.agrona.BitUtil.SIZE_OF_INT;
/**
* Layout
*
* <p>*
*
* <pre>
* +----------------------------+
* | HEADER |
* +----------------------------+
* | DATA SECTION |
* +----------------------------+
* </pre>
*
* Header Layout
*
* <pre>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | SIZE |
* +---------------------------------------------------------------+
* | ELEMENT MAX LENGTH |
* +---------------------------------------------------------------+
* | CAPACITY |
* +---------------------------------------------------------------+
* </pre>
*
* Element Layout
*
* <pre>
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ELEMENT LENGTH |
* +---------------------------------------------------------------+
* | ELEMENT |
* +---------------------------------------------------------------+
* </pre>
*/
public final class CompactListDescriptor {
public static final int HEADER_OFFSET;
public static final int SIZE_OFFSET;
public static final int ELEMENT_MAX_LENGTH_OFFSET;
public static final int CAPACITY_OFFSET;
public static final int HEADER_LENGTH;
public static final int DATA_SECTION_OFFSET;
public static final int ELEMENT_HEADER_LENGTH;
public static final int ELEMENT_LENGTH_OFFSET;
static {
// list header
int offset = 0;
HEADER_OFFSET = offset;
SIZE_OFFSET = offset;
offset += SIZE_OF_INT;
ELEMENT_MAX_LENGTH_OFFSET = offset;
offset += SIZE_OF_INT;
CAPACITY_OFFSET = offset;
offset += SIZE_OF_INT;
HEADER_LENGTH = offset;
// data section
DATA_SECTION_OFFSET = offset;
// element header
offset = 0;
ELEMENT_LENGTH_OFFSET = offset;
offset += SIZE_OF_INT;
ELEMENT_HEADER_LENGTH = offset;
}
public static int headerOffset() {
return HEADER_OFFSET;
}
public static int sizeOffset() {
return SIZE_OFFSET;
}
public static int elementMaxLengthOffset() {
return ELEMENT_MAX_LENGTH_OFFSET;
}
public static int capacityOffset() {
return CAPACITY_OFFSET;
}
public static int dataSectionOffset() {
return DATA_SECTION_OFFSET;
}
public static int headerLength() {
return HEADER_LENGTH;
}
public static int requiredBufferCapacity(final int framedLength, final int capacity) {
return HEADER_LENGTH + (framedLength * capacity);
}
public static int elementOffset(final int framedLength, final int idx) {
return HEADER_LENGTH + (framedLength * idx);
}
public static int elementLengthOffset(final int offset) {
return ELEMENT_LENGTH_OFFSET + offset;
}
public static int elementDataOffset(final int offset) {
return ELEMENT_HEADER_LENGTH + offset;
}
public static int framedLength(final int length) {
return ELEMENT_HEADER_LENGTH + length;
}
}
| 27.113475 | 88 | 0.509809 |
630366995d1cab9c55bbc4b3896f3a38dda76b0c
| 1,960 |
/*
* Copyright 2000-2017 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.component.radiobutton.tests;
import java.util.List;
import com.vaadin.tests.AbstractComponentIT;
import com.vaadin.flow.testutil.TestPath;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
@TestPath("vaadin-radio-button/disabled-items")
public class DisabledItemsPageIT extends AbstractComponentIT {
@Test
public void set_items_to_disabled_group_should_be_disabled() {
open();
WebElement group = findElement(By.id("button-group"));
List<WebElement> buttons = group
.findElements(By.tagName("vaadin-radio-button"));
Assert.assertTrue("No buttons should be present", buttons.isEmpty());
// Click button to add items
findElement(By.id("add-button")).click();
waitForElementPresent(By.tagName("vaadin-radio-button"));
buttons = group.findElements(By.tagName("vaadin-radio-button"));
Assert.assertEquals("Group should have buttons", 2, buttons.size());
// re-get the elements to not get stale element exception.
for (WebElement button : group.findElements(By.tagName("vaadin-radio-button"))) {
Assert.assertEquals("All buttons should be disabled",
Boolean.TRUE.toString(), button.getAttribute("disabled"));
}
}
}
| 36.981132 | 89 | 0.707653 |
e64186efa191129fe287b297ba562da8d20c331f
| 268 |
/*
* Copyright 2010-2011, Sikuli.org
* Released under the MIT License.
*
*/
package org.sikuli.script;
public class AppearEvent extends SikuliEvent {
public AppearEvent(Object ptn, Match m, Region r){
super(ptn, m, r);
type = Type.APPEAR;
}
}
| 16.75 | 53 | 0.660448 |
a4245e62b7fb3d40082b1d5ad6320491b8c6eb38
| 525 |
package pers.jay.wanandroid.widgets;
import android.app.Activity;
import android.content.Context;
import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.DialogLayer;
import pers.jay.wanandroid.R;
public class ConfirmDialog extends DialogLayer {
public ConfirmDialog(Activity activity) {
super(activity);
}
public ConfirmDialog(Context context) {
super(context);
}
public void show() {
// AnyLayer.dialog().contentView(R.layout.base_ui_layout_dialog_confirm).
}
}
| 21.875 | 80 | 0.725714 |
ce644060acad355fe83e4bb934ec380261b5326c
| 4,068 |
package com.stock.chart.core.services;
import com.stock.chart.core.entities.*;
import com.stock.chart.core.repos.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class FileImportService {
@Autowired
private CompanyRepo companyRepo;
@Autowired
private ContactRepo contactRepo;
@Autowired
private StockExchangeRepo stockExchangeRepo;
@Autowired
private StockRepo stockRepo;
@Autowired
private SectorRepo sectorRepo;
public void importExcelFile(InputStream inputStream) throws IOException, ParseException {
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = firstSheet.iterator();
rowIterator.next();
DateFormat format = new SimpleDateFormat("DD-MM-YYYY HH:MM:SS", Locale.ENGLISH);
while(rowIterator.hasNext()) {
Iterator<Cell> cells = rowIterator.next().cellIterator();
String companyName = cells.next().getStringCellValue();
String stockExchangeName = cells.next().getStringCellValue();
Date day = cells.next().getDateCellValue();
Double oprice = cells.next().getNumericCellValue();
Double cprice = cells.next().getNumericCellValue();
StockExchange se = getorCreateStockExchange(stockExchangeName);
createStockPrice(oprice, cprice, day, getOrCreateCompany(companyName, se), se);
}
}
private StockExchange getorCreateStockExchange(String stockExchangeName) {
List<StockExchange> ses = stockExchangeRepo.findByNameContainingIgnoreCase(stockExchangeName);
if (ses == null || ses.size() == 0) {
// Create
StockExchange se = new StockExchange();
se.setName(stockExchangeName);
se.setContact(getOrCreateContact(stockExchangeName+"City"));
return stockExchangeRepo.save(se);
}
else {
return ses.get(0);
}
}
private Contact getOrCreateContact(String cityName) {
List<Contact> cns = contactRepo.findByCityContainingIgnoreCase(cityName);
if (cns == null || cns.size() == 0) {
Contact c = new Contact();
c.setCity(cityName);
return contactRepo.save(c);
}
else {
return cns.get(0);
}
}
private Sector getOrCreateSector() {
List<Sector> ss = sectorRepo.findByNameContainingIgnoreCase("Test");
if(ss == null || ss.size() == 0) {
Sector s = new Sector();
s.setName("Test");
return sectorRepo.save(s);
}
else {
return ss.get(0);
}
}
private Company getOrCreateCompany(String companyName, StockExchange stockExchange) {
List<Company> cs = companyRepo.findByNameContainingIgnoreCase(companyName);
if(cs == null || cs.size() == 0) {
Company c = new Company();
c.setName(companyName);
c.setStockExchanges(new HashSet<>());
c.getStockExchanges().add(stockExchange);
c.setSector(getOrCreateSector());
return companyRepo.save(c);
}
else {
return cs.get(0);
}
}
private Stock createStockPrice(Double oprice, Double cprice, Date day, Company company, StockExchange se) {
Stock s = new Stock();
s.setClosePrice(cprice);
s.setOpenPrice(oprice);
s.setCompany(company);
s.setStockExchange(se);
s.setDate(day);
return stockRepo.save(s);
}
}
| 33.9 | 111 | 0.645034 |
d2de82bbfe5490bf2ff709b57b083b0cdae82b2b
| 3,710 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2021-2022 Yegor Bugayenko
*
* 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 NON-INFRINGEMENT. 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.
*/
// @checkstyle PackageNameCheck (1 line)
package EOorg.EOeolang.EOio;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.eolang.Data;
import org.eolang.Dataized;
import org.eolang.PhConst;
import org.eolang.PhMethod;
import org.eolang.PhWith;
import org.eolang.Phi;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
/**
* Test.
*
* @since 0.1
* @checkstyle TypeNameCheck (100 lines)
*/
public final class EObytes_as_inputEOreadTest {
@ParameterizedTest
@CsvFileSource(resources = "/EOlang/EOio/test-samples.csv")
public void readsBytes(final String text, final int max) throws IOException {
final Phi bytes = new Data.ToPhi(text.getBytes());
Phi input = new PhWith(
new EObytes_as_input(bytes),
"b", bytes
);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true) {
input = new PhConst(
new PhWith(
input.attr("read").get(),
"max", new Data.ToPhi((long) max)
)
);
final byte[] chunk = new Dataized(input).take(byte[].class);
if (chunk.length == 0) {
new Dataized(input.attr("close").get()).take();
break;
}
baos.write(chunk);
}
MatcherAssert.assertThat(
new String(baos.toByteArray(), StandardCharsets.UTF_8),
Matchers.equalTo(text)
);
}
@ParameterizedTest
@CsvFileSource(resources = "/EOlang/EOio/test-samples.csv")
public void readsBytesFromString(final String text, final int max) {
final Phi input = new PhWith(
new EObytes_as_input(Phi.Φ),
"b",
new PhMethod(
new Data.ToPhi(text),
"as-bytes"
)
);
final Phi first = new PhConst(
new PhWith(
input.attr("read").get(),
"max", new Data.ToPhi((long) max)
)
);
final Phi last = new PhConst(
new PhWith(
first.attr("read").get(),
"max", new Data.ToPhi((long) max)
)
).copy();
Assertions.assertDoesNotThrow(
() -> new Dataized(last).take(byte[].class)
);
}
}
| 34.672897 | 81 | 0.630728 |
bd6448632cc757629ce2cd33c65f6ab85c99a428
| 5,458 |
/*
* 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.iotdb.cluster.log.logtypes;
import org.apache.iotdb.cluster.common.TestUtils;
import org.apache.iotdb.cluster.exception.UnknownLogTypeException;
import org.apache.iotdb.cluster.log.Log;
import org.apache.iotdb.cluster.log.LogParser;
import org.apache.iotdb.cluster.rpc.thrift.Node;
import org.apache.iotdb.cluster.utils.Constants;
import org.apache.iotdb.db.exception.metadata.IllegalPathException;
import org.apache.iotdb.db.metadata.PartialPath;
import org.apache.iotdb.db.metadata.mnode.MeasurementMNode;
import org.apache.iotdb.db.qp.physical.crud.InsertRowPlan;
import org.apache.iotdb.db.qp.physical.sys.CreateTimeSeriesPlan;
import org.apache.iotdb.db.qp.physical.sys.SetStorageGroupPlan;
import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SerializeLogTest {
@Test
public void testPhysicalPlanLog() throws UnknownLogTypeException, IllegalPathException {
PhysicalPlanLog log = new PhysicalPlanLog();
log.setCurrLogIndex(2);
log.setCurrLogTerm(2);
InsertRowPlan plan = new InsertRowPlan();
plan.setDeviceId(new PartialPath("root.d1"));
plan.setMeasurements(new String[] {"s1", "s2", "s3"});
plan.setNeedInferType(true);
plan.setDataTypes(new TSDataType[plan.getMeasurements().length]);
plan.setValues(new Object[] {"0.1", "1", "\"dd\""});
MeasurementMNode[] schemas = {
TestUtils.getTestMeasurementMNode(1),
TestUtils.getTestMeasurementMNode(2),
TestUtils.getTestMeasurementMNode(3)
};
schemas[0].getSchema().setType(TSDataType.DOUBLE);
schemas[1].getSchema().setType(TSDataType.INT32);
schemas[2].getSchema().setType(TSDataType.TEXT);
plan.setMeasurementMNodes(schemas);
plan.setTime(1);
log.setPlan(plan);
ByteBuffer byteBuffer = log.serialize();
Log logPrime = LogParser.getINSTANCE().parse(byteBuffer);
assertEquals(log, logPrime);
log = new PhysicalPlanLog(new SetStorageGroupPlan(new PartialPath("root.sg1")));
byteBuffer = log.serialize();
logPrime = LogParser.getINSTANCE().parse(byteBuffer);
assertEquals(log, logPrime);
log =
new PhysicalPlanLog(
new CreateTimeSeriesPlan(
new PartialPath("root.applyMeta" + ".s1"),
TSDataType.DOUBLE,
TSEncoding.RLE,
CompressionType.SNAPPY,
new HashMap<String, String>() {
{
put("MAX_POINT_NUMBER", "100");
}
},
Collections.emptyMap(),
Collections.emptyMap(),
null));
byteBuffer = log.serialize();
logPrime = LogParser.getINSTANCE().parse(byteBuffer);
assertEquals(log, logPrime);
}
@Test
public void testAddNodeLog() throws UnknownLogTypeException {
AddNodeLog log = new AddNodeLog();
log.setCurrLogIndex(2);
log.setCurrLogTerm(2);
log.setNewNode(
new Node("apache.iotdb.com", 1234, 1, 4321, Constants.RPC_PORT, "apache.iotdb.com"));
ByteBuffer byteBuffer = log.serialize();
Log logPrime = LogParser.getINSTANCE().parse(byteBuffer);
assertEquals(log, logPrime);
}
@Test
public void testCloseFileLog() throws UnknownLogTypeException {
CloseFileLog log = new CloseFileLog("root.sg1", 0, true);
log.setCurrLogIndex(2);
log.setCurrLogTerm(2);
ByteBuffer byteBuffer = log.serialize();
CloseFileLog logPrime = (CloseFileLog) LogParser.getINSTANCE().parse(byteBuffer);
assertTrue(logPrime.isSeq());
assertEquals("root.sg1", logPrime.getStorageGroupName());
assertEquals(log, logPrime);
}
@Test
public void testRemoveNodeLog() throws UnknownLogTypeException {
RemoveNodeLog log = new RemoveNodeLog();
log.setCurrLogIndex(2);
log.setCurrLogTerm(2);
log.setRemovedNode(TestUtils.getNode(0));
ByteBuffer byteBuffer = log.serialize();
RemoveNodeLog logPrime = (RemoveNodeLog) LogParser.getINSTANCE().parse(byteBuffer);
assertEquals(log, logPrime);
}
@Test
public void testEmptyContentLog() throws UnknownLogTypeException {
EmptyContentLog log = new EmptyContentLog(2, 2);
ByteBuffer byteBuffer = log.serialize();
EmptyContentLog logPrime = (EmptyContentLog) LogParser.getINSTANCE().parse(byteBuffer);
assertEquals(log, logPrime);
}
}
| 37.902778 | 93 | 0.716013 |
28fe8cbc43ec75909c99a833d74ba18e8f16aab6
| 2,390 |
package com.redescooter.ses.web.ros.controller.warehouse.cn;
import com.redescooter.ses.api.common.vo.base.GeneralEnter;
import com.redescooter.ses.api.common.vo.base.PageResult;
import com.redescooter.ses.api.common.vo.base.Response;
import com.redescooter.ses.web.ros.service.wms.cn.WmsWhInService;
import com.redescooter.ses.web.ros.vo.wms.cn.WmsInWhDetailsResult;
import com.redescooter.ses.web.ros.vo.wms.cn.WmsInWhResult;
import com.redescooter.ses.web.ros.vo.wms.cn.WmsProductListResult;
import com.redescooter.ses.web.ros.vo.wms.cn.WmsWhInDetailsEnter;
import com.redescooter.ses.web.ros.vo.wms.cn.WmsWhInEnter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* @ClassNameWmsWhInController
* @Description
* @Author Joan
* @Date2020/7/20 14:00
* @Version V1.0
**/
@Log4j2
@Api(tags = {"CN-WH入库管理"})
@CrossOrigin
@RestController
@RequestMapping(value = "/warehouse/wms/cn/whIn")
public class WmsWhInController{
@Autowired
private WmsWhInService wmswhinservice;
@PostMapping(value = "/countByType")
@ApiOperation(value = "入库单类型统计", response = Map.class)
public Response<Map<String, Integer>> countByType(@ModelAttribute @ApiParam("请求参数") GeneralEnter enter) {
return new Response<>(wmswhinservice.countByType(enter));
}
@PostMapping(value = "/list")
@ApiOperation(value = "入库列表", response = WmsInWhResult.class)
public Response<PageResult<WmsInWhResult>> wmsInWhResultList(@ModelAttribute @ApiParam("请求参数") WmsWhInEnter enter) {
return new Response<>(wmswhinservice.list(enter));
}
@PostMapping(value = "/detail")
@ApiOperation(value = "详情", response = WmsInWhDetailsResult.class)
public Response<WmsInWhDetailsResult> wmsInWhInfoDetails(@ModelAttribute @ApiParam("请求参数") WmsWhInDetailsEnter enter) {
return new Response<>(wmswhinservice.details(enter));
}
@PostMapping(value = "/detailProductList")
@ApiOperation(value = "入库部件/产品信息详情", response = WmsProductListResult.class)
public Response<PageResult<WmsProductListResult>> whInStockPendingList(@ModelAttribute @ApiParam("请求参数") WmsWhInDetailsEnter enter) {
return new Response<>(wmswhinservice.productList(enter));
}
}
| 38.548387 | 135 | 0.777824 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.