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 |
|---|---|---|---|---|---|
1e5abd6b83a9c0333b67d05b0ac769930f3dbb04 | 2,371 | package de.joemiagroup.krawumm.repositories;
import de.joemiagroup.krawumm.domains.BaseEntity;
import lombok.RequiredArgsConstructor;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* This class is the base for the repositories
* <br>
*
* @author Jessica Eckhardtsberg
*
*/
@RequiredArgsConstructor
public abstract class BaseRepository<E extends BaseEntity> {
protected final EntityManager entityManager;
private final Class<E> type;
/**
*This method saves an entity to the database
*
* @param entity data row for a specific table of the database
*
* @return id of the saved data
*/
public Long save(E entity) {
entityManager.getTransaction().begin();
if(Objects.isNull(entity.getId())){
entityManager.persist(entity);
} else {
entityManager.merge(entity);
}
entityManager.getTransaction().commit();
return entity.getId();
}
/**
*This method searches for data based on the id
*
* @param id primary key of each table of the database
*
* @return data that was looked for
*/
public Optional<E> findBy(Long id) {
return Optional.ofNullable(entityManager.find(type, id));
}
/**
*This method searches for all data of a specific table of the database
*
* @return ResultList all rows of data of the specific table of the database
*/
public List<E> findAll() {
return entityManager.createQuery("SELECT entity FROM " + type.getCanonicalName(), type ).getResultList();
}
/**
*This method deletes a specific row of a table of the database
*
* @param entity data row for a specific table of the database
*
* no return value
*/
public void delete(E entity) {
entityManager.getTransaction().begin();
entityManager.remove(entity);
entityManager.getTransaction().commit();
}
/**
*This method deletes all rows of data of a table of the database
*
* no return value
*/
public void deleteAll() {
entityManager.getTransaction().begin();
entityManager.createQuery("DELETE FROM " + type.getCanonicalName()).executeUpdate();
entityManager.getTransaction().commit();
}
}
| 26.344444 | 113 | 0.64825 |
374a1f7392c0557303c2021773655fc49f1c2bf7 | 185 | package cn.study.spring;
public class Person {
public Person(String s){
super();
}
public static Person newInstance(){
return new Person(null);
}
}
| 14.230769 | 41 | 0.589189 |
98ab6a3777381fd2a39b566ab2cab3da3808189e | 4,009 | package com.capitalone.dashboard.rest;
import com.capitalone.dashboard.model.CloudSubNetwork;
import com.capitalone.dashboard.model.NameValue;
import com.capitalone.dashboard.request.CloudInstanceListRefreshRequest;
import com.capitalone.dashboard.request.CloudSubnetCreateRequest;
import com.capitalone.dashboard.response.CloudSubNetworkAggregatedResponse;
import com.capitalone.dashboard.service.CloudSubnetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.Collection;
import java.util.List;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@RestController
public class CloudSubnetController {
private final CloudSubnetService cloudSubnetService;
@Autowired
public CloudSubnetController(CloudSubnetService cloudSubnetService) {
this.cloudSubnetService = cloudSubnetService;
}
// Cloud Subnet End Points
@RequestMapping(value = "/cloud/subnet/refresh", method = POST, consumes = APPLICATION_JSON_VALUE,
produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<String>> refreshInstances(
@Valid @RequestBody CloudInstanceListRefreshRequest request) {
return ResponseEntity.ok().body(cloudSubnetService.refreshSubnets(request));
}
@RequestMapping(value = "/cloud/subnet/create", method = POST, consumes = APPLICATION_JSON_VALUE,
produces = APPLICATION_JSON_VALUE)
public ResponseEntity<List<String>> upsertSubNetwork(
@Valid @RequestBody List<CloudSubnetCreateRequest> request) {
return ResponseEntity.ok().body(cloudSubnetService.upsertSubNetwork(request));
}
@RequestMapping(value = "/cloud/subnet/details/component/{componentId}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<CloudSubNetwork>> getSubNetworkDetailsByComponentId(
@PathVariable String componentId) {
return ResponseEntity.ok().body(cloudSubnetService.getSubNetworkDetailsByComponentId(componentId));
}
@RequestMapping(value = "/cloud/subnet/details/account/{accountNumber}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<CloudSubNetwork>> getSubNetworkDetailsByAccount(
@PathVariable String accountNumber) {
return ResponseEntity.ok().body(cloudSubnetService.getSubNetworkDetailsByAccount(accountNumber));
}
@RequestMapping(value = "/cloud/subnet/details/subnets/{subnetIds}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<CloudSubNetwork>> getSubNetworkDetailsBySubnetIds(
@PathVariable List<String> subnetIds) {
return ResponseEntity.ok().body(cloudSubnetService.getSubNetworkDetailsBySubnetIds(subnetIds));
}
@RequestMapping(value = "/cloud/subnet/details/tags", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<CloudSubNetwork>> getSubNetworkDetailsByTag(
@Valid @RequestBody List<NameValue> tags) {
return ResponseEntity.ok().body(cloudSubnetService.getSubNetworkDetailsByTags(tags));
}
@RequestMapping(value = "/cloud/subnet/aggregate/{componentId}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CloudSubNetworkAggregatedResponse> getSubNetworkAggregatedData(
@PathVariable String componentId) {
return ResponseEntity.ok().body(cloudSubnetService.getSubNetworkAggregatedData(componentId));
}
}
| 49.493827 | 142 | 0.784485 |
bde9b7de69113948b60f67d11978d0c071b8497c | 520 | package com.yzxie.easy.log.engine.processor.impl;
import com.yzxie.easy.log.common.data.log.impl.StdErrorLogMessage;
import com.yzxie.easy.log.engine.processor.AbstractEngineProcessor;
import lombok.extern.slf4j.Slf4j;
/**
* @author xieyizun
* @date 17/11/2018 16:10
* @description:
*/
@Slf4j
public class StdErrorEngineProcessor extends AbstractEngineProcessor<StdErrorLogMessage> {
@Override
protected void process(StdErrorLogMessage logMessage) {
log.info("process log {}", logMessage);
}
}
| 27.368421 | 90 | 0.759615 |
52e7055e0fe6225e4d19205a78dbe7361fbffb8c | 3,539 | /*******************************************************************************
* 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.hadoop.yarn.server.resourcemanager.reservation.planning;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ReservationDefinition;
import org.apache.hadoop.yarn.api.records.ReservationId;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException;
/**
* An entity that seeks to acquire resources to satisfy an user's contract
*/
public interface ReservationAgent {
/**
* Create a reservation for the user that abides by the specified contract
*
* @param reservationId the identifier of the reservation to be created.
* @param user the user who wants to create the reservation
* @param plan the Plan to which the reservation must be fitted
* @param contract encapsulates the resources the user requires for his
* session
*
* @return whether the create operation was successful or not
* @throws PlanningException if the session cannot be fitted into the plan
*/
public boolean createReservation(ReservationId reservationId, String user,
Plan plan, ReservationDefinition contract) throws PlanningException;
/**
* Update a reservation for the user that abides by the specified contract
*
* @param reservationId the identifier of the reservation to be updated
* @param user the user who wants to create the session
* @param plan the Plan to which the reservation must be fitted
* @param contract encapsulates the resources the user requires for his
* reservation
*
* @return whether the update operation was successful or not
* @throws PlanningException if the reservation cannot be fitted into the plan
*/
public boolean updateReservation(ReservationId reservationId, String user,
Plan plan, ReservationDefinition contract) throws PlanningException;
/**
* Delete an user reservation
*
* @param reservationId the identifier of the reservation to be deleted
* @param user the user who wants to create the reservation
* @param plan the Plan to which the session must be fitted
*
* @return whether the delete operation was successful or not
* @throws PlanningException if the reservation cannot be fitted into the plan
*/
public boolean deleteReservation(ReservationId reservationId, String user,
Plan plan) throws PlanningException;
/**
* Init configuration.
*
* @param conf Configuration
*/
void init(Configuration conf);
}
| 43.158537 | 94 | 0.713761 |
2b2f9d270f24d6cd37f0088f00698022cd2cfb3c | 20,007 | /*
* Copyright 2003 - 2013 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.admin.user;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;
import org.efaps.admin.AbstractAdminObject;
import org.efaps.admin.datamodel.Type;
import org.efaps.ci.CIAdminUser;
import org.efaps.db.Context;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.transaction.ConnectionResource;
import org.efaps.util.EFapsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* @author The eFaps Team
* @version $Id$
*/
public abstract class AbstractUserObject
extends AbstractAdminObject
implements Serializable
{
/**
* Needed for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Logging instance used to give logging information of this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(AbstractUserObject.class);
/**
* Instance variable holding the Status (active, inactive).
*/
private boolean status;
/**
* Constructor to set instance variables of the user object.
*
* @param _id id to set
* @param _uuid uuid to set
* @param _name name to set
* @param _status status to set
*/
protected AbstractUserObject(final long _id,
final String _uuid,
final String _name,
final boolean _status)
{
super(_id, _uuid, _name);
this.status = _status;
}
/**
* Checks, if the given person is assigned to this user object. The method
* must be overwritten by the special implementations.
*
* @param _person person to test
* @return <i>true</i> if the person is assigned to this user object,
* otherwise <i>false</i>
* @see #persons
* @see #getPersons
*/
public abstract boolean hasChildPerson(final Person _person);
/**
* Checks, if the context user is assigned to this user object. The instance
* method uses {@link #hasChildPerson} to test this.
*
* @see #hasChildPerson
* @return true if person is assigned
*/
public boolean isAssigned()
{
boolean ret = false;
try {
ret = hasChildPerson(Context.getThreadContext().getPerson());
} catch (final EFapsException e) {
AbstractUserObject.LOG.error("could not read Person ", e);
}
return ret;
}
/**
* Assign this user object to the given JAAS system under the given JAAS
* key.
*
* @param _jaasSystem JAAS system to which the person is assigned
* @param _jaasKey key under which the person is know in the JAAS
* system
* @throws EFapsException if the assignment could not be made
*/
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public void assignToJAASSystem(final JAASSystem _jaasSystem,
final String _jaasKey)
throws EFapsException
{
ConnectionResource rsrc = null;
try {
final Context context = Context.getThreadContext();
rsrc = context.getConnectionResource();
final Type keyType = CIAdminUser.JAASKey.getType();
PreparedStatement stmt = null;
final StringBuilder cmd = new StringBuilder();
try {
long keyId = 0;
if (Context.getDbType().supportsGetGeneratedKeys()) {
cmd.append("insert into ").append(keyType.getMainTable().getSqlTable()).append(
"(KEY,CREATOR,CREATED,MODIFIER,MODIFIED,").append("USERABSTRACT,USERJAASSYSTEM) ")
.append("values (");
} else {
keyId = Context.getDbType().getNewId(rsrc.getConnection(), keyType.getMainTable().getSqlTable(),
"ID");
cmd.append("insert into ").append(keyType.getMainTable().getSqlTable()).append(
"(ID,KEY,CREATOR,CREATED,MODIFIER,MODIFIED,").append(
"USERABSTRACT,USERJAASSYSTEM) ").append("values (").append(keyId).append(",");
}
cmd.append("'").append(_jaasKey).append("',").append(context.getPersonId()).append(",").append(
Context.getDbType().getCurrentTimeStamp()).append(",").append(context.getPersonId())
.append(",").append(Context.getDbType().getCurrentTimeStamp()).append(",").append(
getId()).append(",").append(_jaasSystem.getId()).append(")");
stmt = rsrc.getConnection().prepareStatement(cmd.toString());
final int rows = stmt.executeUpdate();
if (rows == 0) {
AbstractUserObject.LOG.error("could not execute '" + cmd.toString()
+ "' for JAAS system '" + _jaasSystem.getName()
+ "' for user object '" + toString() + "' with JAAS key '" + _jaasKey + "'");
throw new EFapsException(getClass(), "assignToJAASSystem.NotInserted", _jaasSystem.getName(),
_jaasKey, toString());
}
} catch (final SQLException e) {
AbstractUserObject.LOG.error("could not execute '" + cmd.toString()
+ "' to assign user object '" + toString()
+ "' with JAAS key '" + _jaasKey + "' to JAAS system '" + _jaasSystem.getName() + "'", e);
throw new EFapsException(getClass(), "assignToJAASSystem.SQLException", e, cmd.toString(), _jaasSystem
.getName(), _jaasKey, toString());
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (final SQLException e) {
AbstractUserObject.LOG.error("Could not close a statement.", e);
}
}
rsrc.commit();
} finally {
if (rsrc != null && rsrc.isOpened()) {
rsrc.abort();
}
}
}
/**
* Assign this user object to the given user object for given JAAS system.
*
* @param _assignType type used to assign (in other words the
* relationship type)
* @param _jaasSystem JAAS system for which this user object is assigned
* to the given object
* @param _object user object to which this user object is assigned
* @throws EFapsException if assignment could not be done
*/
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
protected void assignToUserObjectInDb(final Type _assignType,
final JAASSystem _jaasSystem,
final AbstractUserObject _object)
throws EFapsException
{
ConnectionResource rsrc = null;
try {
final Context context = Context.getThreadContext();
rsrc = context.getConnectionResource();
Statement stmt = null;
final StringBuilder cmd = new StringBuilder();
try {
cmd.append("insert into ").append(_assignType.getMainTable().getSqlTable()).append("(");
long keyId = 0;
if (!Context.getDbType().supportsGetGeneratedKeys()) {
keyId = Context.getDbType().getNewId(rsrc.getConnection(),
_assignType.getMainTable().getSqlTable(), "ID");
cmd.append("ID,");
}
cmd.append("TYPEID,CREATOR,CREATED,MODIFIER,MODIFIED,").append(
"USERABSTRACTFROM,USERABSTRACTTO,USERJAASSYSTEM) ").append("values (");
if (keyId != 0) {
cmd.append(keyId).append(",");
}
cmd.append(_assignType.getId()).append(",").append(context.getPersonId()).append(",").append(
Context.getDbType().getCurrentTimeStamp()).append(",").append(context.getPersonId())
.append(",").append(Context.getDbType().getCurrentTimeStamp()).append(",").append(
getId()).append(",").append(_object.getId()).append(",").append(
_jaasSystem.getId()).append(")");
stmt = rsrc.getConnection().createStatement();
final int rows = stmt.executeUpdate(cmd.toString());
if (rows == 0) {
AbstractUserObject.LOG.error("could not execute '" + cmd.toString()
+ "' to assign user object '" + toString()
+ "' to object '" + _object + "' for JAAS system '" + _jaasSystem + "' ");
throw new EFapsException(getClass(), "assignInDb.NotInserted", _jaasSystem.getName(), _object
.getName(), getName());
}
} catch (final SQLException e) {
AbstractUserObject.LOG.error("could not execute '" + cmd.toString()
+ "' to assign user object '" + toString()
+ "' to object '" + _object + "' for JAAS system '" + _jaasSystem + "' ", e);
throw new EFapsException(getClass(), "assignInDb.SQLException", e, cmd.toString(), getName());
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (final SQLException e) {
AbstractUserObject.LOG.error("Could not close a statement.", e);
}
}
rsrc.commit();
} finally {
if (rsrc != null && rsrc.isOpened()) {
rsrc.abort();
}
}
}
/**
* Unassign this user object from the given user object for given JAAS
* system.
*
* @param _unassignType type used to unassign (in other words the
* relationship type)
* @param _jaasSystem JAAS system for which this user object is unassigned
* from given object
* @param _object user object from which this user object is unassigned
* @throws EFapsException if unassignment could not be done
*/
protected void unassignFromUserObjectInDb(final Type _unassignType,
final JAASSystem _jaasSystem,
final AbstractUserObject _object)
throws EFapsException
{
ConnectionResource rsrc = null;
try {
rsrc = Context.getThreadContext().getConnectionResource();
Statement stmt = null;
final StringBuilder cmd = new StringBuilder();
try {
cmd.append("delete from ").append(_unassignType.getMainTable().getSqlTable()).append(" ").append(
"where USERJAASSYSTEM=").append(_jaasSystem.getId()).append(" ").append(
"and USERABSTRACTFROM=").append(getId()).append(" ").append("and USERABSTRACTTO=")
.append(_object.getId());
stmt = rsrc.getConnection().createStatement();
stmt.executeUpdate(cmd.toString());
} catch (final SQLException e) {
AbstractUserObject.LOG.error("could not execute '" + cmd.toString()
+ "' to unassign user object '" + toString()
+ "' from object '" + _object + "' for JAAS system '" + _jaasSystem + "' ", e);
throw new EFapsException(getClass(), "unassignFromUserObjectInDb.SQLException", e, cmd.toString(),
getName());
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (final SQLException e) {
AbstractUserObject.LOG.error("Could not close a statement.", e);
}
}
rsrc.commit();
} finally {
if (rsrc != null && rsrc.isOpened()) {
rsrc.abort();
}
}
}
/**
* This is the getter method for the instance variable {@link #status}.
*
* @return value of instance variable {@link #status}
*/
public boolean getStatus()
{
return this.status;
}
/**
* This is the setter method for the instance variable {@link #status}.
*
* @param _status the status to set
*/
public void setStatus(final boolean _status)
{
this.status = _status;
}
/**
* Get the note belonging to this UserObject.
* <b>Careful. Executes Query against the Database and therefore might be slow.</b>
* @return the note belonging to the UserObject
* @throws EFapsException on error during reading
*/
public String getNote()
throws EFapsException
{
String ret = "";
final QueryBuilder queryBldr = new QueryBuilder(CIAdminUser.Abstract);
queryBldr.addWhereAttrEqValue(CIAdminUser.Abstract.ID, getId());
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CIAdminUser.Abstract.Note);
if (multi.execute()) {
multi.next();
ret = multi.getAttribute(CIAdminUser.Abstract.Note);
}
return ret;
}
/**
* Method to set the status of a UserObject in the eFaps Database.
*
* @param _status status to set
* @throws EFapsException on error
*/
protected void setStatusInDB(final boolean _status)
throws EFapsException
{
ConnectionResource rsrc = null;
try {
final Context context = Context.getThreadContext();
rsrc = context.getConnectionResource();
PreparedStatement stmt = null;
final StringBuilder cmd = new StringBuilder();
try {
cmd.append(" update T_USERABSTRACT set STATUS=? where ID=").append(getId());
stmt = rsrc.getConnection().prepareStatement(cmd.toString());
stmt.setBoolean(1, _status);
final int rows = stmt.executeUpdate();
if (rows == 0) {
AbstractUserObject.LOG.error("could not execute '" + cmd.toString()
+ "' to update status information for person '" + toString() + "'");
throw new EFapsException(getClass(), "setStatusInDB.NotUpdated", cmd.toString(), getName());
}
} catch (final SQLException e) {
AbstractUserObject.LOG.error("could not execute '" + cmd.toString()
+ "' to update status information for person '" + toString() + "'", e);
throw new EFapsException(getClass(), "setStatusInDB.SQLException", e, cmd.toString(), getName());
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (final SQLException e) {
throw new EFapsException(getClass(), "setStatusInDB.SQLException", e, cmd.toString(), getName());
}
}
rsrc.commit();
} finally {
if (rsrc != null && rsrc.isOpened()) {
rsrc.abort();
}
}
}
/**
* Returns for given parameter <i>_uuid</i> the instance of class
* {@link AbstractUserObject}. The returned AbstractUserObject can be a
* {@link Role}, {@link Group}, {@link Company}, {@link Consortium}
* or {@link Person}. It is searched in the given sequence. User is searched last
* due to the reason that it is the only object that is not always stored
* in a cache an might produce queries against the DataBase
*
* @param _uuid UUID to search in the cache
* @return instance of class {@link AbstractUserObject}
* @throws EFapsException on error
*/
public static AbstractUserObject getUserObject(final UUID _uuid)
throws EFapsException
{
AbstractUserObject ret = Role.get(_uuid);
if (ret == null) {
ret = Group.get(_uuid);
}
if (ret == null) {
ret = Company.get(_uuid);
}
if (ret == null) {
ret = Consortium.get(_uuid);
}
if (ret == null) {
ret = Person.get(_uuid);
}
return ret;
}
/**
* Returns for given parameter <i>_id</i> the instance of class
* {@link AbstractUserObject}. The returned AbstractUserObject can be a
* {@link Role}, {@link Group}, {@link Company}, {@link Consortium}
* or {@link Person}. It is searched in the given sequence. User is searched last
* due to the reason that it is the only object that is not always stored
* in a cache an might produce queries against the DataBase
*
* @param _id id to search in the cache
* @return instance of class {@link AbstractUserObject}
* @throws EFapsException on error
*/
public static AbstractUserObject getUserObject(final long _id)
throws EFapsException
{
AbstractUserObject ret = Role.get(_id);
if (ret == null) {
ret = Group.get(_id);
}
if (ret == null) {
ret = Company.get(_id);
}
if (ret == null) {
ret = Consortium.get(_id);
}
if (ret == null) {
ret = Person.get(_id);
}
return ret;
}
/**
* Returns for given parameter <i>_name</i> the instance of class
* {@link AbstractUserObject}.The returned AbstractUserObject can be a
* {@link Role}, {@link Group}, {@link Company}, {@link Consortium}
* or {@link Person}. It is searched in the given sequence. User is searched
* last due to the reason that it is the only object that is not always stored
* in a cache an might produce queries against the DataBase
*
* @param _name name to search in the cache
* @return instance of class {@link AbstractUserObject}
* @throws EFapsException on error
*/
public static AbstractUserObject getUserObject(final String _name)
throws EFapsException
{
AbstractUserObject ret = Role.get(_name);
if (ret == null) {
ret = Group.get(_name);
}
if (ret == null) {
ret = Company.get(_name);
}
if (ret == null) {
ret = Consortium.get(_name);
}
if (ret == null) {
ret = Person.get(_name);
}
return ret;
}
}
| 40.418182 | 118 | 0.548008 |
94d6eba665c2cb174e7ebab6a5bf09836b6ba5e6 | 634 | package org.apache.hadoop.io.erasurecode.codec;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.erasurecode.ErasureCodecOptions;
import org.apache.hadoop.io.erasurecode.coder.*;
public class EVENODDErasureCodec extends ErasureCodec {
public EVENODDErasureCodec(Configuration conf, ErasureCodecOptions options) {
super(conf, options);
}
@Override
public ErasureEncoder createEncoder() {
return new EVENODDErasureEncoder(getCoderOptions());
}
@Override
public ErasureDecoder createDecoder() {
return new EVENODDErasureDecoder(getCoderOptions());
}
}
| 27.565217 | 81 | 0.749211 |
2668cd0d83fb41fc153d862ec4872cab1ecc9043 | 3,125 | package retry;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class mirror {
public static char[][] grid;
public static Set<String> pairs;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("mirror.in"));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
grid = new char[N][M];
pairs = new HashSet<>();
for (int i = 0; i < grid.length; i++) {
grid[i] = br.readLine().toCharArray();
}
br.close();
System.out.println(generateRecursions());
}
public static int generateRecursions() {
int max = -1;
for (int j = 0; j < grid[0].length; j++) { // TOP ROW
recurse(0, j, MoveDirection.DOWN);
if (pairs.size() > max) {
max = pairs.size();
}
pairs.clear();
}
for (int j = 0; j < grid[0].length; j++) { // BOTTOM ROW
recurse(grid.length - 1, j, MoveDirection.UP);
if (pairs.size() > max) {
max = pairs.size();
}
pairs.clear();
}
for (int i = 0; i < grid.length; i++) { // LEFT ROW
recurse(0, i, MoveDirection.RIGHT);
if (pairs.size() > max) {
max = pairs.size();
}
pairs.clear();
}
for (int i = 0; i < grid.length; i++) { // RIGHT ROW
recurse(grid.length - 1, i, MoveDirection.LEFT);
if (pairs.size() > max) {
max = pairs.size();
}
pairs.clear();
}
return max;
}
/*
* @param x -> current x value
* @param y -> current y value
* @param dir -> move direction
*/
public static void recurse(int x, int y, MoveDirection dir) {
String key = formKey(x, y);
if (pairs.contains(key)) {
return;
}
pairs.add(key);
if (grid[x][y] == '/') {
switch (dir) {
case DOWN:
if (inBounds(x - 1, y)) {
recurse(x - 1, y, MoveDirection.LEFT);
}
break;
case UP:
if (inBounds(x + 1, y)) {
recurse(x + 1, y, MoveDirection.RIGHT);
}
break;
case LEFT:
if (inBounds(x, y - 1)) {
recurse(x, y - 1, MoveDirection.UP);
}
break;
case RIGHT:
if (inBounds(x, y + 1)) {
recurse(x, y + 1, MoveDirection.DOWN);
}
break;
}
} else if (grid[x][y] == '\\') {
switch (dir) {
case DOWN:
if (inBounds(x - 1, y)) {
recurse(x - 1, y, MoveDirection.RIGHT);
}
break;
case UP:
if (inBounds(x + 1, y)) {
recurse(x + 1, y, MoveDirection.LEFT);
}
break;
case LEFT:
if (inBounds(x, y - 1)) {
recurse(x, y - 1, MoveDirection.DOWN);
}
break;
case RIGHT:
if (inBounds(x, y + 1)) {
recurse(x, y + 1, MoveDirection.UP);
}
break;
}
}
}
private enum MoveDirection {
UP, DOWN, LEFT, RIGHT;
}
public static boolean inBounds(int x, int y) {
return x >= 0 && x < grid.length && y >= 0 && y < grid[0].length;
}
public static String formKey(int x, int y) {
return x + "_" + y;
}
}
| 22.007042 | 70 | 0.55296 |
969aa25fe1ad889cfb65cd49f94d762bba71c61c | 1,169 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.fileEditor.impl;
import com.intellij.ide.ui.VirtualFileAppearanceListener;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
public class FileEditorVirtualFileAppearanceListener implements VirtualFileAppearanceListener {
@NotNull private final Project myProject;
public FileEditorVirtualFileAppearanceListener(@NotNull Project project) {
myProject = project;
}
@Override
public void virtualFileAppearanceChanged(@NotNull VirtualFile virtualFile) {
FileEditorManagerEx fileEditorManager = (FileEditorManagerEx)FileEditorManager.getInstance(myProject);
final VirtualFile currentFile = fileEditorManager.getCurrentFile();
if (Objects.equals(virtualFile, currentFile)) {
fileEditorManager.updateFilePresentation(currentFile);
}
}
} | 41.75 | 140 | 0.816938 |
907918d6078e3a568272f37412182e6107c0927f | 2,310 | /*
* Copyright (c) 2010-2014 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.prism;
import com.evolveum.midpoint.prism.impl.PrismContextImpl;
import com.evolveum.midpoint.prism.impl.lex.dom.DomLexicalProcessor;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.prism.impl.xnode.PrimitiveXNodeImpl;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.SchemaException;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import java.io.IOException;
import static com.evolveum.midpoint.prism.PrismInternalTestUtil.DEFAULT_NAMESPACE_PREFIX;
import static org.testng.Assert.assertTrue;
import static org.testng.AssertJUnit.assertEquals;
/**
* @author mederly
*
*/
public class TestXmlSerialization extends AbstractPrismTest {
@Test
public void testHandlingInvalidChars() throws Exception {
// GIVEN
PrismContext prismContext = getPrismContext();
// WHEN
PrimitiveXNodeImpl<String> valOkNode = new PrimitiveXNodeImpl<>("abcdef");
PrimitiveXNodeImpl<String> valWrongNode = new PrimitiveXNodeImpl<>("abc\1def");
// THEN
final DomLexicalProcessor domLexicalProcessor = ((PrismContextImpl) prismContext).getParserDom();
String ok = domLexicalProcessor.write(valOkNode, new QName("ok"), null);
System.out.println("correct value serialized to: " + ok);
assertEquals("Wrong serialization", "<ok>abcdef</ok>", ok.trim()); // todo make this less brittle with regards to serialization style
try {
String wrong = domLexicalProcessor.write(valWrongNode, new QName("wrong"), null);
System.out.println("wrong value serialized to: " + wrong);
assert false : "Wrong value serialization had to fail but it didn't!";
} catch (RuntimeException e) {
System.out.println("wrong value was not serialized (as expected): " + e);
assertTrue(e.getMessage().contains("Invalid character"), "Didn't get expected error message");
}
}
}
| 37.868852 | 149 | 0.724242 |
09388bbf4ecf287a86a0dcc707e7e8c3b3713346 | 216 | package com.manan.busservice;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BusserviceApplicationTests {
@Test
void contextLoads() {
}
}
| 15.428571 | 60 | 0.791667 |
5d4cf44b2daa0a6c75709f2f6127710e085b43ba | 1,826 | package com.yt.action;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.google.gson.GsonBuilder;
import com.opensymphony.xwork2.Action;
import com.yt.entity.Score;
import com.yt.service.PaperService;
import com.yt.service.PaperServiceImpI;
public class ScoreListAction implements Action {
public PaperService paperService=new PaperServiceImpI();
@Override
public String execute() throws Exception {
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
String m=ServletActionContext.getRequest().getParameter("m");;
int page=0,rows=0;
if(!"".equals(ServletActionContext.getRequest().getParameter("page"))&&ServletActionContext.getRequest().getParameter("page")!=null){
page=Integer.parseInt(ServletActionContext.getRequest().getParameter("page"));
}
if(!"".equals(ServletActionContext.getRequest().getParameter("rows"))&&ServletActionContext.getRequest().getParameter("rows")!=null){
rows=Integer.parseInt(ServletActionContext.getRequest().getParameter("rows"));
}
if("findWithPage".equals(m)){
Map<String,Object> map=new HashMap<String,Object>();
Score score=new Score();
//从查询按钮获取参数
score.setUsername(ServletActionContext.getRequest().getParameter("sName"));
score.setSubject(ServletActionContext.getRequest().getParameter("sSubject"));
List<Score>list=paperService.findWithPage(page, rows,score);
map.put("rows", list); //记录的数据
map.put("total", paperService.getRows()); //总共多少记录
ServletActionContext.getResponse().getWriter().print(new GsonBuilder().create().toJson(map));
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();
}
return null;
}
}
| 39.695652 | 136 | 0.738773 |
ee5330256b23d207d1f68cd3ae0269255740bc60 | 772 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/spanner/admin/database/v1/spanner_database_admin.proto
package com.google.spanner.admin.database.v1;
public interface GetDatabaseDdlRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.spanner.admin.database.v1.GetDatabaseDdlRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The database whose schema we wish to get.
* </pre>
*
* <code>string database = 1;</code>
*/
java.lang.String getDatabase();
/**
*
*
* <pre>
* Required. The database whose schema we wish to get.
* </pre>
*
* <code>string database = 1;</code>
*/
com.google.protobuf.ByteString getDatabaseBytes();
}
| 24.125 | 105 | 0.680052 |
8aad8eed5ca64d2758a6c5fc9e49eaf7fdde76d7 | 2,757 | package com.hazelcast.jet.demos.bitcoin.job;
import java.math.BigDecimal;
import java.time.LocalDate;
import com.hazelcast.jet.datamodel.Tuple3;
import com.hazelcast.jet.demos.bitcoin.domain.Price;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* <p>Merge two price streams, 50-point on the left
* and 200-point on the right. As the 50-point starts
* first it will always exist, for the first 150
* observations the right stream (200-point) will have
* no matching value.
* </p>
*/
@Data
@Slf4j
public class MyPriceAccumulator {
private LocalDate date;
private BigDecimal left;
private BigDecimal right;
/**
* <p>Apply a new data from the 50-point stream into
* the current accumulator.
* </p>
*
* @param arg0 The 50-point stream
* @return A trio combining 50-point and 200-point
*/
public MyPriceAccumulator setLeft(Price arg0) {
this.left = arg0.getRate();
if (this.date != null) {
if (!this.date.isEqual(arg0.getLocalDate())) {
log.error("Date clash: {} but setLeft({})", this, arg0);
}
} else {
this.date = arg0.getLocalDate();
}
return this;
}
/**
* <p>Apply a new data from the 200-point stream into
* the current accumulator.
* </p>
*
* @param arg0 The 200-point stream
* @return A trio combining 50-point and 200-point
*/
public MyPriceAccumulator setRight(Price arg0) {
this.right = arg0.getRate();
if (this.date != null) {
if (!this.date.isEqual(arg0.getLocalDate())) {
log.error("Date clash: {} but setRight({})", this, arg0);
}
} else {
this.date = arg0.getLocalDate();
}
return this;
}
/**
* <p>Merge two accumulators together, eg. if accumulated on
* another CPU. We do not expect the incoming side to overwrite
* any data, so report error if so.
* </p>
*
* @param that The other accumulator
* @return A trio combining 50-point and 200-point
*/
public MyPriceAccumulator combine(MyPriceAccumulator that) {
if (this.date == null) {
this.date = that.getDate();
} else {
if (that.getDate() != null && !this.getDate().equals(that.getDate())) {
log.error("Date clash: {} but combine with ({})", this, that);
}
}
if (this.left == null) {
this.left = that.getLeft();
} else {
if (that.getLeft() != null && !this.getLeft().equals(that.getLeft())) {
log.error("Left clash: {} but combine with ({})", this, that);
}
}
if (this.right == null) {
this.right = that.getRight();
} else {
if (that.getLeft() != null && !this.getRight().equals(that.getRight())) {
log.error("Right clash: {} but combine with ({})", this, that);
}
}
return this;
}
public Tuple3<LocalDate, BigDecimal, BigDecimal> result() {
return Tuple3.tuple3(this.date, this.left, this.right);
}
}
| 25.766355 | 76 | 0.651433 |
b17a09ed44961217e944235b2e70660ab24968dd | 5,081 | package org.tools4j.tabular.service;
import org.tools4j.tabular.util.IndentableStringBuilder;
import org.tools4j.tabular.properties.PropertiesRepo;
import org.tools4j.tabular.properties.ResolvedMap;
import java.util.*;
/**
* User: ben
* Date: 24/10/17
* Time: 6:57 AM
*/
public class DataSet<T extends Row> implements TableWithColumnHeadings<T>, Pretty{
private final List<String> columns;
private final List<T> table;
public DataSet(final List<T> table) {
this(extractColumnNames(table), table);
}
public DataSet(final List<String> columns, final List<T> table) {
this.columns = columns;
this.table = table;
}
private static List<String> extractColumnNames(List<? extends Row> table) {
List<String> firstRowColumnHeaders = null;
for (Map<String, String> row : table) {
ArrayList<String> currentRowColumnHeaders = new ArrayList<>(row.keySet());
if(firstRowColumnHeaders == null){
firstRowColumnHeaders = currentRowColumnHeaders;
} else if(!currentRowColumnHeaders.equals(firstRowColumnHeaders)){
throw new IllegalArgumentException("Column headers do not match between rows. firstRowColumnHeaders " + firstRowColumnHeaders + ", currentRowColumnHeaders " + currentRowColumnHeaders);
}
}
return firstRowColumnHeaders;
}
@Override
public String toString() {
return "Data{" +
"columns=" + columns +
", table=" + table +
'}';
}
public DataSet<RowFromMap> resolveVariablesInCells(final PropertiesRepo... usingAdditionalProperties){
final Map<String, String> additionalProperties = new HashMap<>();
for(int i=0; i<usingAdditionalProperties.length; i++){
additionalProperties.putAll(usingAdditionalProperties[i].asMap());
}
final List<RowFromMap> tableWithResolvedCells = new ArrayList<>();
for(final T row: table){
final RowFromMap rowWithResolvedCells = new RowFromMap(new ResolvedMap(row, additionalProperties).resolve());
tableWithResolvedCells.add(rowWithResolvedCells);
}
return new DataSet<>(columns, tableWithResolvedCells);
}
public DataSet<RowWithCommands> resolveCommands(final CommandMetadatas commandMetadatas, final PropertiesRepo propertiesRepo){
final List<RowWithCommands> rowWithCommands = new ArrayList<>(table.size());
for(final T row: table){
final CommandMetadatas commandMetadatasForRow = commandMetadatas.getCommandsFor(row);
final List<Command> commandInstancesForRow = commandMetadatasForRow.getCommandInstances(row, propertiesRepo);
final RowWithCommands rowWithResolvedCells = new RowWithCommands(row, commandInstancesForRow);
rowWithCommands.add(rowWithResolvedCells);
}
return new DataSet(columns, rowWithCommands);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DataSet<?> dataSet = (DataSet<?>) o;
return Objects.equals(columns, dataSet.columns) &&
Objects.equals(table, dataSet.table);
}
@Override
public int hashCode() {
return Objects.hash(columns, table);
}
@Override
public List<String> getColumnHeadings() {
return columns;
}
@Override
public int size() {
return table.size();
}
@Override
public List<T> getRows() {
return table;
}
@Override
public String toPrettyString(final String indent) {
final IndentableStringBuilder sb = new IndentableStringBuilder(indent);
sb.append("dataSet{\n");
sb.activateIndent();
sb.append("columns=").append(columns).append("\n");
sb.append("table=").append(table).append("\n");
sb.decactivateIndent();
sb.append("}");
return sb.toString();
}
public String toCsv(){
final StringBuilder sb = new StringBuilder();
sb.append(join(columns)).append("\n");
final Iterator<T> rows = table.iterator();
while(rows.hasNext()){
sb.append(join(rows.next().values()));
if(rows.hasNext()){
sb.append("\n");
}
}
return sb.toString();
}
public String join(final Collection collection){
return join(collection, ",");
}
public String join(final Collection collection, final String delimiter){
final StringBuilder sb = new StringBuilder();
final Iterator iterator = collection.iterator();
while(iterator.hasNext()){
sb.append(iterator.next().toString());
if(iterator.hasNext()){
sb.append(delimiter);
}
}
return sb.toString();
}
public int rowCount() {
return table.size();
}
public T getRow(final int i) {
return table.get(i);
}
}
| 33.873333 | 200 | 0.630191 |
f51c3f4c10aac9482594f32fb28cb61d6f3f3c57 | 1,639 | package com.jfinalshop.service;
import net.hasor.core.Inject;
import net.hasor.core.Singleton;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.render.FreeMarkerRender;
import freemarker.template.Configuration;
/**
* Service - 缓存
*
*
*/
@Singleton
public class CacheService {
private CacheManager cacheManager = CacheKit.getCacheManager();
private Configuration freeMarkerConfigurer = FreeMarkerRender.getConfiguration();
@Inject
private ConfigService configService;
/**
* 获取缓存存储路径
*
* @return 缓存存储路径
*/
public String getDiskStorePath() {
return cacheManager.getConfiguration().getDiskStoreConfiguration().getPath();
}
/**
* 获取缓存数
*
* @return 缓存数
*/
public int getCacheSize() {
int cacheSize = 0;
String[] cacheNames = cacheManager.getCacheNames();
if (cacheNames != null) {
for (String cacheName : cacheNames) {
Ehcache cache = cacheManager.getEhcache(cacheName);
if (cache != null) {
cacheSize += cache.getSize();
}
}
}
return cacheSize;
}
/**
* 清除缓存
*/
public void clear() {
String[] cacheNames = new String[] {"setting", "logConfig", "templateConfig", "pluginConfig", "messageConfig", "area", "seo", "adPosition", "memberAttribute", "navigation", "tag", "friendLink", "brand", "attribute", "article", "articleCategory", "goods", "productCategory", "review", "consultation","promotion", "shipping", "authorization"};
freeMarkerConfigurer.clearTemplateCache();
for (String cacheName : cacheNames) {
CacheKit.removeAll(cacheName);
}
configService.init();
}
} | 24.102941 | 343 | 0.703478 |
c77878fd84e4c50025dd695a53d87c1ae3d84ffc | 20,930 | package test_locally.api.model.block;
import com.google.gson.Gson;
import com.slack.api.model.Message;
import com.slack.api.model.block.*;
import com.slack.api.model.block.element.*;
import com.slack.api.model.view.View;
import org.junit.Test;
import test_locally.unit.GsonFactory;
import java.util.Arrays;
import java.util.List;
import static com.slack.api.model.block.Blocks.*;
import static com.slack.api.model.block.composition.BlockCompositions.asSectionFields;
import static com.slack.api.model.block.composition.BlockCompositions.plainText;
import static com.slack.api.model.block.element.BlockElements.*;
import static com.slack.api.model.view.Views.view;
import static com.slack.api.model.view.Views.viewSubmit;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
public class BlocksTest {
@Test
public void testActions() {
List<BlockElement> elements = asElements(button(r -> r.value("v")));
{
ActionsBlock block = actions(elements);
assertThat(block, is(notNullValue()));
}
{
ActionsBlock block = actions("block-id", elements);
assertThat(block, is(notNullValue()));
}
}
@Test
public void testContext() {
List<ContextBlockElement> elements = asContextElements(imageElement(r -> r.imageUrl("https://www.example.com/logo.png")));
{
ContextBlock block = context(elements);
assertThat(block, is(notNullValue()));
}
{
ContextBlock block = context("block-id", elements);
assertThat(block, is(notNullValue()));
}
}
@Test
public void testDivider() {
assertThat(divider(), is(notNullValue()));
assertThat(divider("block-id"), is(notNullValue()));
}
@Test
public void testFile() {
assertThat(file(f -> f.blockId("block-id")), is(notNullValue()));
}
@Test
public void testCall() {
assertThat(call(f -> f.blockId("block-id").callId("R111")), is(notNullValue()));
}
@Test
public void testImage() {
assertThat(Blocks.image(i -> i.blockId("block-id").imageUrl("https://www.example.com/")), is(notNullValue()));
}
@Test
public void testInput() {
assertThat(input(i -> i.blockId("block-id").element(button(b -> b.value("v")))), is(notNullValue()));
}
@Test
public void testHeader() {
assertThat(header(h -> h.blockId("block-id").text(plainText("This is the headline!"))), is(notNullValue()));
}
@Test
public void testRichText() {
assertThat(richText(i -> i
.blockId("block-id")
.elements(asElements(button(b -> b.value("v"))))
), is(notNullValue()));
}
String richTextSkinTone = "{ \"blocks\": [\n" +
" {\n" +
" \"type\": \"rich_text\",\n" +
" \"block_id\": \"b123\",\n" +
" \"elements\": [\n" +
" {\n" +
" \"type\": \"rich_text_section\",\n" +
" \"elements\": [\n" +
" {\n" +
" \"type\": \"text\",\n" +
" \"text\": \"Hello\"\n" +
" },\n" +
" {\n" +
" \"type\": \"emoji\",\n" +
" \"name\": \"wave\",\n" +
" \"skin_tone\": 3\n" +
" },\n" +
" {\n" +
" \"type\": \"emoji\",\n" +
" \"name\": \"rocket\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
"]}";
@Test
public void testRichTextSkinToneEmoji() {
Message message = GsonFactory.createSnakeCase().fromJson(richTextSkinTone, Message.class);
assertNotNull(message);
}
@Test
public void testSection() {
assertThat(section(s -> s.blockId("block-id").fields(asSectionFields(plainText("foo")))), is(notNullValue()));
}
@Test
public void testCheckboxes() {
assertThat(section(s -> s.blockId("block-id").accessory(checkboxes(c -> c.actionId("foo")))), is(notNullValue()));
assertThat(input(i -> i.element(checkboxes(c -> c.actionId("foo")))), is(notNullValue()));
}
@Test
public void testConversationsFilter() {
String json = "{\"blocks\":[\n" +
" {\n" +
" \"type\": \"input\",\n" +
" \"element\": {\n" +
" \"type\": \"conversations_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a conversation\",\n" +
" \"emoji\": true\n" +
" },\n" +
" \"filter\": {\n" +
" \"include\": [\n" +
" \"public\",\n" +
" \"mpim\"\n" +
" ],\n" +
" \"exclude_bot_users\": true\n" +
" }\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\",\n" +
" \"emoji\": true\n" +
" }\n" +
" }\n" +
"]}";
Message message = GsonFactory.createSnakeCase().fromJson(json, Message.class);
assertNotNull(message);
assertEquals(1, message.getBlocks().size());
InputBlock block = (InputBlock) message.getBlocks().get(0);
ConversationsSelectElement element = (ConversationsSelectElement) block.getElement();
assertEquals(Arrays.asList("public", "mpim"), element.getFilter().getInclude());
assertTrue(element.getFilter().getExcludeBotUsers());
assertNull(element.getFilter().getExcludeExternalSharedChannels());
}
@Test
public void testConversationsFilter_multi() {
String json = "{\"blocks\":[\n" +
" {\n" +
" \"type\": \"input\",\n" +
" \"element\": {\n" +
" \"type\": \"multi_conversations_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a conversation\",\n" +
" \"emoji\": true\n" +
" },\n" +
" \"filter\": {\n" +
" \"include\": [\n" +
" \"public\",\n" +
" \"mpim\"\n" +
" ],\n" +
" \"exclude_bot_users\": true\n" +
" }\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\",\n" +
" \"emoji\": true\n" +
" }\n" +
" }\n" +
"]}";
Message message = GsonFactory.createSnakeCase().fromJson(json, Message.class);
assertNotNull(message);
assertEquals(1, message.getBlocks().size());
InputBlock block = (InputBlock) message.getBlocks().get(0);
MultiConversationsSelectElement element = (MultiConversationsSelectElement) block.getElement();
assertEquals(Arrays.asList("public", "mpim"), element.getFilter().getInclude());
assertTrue(element.getFilter().getExcludeBotUsers());
assertNull(element.getFilter().getExcludeExternalSharedChannels());
}
@Test
public void testResponseUrlEnabled_conversations() {
{
String json = "{\"blocks\":[\n" +
" {\n" +
" \"type\": \"input\",\n" +
" \"element\": {\n" +
" \"type\": \"conversations_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a conversation\",\n" +
" \"emoji\": true\n" +
" },\n" +
" \"response_url_enabled\": true\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\",\n" +
" \"emoji\": true\n" +
" }\n" +
" }\n" +
"]}";
Message message = GsonFactory.createSnakeCase().fromJson(json, Message.class);
assertNotNull(message);
assertEquals(1, message.getBlocks().size());
InputBlock block = (InputBlock) message.getBlocks().get(0);
ConversationsSelectElement element = (ConversationsSelectElement) block.getElement();
assertTrue(element.getResponseUrlEnabled());
}
{
String json = "{\"blocks\":[\n" +
" {\n" +
" \"type\": \"input\",\n" +
" \"element\": {\n" +
" \"type\": \"conversations_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a conversation\",\n" +
" \"emoji\": true\n" +
" }\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\",\n" +
" \"emoji\": true\n" +
" },\n" +
" \"hint\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\",\n" +
" \"emoji\": true\n" +
" }\n" +
" }\n" +
"]}";
Message message = GsonFactory.createSnakeCase().fromJson(json, Message.class);
assertNotNull(message);
assertEquals(1, message.getBlocks().size());
InputBlock block = (InputBlock) message.getBlocks().get(0);
ConversationsSelectElement element = (ConversationsSelectElement) block.getElement();
assertNull(element.getResponseUrlEnabled());
}
}
@Test
public void testResponseUrlEnabled_channels() {
{
String json = "{\"blocks\":[\n" +
" {\n" +
" \"type\": \"input\",\n" +
" \"element\": {\n" +
" \"type\": \"channels_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a conversation\",\n" +
" \"emoji\": true\n" +
" },\n" +
" \"response_url_enabled\": true\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\",\n" +
" \"emoji\": true\n" +
" }\n" +
" }\n" +
"]}";
Message message = GsonFactory.createSnakeCase().fromJson(json, Message.class);
assertNotNull(message);
assertEquals(1, message.getBlocks().size());
InputBlock block = (InputBlock) message.getBlocks().get(0);
ChannelsSelectElement element = (ChannelsSelectElement) block.getElement();
assertTrue(element.getResponseUrlEnabled());
}
{
String json = "{\"blocks\":[\n" +
" {\n" +
" \"type\": \"input\",\n" +
" \"element\": {\n" +
" \"type\": \"channels_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a conversation\",\n" +
" \"emoji\": true\n" +
" }\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\",\n" +
" \"emoji\": true\n" +
" }\n" +
" }\n" +
"]}";
Message message = GsonFactory.createSnakeCase().fromJson(json, Message.class);
assertNotNull(message);
assertEquals(1, message.getBlocks().size());
InputBlock block = (InputBlock) message.getBlocks().get(0);
ChannelsSelectElement element = (ChannelsSelectElement) block.getElement();
assertNull(element.getResponseUrlEnabled());
}
}
@Test
public void defaultToCurrentConversation() {
String json = "{\n" +
" \"blocks\": [\n" +
" {\n" +
" \"type\": \"section\",\n" +
" \"text\": {\n" +
" \"type\": \"mrkdwn\",\n" +
" \"text\": \"Test block with multi conversations select\"\n" +
" },\n" +
" \"accessory\": {\n" +
" \"type\": \"multi_conversations_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select conversations\",\n" +
" \"emoji\": true\n" +
" },\n" +
" \"default_to_current_conversation\": true\n" +
" }\n" +
" },\n" +
" {\n" +
" \"type\": \"section\",\n" +
" \"text\": {\n" +
" \"type\": \"mrkdwn\",\n" +
" \"text\": \"Test block with multi conversations select\"\n" +
" },\n" +
" \"accessory\": {\n" +
" \"type\": \"conversations_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select conversations\",\n" +
" \"emoji\": true\n" +
" },\n" +
" \"default_to_current_conversation\": true\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
Message message = GsonFactory.createSnakeCase().fromJson(json, Message.class);
assertNotNull(message);
assertEquals(2, message.getBlocks().size());
SectionBlock section1 = (SectionBlock) message.getBlocks().get(0);
MultiConversationsSelectElement elem1 = (MultiConversationsSelectElement) (section1).getAccessory();
assertTrue(elem1.getDefaultToCurrentConversation());
SectionBlock section2 = (SectionBlock) message.getBlocks().get(1);
ConversationsSelectElement elem2 = (ConversationsSelectElement) (section2).getAccessory();
assertTrue(elem2.getDefaultToCurrentConversation());
}
@Test
public void codeInDocs() {
View modalView = view(v -> v
.type("modal")
.callbackId("view-id")
.submit(viewSubmit(vs -> vs.type("plain_text").text("Submit")))
.blocks(asBlocks(
section(s -> s
.text(plainText("Conversation to post the result"))
.accessory(conversationsSelect(conv -> conv
.actionId("a")
.defaultToCurrentConversation(true)
.responseUrlEnabled(true))
)
)
)));
assertNotNull(modalView);
}
@Test
public void timePickerElement() {
// https://api.slack.com/reference/block-kit/block-elements#timepicker
String json = "{\n" +
" \"type\": \"section\",\n" +
" \"block_id\": \"section1234\",\n" +
" \"text\": {\n" +
" \"type\": \"mrkdwn\",\n" +
" \"text\": \"Pick a date for the deadline.\"\n" +
" },\n" +
" \"accessory\": {\n" +
" \"type\": \"timepicker\",\n" +
" \"action_id\": \"timepicker123\",\n" +
" \"initial_time\": \"11:40\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a time\"\n" +
" }\n" +
" }\n" +
"}";
Gson gson = GsonFactory.createSnakeCase();
SectionBlock section = gson.fromJson(json, SectionBlock.class);
assertThat(section.getBlockId(), is("section1234"));
TimePickerElement accessory = (TimePickerElement) section.getAccessory();
assertThat(accessory.getActionId(), is("timepicker123"));
assertThat(accessory.getInitialTime(), is("11:40"));
assertThat(accessory.getPlaceholder().getText(), is("Select a time"));
assertThat(accessory.getConfirm(), is(nullValue()));
String output = gson.toJson(section);
assertThat(output, is("{\"type\":\"section\",\"text\":{\"type\":\"mrkdwn\",\"text\":\"Pick a date for the deadline.\"},\"block_id\":\"section1234\",\"accessory\":{\"type\":\"timepicker\",\"action_id\":\"timepicker123\",\"placeholder\":{\"type\":\"plain_text\",\"text\":\"Select a time\"},\"initial_time\":\"11:40\"}}"));
}
@Test
public void focusOnLoad() {
String json = "{\"blocks\":[\n" +
" {\n" +
" \"type\": \"input\",\n" +
" \"element\": {\n" +
" \"type\": \"conversations_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a conversation\"\n" +
" },\n" +
" \"focus_on_load\": true\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\"\n" +
" }\n" +
" }\n" +
"]}";
View view = GsonFactory.createSnakeCase().fromJson(json, View.class);
assertNotNull(view);
assertEquals(1, view.getBlocks().size());
InputBlock block = (InputBlock) view.getBlocks().get(0);
ConversationsSelectElement element = (ConversationsSelectElement) block.getElement();
assertTrue(element.getFocusOnLoad());
}
@Test
public void noFocusOnLoad() {
String json = "{\"blocks\":[\n" +
" {\n" +
" \"type\": \"input\",\n" +
" \"element\": {\n" +
" \"type\": \"conversations_select\",\n" +
" \"placeholder\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Select a conversation\"\n" +
" }\n" +
" },\n" +
" \"label\": {\n" +
" \"type\": \"plain_text\",\n" +
" \"text\": \"Choose the conversation to publish your result to:\"\n" +
" }\n" +
" }\n" +
"]}";
View view = GsonFactory.createSnakeCase().fromJson(json, View.class);
assertNotNull(view);
assertEquals(1, view.getBlocks().size());
InputBlock block = (InputBlock) view.getBlocks().get(0);
ConversationsSelectElement element = (ConversationsSelectElement) block.getElement();
assertNull(element.getFocusOnLoad());
}
} | 43.333333 | 328 | 0.427711 |
2259281dd8cfd2fc39ad57cd20fcfd8bcf4ba5ce | 14,432 | /*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.basic;
import javax.swing.*;
import javax.swing.colorchooser.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import sun.swing.DefaultLookup;
/**
* Provides the basic look and feel for a JColorChooser.
*
* @author Tom Santos
* @author Steve Wilson
*/
public class BasicColorChooserUI extends ColorChooserUI
{
/**
* JColorChooser this BasicColorChooserUI is installed on.
*
* @since 1.5
*/
protected JColorChooser chooser;
JTabbedPane tabbedPane;
JPanel singlePanel;
JPanel previewPanelHolder;
JComponent previewPanel;
boolean isMultiPanel = false;
private static TransferHandler defaultTransferHandler = new ColorTransferHandler();
/**
* The array of default color choosers.
*/
protected AbstractColorChooserPanel[] defaultChoosers;
/**
* The instance of {@code ChangeListener}.
*/
protected ChangeListener previewListener;
/**
* The instance of {@code PropertyChangeListener}.
*/
protected PropertyChangeListener propertyChangeListener;
private Handler handler;
/**
* Constructs a {@code BasicColorChooserUI}.
*/
public BasicColorChooserUI() {}
/**
* Returns a new instance of {@code BasicColorChooserUI}.
*
* @param c a component
* @return a new instance of {@code BasicColorChooserUI}
*/
public static ComponentUI createUI(JComponent c) {
return new BasicColorChooserUI();
}
/**
* Returns an array of default color choosers.
*
* @return an array of default color choosers
*/
protected AbstractColorChooserPanel[] createDefaultChoosers() {
AbstractColorChooserPanel[] panels = ColorChooserComponentFactory.getDefaultChooserPanels();
return panels;
}
/**
* Uninstalls default color choosers.
*/
protected void uninstallDefaultChoosers() {
AbstractColorChooserPanel[] choosers = chooser.getChooserPanels();
for( int i = 0 ; i < choosers.length; i++) {
chooser.removeChooserPanel( choosers[i] );
}
}
public void installUI( JComponent c ) {
chooser = (JColorChooser)c;
super.installUI( c );
installDefaults();
installListeners();
tabbedPane = new JTabbedPane();
tabbedPane.setName("ColorChooser.tabPane");
tabbedPane.setInheritsPopupMenu(true);
tabbedPane.getAccessibleContext().setAccessibleDescription(tabbedPane.getName());
singlePanel = new JPanel(new CenterLayout());
singlePanel.setName("ColorChooser.panel");
singlePanel.setInheritsPopupMenu(true);
chooser.setLayout( new BorderLayout() );
defaultChoosers = createDefaultChoosers();
chooser.setChooserPanels(defaultChoosers);
previewPanelHolder = new JPanel(new CenterLayout());
previewPanelHolder.setName("ColorChooser.previewPanelHolder");
if (DefaultLookup.getBoolean(chooser, this,
"ColorChooser.showPreviewPanelText", true)) {
String previewString = UIManager.getString(
"ColorChooser.previewText", chooser.getLocale());
previewPanelHolder.setBorder(new TitledBorder(previewString));
}
previewPanelHolder.setInheritsPopupMenu(true);
installPreviewPanel();
chooser.applyComponentOrientation(c.getComponentOrientation());
}
public void uninstallUI( JComponent c ) {
chooser.remove(tabbedPane);
chooser.remove(singlePanel);
chooser.remove(previewPanelHolder);
uninstallDefaultChoosers();
uninstallListeners();
uninstallPreviewPanel();
uninstallDefaults();
previewPanelHolder = null;
previewPanel = null;
defaultChoosers = null;
chooser = null;
tabbedPane = null;
handler = null;
}
/**
* Installs preview panel.
*/
protected void installPreviewPanel() {
JComponent previewPanel = this.chooser.getPreviewPanel();
if (previewPanel == null) {
previewPanel = ColorChooserComponentFactory.getPreviewPanel();
}
else if (JPanel.class.equals(previewPanel.getClass()) && (0 == previewPanel.getComponentCount())) {
previewPanel = null;
}
this.previewPanel = previewPanel;
if (previewPanel != null) {
chooser.add(previewPanelHolder, BorderLayout.SOUTH);
previewPanel.setForeground(chooser.getColor());
previewPanelHolder.add(previewPanel);
previewPanel.addMouseListener(getHandler());
previewPanel.setInheritsPopupMenu(true);
}
}
/**
* Removes installed preview panel from the UI delegate.
*
* @since 1.7
*/
protected void uninstallPreviewPanel() {
if (this.previewPanel != null) {
this.previewPanel.removeMouseListener(getHandler());
this.previewPanelHolder.remove(this.previewPanel);
}
this.chooser.remove(this.previewPanelHolder);
}
/**
* Installs default properties.
*/
protected void installDefaults() {
LookAndFeel.installColorsAndFont(chooser, "ColorChooser.background",
"ColorChooser.foreground",
"ColorChooser.font");
LookAndFeel.installProperty(chooser, "opaque", Boolean.TRUE);
TransferHandler th = chooser.getTransferHandler();
if (th == null || th instanceof UIResource) {
chooser.setTransferHandler(defaultTransferHandler);
}
}
/**
* Uninstalls default properties.
*/
protected void uninstallDefaults() {
if (chooser.getTransferHandler() instanceof UIResource) {
chooser.setTransferHandler(null);
}
}
/**
* Registers listeners.
*/
protected void installListeners() {
propertyChangeListener = createPropertyChangeListener();
chooser.addPropertyChangeListener(propertyChangeListener);
previewListener = getHandler();
chooser.getSelectionModel().addChangeListener(previewListener);
}
private Handler getHandler() {
if (handler == null) {
handler = new Handler();
}
return handler;
}
/**
* Returns an instance of {@code PropertyChangeListener}.
*
* @return an instance of {@code PropertyChangeListener}
*/
protected PropertyChangeListener createPropertyChangeListener() {
return getHandler();
}
/**
* Unregisters listeners.
*/
protected void uninstallListeners() {
chooser.removePropertyChangeListener( propertyChangeListener );
chooser.getSelectionModel().removeChangeListener(previewListener);
previewListener = null;
}
private void selectionChanged(ColorSelectionModel model) {
JComponent previewPanel = this.chooser.getPreviewPanel();
if (previewPanel != null) {
previewPanel.setForeground(model.getSelectedColor());
previewPanel.repaint();
}
AbstractColorChooserPanel[] panels = this.chooser.getChooserPanels();
if (panels != null) {
for (AbstractColorChooserPanel panel : panels) {
if (panel != null) {
panel.updateChooser();
}
}
}
}
private class Handler implements ChangeListener, MouseListener,
PropertyChangeListener {
//
// ChangeListener
//
public void stateChanged(ChangeEvent evt) {
selectionChanged((ColorSelectionModel) evt.getSource());
}
//
// MouseListener
public void mousePressed(MouseEvent evt) {
if (chooser.getDragEnabled()) {
TransferHandler th = chooser.getTransferHandler();
th.exportAsDrag(chooser, evt, TransferHandler.COPY);
}
}
public void mouseReleased(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
//
// PropertyChangeListener
//
public void propertyChange(PropertyChangeEvent evt) {
String prop = evt.getPropertyName();
if (prop == JColorChooser.CHOOSER_PANELS_PROPERTY) {
AbstractColorChooserPanel[] oldPanels =
(AbstractColorChooserPanel[])evt.getOldValue();
AbstractColorChooserPanel[] newPanels =
(AbstractColorChooserPanel[])evt.getNewValue();
for (int i = 0; i < oldPanels.length; i++) { // remove old panels
Container wrapper = oldPanels[i].getParent();
if (wrapper != null) {
Container parent = wrapper.getParent();
if (parent != null)
parent.remove(wrapper); // remove from hierarchy
oldPanels[i].uninstallChooserPanel(chooser); // uninstall
}
}
int numNewPanels = newPanels.length;
if (numNewPanels == 0) { // removed all panels and added none
chooser.remove(tabbedPane);
return;
}
else if (numNewPanels == 1) { // one panel case
chooser.remove(tabbedPane);
JPanel centerWrapper = new JPanel( new CenterLayout() );
centerWrapper.setInheritsPopupMenu(true);
centerWrapper.add(newPanels[0]);
singlePanel.add(centerWrapper, BorderLayout.CENTER);
chooser.add(singlePanel);
}
else { // multi-panel case
if ( oldPanels.length < 2 ) {// moving from single to multiple
chooser.remove(singlePanel);
chooser.add(tabbedPane, BorderLayout.CENTER);
}
for (int i = 0; i < newPanels.length; i++) {
JPanel centerWrapper = new JPanel( new CenterLayout() );
centerWrapper.setInheritsPopupMenu(true);
String name = newPanels[i].getDisplayName();
int mnemonic = newPanels[i].getMnemonic();
centerWrapper.add(newPanels[i]);
tabbedPane.addTab(name, centerWrapper);
if (mnemonic > 0) {
tabbedPane.setMnemonicAt(i, mnemonic);
int index = newPanels[i].getDisplayedMnemonicIndex();
if (index >= 0) {
tabbedPane.setDisplayedMnemonicIndexAt(i, index);
}
}
}
}
chooser.applyComponentOrientation(chooser.getComponentOrientation());
for (int i = 0; i < newPanels.length; i++) {
newPanels[i].installChooserPanel(chooser);
}
}
else if (prop == JColorChooser.PREVIEW_PANEL_PROPERTY) {
uninstallPreviewPanel();
installPreviewPanel();
}
else if (prop == JColorChooser.SELECTION_MODEL_PROPERTY) {
ColorSelectionModel oldModel = (ColorSelectionModel) evt.getOldValue();
oldModel.removeChangeListener(previewListener);
ColorSelectionModel newModel = (ColorSelectionModel) evt.getNewValue();
newModel.addChangeListener(previewListener);
selectionChanged(newModel);
}
else if (prop == "componentOrientation") {
ComponentOrientation o =
(ComponentOrientation)evt.getNewValue();
JColorChooser cc = (JColorChooser)evt.getSource();
if (o != (ComponentOrientation)evt.getOldValue()) {
cc.applyComponentOrientation(o);
cc.updateUI();
}
}
}
}
/**
* This class should be treated as a "protected" inner class.
* Instantiate it only within subclasses of {@code BasicColorChooserUI}.
*/
public class PropertyHandler implements PropertyChangeListener {
/**
* Constructs a {@code PropertyHandler}.
*/
public PropertyHandler() {}
public void propertyChange(PropertyChangeEvent e) {
getHandler().propertyChange(e);
}
}
@SuppressWarnings("serial") // JDK-implementation class
static class ColorTransferHandler extends TransferHandler implements UIResource {
ColorTransferHandler() {
super("color");
}
}
}
| 35.286064 | 107 | 0.602966 |
3b5b55faa46e0fbcdca7f91894ffdec9b2385f34 | 1,662 | package com.orangetalents.mercadolivre.produtos;
import com.orangetalents.mercadolivre.categorias.Categoria;
import com.orangetalents.mercadolivre.compartilhado.credenciais.BuscaUsuario;
import com.orangetalents.mercadolivre.usuarios.Usuario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import javax.validation.Valid;
@RestController
@RequestMapping("/produtos")
public class ProdutoController {
@PersistenceContext
private EntityManager manager;
@Autowired
private BuscaUsuario buscaUsuario;
@PostMapping
@Transactional
public ResponseEntity<ProdutoDto> cadastrar(@RequestBody @Valid FormProdutoRequest formProdutoRequest, @AuthenticationPrincipal UserDetails usuarioLogado) {
Usuario usuario = buscaUsuario.retornaUsuario(manager, usuarioLogado.getUsername());
Categoria categoria = manager.find(Categoria.class, formProdutoRequest.getIdCategoria());
Produto produto = formProdutoRequest.converter(categoria, usuario);
manager.persist(produto);
return ResponseEntity.ok(new ProdutoDto(produto));
}
}
| 40.536585 | 160 | 0.821901 |
b64ce00f50f5831e3d1e6075dc7ad94339d0e09a | 7,289 | /*
* Copyright (c) 2018 - 2019 - Frank Hossfeld
*
* 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.nalukit.gwtbootstarternalu.client.ui.content.composite.application;
import com.github.nalukit.gwtbootstarternalu.client.ui.content.composite.application.IApplicationComponent.Controller;
import com.github.nalukit.gwtbootstarternalu.shared.model.NaluGeneraterParms;
import com.github.nalukit.nalu.client.component.AbstractCompositeComponent;
import elemental2.dom.HTMLDivElement;
import elemental2.dom.HTMLElement;
import org.dominokit.domino.ui.cards.Card;
import org.dominokit.domino.ui.forms.CheckBox;
import org.dominokit.domino.ui.forms.FieldsGrouping;
import org.dominokit.domino.ui.grid.Column;
import org.dominokit.domino.ui.grid.Row;
import org.dominokit.domino.ui.header.BlockHeader;
import org.dominokit.domino.ui.style.Color;
public class ApplicationComponent
extends AbstractCompositeComponent<Controller, HTMLElement>
implements IApplicationComponent {
private CheckBox cbApplicationLoader;
private CheckBox cbDebugSupport;
private CheckBox cbLoginScreen;
private CheckBox cbErrorScreen;
private CheckBox cbHashUrl;
private FieldsGrouping grouping;
public ApplicationComponent() {
}
@Override
public void render() {
this.grouping = new FieldsGrouping();
this.cbApplicationLoader = CheckBox.create("Generate Application Loader class")
.check()
.setColor(Color.BLUE_GREY)
.filledIn()
.styler(style -> style.setMarginBottom("0px"))
.groupBy(this.grouping);
this.cbDebugSupport = CheckBox.create("Generate Debug support (in development mode)")
.check()
.setColor(Color.BLUE_GREY)
.filledIn()
.styler(style -> style.setMarginBottom("0px"))
.groupBy(this.grouping);
this.cbLoginScreen = CheckBox.create("Generate Login screen and Login filter")
.check()
.setColor(Color.BLUE_GREY)
.filledIn()
.styler(style -> style.setMarginBottom("0px"))
.groupBy(this.grouping);
this.cbErrorScreen = CheckBox.create("Generate Error Screen")
.check()
.setColor(Color.BLUE_GREY)
.filledIn()
.styler(style -> style.setMarginBottom("0px"))
.groupBy(this.grouping);
this.cbHashUrl = CheckBox.create("Use hash in URL")
.check()
.setColor(Color.BLUE_GREY)
.filledIn()
.styler(style -> style.setMarginBottom("0px"))
.groupBy(this.grouping);
HTMLDivElement element = Row.create()
.appendChild(Column.span10()
.offset1()
.appendChild(BlockHeader.create("Application Meta Data"))
.appendChild(Card.create()
.appendChild(Row.create()
.appendChild(Column.span6()
.condenced()
.appendChild(this.cbApplicationLoader))
.appendChild(Column.span6()
.condenced()
.appendChild(this.cbDebugSupport)))
.appendChild(Row.create()
.appendChild(Column.span6()
.condenced()
.appendChild(this.cbLoginScreen))
.appendChild(Column.span6()
.condenced()
.appendChild(this.cbErrorScreen)))
.appendChild(Row.create()
.appendChild(Column.span12()
.condenced()
.appendChild(this.cbHashUrl))))
.style())
.asElement();
initElement(element);
}
@Override
public void edit(NaluGeneraterParms naluGeneraterParms) {
this.cbApplicationLoader.setValue(naluGeneraterParms.isApplicationLoader());
this.cbDebugSupport.setValue(naluGeneraterParms.isDebug());
this.cbErrorScreen.setValue(naluGeneraterParms.hasErrorScreen());
this.cbLoginScreen.setValue(naluGeneraterParms.hasLoginScreen());
this.cbHashUrl.setValue(naluGeneraterParms.hasHashUrl());
}
@Override
public NaluGeneraterParms flush(NaluGeneraterParms naluGeneraterParms) {
naluGeneraterParms.setApplicationLoader(cbApplicationLoader.getValue());
naluGeneraterParms.setDebug(cbDebugSupport.getValue());
naluGeneraterParms.setErrorScreen(cbErrorScreen.getValue());
naluGeneraterParms.setLoginScreen(cbLoginScreen.getValue());
naluGeneraterParms.setHashUrl(cbHashUrl.getValue());
return naluGeneraterParms;
}
@Override
public boolean isVald() {
return this.grouping.validate()
.isValid();
}
}
| 53.595588 | 142 | 0.476197 |
f80ae44495e039c6120bcac5a2bf7925937e8bee | 2,210 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.kafka.listener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.springframework.util.Assert;
/**
* A {@link BatchInterceptor} that delegates to one or more {@link BatchInterceptor}s in
* order.
*
* @param <K> the key type.
* @param <V> the value type.
*
* @author Gary Russell
* @since 2.7
*
*/
public class CompositeBatchInterceptor<K, V> implements BatchInterceptor<K, V> {
private final Collection<BatchInterceptor<K, V>> delegates = new ArrayList<>();
/**
* Construct an instance with the provided delegates.
* @param delegates the delegates.
*/
@SafeVarargs
@SuppressWarnings("varargs")
public CompositeBatchInterceptor(BatchInterceptor<K, V>... delegates) {
Assert.notNull(delegates, "'delegates' cannot be null");
Assert.noNullElements(delegates, "'delegates' cannot have null entries");
this.delegates.addAll(Arrays.asList(delegates));
}
@Override
public ConsumerRecords<K, V> intercept(ConsumerRecords<K, V> records) {
ConsumerRecords<K, V> recordsToIntercept = records;
for (BatchInterceptor<K, V> delegate : this.delegates) {
recordsToIntercept = delegate.intercept(recordsToIntercept);
}
return recordsToIntercept;
}
@Override
public void success(ConsumerRecords<K, V> records) {
this.delegates.forEach(del -> del.success(records));
}
@Override
public void failure(ConsumerRecords<K, V> records, Exception exception) {
this.delegates.forEach(del -> del.failure(records, exception));
}
}
| 29.864865 | 88 | 0.740271 |
d2689e666f4ac4f21014f13f7d9e5aa55050818c | 1,534 | package classes;
public class Rating {
private double note1;
private double note2;
private Student stud;
private Subject sub;
public Rating(double note1, double note2, Student stud, Subject sub) {
this.note1 = note1;
this.note2 = note2;
this.stud = stud;
this.sub = sub;
}
public double getNote1() {
return this.note1;
}
public void setNote1(double note1) {
this.note1 = note1;
}
public double getNote2() {
return this.note2;
}
public void setNote2(double note2) {
this.note2 = note2;
}
public Student getStud() {
return this.stud;
}
public void setStud(Student stud) {
this.stud = stud;
}
public Subject getSub() {
return this.sub;
}
public void setSub(Subject sub) {
this.sub = sub;
}
public Rating note1(double note1) {
this.note1 = note1;
return this;
}
public Rating note2(double note2) {
this.note2 = note2;
return this;
}
public Rating stud(Student stud) {
this.stud = stud;
return this;
}
public Rating sub(Subject sub) {
this.sub = sub;
return this;
}
@Override
public String toString() {
return "{" +
" note1='" + getNote1() + "'" +
", note2='" + getNote2() + "'" +
", stud='" + getStud() + "'" +
", sub='" + getSub() + "'" +
"}";
}
}
| 19.175 | 74 | 0.51043 |
75912d3ab7a91117d671bb96e58894deca93bba8 | 1,466 | /*
* 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 cn.hippo4j.common.api;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* Client close hook execute.
*
* @author chen.ma
* @date 2022/1/6 22:14
*/
public interface ClientCloseHookExecute {
/**
* Client close hook function execution.
*
* @param req
*/
void closeHook(ClientCloseHookReq req);
@Data
@Accessors(chain = true)
class ClientCloseHookReq {
/**
* appName
*/
private String appName;
/**
* instanceId
*/
private String instanceId;
/**
* groupKey
*/
private String groupKey;
}
}
| 25.275862 | 75 | 0.664393 |
7e3fbd5547eee8e081cdf4a393bb865c27d26bf7 | 6,301 | package ru.saidgadjiev.ormnext.core.loader.object.collection;
import ru.saidgadjiev.ormnext.core.dao.Session;
import ru.saidgadjiev.ormnext.core.loader.object.Lazy;
import ru.saidgadjiev.ormnext.core.logger.Log;
import ru.saidgadjiev.ormnext.core.logger.LoggerFactory;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* Base class for implement lazy collection.
*
* @param <T> value type
* @author Said Gadjiev
*/
public abstract class AbstractLazyCollection<T> implements Collection<T>, Lazy {
/**
* Logger.
*/
private static final Log LOG = LoggerFactory.getLogger(AbstractLazyCollection.class);
/**
* Current session manager.
*/
private Session session;
/**
* Collection owner id.
*/
private Object ownerId;
/**
* Original collection.
*/
private Collection<T> collection;
/**
* Initialized state.
*/
private boolean initialized = false;
/**
* Collection loader.
*
* @see CollectionLoader
*/
private CollectionLoader collectionLoader;
/**
* Cached collection size.
*/
private long cachedSize;
/**
* Create a new lazy collection.
*
* @param session target session
* @param collectionLoader collection loader
* @param ownerId owner object id
* @param collection original collection
*/
public AbstractLazyCollection(CollectionLoader collectionLoader,
Session session,
Object ownerId,
Collection<T> collection) {
this.collectionLoader = collectionLoader;
this.session = session;
this.ownerId = ownerId;
this.collection = collection;
}
/**
* Read collection items and add all to original collection {@link #collection}.
*/
final void read() {
if (initialized) {
return;
}
try {
Collection<?> loadedObjects = collectionLoader.loadCollection(session, ownerId);
collection.addAll((Collection<? extends T>) loadedObjects);
Field field = collectionLoader.getForeignCollectionColumnType().getField();
LOG.debug(
"Collection %s lazy initialized with items %s",
field.toString(),
loadedObjects
);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
initialized = true;
}
/**
* Read collection items size.
* If already initialized return false, else select size and cache to {@link #cachedSize}.
*
* @return false if already initialized
*/
private boolean readSize() {
if (initialized) {
return false;
}
try {
cachedSize = collectionLoader.loadSize(session, ownerId);
Field field = collectionLoader.getForeignCollectionColumnType().getField();
LOG.debug(
"Collection %s lazy read size %s",
field.toString(),
cachedSize
);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return true;
}
@Override
public int size() {
return readSize() ? (int) cachedSize : collection.size();
}
@Override
public boolean isEmpty() {
read();
return collection.isEmpty();
}
@Override
public boolean contains(Object o) {
read();
return collection.contains(o);
}
@Override
public Iterator<T> iterator() {
read();
return collection.iterator();
}
@Override
public Object[] toArray() {
read();
return collection.toArray();
}
@Override
public <T1> T1[] toArray(T1[] a) {
read();
return collection.toArray(a);
}
@Override
public boolean add(T t) {
read();
return collection.add(t);
}
@Override
public boolean remove(Object o) {
read();
return collection.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
read();
return collection.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends T> c) {
read();
return collection.addAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
read();
return collection.removeAll(c);
}
@Override
public boolean removeIf(Predicate<? super T> filter) {
read();
return collection.removeIf(filter);
}
@Override
public boolean retainAll(Collection<?> c) {
read();
return collection.retainAll(c);
}
@Override
public void clear() {
read();
collection.clear();
}
@Override
public boolean equals(Object o) {
read();
return collection.equals(o);
}
@Override
public int hashCode() {
read();
return collection.hashCode();
}
@Override
public Spliterator<T> spliterator() {
read();
return collection.spliterator();
}
@Override
public Stream<T> stream() {
read();
return collection.stream();
}
@Override
public Stream<T> parallelStream() {
read();
return collection.parallelStream();
}
@Override
public void forEach(Consumer<? super T> action) {
read();
collection.forEach(action);
}
@Override
public void attach(Session session) {
this.session = session;
}
@Override
public boolean isInitialized() {
return initialized;
}
@Override
public synchronized void setNonInitialized() {
initialized = false;
collection.clear();
}
@Override
public String toString() {
read();
return "AbstractLazyCollection{"
+ "collection=" + collection
+ '}';
}
}
| 21.431973 | 94 | 0.571179 |
2ee48482439db6998e4067ad5f2b702bb4e61bb2 | 162 | public class Tuple<L, R> {
public final L left;
public final R right;
public Tuple(L l, R r) {
this.left = l;
this.right = r;
}
} | 18 | 28 | 0.524691 |
487d5aeceb0a7f036c39f113b797b6b71036146a | 4,324 | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.RelevantAttributePrinter;
import net.sourceforge.pmd.lang.java.JavaParsingHelper;
public class Java16TreeDumpTest extends BaseTreeDumpTest {
private final JavaParsingHelper java16 =
JavaParsingHelper.WITH_PROCESSING.withDefaultVersion("16")
.withResourceContext(Java16TreeDumpTest.class, "jdkversiontests/java16/");
private final JavaParsingHelper java15 = java16.withDefaultVersion("15");
public Java16TreeDumpTest() {
super(new RelevantAttributePrinter(), ".java");
}
@Override
public BaseParsingHelper<?, ?> getParser() {
return java16;
}
@Test
public void patternMatchingInstanceof() {
doTest("PatternMatchingInstanceof");
// extended tests for type resolution etc.
ASTCompilationUnit compilationUnit = java16.parseResource("PatternMatchingInstanceof.java");
List<ASTInstanceOfExpression> instanceOfExpressions = compilationUnit.findDescendantsOfType(ASTInstanceOfExpression.class);
for (ASTInstanceOfExpression expr : instanceOfExpressions) {
ASTVariableDeclaratorId variable = expr.getChild(1).getFirstChildOfType(ASTVariableDeclaratorId.class);
Assert.assertEquals(String.class, variable.getType());
// Note: these variables are not part of the symbol table
// See ScopeAndDeclarationFinder#visit(ASTVariableDeclaratorId, Object)
Assert.assertNull(variable.getNameDeclaration());
}
}
@Test(expected = ParseException.class)
public void patternMatchingInstanceofBeforeJava16ShouldFail() {
java15.parseResource("PatternMatchingInstanceof.java");
}
@Test
public void localClassAndInterfaceDeclarations() {
doTest("LocalClassAndInterfaceDeclarations");
}
@Test(expected = ParseException.class)
public void localClassAndInterfaceDeclarationsBeforeJava16ShouldFail() {
java15.parseResource("LocalClassAndInterfaceDeclarations.java");
}
@Test(expected = ParseException.class)
public void localAnnotationsAreNotAllowed() {
java16.parse("public class Foo { { @interface MyLocalAnnotation {} } }");
}
@Test
public void localRecords() {
doTest("LocalRecords");
}
@Test
public void recordPoint() {
doTest("Point");
// extended tests for type resolution etc.
ASTCompilationUnit compilationUnit = java16.parseResource("Point.java");
ASTRecordDeclaration recordDecl = compilationUnit.getFirstDescendantOfType(ASTRecordDeclaration.class);
List<ASTRecordComponent> components = recordDecl.getFirstChildOfType(ASTRecordComponentList.class)
.findChildrenOfType(ASTRecordComponent.class);
Assert.assertNull(components.get(0).getVarId().getNameDeclaration().getAccessNodeParent());
Assert.assertEquals(Integer.TYPE, components.get(0).getVarId().getNameDeclaration().getType());
Assert.assertEquals("int", components.get(0).getVarId().getNameDeclaration().getTypeImage());
}
@Test(expected = ParseException.class)
public void recordPointBeforeJava16ShouldFail() {
java15.parseResource("Point.java");
}
@Test(expected = ParseException.class)
public void recordCtorWithThrowsShouldFail() {
java16.parse(" record R {"
+ " R throws IOException {}"
+ " }");
}
@Test(expected = ParseException.class)
public void recordMustNotExtend() {
java16.parse("record RecordEx(int x) extends Number { }");
}
@Test
public void innerRecords() {
doTest("Records");
}
@Test(expected = ParseException.class)
public void recordIsARestrictedIdentifier() {
java16.parse("public class record {}");
}
@Test
public void sealedAndNonSealedIdentifiers() {
doTest("NonSealedIdentifier");
}
}
| 36.033333 | 131 | 0.703978 |
1e863b1b5742915c89c2945e67608c829371f789 | 27,441 | package cn.dustlight.auth.controllers;
import cn.dustlight.auth.configurations.components.TokenConfiguration;
import cn.dustlight.auth.controllers.resources.ClientResource;
import cn.dustlight.auth.controllers.resources.UserResource;
import cn.dustlight.auth.entities.*;
import cn.dustlight.auth.services.ClientService;
import cn.dustlight.auth.services.oauth.EnhancedTokenStore;
import cn.dustlight.auth.util.Constants;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.approval.Approval;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint;
import org.springframework.security.oauth2.provider.endpoint.RedirectResolver;
import org.springframework.security.oauth2.provider.implicit.ImplicitTokenRequest;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URI;
import java.security.Principal;
import java.util.*;
@Tag(name = "Authorization", description = "OAuth2 应用授权。")
@RestController
@RequestMapping(path = Constants.API_ROOT, produces = Constants.ContentType.APPLICATION_JSON)
@SecurityRequirement(name = "AccessToken")
@CrossOrigin(origins = Constants.CrossOrigin.origin, allowCredentials = Constants.CrossOrigin.allowCredentials)
public class AuthorizationController {
static final String AUTHORIZATION_REQUEST_ATTR_NAME = "authorizationRequest";
static final String ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME = "org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST";
private static final Log logger = LogFactory.getLog(AuthorizationController.class.getName());
@Autowired
private AuthorizationEndpoint authorizationEndpoint;
@Autowired
private ClientService clientService;
@Autowired
private ApprovalStore authApprovalStore;
@Autowired
private TokenStore authTokenStore;
@Autowired
private EnhancedTokenStore enhancedTokenStore;
@Autowired
private OAuth2RequestFactory oAuth2RequestFactory;
@Autowired
private RedirectResolver redirectResolver;
@Autowired
private OAuth2RequestValidator oAuth2RequestValidator;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
private TokenGranter tokenGranter;
@Autowired
TokenConfiguration.Jwt jwt;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
private Object implicitLock = new Object();
/**
* @see AuthorizationEndpoint
*/
@PreAuthorize("#oauth2.clientHasRole('AUTHORIZE')")
@Operation(summary = "获取应用授权", description = "获取包含应用信息、所属用户信息、回调地址以及是否已授权。应用需要 AUTHORIZE 权限。")
@GetMapping("oauth/authorization")
public AuthorizationResponse getAuthorization(@Parameter(hidden = true) @RequestParam Map<String, String> parameters,
@RequestParam("client_id") String clientId,
@RequestParam(value = "response_type", defaultValue = "code") String responseType,
@RequestParam(value = "redirect_uri", required = false) String redirectUri,
@RequestParam(value = "scope", required = false) Collection<String> scopes,
@RequestParam(value = "state", required = false) String state,
@RequestParam(value = "jwt", required = false) Boolean isJwt,
HttpServletRequest httpServletRequest,
Principal principal) {
logger.info("?????????" + isJwt);
try {
AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(parameters);
Set<String> responseTypes = authorizationRequest.getResponseTypes();
if (!responseTypes.contains("token") && !responseTypes.contains("code"))
throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
if (authorizationRequest.getClientId() == null)
throw new InvalidClientException("A client id must be provided");
if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated())
throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorization can be completed.");
Client client = clientService.loadClientByClientId(authorizationRequest.getClientId());
PublicUser owner = clientService.getOwnerPublic(clientId);
String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
if (!StringUtils.hasText(resolvedRedirect))
throw new RedirectMismatchException("A redirectUri must be either supplied or preconfigured in the ClientDetails");
authorizationRequest.setRedirectUri(resolvedRedirect);
oAuth2RequestValidator.validateScope(authorizationRequest, client);
authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, (Authentication) principal);
boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
authorizationRequest.setApproved(approved);
AuthorizationResponse response = new AuthorizationResponse();
AuthorizationResponse.AuthorizationClient authorizationClient = new AuthorizationResponse.AuthorizationClient();
authorizationClient.setClientId(clientId);
authorizationClient.setLogo(client.getLogo());
authorizationClient.setCreatedAt(client.getCreatedAt());
authorizationClient.setName(client.getName());
authorizationClient.setDescription(client.getDescription());
response.setRedirect(resolvedRedirect);
if (authorizationRequest.isApproved()) {
if (responseTypes.contains("token")) {
response.setRedirect(getImplicitGrantRedirect(authorizationRequest, (Authentication) principal, isJwt));
} else if (responseTypes.contains("code")) {
response.setRedirect(getAuthorizationCodeRedirect(authorizationRequest, (Authentication) principal, isJwt));
}
}
authorizationClient.setScopes(getUserApprovalScopes(authorizationRequest, principal.getName(), client));
HttpSession session = httpServletRequest.getSession(true);
session.setAttribute(AUTHORIZATION_REQUEST_ATTR_NAME, authorizationRequest);
session.setAttribute(ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME, unmodifiableMap(authorizationRequest));
response.setClient(ClientResource.setLogo(authorizationClient));
response.setOwner(UserResource.setAvatar((DefaultPublicUser) owner));
response.setApproved(approved);
response.setCount(enhancedTokenStore.countClientToken(clientId));
return response;
} catch (RuntimeException e) {
HttpSession session = httpServletRequest.getSession(false);
if (session != null) {
session.removeAttribute(AUTHORIZATION_REQUEST_ATTR_NAME);
session.removeAttribute(ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME);
}
throw e;
}
}
@PreAuthorize("#oauth2.clientHasRole('AUTHORIZE')")
@Operation(summary = "应用授权", description = "应用需要 AUTHORIZE 权限。")
@PostMapping("oauth/authorization")
public AuthorizationResponse createAuthorization(@RequestParam("approved") boolean approved,
@RequestParam("scope") Set<String> scopes,
@RequestParam(value = "jwt", required = false) Boolean isJwt,
HttpServletRequest httpServletRequest,
Principal principal) {
logger.info("!!!!!!!!!!!" + isJwt);
Map<String, String> approvalParameters = new LinkedHashMap<>();
approvalParameters.put("user_oauth_approval", approved ? "true" : "false");
for (String scope : scopes)
if (scope.startsWith("scope."))
approvalParameters.put(scope, "true");
else
approvalParameters.put("scope." + scope, "true");
if (!(principal instanceof Authentication)) {
throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorizing an AccessToken.");
}
HttpSession session = httpServletRequest.getSession(false);
AuthorizationRequest authorizationRequest;
if (session == null ||
(authorizationRequest = (AuthorizationRequest) session.getAttribute(AUTHORIZATION_REQUEST_ATTR_NAME)) == null) {
if (session != null) {
session.removeAttribute(AUTHORIZATION_REQUEST_ATTR_NAME);
session.removeAttribute(ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME);
}
throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
}
// Check to ensure the Authorization Request was not modified during the user approval step
@SuppressWarnings("unchecked")
Map<String, Object> originalAuthorizationRequest = (Map<String, Object>) session.getAttribute(ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME);
if (isAuthorizationRequestModified(authorizationRequest, originalAuthorizationRequest)) {
throw new InvalidRequestException("Changes were detected from the original authorization request.");
}
try {
Set<String> responseTypes = authorizationRequest.getResponseTypes();
authorizationRequest.setApprovalParameters(approvalParameters);
authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest, (Authentication) principal);
boolean isApproved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
authorizationRequest.setApproved(isApproved);
if (authorizationRequest.getRedirectUri() == null) {
session.removeAttribute(AUTHORIZATION_REQUEST_ATTR_NAME);
session.removeAttribute(ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME);
throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
}
AuthorizationResponse response = new AuthorizationResponse();
response.setApproved(isApproved);
if (!authorizationRequest.isApproved()) {
response.setRedirect(getUnsuccessfulRedirect(authorizationRequest,
new UserDeniedAuthorizationException("User denied access"),
responseTypes.contains("token")));
} else if (responseTypes.contains("token")) {
response.setRedirect(getImplicitGrantRedirect(authorizationRequest, (Authentication) principal, isJwt));
} else {
response.setRedirect(getAuthorizationCodeRedirect(authorizationRequest, (Authentication) principal, isJwt));
}
return response;
} finally {
session.removeAttribute(AUTHORIZATION_REQUEST_ATTR_NAME);
session.removeAttribute(ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME);
}
}
private Map<String, Object> unmodifiableMap(AuthorizationRequest authorizationRequest) {
Map<String, Object> authorizationRequestMap = new HashMap<String, Object>();
authorizationRequestMap.put(OAuth2Utils.CLIENT_ID, authorizationRequest.getClientId());
authorizationRequestMap.put(OAuth2Utils.STATE, authorizationRequest.getState());
authorizationRequestMap.put(OAuth2Utils.REDIRECT_URI, authorizationRequest.getRedirectUri());
if (authorizationRequest.getResponseTypes() != null) {
authorizationRequestMap.put(OAuth2Utils.RESPONSE_TYPE,
Collections.unmodifiableSet(new HashSet<String>(authorizationRequest.getResponseTypes())));
}
if (authorizationRequest.getScope() != null) {
authorizationRequestMap.put(OAuth2Utils.SCOPE,
Collections.unmodifiableSet(new HashSet<String>(authorizationRequest.getScope())));
}
authorizationRequestMap.put("approved", authorizationRequest.isApproved());
if (authorizationRequest.getResourceIds() != null) {
authorizationRequestMap.put("resourceIds",
Collections.unmodifiableSet(new HashSet<String>(authorizationRequest.getResourceIds())));
}
if (authorizationRequest.getAuthorities() != null) {
authorizationRequestMap.put("authorities",
Collections.unmodifiableSet(new HashSet<GrantedAuthority>(authorizationRequest.getAuthorities())));
}
return Collections.unmodifiableMap(authorizationRequestMap);
}
/**
* @see AuthorizationEndpoint
*/
private boolean isAuthorizationRequestModified(
AuthorizationRequest authorizationRequest, Map<String, Object> originalAuthorizationRequest) {
if (!ObjectUtils.nullSafeEquals(
authorizationRequest.getClientId(),
originalAuthorizationRequest.get(OAuth2Utils.CLIENT_ID))) {
return true;
}
if (!ObjectUtils.nullSafeEquals(
authorizationRequest.getState(),
originalAuthorizationRequest.get(OAuth2Utils.STATE))) {
return true;
}
if (!ObjectUtils.nullSafeEquals(
authorizationRequest.getRedirectUri(),
originalAuthorizationRequest.get(OAuth2Utils.REDIRECT_URI))) {
return true;
}
if (!ObjectUtils.nullSafeEquals(
authorizationRequest.getResponseTypes(),
originalAuthorizationRequest.get(OAuth2Utils.RESPONSE_TYPE))) {
return true;
}
if (!ObjectUtils.nullSafeEquals(
authorizationRequest.getScope(),
originalAuthorizationRequest.get(OAuth2Utils.SCOPE))) {
return true;
}
if (!ObjectUtils.nullSafeEquals(
authorizationRequest.isApproved(),
originalAuthorizationRequest.get("approved"))) {
return true;
}
if (!ObjectUtils.nullSafeEquals(
authorizationRequest.getResourceIds(),
originalAuthorizationRequest.get("resourceIds"))) {
return true;
}
if (!ObjectUtils.nullSafeEquals(
authorizationRequest.getAuthorities(),
originalAuthorizationRequest.get("authorities"))) {
return true;
}
return false;
}
/**
* @see AuthorizationEndpoint
*/
private Collection<AuthorizationResponse.AuthorizationClientScope> getUserApprovalScopes(AuthorizationRequest authorizationRequest, String username, Client client) {
Set<String> approvedScopes = new LinkedHashSet<>(); // 已授权的Scopes
Set<String> requestScopes = authorizationRequest.getScope(); // 请求授权的Scope
Set<AuthorizationResponse.AuthorizationClientScope> resultScopes = new LinkedHashSet<>();
/* 获取已授权的Scopes */
Collection<Approval> approvals = authApprovalStore.getApprovals(username, client.getClientId());
for (Approval approval : approvals)
if (approval.isCurrentlyActive())
approvedScopes.add(approval.getScope());
for (ClientScope clientScope : client.getScopes()) {
if (clientScope == null)
continue;
if (requestScopes.contains(clientScope.getName())) {
AuthorizationResponse.AuthorizationClientScope oAuth2ClientScope = AuthorizationResponse.AuthorizationClientScope.from(clientScope);
if (approvedScopes.contains(clientScope.getName()))
oAuth2ClientScope.setApproved(true);
resultScopes.add(oAuth2ClientScope);
}
}
return resultScopes;
}
/**
* @see AuthorizationEndpoint
*/
private String getAuthorizationCodeRedirect(AuthorizationRequest authorizationRequest,
Authentication authUser,
boolean isJwt) {
AuthorizationResponse response = new AuthorizationResponse();
try {
return getSuccessfulRedirect(authorizationRequest, generateCode(authorizationRequest, authUser), isJwt);
} catch (OAuth2Exception e) {
return getUnsuccessfulRedirect(authorizationRequest, e, false);
}
}
/**
* @see AuthorizationEndpoint
*/
private String getImplicitGrantRedirect(AuthorizationRequest authorizationRequest,
Authentication authentication,
boolean isJwt) {
try {
TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(authorizationRequest, "implicit");
OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
OAuth2AccessToken accessToken = getAccessTokenForImplicitGrant(tokenRequest, storedOAuth2Request);
if (accessToken == null) {
throw new UnsupportedResponseTypeException("Unsupported response type: token");
}
if (isJwt) {
accessToken = jwt.convert(accessToken, new OAuth2Authentication(storedOAuth2Request, authentication));
}
return appendAccessToken(authorizationRequest, accessToken);
} catch (OAuth2Exception e) {
return getUnsuccessfulRedirect(authorizationRequest, e, true);
}
}
/**
* @see AuthorizationEndpoint
*/
private OAuth2AccessToken getAccessTokenForImplicitGrant(TokenRequest tokenRequest, OAuth2Request storedOAuth2Request) {
OAuth2AccessToken accessToken = null;
// These 1 method calls have to be atomic, otherwise the ImplicitGrantService can have a race condition where
// one thread removes the token request before another has a chance to redeem it.
synchronized (this.implicitLock) {
accessToken = tokenGranter.grant("implicit", new ImplicitTokenRequest(tokenRequest, storedOAuth2Request));
}
return accessToken;
}
/**
* @see AuthorizationEndpoint
*/
private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) {
Map<String, Object> vars = new LinkedHashMap<String, Object>();
Map<String, String> keys = new HashMap<String, String>();
if (accessToken == null) {
throw new InvalidRequestException("An implicit grant could not be made");
}
vars.put("access_token", accessToken.getValue());
vars.put("token_type", accessToken.getTokenType());
String state = authorizationRequest.getState();
if (state != null) {
vars.put("state", state);
}
Date expiration = accessToken.getExpiration();
if (expiration != null) {
long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
vars.put("expires_in", expires_in);
}
String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
if (originalScope == null || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope()));
}
Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
for (String key : additionalInformation.keySet()) {
Object value = additionalInformation.get(key);
if (value != null) {
keys.put("extra_" + key, key);
vars.put("extra_" + key, value);
}
}
// Do not include the refresh token (even if there is one)
return append(authorizationRequest.getRedirectUri(), vars, keys, true);
}
/**
* @see AuthorizationEndpoint
*/
private String generateCode(AuthorizationRequest authorizationRequest, Authentication authentication) throws AuthenticationException {
try {
OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
OAuth2Authentication combinedAuth = new OAuth2Authentication(storedOAuth2Request, authentication);
String code = authorizationCodeServices.createAuthorizationCode(combinedAuth);
return code;
} catch (OAuth2Exception e) {
if (authorizationRequest.getState() != null) {
e.addAdditionalInformation("state", authorizationRequest.getState());
}
throw e;
}
}
/**
* @see AuthorizationEndpoint
*/
private String getSuccessfulRedirect(AuthorizationRequest authorizationRequest,
String authorizationCode,
boolean isJwt) {
if (authorizationCode == null) {
throw new IllegalStateException("No authorization code found in the current request scope.");
}
Map<String, String> query = new LinkedHashMap<String, String>();
query.put("code", authorizationCode);
if (isJwt)
query.put("jwt", "true");
String state = authorizationRequest.getState();
if (state != null) {
query.put("state", state);
}
return append(authorizationRequest.getRedirectUri(), query, false);
}
/**
* @see AuthorizationEndpoint
*/
private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure, boolean fragment) {
if (authorizationRequest == null || authorizationRequest.getRedirectUri() == null) {
// we have no redirect for the user. very sad.
throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.", failure);
}
Map<String, String> query = new LinkedHashMap<String, String>();
query.put("error", failure.getOAuth2ErrorCode());
query.put("error_description", failure.getMessage());
if (authorizationRequest.getState() != null) {
query.put("state", authorizationRequest.getState());
}
if (failure.getAdditionalInformation() != null) {
for (Map.Entry<String, String> additionalInfo : failure.getAdditionalInformation().entrySet()) {
query.put(additionalInfo.getKey(), additionalInfo.getValue());
}
}
return append(authorizationRequest.getRedirectUri(), query, fragment);
}
/**
* @see AuthorizationEndpoint
*/
private String append(String base, Map<String, ?> query, boolean fragment) {
return append(base, query, null, fragment);
}
/**
* @see AuthorizationEndpoint
*/
private String append(String base, Map<String, ?> query, Map<String, String> keys, boolean fragment) {
UriComponentsBuilder template = UriComponentsBuilder.newInstance();
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base);
URI redirectUri;
try {
// assume it's encoded to start with (if it came in over the wire)
redirectUri = builder.build(true).toUri();
} catch (Exception e) {
// ... but allow client registrations to contain hard-coded non-encoded values
redirectUri = builder.build().toUri();
builder = UriComponentsBuilder.fromUri(redirectUri);
}
template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost())
.userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath());
if (fragment) {
StringBuilder values = new StringBuilder();
if (redirectUri.getFragment() != null) {
String append = redirectUri.getFragment();
values.append(append);
}
for (String key : query.keySet()) {
if (values.length() > 0) {
values.append("&");
}
String name = key;
if (keys != null && keys.containsKey(key)) {
name = keys.get(key);
}
values.append(name + "={" + key + "}");
}
if (values.length() > 0) {
template.fragment(values.toString());
}
UriComponents encoded = template.build().expand(query).encode();
builder.fragment(encoded.getFragment());
} else {
for (String key : query.keySet()) {
String name = key;
if (keys != null && keys.containsKey(key)) {
name = keys.get(key);
}
template.queryParam(name, "{" + key + "}");
}
template.fragment(redirectUri.getFragment());
UriComponents encoded = template.build().expand(query).encode();
builder.query(encoded.getQuery());
}
return builder.build().toUriString();
}
}
| 49.177419 | 176 | 0.663132 |
6d723e53a149a31e4399d75590644af89a32bda7 | 1,257 | package org.qiunet.utils.test.math;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.qiunet.utils.math.MathUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author qiunet
* Created on 16/11/6 13:54.
*/
@RunWith(Parameterized.class)
public class TestMathUtilPowerTwo {
private final int val;
private final boolean eq;
public TestMathUtilPowerTwo(int val, boolean eq) {
this.eq = eq;
this.val = val;
}
@Parameterized.Parameters
public static Collection params(){
List<Object[]> ret = new ArrayList<>();
ret.add(new Object[]{0, true});
ret.add(new Object[]{1, true});
ret.add(new Object[]{2, true});
ret.add(new Object[]{4, true});
ret.add(new Object[]{8, true});
ret.add(new Object[]{16, true});
ret.add(new Object[]{32, true});
ret.add(new Object[]{64, true});
ret.add(new Object[]{128, true});
ret.add(new Object[]{1024, true});
ret.add(new Object[]{3, false});
ret.add(new Object[]{5, false});
ret.add(new Object[]{6, false});
ret.add(new Object[]{1023, false});
return ret;
}
@Test
public void testRandom(){
Assert.assertEquals(MathUtil.isPowerOfTwo(val), eq);
}
}
| 24.647059 | 54 | 0.680986 |
bc9dff12237649b5346576609231e1599846f134 | 1,348 | protected CommandProcessor newCommandProcessor(JSONArray array) throws JSONException {
if (array.length() == 0) {
return new NopProcessor();
} else if (array.get(0) instanceof JSONArray) {
return new CommandProcessorComposite(newCommandProcessors(array));
} else {
Class<?>[] paramTypes = new Class<?>[array.length() - 1];
Object[] params = new Object[array.length() - 1];
for (int i = 0; i < array.length() - 1; i++) {
if (array.get(i + 1) instanceof JSONArray) {
paramTypes[i] = CommandProcessor.class;
params[i] = newCommandProcessor(array.getJSONArray(i + 1));
} else {
paramTypes[i] = array.get(i + 1).getClass();
params[i] = array.get(i + 1);
}
}
String cpClassName = PACKAGE + array.getString(0) + "Processor";
try {
Class<?> cpClass = Class.forName(cpClassName);
Constructor<?> constructor = cpClass.getConstructor(paramTypes);
return (CommandProcessor) constructor.newInstance(params);
} catch (Exception e) {
throw new RuntimeException("Could not instantiate " + cpClassName, e);
}
}
}
| 48.142857 | 90 | 0.531157 |
e42e06cc7143f027beba954f72a8605b03ba6c54 | 1,568 | package ru.job4j.lsp.action;
import ru.job4j.lsp.controll.ControllQuality;
import ru.job4j.lsp.UIStorageFood;
import ru.job4j.lsp.input.InputInterface;
import ru.job4j.lsp.model.Food;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class AddFood extends BaseAction {
private static final Random RN = new Random();
public AddFood(int key, String info) {
super(key, info);
}
@Override
public void execute(UIStorageFood ui, InputInterface input) {
String name = input.ask("Input name the product");
Date expiryDate = parseDate(input.ask("Input expiry date in the format yyyy-MM-dd of the product"));
Date createDate = parseDate(input.ask("Input create datein the format yyyy-MM-dd of the product"));
int price = Integer.parseInt(input.ask("Input price of the product"));
Food food = new Food(name, expiryDate, createDate, price);
if (food.getId() == 0) {
food.setId(generatedId());
}
this.runControll(food, ui);
}
protected void runControll(Food food, UIStorageFood ui) {
new ControllQuality().distribute(food, ui);
}
public static Date parseDate(String date) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(date);
} catch (ParseException e) {
return null;
}
}
private static long generatedId() {
return Long.parseLong(String.valueOf(System.currentTimeMillis() + RN.nextInt()));
}
}
| 31.36 | 108 | 0.663903 |
ad0aeafc269c69e55a2179b5d7118dbd4a4aac0f | 490 | package io.semantic.openscore.core.model;
import javax.persistence.Entity;
@Entity
public class PreguntaSecreta extends Storable {
private String codigo;
private String pregunta;
public String getPregunta() {
return pregunta;
}
public void setPregunta(String pregunta) {
this.pregunta = pregunta;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
}
| 16.896552 | 47 | 0.657143 |
512855bd3999de3b4f0896370c6dc576dd69ccff | 1,354 | /*
* Copyright 2018 technosf [https://github.com/technosf]
*
* 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.technosf.posterer.models.impl;
import com.github.technosf.posterer.models.Auth;
/**
* HTTP Authentication bean.
*
* @author technosf
* @since 0.0.1
* @version 0.0.1
*/
public class AuthBean
implements Auth
{
private final String user;
private final String password;
public AuthBean(String user, String password)
{
this.user = user;
this.password = password;
}
/* (non-Javadoc)
* @see com.github.technosf.posterer.models.impl.Auth#getUser()
*/
@Override
public String getUser()
{
return user;
}
/* (non-Javadoc)
* @see com.github.technosf.posterer.models.impl.Auth#getPassword()
*/
@Override
public String getPassword()
{
return password;
}
}
| 23.754386 | 100 | 0.702363 |
6df007a7302adaa2ec758017473028702fc3efa9 | 1,430 | package ooga.model.cards.cardcomponents;
import java.util.ResourceBundle;
import ooga.Config;
import ooga.model.exceptions.InvalidCardParameterException;
/**
* Concrete immutable class implementing the CardInfo interface, represents the information on a
* UnoCard, no setter methods / no way to modify after creation
*
* @author Alicia Wu
*/
public class UnoCardInfo implements CardInfo {
private String type;
private int param;
/**
* creates a new instance of UnoCardInfo given the card's type and parameter value
*
* @param type UnoCard's type
* @param param UnoCard's action parameter
*/
public UnoCardInfo(String type, int param) {
if (param < 0) {
ResourceBundle myResources = ResourceBundle.getBundle(
Config.PROPERTIES_FILES_PATH + Config.ENGLISH_EXTENSION);
throw new InvalidCardParameterException(
myResources.getString(InvalidCardParameterException.class.getSimpleName()));
}
this.type = type.toLowerCase();
this.param = param;
}
/**
* gets the card's type (e.g.: skip, number, wild, etc.)
*
* @return String representing a card's type
*/
@Override
public String getType() {
return type;
}
/**
* gets the card's action parameter (i.e.: 2 in "draw 2", 1 in "skip 1", 7 in "number 7")
*
* @return int representing a card's parameter
*/
@Override
public int getParam() {
return param;
}
}
| 25.535714 | 96 | 0.687413 |
e877cb65cd5a5da270679ad88574c530adcfa19d | 1,966 | package com.coderstower.socialmediapubisher.springpublisher.main.aws.repository.oauth2;
import com.coderstower.socialmediapubisher.springpublisher.abstraction.security.repository.OAuth2Credentials;
import com.coderstower.socialmediapubisher.springpublisher.abstraction.security.repository.OAuth2CredentialsRepository;
import java.util.Optional;
public class OAuth2CredentialAWSRepository implements OAuth2CredentialsRepository {
private final OAuth2CredentialDynamoRepository oauth2CredentialDynamoRepository;
public OAuth2CredentialAWSRepository(OAuth2CredentialDynamoRepository oauth2CredentialDynamoRepository) {
this.oauth2CredentialDynamoRepository = oauth2CredentialDynamoRepository;
}
@Override
public OAuth2Credentials save(OAuth2Credentials oAuth2Credentials) {
return convert(oauth2CredentialDynamoRepository.save(convert(oAuth2Credentials)));
}
@Override
public OAuth2Credentials update(OAuth2Credentials oAuth2Credentials) {
return convert(oauth2CredentialDynamoRepository.save(convert(oAuth2Credentials)));
}
@Override
public Optional<OAuth2Credentials> getCredentials(String id) {
return oauth2CredentialDynamoRepository.findById(id).map(this::convert);
}
private OAuth2CredentialDynamo convert(OAuth2Credentials oAuth2Credentials) {
return OAuth2CredentialDynamo.builder()
.accessToken(oAuth2Credentials.getAccessToken())
.id(oAuth2Credentials.getId())
.expirationDate(oAuth2Credentials.getExpirationDate())
.build();
}
private OAuth2Credentials convert(OAuth2CredentialDynamo oauth2CredentialDynamo) {
return OAuth2Credentials.builder()
.accessToken(oauth2CredentialDynamo.getAccessToken())
.id(oauth2CredentialDynamo.getId())
.expirationDate(oauth2CredentialDynamo.getExpirationDate())
.build();
}
}
| 42.73913 | 119 | 0.763988 |
e5781c014150dc52db4e1f49a8b4e111a6097151 | 162 | package pacman;
import java.awt.*;
public abstract class BoardPiece {
protected Image sprite;
public Image getImage() {
return sprite;
}
}
| 13.5 | 34 | 0.654321 |
017d3fd4826f4316e748a7ee04d92e685352742a | 975 | package com.compuware.ispw.model.rest;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="containerList")
@XmlAccessorType(XmlAccessType.NONE)
public class ContainerListResponse
{
@XmlElement(name = "containers")
private List<ContainerListInfo> containerList = new ArrayList<ContainerListInfo>();
@XmlElement(name = "message")
private String message;
public ContainerListResponse()
{
}
public void addContainer(ContainerListInfo containerListInfo)
{
containerList.add(containerListInfo);
}
public List<ContainerListInfo> getContainerList()
{
return containerList;
}
public void setMessage(String message)
{
this.message = message;
}
public String getMessage()
{
return message;
}
} | 23.214286 | 86 | 0.749744 |
e5ab33c02150027acb4a68c83fa26cf112de6c69 | 3,364 | package com.home.commonBase.data.scene.unit.identity;
import com.home.commonBase.constlist.generate.BaseDataType;
import com.home.commonBase.data.scene.unit.UnitIdentityData;
import com.home.shine.bytes.BytesReadStream;
import com.home.shine.bytes.BytesWriteStream;
import com.home.shine.data.BaseData;
import com.home.shine.support.DataWriter;
import com.home.shine.support.pool.DataPool;
/** 操作体身份数据(generated by shine) */
public class OperationIdentityData extends UnitIdentityData
{
/** id */
public int id;
/** 操作体状态(见OperationStateType) */
public int state;
/** 数据类型ID */
public static final int dataID=BaseDataType.OperationIdentity;
public OperationIdentityData()
{
_dataID=BaseDataType.OperationIdentity;
}
/** 获取数据类名 */
@Override
public String getDataClassName()
{
return "OperationIdentityData";
}
/** 读取字节流(完整版) */
@Override
protected void toReadBytesFull(BytesReadStream stream)
{
super.toReadBytesFull(stream);
stream.startReadObj();
this.id=stream.readInt();
this.state=stream.readInt();
stream.endReadObj();
}
/** 写入字节流(完整版) */
@Override
protected void toWriteBytesFull(BytesWriteStream stream)
{
super.toWriteBytesFull(stream);
stream.startWriteObj();
stream.writeInt(this.id);
stream.writeInt(this.state);
stream.endWriteObj();
}
/** 读取字节流(简版) */
@Override
protected void toReadBytesSimple(BytesReadStream stream)
{
super.toReadBytesSimple(stream);
this.id=stream.readInt();
this.state=stream.readInt();
}
/** 写入字节流(简版) */
@Override
protected void toWriteBytesSimple(BytesWriteStream stream)
{
super.toWriteBytesSimple(stream);
stream.writeInt(this.id);
stream.writeInt(this.state);
}
/** 复制(潜拷贝) */
@Override
protected void toShadowCopy(BaseData data)
{
super.toShadowCopy(data);
if(!(data instanceof OperationIdentityData))
return;
OperationIdentityData mData=(OperationIdentityData)data;
this.id=mData.id;
this.state=mData.state;
}
/** 复制(深拷贝) */
@Override
protected void toCopy(BaseData data)
{
super.toCopy(data);
if(!(data instanceof OperationIdentityData))
return;
OperationIdentityData mData=(OperationIdentityData)data;
this.id=mData.id;
this.state=mData.state;
}
/** 是否数据一致 */
@Override
protected boolean toDataEquals(BaseData data)
{
if(!super.toDataEquals(data))
return false;
OperationIdentityData mData=(OperationIdentityData)data;
if(this.id!=mData.id)
return false;
if(this.state!=mData.state)
return false;
return true;
}
/** 转文本输出 */
@Override
protected void toWriteDataString(DataWriter writer)
{
super.toWriteDataString(writer);
writer.writeTabs();
writer.sb.append("id");
writer.sb.append(':');
writer.sb.append(this.id);
writer.writeEnter();
writer.writeTabs();
writer.sb.append("state");
writer.sb.append(':');
writer.sb.append(this.state);
writer.writeEnter();
}
/** 初始化初值 */
@Override
public void initDefault()
{
super.initDefault();
}
/** 回池 */
@Override
protected void toRelease(DataPool pool)
{
super.toRelease(pool);
this.id=0;
this.state=0;
}
}
| 19.113636 | 64 | 0.664982 |
3b9c6e53dd5798490382197969712719d5863c49 | 460 | package com.onlinepayments.webhooks;
/**
* Represents an error while validating webhooks signatures.
*/
@SuppressWarnings("serial")
public class SignatureValidationException extends RuntimeException {
public SignatureValidationException(String message) {
super(message);
}
public SignatureValidationException(Throwable cause) {
super(cause);
}
public SignatureValidationException(String message, Throwable cause) {
super(message, cause);
}
}
| 21.904762 | 71 | 0.784783 |
a7b677cb2671f5e069887379e68462f4d45c504e | 13,905 | /*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/9.0.0.M1
* Generated at: 2016-03-25 04:09:18 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.hitachigst.prb.te.teweb.*;
import com.hitachigst.prb.itd.itdtools.util.*;
import com.hitachigst.prb.te.teweb.*;
import com.hitachigst.prb.itd.itdtools.util.*;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent,
org.apache.jasper.runtime.JspSourceImports {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
static {
_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(2);
_jspx_dependants.put("/PageLayout/footerlayout.jsp", Long.valueOf(1455876871114L));
_jspx_dependants.put("/PageLayout/logintoplayout.jsp", Long.valueOf(1455876871131L));
}
private static final java.util.Set<java.lang.String> _jspx_imports_packages;
private static final java.util.Set<java.lang.String> _jspx_imports_classes;
static {
_jspx_imports_packages = new java.util.HashSet<>();
_jspx_imports_packages.add("javax.servlet");
_jspx_imports_packages.add("javax.servlet.http");
_jspx_imports_packages.add("com.hitachigst.prb.te.teweb");
_jspx_imports_packages.add("javax.servlet.jsp");
_jspx_imports_packages.add("com.hitachigst.prb.itd.itdtools.util");
_jspx_imports_classes = null;
}
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public java.util.Set<java.lang.String> getPackageImports() {
return _jspx_imports_packages;
}
public java.util.Set<java.lang.String> getClassImports() {
return _jspx_imports_classes;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
if (_el_expressionfactory == null) {
synchronized (this) {
if (_el_expressionfactory == null) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
}
}
}
return _el_expressionfactory;
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
if (_jsp_instancemanager == null) {
synchronized (this) {
if (_jsp_instancemanager == null) {
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
}
}
return _jsp_instancemanager;
}
public void _jspInit() {
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final java.lang.String _jspx_method = request.getMethod();
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
return;
}
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=TIS-620");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
out.write("<head>\r\n");
out.write("\t<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\r\n");
out.write(" <meta http-equiv=\"imagetoolbar\" content=\"no\" />\r\n");
out.write(" <meta name=\"description\" content=\"\" />\r\n");
out.write(" <meta name=\"keywords\" content=\"\" />\r\n");
out.write(" <meta name=\"author\" content=\"James Koster || www.sixshootermedia.com\" />\r\n");
out.write(" <meta name=\"copyright\" content=\"\" />\r\n");
out.write(" <meta name=\"company\" content=\"\" />\r\n");
out.write("\r\n");
out.write(" <meta name=\"revisit-after\" content=\"7 days\" />\r\n");
out.write("\t\r\n");
out.write("\t");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String apppath=application.getRealPath("");
String webpath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"";
new TeWebConfig(apppath,webpath);
String version="";
String webname="";
webname=IniFilesReader.getReturnProperties("Local.Application","Application Name");
version=TeWebVersionControl.getVersion();
out.write("\r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\t<title>");
out.println(webname);
out.write("</title>\r\n");
out.write("\t\r\n");
out.write(" <link href=\"DATA-INF/CSS/1.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n");
out.write(" <style type=\"text/css\">\r\n");
out.write("<!--\r\n");
out.write(".form-noindent {\tBORDER-RIGHT: #c3d9ff 1px solid; BORDER-TOP: #c3d9ff 1px solid; BORDER-LEFT: #c3d9ff 1px solid; BORDER-BOTTOM: #c3d9ff 1px solid; BACKGROUND-COLOR: #ffffff\r\n");
out.write("}\r\n");
out.write(".style1 {\tfont-size: 16px;\r\n");
out.write("\tfont-weight: bold;\r\n");
out.write("}\r\n");
out.write("-->\r\n");
out.write(" </style>\r\n");
out.write("</head>\r\n");
out.write("\r\n");
out.write("<body>\r\n");
out.write("\r\n");
out.write(" ");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("<!-- ============================================Top Layout============================================================================== -->\t\r\n");
out.write("<div id=\"header\">\r\n");
out.write(" <table width=\"100%\" border=\"0\">\r\n");
out.write(" <tr> \r\n");
out.write(" <td width=\"33%\"><img src=\"DATA-INF/Image/telogo.jpg\" alt=\"Your Logo\" title=\"Your Logo\" /></td>\r\n");
out.write(" <td width=\"33%\"><h1><a name=\"Top\" id=\"Top\"></a><a href=\"#\">");
//out.println(webname);
out.write(" </a></h1></td>\r\n");
out.write(" <td width=\"34%\"> <p>Version : ");
out.println(version);
out.write(" <br /></p> </td>\t \r\n");
out.write(" </tr>\r\n");
out.write("\t<tr> \r\n");
out.write("\t <td width=\"33%\"></td>\r\n");
out.write(" <td width=\"33%\"></td>\r\n");
out.write(" <td width=\"34%\"></td>\r\n");
out.write("\t</tr> \r\n");
out.write(" </table>\r\n");
out.write(" <div id=\"header-container\">\t \r\n");
out.write("\t\t <!-- <h1><a name=\"Top\" id=\"Top\"></a><a href=\"#\">");
//out.println(webname);
out.write(" </a></h1> -->\r\n");
out.write(" <ul><li></li></ul>\r\n");
out.write("\t\t<br class=\"clear\" />\r\n");
out.write(" </div> \r\n");
out.write("</div>\r\n");
out.write("<!-- ================================================================================================================================== -->\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\t\r\n");
out.write("\t<table width=\"100%\" border=\"0\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td height=\"243\" align=\"center\" valign=\"top\">\r\n");
out.write(" <table class=\"form-noindent\" cellspacing=\"3\" cellpadding=\"5\" width=\"40%\" \r\n");
out.write(" border=\"0\">\r\n");
out.write(" <tbody>\r\n");
out.write(" <tr>\r\n");
out.write(" <td style=\"TEXT-ALIGN: center\" valign=\"top\" nowrap=\"nowrap\" bgcolor=\"#e8eefa\"><form action=\"logon_process.jsp\" method=\"post\" name=\"form1\" target=\"_parent\" id=\"form1\">\r\n");
out.write(" <table width=\"100%\" border=\"0\">\r\n");
out.write(" <tr>\r\n");
out.write(" <td colspan=\"3\" align=\"left\"><span class=\"style1\">Logon</span></td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td colspan=\"3\"> </td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td width=\"25%\" align=\"left\">Username:\r\n");
out.write(" <label></label></td>\r\n");
out.write(" <td colspan=\"2\" align=\"left\"><label>\r\n");
out.write(" <input name=\"username\" type=\"text\" id=\"username\" size=\"32\" />\r\n");
out.write(" </label></td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td align=\"left\">Password:</td>\r\n");
out.write(" <td colspan=\"2\" align=\"left\"><label>\r\n");
out.write(" <input name=\"password\" type=\"password\" id=\"password\" size=\"32\" />\r\n");
out.write(" </label></td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td colspan=\"3\"> </td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td align=\"center\"> </td>\r\n");
out.write(" <td width=\"17%\" align=\"left\" valign=\"middle\"><input type=\"submit\" name=\"button\" id=\"button\" value=\"Submit\" /></td>\r\n");
out.write(" <td width=\"58%\" align=\"left\" valign=\"middle\"><label>\r\n");
out.write(" <input type=\"reset\" name=\"button2\" id=\"button2\" value=\"Cancel\" />\r\n");
out.write(" </label></td>\r\n");
out.write(" </tr>\r\n");
out.write(" <tr>\r\n");
out.write(" <td colspan=\"3\"> </td>\r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.write(" </form></td>\r\n");
out.write(" </tr>\r\n");
out.write(" </tbody>\r\n");
out.write(" </table></td>\r\n");
out.write(" </tr>\r\n");
out.write(" </table>\r\n");
out.write(" ");
out.write("<!-- ============================================Top Layout============================================================================== -->\t\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" <div align = \"right\" id=\"footer\">\r\n");
out.write("\t\t<div id=\"footercontent\" align=\"center\">\r\n");
out.write("\t\t\r\n");
out.write("\t\t<table align = \"center\">\t\r\n");
out.write("\t\t© HGST aWestern Digital company (Thailand) Limited. All rigths reserved\r\n");
out.write("\t\t</table\r\n");
out.write("\t\t</div>\r\n");
out.write("\t</div>\r\n");
out.write("\r\n");
out.write("<!-- ================================================================================================================================== -->\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("</body>\r\n");
out.write("</html>\r\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| 46.818182 | 224 | 0.528443 |
522f6f9ff03d510d2aa94926b78209cddf8873d4 | 287 |
// https://leetcode.com/contest/weekly-contest-241/problems/sum-of-all-subset-xor-totals/
public class SumOfAllSubsetXORTotals {
public int subsetXORSum(int[] nums) {
int res = 0;
for (int num : nums) {
res |= num;
}
return res * (1 << nums.length - 1);
}
}
| 20.5 | 89 | 0.623693 |
3a676cedf2617e63232797fe4f89566e07b43723 | 3,817 | /*
* Copyright 2017 SIB Visions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.sibvisions.rad.lua.support.functions;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.luaj.vm2.LuaError;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.VarArgFunction;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;
import org.luaj.vm2.lib.jse.CoerceLuaToJava;
/**
* The {@link StaticFunctionInvokingFunction} is a {@link VarArgFunction} which
* invokes the best fitting static function on an object.
*
* @author Robert Zenz
*/
public class StaticFunctionInvokingFunction extends VarArgFunction
{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Class members
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** The {@link Method}s. */
private List<Method> methods = new ArrayList<>();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Initialization
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Creates a new instance of {@link StaticFunctionInvokingFunction}.
*
* @param pClass the {@link Class class}.
* @param pStaticMethodName the {@link String static method name}.
*/
public StaticFunctionInvokingFunction(Class<?> pClass, String pStaticMethodName)
{
super();
for (Method method : pClass.getMethods())
{
if (method.getName().equals(pStaticMethodName))
{
methods.add(method);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Overwritten methods
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* {@inheritDoc}
*/
@Override
public Varargs invoke(Varargs pArgs)
{
Object[] parameters = new Object[pArgs.narg()];
Class<?>[] parameterClasses = new Class[pArgs.narg()];
for (int index = 0; index < pArgs.narg(); index++)
{
if (pArgs.isnil(index + 1))
{
parameterClasses[index] = Object.class;
parameters[index] = null;
}
else if (pArgs.isnumber(index + 1))
{
parameterClasses[index] = int.class;
parameters[index] = Integer.valueOf(pArgs.toint(index + 1));
}
else if (pArgs.isstring(index + 1))
{
parameterClasses[index] = String.class;
parameters[index] = pArgs.tojstring(index + 1);
}
else if (pArgs.isuserdata(index + 1))
{
parameterClasses[index] = Object.class;
parameters[index] = CoerceLuaToJava.coerce(pArgs.arg(index + 1), Object.class);
}
}
Method matchingMethod = null;
for (Method method : methods)
{
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == pArgs.narg())
{
for (int index = 0; index < parameterTypes.length; index++)
{
if (!parameterTypes[index].equals(parameterClasses[index]))
{
break;
}
}
matchingMethod = method;
}
}
if (matchingMethod == null)
{
throw new LuaError("No fitting method found.");
}
try
{
return CoerceJavaToLua.coerce(matchingMethod.invoke(null, parameters));
}
catch (Exception e)
{
throw new LuaError(e);
}
}
} // StaticFunctionInvokingFunction
| 27.264286 | 84 | 0.583966 |
673e41bdf98bf01cd25d9caf51da8fa37fd24526 | 1,617 | package com.lufax.jijin.fundation.repository;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.lufax.jijin.base.repository.BaseRepository;
import com.lufax.jijin.base.utils.MapUtils;
import com.lufax.jijin.fundation.constant.SyncFileStatus;
import com.lufax.jijin.fundation.dto.JijinSyncFileDTO;
@Repository
public class JijinSyncFileRepository extends BaseRepository<JijinSyncFileDTO>{
protected String nameSpace(){
return "BusJijinSyncFile";
}
public Long getNextVal(){
return (Long)super.queryObject("getNextVal");
}
public Object insertBusJijinSyncFile(JijinSyncFileDTO busJijinSyncFileDTO) {
return super.insert("insertBusJijinSyncFile", busJijinSyncFileDTO);
}
public int batchInsertBusJijinSyncFile(List<JijinSyncFileDTO> busJijinSyncFileDTOs) {
return super.batchInsert("insertBusJijinSyncFile", busJijinSyncFileDTOs);
}
public JijinSyncFileDTO findBusJijinSyncFile(Map condition) {
return super.query("findBusJijinSyncFile", condition);
}
public List<JijinSyncFileDTO> findBusJijinSyncFileList(Map condition) {
return super.queryList("findBusJijinSyncFile", condition);
}
public int updateBusJijinSyncFile(Map condition) {
return super.update("updateBusJijinSyncFile", condition);
}
public int updateBusJijinSyncFileStatus(long id, SyncFileStatus status, String comment){
return super.update("updateBusJijinSyncFile", MapUtils.buildKeyValueMap("id", id, "status", status.name(),"memo", comment));
}
}
| 33.6875 | 130 | 0.753865 |
ab95755cc985d78593c6e301f85adc607f11afca | 652 | package com.deer.wms.bill.manage.service;
import com.deer.wms.bill.manage.model.BillDetail;
import com.deer.wms.bill.manage.model.BillDetailCriteria;
import com.deer.wms.bill.manage.model.BillDetailDto;
import com.deer.wms.project.seed.core.service.Service;
import java.util.List;
/**
* Created by guo on 2018/07/05.
*/
public interface BillDetailService extends Service<BillDetail, String> {
List<BillDetailDto> findList(BillDetailCriteria criteria);
void deleteByC(BillDetailCriteria criteria);
List<BillDetailDto> findYesterday(BillDetailCriteria criteria);
List<BillDetailDto> findShangYue(BillDetailCriteria criteria);
}
| 27.166667 | 72 | 0.791411 |
7498dd5012d320508ec7ff05c9be84b1e78275e3 | 219 | package com.app.pixstory.ui.splash;
/**
* Author : Arvindo Mondal
* Created on 14-03-2020
*/
interface SplashNavigator {
void openWelcomeScreen();
void openLoginScreen();
void openDashboardScreen();
}
| 15.642857 | 35 | 0.694064 |
14c9dc4422a1365712354702acd0b6185bf4b5ee | 2,192 | /*
* The MIT License
*
* Copyright (c) 2009-2021 PrimeTek
*
* 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.primefaces.component.rowtoggler;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.primefaces.component.datatable.DataTable;
public class RowToggler extends RowTogglerBase {
public static final String COMPONENT_TYPE = "org.primefaces.component.RowToggler";
public static final String COLLAPSED_ICON = "ui-icon ui-icon-circle-triangle-e";
public static final String EXPANDED_ICON = "ui-icon ui-icon-circle-triangle-s";
public static final String ROW_TOGGLER = "primefaces.rowtoggler.aria.ROW_TOGGLER";
private DataTable parentTable;
public DataTable getParentTable(FacesContext context) {
if (parentTable == null) {
UIComponent parent = getParent();
while (parent != null) {
if (parent instanceof DataTable) {
parentTable = (DataTable) parent;
break;
}
parent = parent.getParent();
}
}
return parentTable;
}
} | 37.152542 | 86 | 0.71031 |
3bdd80fb3ec63b330198446de7412fb8c80b6693 | 438 | package com.predictivemovement.route.optimization;
import org.json.JSONObject;
/**
* Added to allow different kind of processings; needed to add metrics. Can be
* removed when there will be a better metric solution.
*/
public interface RouteProcessing {
public void calculate(JSONObject routeRequest) throws RouteOptimizationException;
public VRPSolution getVRPSolution();
public StatusResponse getStatusResponse();
}
| 25.764706 | 85 | 0.783105 |
aefffa7ca761b60b1e87e4ab5c75a67dfe9b949e | 15,501 | package gov.cms.dpc.api;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.client.api.ServerValidationModeEnum;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.rest.gclient.ICreateTyped;
import ca.uhn.fhir.rest.gclient.IUpdateExecutable;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.typesafe.config.ConfigFactory;
import gov.cms.dpc.api.auth.OrganizationPrincipal;
import gov.cms.dpc.api.exceptions.JsonParseExceptionMapper;
import gov.cms.dpc.fhir.DPCResourceType;
import gov.cms.dpc.fhir.configuration.DPCFHIRConfiguration;
import gov.cms.dpc.fhir.dropwizard.handlers.BundleHandler;
import gov.cms.dpc.fhir.dropwizard.handlers.FHIRHandler;
import gov.cms.dpc.fhir.dropwizard.handlers.exceptions.DefaultFHIRExceptionHandler;
import gov.cms.dpc.fhir.dropwizard.handlers.exceptions.HAPIExceptionHandler;
import gov.cms.dpc.fhir.dropwizard.handlers.exceptions.JerseyExceptionHandler;
import gov.cms.dpc.fhir.dropwizard.handlers.exceptions.PersistenceExceptionHandler;
import gov.cms.dpc.fhir.hapi.ContextUtils;
import gov.cms.dpc.fhir.validations.DPCProfileSupport;
import gov.cms.dpc.fhir.validations.ProfileValidator;
import gov.cms.dpc.fhir.validations.dropwizard.FHIRValidatorProvider;
import gov.cms.dpc.fhir.validations.dropwizard.InjectingConstraintValidatorFactory;
import gov.cms.dpc.queue.models.JobQueueBatch;
import gov.cms.dpc.testing.factories.FHIRPatientBuilder;
import gov.cms.dpc.testing.factories.FHIRPractitionerBuilder;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.testing.DropwizardTestSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.jetty.http.HttpStatus;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.hl7.fhir.dstu3.hapi.ctx.DefaultProfileValidationSupport;
import org.hl7.fhir.dstu3.hapi.validation.ValidationSupportChain;
import org.hl7.fhir.dstu3.model.*;
import org.hl7.fhir.dstu3.model.codesystems.V3RoleClass;
import org.hl7.fhir.instance.model.api.IBaseOperationOutcome;
import org.hl7.fhir.instance.model.api.IBaseResource;
import javax.validation.Validation;
import javax.validation.Validator;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class APITestHelpers {
private static final String ATTRIBUTION_URL = "http://localhost:3500/v1";
private static final String CONSENT_URL = "http://localhost:3600/v1";
public static final String ORGANIZATION_ID = "46ac7ad6-7487-4dd0-baa0-6e2c8cae76a0";
private static final String ATTRIBUTION_TRUNCATE_TASK = "http://localhost:9902/tasks/truncate";
public static String BASE_URL = "https://dpc.cms.gov/api";
public static String ORGANIZATION_NPI = "1111111112";
private static final ObjectMapper mapper = new ObjectMapper();
private APITestHelpers() {
// Not used
}
public static OrganizationPrincipal makeOrganizationPrincipal() {
Organization org = new Organization();
org.setId(ORGANIZATION_ID);
return new OrganizationPrincipal(org);
}
public static OrganizationPrincipal makeOrganizationPrincipal(String id) {
Organization org = new Organization();
org.setId(id);
return new OrganizationPrincipal(org);
}
public static IGenericClient buildAttributionClient(FhirContext ctx) {
ctx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
IGenericClient client = ctx.newRestfulGenericClient(ATTRIBUTION_URL);
// Disable logging for tests
LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
loggingInterceptor.setLogRequestSummary(false);
loggingInterceptor.setLogResponseSummary(false);
client.registerInterceptor(loggingInterceptor);
return client;
}
public static IGenericClient buildConsentClient(FhirContext ctx){
ContextUtils.prefetchResourceModels(ctx, JobQueueBatch.validResourceTypes);
ctx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
return ctx.newRestfulGenericClient(CONSENT_URL);
}
public static void setupPractitionerTest(IGenericClient client, IParser parser) throws IOException {
try (InputStream inputStream = APITestHelpers.class.getClassLoader().getResourceAsStream("provider_bundle.json")) {
final Parameters providerParameters = (Parameters) parser.parseResource(inputStream);
client
.operation()
.onType(Practitioner.class)
.named("submit")
.withParameters(providerParameters)
.encodedJson()
.execute();
}
}
public static void setupPatientTest(IGenericClient client, IParser parser) throws IOException {
try (InputStream inputStream = APITestHelpers.class.getClassLoader().getResourceAsStream("patient_bundle.json")) {
final Parameters patientParameters = (Parameters) parser.parseResource(inputStream);
client
.operation()
.onType(Patient.class)
.named("submit")
.withParameters(patientParameters)
.encodedJson()
.execute();
}
}
/**
* Build Dropwizard test instance with a specific subset of Resources and Providers
*
* @param ctx - {@link FhirContext} context to use
* @param resources - {@link List} of resources to add to test instance
* @param providers - {@link List} of providers to add to test instance
* @param validation - {@code true} enable custom validation. {@code false} Disable custom validation
* @return - {@link ResourceExtension}
*/
public static ResourceExtension buildResourceExtension(FhirContext
ctx, List<Object> resources, List<Object> providers, boolean validation) {
final FHIRHandler fhirHandler = new FHIRHandler(ctx);
final var builder = ResourceExtension
.builder()
.setRegisterDefaultExceptionMappers(false)
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addProvider(fhirHandler)
.addProvider(new BundleHandler(fhirHandler))
.addProvider(JerseyExceptionHandler.class)
.addProvider(PersistenceExceptionHandler.class)
.addProvider(HAPIExceptionHandler.class)
.addProvider(DefaultFHIRExceptionHandler.class)
.addProvider(JsonParseExceptionMapper.class)
.addProvider(new AuthValueFactoryProvider.Binder<>(OrganizationPrincipal.class));
// Optionally enable validation
if (validation) {
// Validation config
final DPCFHIRConfiguration.FHIRValidationConfiguration config = new DPCFHIRConfiguration.FHIRValidationConfiguration();
config.setEnabled(true);
config.setSchematronValidation(true);
config.setSchemaValidation(true);
final DPCProfileSupport dpcModule = new DPCProfileSupport(ctx);
final ValidationSupportChain support = new ValidationSupportChain(new DefaultProfileValidationSupport(), dpcModule);
final InjectingConstraintValidatorFactory constraintFactory = new InjectingConstraintValidatorFactory(
Set.of(new ProfileValidator(new FHIRValidatorProvider(ctx, config, support).get())));
builder.setValidator(provideValidator(constraintFactory));
}
resources.forEach(builder::addResource);
providers.forEach(builder::addProvider);
return builder.build();
}
static <C extends io.dropwizard.Configuration> void setupApplication(DropwizardTestSupport<C> application) throws
Exception {
ConfigFactory.invalidateCaches();
// Truncate attribution database
truncateDatabase();
application.before();
// Truncate the Auth DB
application.getApplication().run("db", "drop-all", "--confirm-delete-everything", "ci.application.conf");
application.getApplication().run("db", "migrate", "ci.application.conf");
}
private static void truncateDatabase() throws IOException {
try (CloseableHttpClient client = HttpClients.createDefault()) {
final HttpPost post = new HttpPost(ATTRIBUTION_TRUNCATE_TASK);
try (CloseableHttpResponse execute = client.execute(post)) {
assertEquals(HttpStatus.OK_200, execute.getStatusLine().getStatusCode(), "Should have truncated database");
}
}
}
static <C extends io.dropwizard.Configuration> void checkHealth(DropwizardTestSupport<C> application) throws
IOException {
// URI of the API Service Healthcheck
final String healthURI = String.format("http://localhost:%s/healthcheck", application.getAdminPort());
try (CloseableHttpClient client = HttpClients.createDefault()) {
final HttpGet healthCheck = new HttpGet(healthURI);
try (CloseableHttpResponse execute = client.execute(healthCheck)) {
assertEquals(HttpStatus.OK_200, execute.getStatusLine().getStatusCode(), "Should be healthy");
}
}
}
private static Validator provideValidator(InjectingConstraintValidatorFactory factory) {
return Validation.byDefaultProvider()
.configure().constraintValidatorFactory(factory)
.buildValidatorFactory().getValidator();
}
public static Practitioner createPractitionerResource(String npi, String orgID) {
return FHIRPractitionerBuilder.newBuilder()
.withNpi(npi)
.withOrgTag(orgID)
.withName("Test", "Practitioner")
.build();
}
public static Patient createPatientResource(String mbi, String organizationID) {
return FHIRPatientBuilder.newBuild()
.withMbi(mbi)
.withBirthDate("1990-01-01")
.withName("Test", "Patient")
.withGender(Enumerations.AdministrativeGender.OTHER)
.managedBy(organizationID)
.build();
}
public static Provenance createProvenance(String orgId, String practitionerId, List<String> patientIds){
final Coding reasonCoding = new Coding().setSystem("http://hl7.org/fhir/v3/ActReason").setCode("TREAT");
final Coding roleCode = new Coding()
.setSystem(V3RoleClass.AGNT.getSystem())
.setCode(V3RoleClass.AGNT.toCode());
final CodeableConcept roleConcept = new CodeableConcept().addCoding(roleCode);
final Provenance.ProvenanceAgentComponent component = new Provenance.ProvenanceAgentComponent()
.setRole(Collections.singletonList(roleConcept))
.setWho(new Reference(new IdType("Organization", orgId)))
.setOnBehalfOf(new Reference(practitionerId));
final Provenance provenance = new Provenance()
.setRecorded(Date.valueOf(Instant.now().atZone(ZoneOffset.UTC).toLocalDate()))
.setReason(Collections.singletonList(reasonCoding))
.addAgent(component);
for(String patientId:patientIds){
provenance.addTarget(new Reference(patientId));
}
return provenance;
}
public static MethodOutcome createResource(IGenericClient client, IBaseResource resource, Map<String,String> extraHeaders){
ICreateTyped iCreateTyped = client.create()
.resource(resource)
.encodedJson();
extraHeaders.entrySet().forEach(entry -> iCreateTyped.withAdditionalHeader(entry.getKey(),entry.getValue()));
return iCreateTyped.execute();
}
public static MethodOutcome createResource(IGenericClient client, IBaseResource resource){
return createResource(client,resource, Maps.newHashMap());
}
public static <T extends IBaseResource> T getResourceById(IGenericClient client, Class<T> clazz, String resourceId){
return client.read()
.resource(clazz)
.withId(resourceId).encodedJson().execute();
}
public static Bundle resourceSearch(IGenericClient client, DPCResourceType resourceType, Map<String,List<String>> searchParams){
return client
.search()
.forResource(resourceType.name())
.whereMap(searchParams)
.returnBundle(Bundle.class)
.encodedJson()
.execute();
}
public static Bundle resourceSearch(IGenericClient client, DPCResourceType resourceType){
return resourceSearch(client,resourceType, Maps.newHashMap());
}
public static IBaseOperationOutcome deleteResourceById(IGenericClient client, DPCResourceType resourceType, String resourceId){
return client.delete()
.resourceById(resourceType.name(), resourceId)
.execute();
}
public static MethodOutcome updateResource(IGenericClient client, String id, IBaseResource resource, Map<String,String> extraHeaders){
IUpdateExecutable executable = client
.update()
.resource(resource)
.withId(id)
.encodedJson();
extraHeaders.entrySet().forEach(entry -> executable.withAdditionalHeader(entry.getKey(),entry.getValue()));
return executable.execute();
}
public static MethodOutcome updateResource(IGenericClient client, String id, IBaseResource resource){
return updateResource(client, id,resource, Maps.newHashMap());
}
public static Bundle getPatientEverything(IGenericClient client, String patientId, String provenance){
return client
.operation()
.onInstance(new IdType("Patient", patientId))
.named("$everything")
.withNoParameters(Parameters.class)
.returnResourceType(Bundle.class)
.useHttpGet()
.withAdditionalHeader("X-Provenance", provenance)
.execute();
}
public static Bundle doGroupExport(IGenericClient client,String groupId, String provenance){
return client
.operation()
.onInstance(new IdType("Group", groupId))
.named("$export")
.withNoParameters(Parameters.class)
.returnResourceType(Bundle.class)
.useHttpGet()
.withAdditionalHeader("X-Provenance", provenance)
.execute();
}
}
| 44.800578 | 141 | 0.690923 |
53a7e626f34650e6de567ae0e956de2433dff3c5 | 7,147 | package org.vinevweb.cardiohristov.web.controllers;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.vinevweb.cardiohristov.domain.models.binding.AppointmentCreateBindingModel;
import org.vinevweb.cardiohristov.domain.models.binding.AppointmentDeleteBindingModel;
import org.vinevweb.cardiohristov.domain.models.binding.UserRegisterBindingModel;
import org.vinevweb.cardiohristov.domain.models.service.AppointmentServiceModel;
import org.vinevweb.cardiohristov.domain.models.view.AllAppointmentViewModel;
import org.vinevweb.cardiohristov.domain.models.view.AllProceduresProcedureViewModel;
import org.vinevweb.cardiohristov.domain.models.view.AppointmentCreatedViewModel;
import org.vinevweb.cardiohristov.domain.models.view.EditDeleteAppointmentViewModel;
import org.vinevweb.cardiohristov.errors.AppointmentCreateFailureException;
import org.vinevweb.cardiohristov.services.AppointmentService;
import org.vinevweb.cardiohristov.services.ProcedureService;
import org.vinevweb.cardiohristov.web.annotations.PageTitle;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.vinevweb.cardiohristov.common.Constants.APPOINTMENT_CREATE_FAILURE_EXCEPTION;
import static org.vinevweb.cardiohristov.common.Constants.TITLE_SCHEDULE;
@Controller
@RequestMapping("/appointments")
public class AppointmentController extends BaseController {
private final ModelMapper modelMapper;
private final AppointmentService appointmentService;
private final ProcedureService procedureService;
@Autowired
public AppointmentController(ModelMapper modelMapper, AppointmentService appointmentService, ProcedureService procedureService) {
this.modelMapper = modelMapper;
this.appointmentService = appointmentService;
this.procedureService = procedureService;
}
@GetMapping(value = "/api/checkSpecificHour", produces = "application/json")
@ResponseBody
public boolean checkAvailableDateTime(@RequestParam("date") String date,
@RequestParam("time") String time) {
return appointmentService.findByDateTime(date, time);
}
@GetMapping(value = "/api/getBuzyHoursForDate", produces = "application/json")
@ResponseBody
public String[][] getBuzyHoursForDate(@RequestParam("date") String date) {
String[][] result = appointmentService.getBuzyHoursForDate(date);
return result;
}
@GetMapping(value = "/api/getAppointmentById", produces = "application/json")
@ResponseBody
@PreAuthorize("hasRole('ROLE_ADMIN')")
public EditDeleteAppointmentViewModel editDeleteAppointmentViewModel(@RequestParam("id") String id) {
EditDeleteAppointmentViewModel editDeleteAppointmentViewModel = modelMapper.map(appointmentService.findById(id),
EditDeleteAppointmentViewModel.class);
editDeleteAppointmentViewModel.setAppointmentTime();
editDeleteAppointmentViewModel.setAppointmentDate();
return editDeleteAppointmentViewModel;
}
@PostMapping("/create")
public ModelAndView createAppointmentConfirm(@Valid @ModelAttribute AppointmentCreateBindingModel appointmentCreateBindingModel,
@ModelAttribute("userRegisterBindingModel") UserRegisterBindingModel userRegisterBindingModel,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new AppointmentCreateFailureException(APPOINTMENT_CREATE_FAILURE_EXCEPTION);
}
appointmentCreateBindingModel.setDatetime();
AppointmentServiceModel appointmentServiceModel = this.modelMapper
.map(appointmentCreateBindingModel, AppointmentServiceModel.class);
String id = this.appointmentService
.createAppointment(appointmentServiceModel);
if (id == null) {
return super.view("appointment-failed", "appointment", appointmentCreateBindingModel);
}
AppointmentCreatedViewModel appointmentCreatedViewModel = modelMapper.map(appointmentCreateBindingModel ,
AppointmentCreatedViewModel.class);
appointmentCreatedViewModel.setId(id);
return super.view("appointment-created", "appointment", appointmentCreatedViewModel);
}
@PostMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ModelAndView updateAppointmentConfirm(@ModelAttribute AppointmentCreateBindingModel appointmentCreateBindingModel) {
appointmentCreateBindingModel.setDatetime();
AppointmentServiceModel appointmentServiceModel = this.modelMapper
.map(appointmentCreateBindingModel, AppointmentServiceModel.class);
this.appointmentService
.updateAppointment(appointmentServiceModel);
return super.redirect("/appointments/all");
}
@PostMapping("/delete")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ModelAndView deleteAppointment(@ModelAttribute AppointmentDeleteBindingModel appointmentDeleteBindingModel) {
AppointmentServiceModel appointmentServiceModel = this.modelMapper
.map(appointmentDeleteBindingModel, AppointmentServiceModel.class);
this.appointmentService
.deleteAppointment(appointmentServiceModel);
return super.redirect("/appointments/all");
}
@GetMapping("/annul")
public ModelAndView annul(@RequestParam("id") String id) {
this.appointmentService
.annulAppointment(id);
return super.redirect("/");
}
@GetMapping("/all")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PageTitle(TITLE_SCHEDULE)
public ModelAndView getAppointments(@ModelAttribute("userRegisterBindingModel") UserRegisterBindingModel userRegisterBindingModel) {
Map<String, Object> stringObjectMap = new HashMap<>();
List<AllProceduresProcedureViewModel> allProceduresProcedureViewModelSet = procedureService.getAllByDateAsc().stream()
.map(p -> modelMapper.map(p, AllProceduresProcedureViewModel.class))
.collect(Collectors.toList());
stringObjectMap.put("procedures", allProceduresProcedureViewModelSet);
List<AllAppointmentViewModel> allAppointmentViewModels = appointmentService.getAllByDateTimeAsc().stream()
.map(p -> modelMapper.map(p, AllAppointmentViewModel.class))
.collect(Collectors.toList());
stringObjectMap.put("appointments", allAppointmentViewModels);
return super.view("schedule", stringObjectMap);
}
@GetMapping("/create")
public ModelAndView createAppointment() {
return super.redirect("/");
}
}
| 43.579268 | 143 | 0.748706 |
4d87446ff4895f92736210beadd921aaadb727e6 | 2,146 | package org.schoellerfamily.gedbrowser.controller.test;
import static org.assertj.core.api.BDDAssertions.then;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.schoellerfamily.gedbrowser.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Dick Schoeller
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {"management.port=0"})
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public class PlaceIndexControllerTest implements MenuTestHelper {
/**
* Not sure what this is good for.
*/
@Autowired
private TestRestTemplate testRestTemplate;
/**
* Server port.
*/
@LocalServerPort
private int port;
/** */
@Test
public void testControllerGL120368() {
final String url = "http://localhost:" + port
+ "/gedbrowser/places?db=gl120368";
final ResponseEntity<String> entity = testRestTemplate.getForEntity(url,
String.class);
then(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
then(entity.getBody()).contains("<title>Places - gl120368</title>")
.contains(getMenu("A"));
}
/** */
@Test
public final void testControllerBadDataSet() {
final ResponseEntity<String> entity = testRestTemplate.getForEntity(
"http://localhost:" + port
+ "/gedbrowser/places?db=XYZZY",
String.class);
then(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
then(entity.getBody()).contains("Data set not found");
}
}
| 34.612903 | 80 | 0.712488 |
83ff77f8d27fba4164dbf149c2ce89a8f7f490c9 | 747 | package mekanism.api._helpers_pls_remove;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.util.Identifier;
import java.util.HashMap;
import java.util.Map;
public class CraftingHelper {
private static final Map<Identifier, IConditionSerializer<?>> conditions = new HashMap<>();
public static <T extends ICondition> JsonObject serialize(T condition) {
@SuppressWarnings("unchecked")
IConditionSerializer<T> serializer = (IConditionSerializer<T>) conditions.get(condition.getID());
if (serializer == null)
throw new JsonSyntaxException("Unknown condition type: " + condition.getID().toString());
return serializer.getJson(condition);
}
}
| 35.571429 | 105 | 0.736278 |
ef110101eb2197f86569713beb051ce5c60b4b28 | 4,854 | package me.mariotti.opencv;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.util.Log;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
public class ColorBlobDetector {
private static final String TAG = "ColorBlobDetector";
// Lower and Upper bounds for range checking in HSV color space
private Scalar mLowerBound = new Scalar(0);
private Scalar mUpperBound = new Scalar(0);
// Minimum contour area in percent for contours filtering
private static double mMinContourArea = 0.1;
// Color radius for range checking in HSV color space
private Scalar mColorRadius = new Scalar(25, 50, 50, 0);
private Mat mSpectrum = new Mat();
private List<MatOfPoint> mContours = new ArrayList<>();
// Cache
Mat mPyrDownMat = new Mat();
Mat mHsvMat = new Mat();
Mat mMask = new Mat();
Mat mDilatedMask = new Mat();
Mat mHierarchy = new Mat();
public static Scalar convertScalarHsv2Rgba(Scalar mHsvColor) {
Mat mPointMatRgba = new Mat();
Mat mPointMatHsv = new Mat(1, 1, CvType.CV_8UC3, mHsvColor);
Imgproc.cvtColor(mPointMatHsv, mPointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);
Log.i(TAG, "Source HSV color: (" + mHsvColor.val[0] + ", " + mHsvColor.val[1] +
", " + mHsvColor.val[2] + ", " + mHsvColor.val[3] + ")");
Log.i(TAG, "Converted RGBA color: (" + (new Scalar(mPointMatRgba.get(0, 0))).val[0] +
", " + (new Scalar(mPointMatRgba.get(0, 0))).val[1] + ", " + (new Scalar(mPointMatRgba.get(0, 0))).val[2] + ", " + (new Scalar(mPointMatRgba.get(0, 0))).val[3] + ")");
return new Scalar(mPointMatRgba.get(0, 0));
}
public Scalar convertScalarRgba2Hsv(Scalar rgbaColor) {
Mat mPointMatHsv = new Mat();
Mat mPointMatRgba = new Mat(1, 1, CvType.CV_8UC3, rgbaColor);
Imgproc.cvtColor(mPointMatRgba, mPointMatHsv, Imgproc.COLOR_RGB2HSV_FULL);
return new Scalar(mPointMatHsv.get(0, 0));
}
public void setHsvColor(Scalar mHsvColor) {
double mMinH = (mHsvColor.val[0] >= mColorRadius.val[0]) ? mHsvColor.val[0] - mColorRadius.val[0] : 0;
double mMaxH = (mHsvColor.val[0] + mColorRadius.val[0] <= 360) ? mHsvColor.val[0] + mColorRadius.val[0] : 360;
mLowerBound.val[0] = mMinH;
mUpperBound.val[0] = mMaxH;
mLowerBound.val[1] = mHsvColor.val[1] - mColorRadius.val[1];
mUpperBound.val[1] = mHsvColor.val[1] + mColorRadius.val[1];
mLowerBound.val[2] = mHsvColor.val[2] - mColorRadius.val[2];
mUpperBound.val[2] = mHsvColor.val[2] + mColorRadius.val[2];
mLowerBound.val[3] = 0;
mUpperBound.val[3] = 255;
Mat mSpectrumHsv = new Mat(1, (int) (mMaxH - mMinH), CvType.CV_8UC3);
for (int j = 0; j < mMaxH - mMinH; j++) {
byte[] tmp = {(byte) (mMinH + j), (byte) mHsvColor.val[1], (byte) mHsvColor.val[2]};
mSpectrumHsv.put(0, j, tmp);
}
Imgproc.cvtColor(mSpectrumHsv, mSpectrum, Imgproc.COLOR_HSV2RGB_FULL, 4);
}
public void process(Mat rgbaImage) {
Imgproc.pyrDown(rgbaImage, mPyrDownMat);
Imgproc.pyrDown(mPyrDownMat, mPyrDownMat);
Imgproc.cvtColor(mPyrDownMat, mHsvMat, Imgproc.COLOR_RGB2HSV_FULL);
Core.inRange(mHsvMat, mLowerBound, mUpperBound, mMask);
Imgproc.dilate(mMask, mDilatedMask, new Mat());
List<MatOfPoint> mContours = new ArrayList<MatOfPoint>();
Imgproc.findContours(mDilatedMask, mContours, mHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Find max contour area
double mMaxArea = 0;
Iterator<MatOfPoint> mEach = mContours.iterator();
while (mEach.hasNext()) {
MatOfPoint mWrapper = mEach.next();
double mArea = Imgproc.contourArea(mWrapper);
if (mArea > mMaxArea)
mMaxArea = mArea;
}
// Filter contours by area and resize to fit the original image size
this.mContours.clear();
mEach = mContours.iterator();
while (mEach.hasNext()) {
MatOfPoint mContour = mEach.next();
if (Imgproc.contourArea(mContour) > mMinContourArea * mMaxArea) {
Core.multiply(mContour, new Scalar(4, 4), mContour);
this.mContours.add(mContour);
}
}
}
public List<MatOfPoint> getContours() {
return mContours;
}
public Mat getSpectrum() {
return mSpectrum;
}
public void setMinContourArea(double mArea) {
mMinContourArea = mArea;
}
public void setColorRadius(Scalar radius) {
mColorRadius = radius;
}
}
| 37.627907 | 186 | 0.632262 |
42b873709865c50d798d7b547a61f26c5082b7ab | 2,861 | /*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID 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.opensaml.xml.security.x509;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.opensaml.xml.security.CriteriaSet;
import org.opensaml.xml.security.SecurityException;
/**
* An implementation of {@link PKIXValidationInformationResolver} which always returns a static, fixed set of
* information.
*/
public class StaticPKIXValidationInformationResolver implements PKIXValidationInformationResolver {
/** The PKIX validation information to return. */
private List<PKIXValidationInformation> pkixInfo;
/** The set of trusted names to return. */
private Set<String> trustedNames;
/**
* Constructor.
*
* @param info list of PKIX validation information to return
* @param names set of trusted names to return
*/
public StaticPKIXValidationInformationResolver(List<PKIXValidationInformation> info, Set<String> names) {
if (info != null) {
pkixInfo = new ArrayList<PKIXValidationInformation>(info);
} else {
pkixInfo = Collections.EMPTY_LIST;
}
if (names != null) {
trustedNames = new HashSet<String>(names);
} else {
trustedNames = Collections.EMPTY_SET;
}
}
/** {@inheritDoc} */
public Set<String> resolveTrustedNames(CriteriaSet criteriaSet) throws SecurityException,
UnsupportedOperationException {
return trustedNames;
}
/** {@inheritDoc} */
public boolean supportsTrustedNameResolution() {
return true;
}
/** {@inheritDoc} */
public Iterable<PKIXValidationInformation> resolve(CriteriaSet criteria) throws SecurityException {
return pkixInfo;
}
/** {@inheritDoc} */
public PKIXValidationInformation resolveSingle(CriteriaSet criteria) throws SecurityException {
if (!pkixInfo.isEmpty()) {
return pkixInfo.get(0);
}
return null;
}
}
| 32.885057 | 109 | 0.699406 |
18e383045d21eb362d83f34189477e3b0f93be95 | 6,445 | /*
* 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.nifi.serialization;
import org.apache.nifi.annotation.lifecycle.OnEnabled;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.controller.AbstractControllerService;
import org.apache.nifi.controller.ConfigurationContext;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.schema.access.SchemaAccessStrategy;
import org.apache.nifi.schema.access.SchemaAccessUtils;
import org.apache.nifi.schema.access.SchemaField;
import org.apache.nifi.schema.access.SchemaNotFoundException;
import org.apache.nifi.schemaregistry.services.SchemaRegistry;
import org.apache.nifi.serialization.record.RecordSchema;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import static org.apache.nifi.schema.access.SchemaAccessUtils.HWX_CONTENT_ENCODED_SCHEMA;
import static org.apache.nifi.schema.access.SchemaAccessUtils.HWX_SCHEMA_REF_ATTRIBUTES;
import static org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_ACCESS_STRATEGY;
import static org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_NAME;
import static org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_NAME_PROPERTY;
import static org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_REGISTRY;
import static org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_TEXT;
import static org.apache.nifi.schema.access.SchemaAccessUtils.SCHEMA_TEXT_PROPERTY;
public abstract class SchemaRegistryService extends AbstractControllerService {
private volatile ConfigurationContext configurationContext;
private volatile SchemaAccessStrategy schemaAccessStrategy;
private final List<AllowableValue> strategyList = Collections.unmodifiableList(Arrays.asList(SCHEMA_NAME_PROPERTY, SCHEMA_TEXT_PROPERTY, HWX_SCHEMA_REF_ATTRIBUTES, HWX_CONTENT_ENCODED_SCHEMA));
private PropertyDescriptor getSchemaAcessStrategyDescriptor() {
return getPropertyDescriptor(SCHEMA_ACCESS_STRATEGY.getName());
}
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
final List<PropertyDescriptor> properties = new ArrayList<>(2);
final AllowableValue[] strategies = getSchemaAccessStrategyValues().toArray(new AllowableValue[0]);
properties.add(new PropertyDescriptor.Builder()
.fromPropertyDescriptor(SCHEMA_ACCESS_STRATEGY)
.allowableValues(strategies)
.defaultValue(getDefaultSchemaAccessStrategy().getValue())
.build());
properties.add(SCHEMA_REGISTRY);
properties.add(SCHEMA_NAME);
properties.add(SCHEMA_TEXT);
return properties;
}
protected AllowableValue getDefaultSchemaAccessStrategy() {
return SCHEMA_NAME_PROPERTY;
}
@OnEnabled
public void storeSchemaAccessStrategy(final ConfigurationContext context) {
this.configurationContext = context;
final SchemaRegistry schemaRegistry = context.getProperty(SCHEMA_REGISTRY).asControllerService(SchemaRegistry.class);
final PropertyDescriptor descriptor = getSchemaAcessStrategyDescriptor();
final String schemaAccess = context.getProperty(descriptor).getValue();
this.schemaAccessStrategy = getSchemaAccessStrategy(schemaAccess, schemaRegistry, context);
}
protected ConfigurationContext getConfigurationContext() {
return configurationContext;
}
protected SchemaAccessStrategy getSchemaAccessStrategy() {
return schemaAccessStrategy;
}
public RecordSchema getSchema(final FlowFile flowFile, final InputStream contentStream) throws SchemaNotFoundException, IOException {
return getSchemaAccessStrategy().getSchema(flowFile, contentStream);
}
@Override
protected Collection<ValidationResult> customValidate(final ValidationContext validationContext) {
final String schemaAccessStrategy = validationContext.getProperty(getSchemaAcessStrategyDescriptor()).getValue();
return SchemaAccessUtils.validateSchemaAccessStrategy(validationContext, schemaAccessStrategy, getSchemaAccessStrategyValues());
}
protected List<AllowableValue> getSchemaAccessStrategyValues() {
return strategyList;
}
protected Set<SchemaField> getSuppliedSchemaFields(final ValidationContext validationContext) {
final String accessStrategyValue = validationContext.getProperty(getSchemaAcessStrategyDescriptor()).getValue();
final SchemaRegistry schemaRegistry = validationContext.getProperty(SCHEMA_REGISTRY).asControllerService(SchemaRegistry.class);
final SchemaAccessStrategy accessStrategy = getSchemaAccessStrategy(accessStrategyValue, schemaRegistry, validationContext);
final Set<SchemaField> suppliedFields = accessStrategy.getSuppliedSchemaFields();
return suppliedFields;
}
protected SchemaAccessStrategy getSchemaAccessStrategy(final String allowableValue, final SchemaRegistry schemaRegistry, final ConfigurationContext context) {
return SchemaAccessUtils.getSchemaAccessStrategy(allowableValue, schemaRegistry, context);
}
protected SchemaAccessStrategy getSchemaAccessStrategy(final String allowableValue, final SchemaRegistry schemaRegistry, final ValidationContext context) {
return SchemaAccessUtils.getSchemaAccessStrategy(allowableValue, schemaRegistry, context);
}
}
| 47.043796 | 197 | 0.797828 |
c346d3bcad116dde787b429c11c6eb7c544ed922 | 2,473 | package com.example.reboundexampleapp.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringConfig;
import com.facebook.rebound.SpringListener;
import com.facebook.rebound.SpringSystem;
public class MainActivity extends Activity implements View.OnTouchListener, View.OnClickListener, SpringListener {
private static double TENSION = 800;
private static double DAMPER = 20; //friction
private ImageView mImageToAnimate;
private SpringSystem mSpringSystem;
private Spring mSpring;
private boolean mMovedUp = false;
private float mOrigY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageToAnimate = (ImageView) findViewById(R.id.imageView);
mImageToAnimate.setOnTouchListener(this);
//mImageToAnimate.setOnClickListener(this);
mSpringSystem = SpringSystem.create();
mSpring = mSpringSystem.createSpring();
mSpring.addListener(this);
SpringConfig config = new SpringConfig(TENSION, DAMPER);
mSpring.setSpringConfig(config);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mSpring.setEndValue(1f);
return true;
case MotionEvent.ACTION_UP:
mSpring.setEndValue(0f);
return true;
}
return false;
}
@Override
public void onClick(View v) {
if (mMovedUp) {
mSpring.setEndValue(mOrigY);
} else {
mOrigY = mImageToAnimate.getY();
mSpring.setEndValue(mOrigY - 300f);
}
mMovedUp = !mMovedUp;
}
@Override
public void onSpringUpdate(Spring spring) {
float value = (float) spring.getCurrentValue();
float scale = 1f - (value * 0.5f);
mImageToAnimate.setScaleX(scale);
mImageToAnimate.setScaleY(scale);
//mImageToAnimate.setY(value);
}
@Override
public void onSpringAtRest(Spring spring) {
}
@Override
public void onSpringActivate(Spring spring) {
}
@Override
public void onSpringEndStateChange(Spring spring) {
}
}
| 25.494845 | 114 | 0.663567 |
77c7d306de554c2a03948da753236bf1f7e9fb5c | 12,781 | package com.samton.erp.api.pm.controller;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.samton.erp.api.pm.bean.CheckCodeBean;
import com.samton.erp.api.pm.constant.ErpPmConstant;
import com.samton.erp.api.pm.constant.ErpPmExpCodeConstant;
import com.samton.erp.api.pm.constant.PmConstant;
import com.samton.erp.api.pm.service.IErpPmService;
import com.samton.erp.api.pm.util.IdentifyingCode;
import com.samton.platform.common.bean.param.JqParamBean;
import com.samton.platform.framework.base.SdkBaseController;
import com.samton.platform.framework.exception.ControllerException;
import com.samton.platform.framework.exception.constant.ExpCodeConstant;
import com.samton.platform.framework.mybatis.pagination.Pagination;
import com.samton.platform.framework.util.CurrentUtil;
import com.samton.platform.framework.util.NetworkUtil;
import com.samton.platform.pm.bean.entity.TPlatformPmUser;
import com.samton.platform.pm.constant.PmExpCodeConstant;
import com.samton.platform.pm.constant.PmStateConstant;
import com.samton.platform.pm.service.IPmService;
@Controller
@RequestMapping("/api/pm")
public class ErpPmController extends SdkBaseController{
@Resource
private IPmService pmService;
@Resource
private IErpPmService erpPmService;
@RequestMapping("/checkCodePic")
@ResponseBody
public void checkCodePic() throws Exception{
HttpServletResponse response=this.getResponse();
//设置不缓存图片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
//指定生成的相应图片
response.setContentType("image/jpeg");
IdentifyingCode idCode = new IdentifyingCode();
BufferedImage image =new BufferedImage(idCode.getWidth() , idCode.getHeight() , BufferedImage.TYPE_INT_BGR) ;
Graphics2D g = image.createGraphics();
//定义字体样式
Font myFont = new Font("黑体" , Font.BOLD , 26);
//设置字体
g.setFont(myFont);
g.setColor(idCode.getRandomColor(200 , 250));
//绘制背景
g.fillRect(0, 0, idCode.getWidth() , idCode.getHeight());
g.setColor(idCode.getRandomColor(180, 200));
idCode.drawRandomLines(g, 160);
String checkCodePic=idCode.drawRandomString(4, g);
this.setSessionAttribute(PmConstant.PICTURE_CHECK_CODE, checkCodePic);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
}
/**
*
* @Description: 发送注册验证码
* @param @param loginName
* @param @param picCheckCode
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月15日
*/
@RequestMapping("/generateCheckCodeRegister")
@ResponseBody
public Map<String, Object> generateCheckCodeRegister(String loginName,String picCheckCode) throws Exception{
if(StringUtils.isEmpty(loginName)){
throw new ControllerException(ExpCodeConstant.PARAMTER_ILLEGAL, "generateCheckCode--->登录名为空",false);
}
if(!pmService.isLoginNameUnique(loginName)){
throw new ControllerException(PmExpCodeConstant.PM_LOGINNAME_EXIST_ERROR, null,false);
}
CheckCodeBean checkCodeBean=(CheckCodeBean) this.getSessionAttribute(ErpPmConstant.REGISTER_CHECK_CODE);
if(checkCodeBean==null){
checkCodeBean=erpPmService.sendCheckCodeMsg(loginName);
this.setSessionAttribute(ErpPmConstant.REGISTER_CHECK_CODE, checkCodeBean);
}else {
long checkCodeTime=checkCodeBean.getTime();
long currentTime=System.currentTimeMillis();
//超过1min,重新生成checkCode
if(currentTime-checkCodeTime>60*1000){
checkCodeBean=erpPmService.sendCheckCodeMsg(loginName);
this.setSessionAttribute(ErpPmConstant.REGISTER_CHECK_CODE, checkCodeBean);
}else {
throw new ControllerException(ErpPmExpCodeConstant.GENERATE_CHECK_CODE_INTERVAL_TOO_SHORT, true);
}
}
return this.getResultMap(true, checkCodeBean);
//return this.getResultMap(true);
}
/**
*
* @Description: 注册
* @param @param loginName
* @param @param checkCode
* @param @param pwd
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月18日
*/
@RequestMapping("/registerUser")
@ResponseBody
public Map<String, Object> registerUser(String loginName,String checkCode,String pwd) throws Exception{
//基础参数非空验证
if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(pwd)){
throw new ControllerException(ExpCodeConstant.PARAMTER_ILLEGAL, "registerUser--->参数非法",false);
}
//用户名已经存在
if(!pmService.isLoginNameUnique(loginName)){
throw new ControllerException(PmExpCodeConstant.PM_LOGINNAME_EXIST_ERROR, "registerUser--->参数非法",false);
}
//判断是否通过验证
CheckCodeBean checkCodeBean=(CheckCodeBean) this.getSessionAttribute(ErpPmConstant.REGISTER_CHECK_CODE);
if(checkCodeBean==null || ( checkCodeBean!=null && checkCodeBean.isCheckFlag() ) ){
throw new ControllerException(ErpPmExpCodeConstant.CHECK_CODE_INVALID, null,false);
}
boolean checkFlag=checkCodeBean!=null&&checkCodeBean.getLoginName().equals(loginName)&&checkCode.equalsIgnoreCase(checkCodeBean.getCheckCode()) && !checkCodeBean.isCheckFlag();
if(!checkFlag){
throw new ControllerException(ErpPmExpCodeConstant.CHECK_CODE_ERROR, null,false);
}else{
checkCodeBean.setCheckFlag(true);
}
TPlatformPmUser user = new TPlatformPmUser();
user.setLoginName(loginName);
user.setPwd(pwd);
user.setRegisterAddress(NetworkUtil.getIpAddress(request));
user.setRegisterType(PmStateConstant.REGISTER_TYPE_PC);
int result = erpPmService.registerUser(user);
if(result>0){
//注册成功后短信邮箱提示
//erpPmService.sendSuccesMsg(loginName,loginName,pwd);
}
return this.getResultMap(result > 0 ? true : false);
}
/**
*
* @Description: 获取当前登录企业用户信息
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月19日
*/
@RequestMapping("/getCurrentUser")
@ResponseBody
public Map<String, Object> getCurrentUser() throws Exception {
long userId = CurrentUtil.getCurrentUser().getUserId();
TPlatformPmUser user = pmService.getUserById(userId);
return this.getResultMap(user!=null, user);
}
/**
*
* @Description: 更新当前个人用户信息
* @param @param user
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月19日
*/
@RequestMapping("/updateCurrentUserInfo")
@ResponseBody
public Map<String, Object> updateCurrentUserInfo(TPlatformPmUser user) throws Exception {
TPlatformPmUser pmUser = new TPlatformPmUser();
pmUser.setUserId( CurrentUtil.getCurrentUser().getUserId() );
pmUser.setEnterpriseId( CurrentUtil.getCurrentUser().getEnterpriseId());
pmUser.setUserName(user.getUserName());
pmUser.setMobilePhone(user.getMobilePhone());
pmUser.setEmail(user.getEmail());
int result = pmService.updatePmUser(pmUser);
return this.getResultMap(result>0);
}
/**
*
* @Description: 更新当前用户密码
* @param @param oldPwd
* @param @param pwd
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月19日
*/
@RequestMapping("/updateCurrentPwd")
@ResponseBody
public Map<String, Object> updateCurrentPwd(String oldPwd,String pwd) throws Exception {
//基础参数非空验证
if(StringUtils.isEmpty(oldPwd)||StringUtils.isEmpty(pwd) ){
throw new ControllerException(ExpCodeConstant.PARAMTER_ILLEGAL, "registerUser--->参数非法",false);
}
int result = pmService.updateCurrentPwd(oldPwd, pwd);
return this.getResultMap(result>0);
}
/**
*
* @Description: 找回密码生产验证码
* @param @param loginName
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月19日
*/
@RequestMapping("/generateCheckCodeForgetPwd")
@ResponseBody
public Map<String, Object> generateCheckCodeForgetPwd(String loginName) throws Exception{
if(StringUtils.isEmpty(loginName)){
throw new ControllerException(ExpCodeConstant.PARAMTER_ILLEGAL, "retrievePwd--->登录名为空",false);
}
if(pmService.isLoginNameUnique(loginName)){
throw new ControllerException(PmExpCodeConstant.NO_LOGIN_NAME, null, false);
}
Map<String, Object> jo=new HashMap<>();
CheckCodeBean checkCodeBean=(CheckCodeBean) this.getSessionAttribute(ErpPmConstant.RETRIEVE_PWD_CHECK_CODE);
if(checkCodeBean==null){
checkCodeBean=erpPmService.sendCheckCodeMsgForPwd(loginName);
this.setSessionAttribute(ErpPmConstant.RETRIEVE_PWD_CHECK_CODE, checkCodeBean);
jo.put("rs",1);
return this.getResultMap(checkCodeBean);
}else {
long checkCodeTime=checkCodeBean.getTime();
long currentTime=System.currentTimeMillis();
//超过1min,重新生成checkCode
if(currentTime-checkCodeTime>60*1000){
checkCodeBean=erpPmService.sendCheckCodeMsgForPwd(loginName);
this.setSessionAttribute(ErpPmConstant.RETRIEVE_PWD_CHECK_CODE,checkCodeBean);
jo.put("rs",1);
return this.getResultMap(checkCodeBean);
}else {
throw new ControllerException(ErpPmExpCodeConstant.GENERATE_CHECK_CODE_INTERVAL_TOO_SHORT, null,false);
}
}
}
/**
*
* @Description: 找回密码(校验验证码是否正确)
* @param @param loginName
* @param @param checkCode
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月19日
*/
@RequestMapping("/retrievePwdCheck")
@ResponseBody
public Map<String, Object> retrievePwdCheck(String loginName,String checkCode) throws Exception{
if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(checkCode)){
throw new ControllerException(ExpCodeConstant.PARAMTER_ILLEGAL, "retrievePwdCheck--->非法参数",false);
}
//判断验证码是否正确
CheckCodeBean checkCodeBean=(CheckCodeBean) this.getSessionAttribute(ErpPmConstant.RETRIEVE_PWD_CHECK_CODE);
if(checkCodeBean==null || ( checkCodeBean!=null && checkCodeBean.isCheckFlag() ) ){
throw new ControllerException(ErpPmExpCodeConstant.CHECK_CODE_INVALID, null,false);
}
boolean checkFlag= checkCodeBean.getLoginName().equals(loginName)&&checkCode.equalsIgnoreCase(checkCodeBean.getCheckCode()) && !checkCodeBean.isCheckFlag();
if(!checkFlag){
throw new ControllerException(ErpPmExpCodeConstant.CHECK_CODE_ERROR, null,false);
}else{
checkCodeBean.setCheckFlag(true);
}
return this.getResultMap(checkFlag);
}
/**
*
* @Description: 找回密码(重置密码)
* @param @param loginName
* @param @param checkCode
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月19日
*/
@RequestMapping("/retrievePwd")
@ResponseBody
public Map<String, Object> retrievePwd(String loginName,String pwd) throws Exception{
CheckCodeBean checkCodeBean=(CheckCodeBean) this.getSessionAttribute(PmConstant.RETRIEVE_PWD_CHECK_CODE);
if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(pwd)||!loginName.equals(checkCodeBean.getLoginName())){
throw new ControllerException(ExpCodeConstant.PARAMTER_ILLEGAL, "retrievePwd--->非法参数", false);
}
if(checkCodeBean==null||!checkCodeBean.isCheckFlag()){
throw new ControllerException(ErpPmExpCodeConstant.CHECK_CODE_INVALID,false);
}
Long userId = CurrentUtil.getCurrentUser().getUserId();
TPlatformPmUser user=pmService.getUserById(userId) ;
if(!loginName.equals(user.getLoginName())){
throw new ControllerException(ErpPmExpCodeConstant.CHECK_CODE_INVALID,false);
}
int result = pmService.updateCurrentPwd(null, pwd);
return this.getResultMap(result>0);
}
/**
*
* @Description: 查询某个企业所有用户的信息
* @param @param paramBean
* @param @param pmUser
* @param @return
* @param @throws Exception
* @return Map<String,Object>
* @throws
* @author yokoboy
* @date 2016年4月21日
*/
@RequestMapping("/queryUsers")
@ResponseBody
public Map<String, Object> queryUsers(JqParamBean paramBean,
TPlatformPmUser pmUser) throws Exception {
pmUser.setSystemId(CurrentUtil.getCurrentSystemId());
pmUser.setState(PmStateConstant.ADD);
paramBean.setSearch(pmUser);
paramBean.setEnterpriseId(pmUser.getEnterpriseId());
Pagination<TPlatformPmUser> users = pmService.queryUsers(paramBean);
return this.getResultMap(true, users);
}
}
| 35.30663 | 178 | 0.744464 |
e06df41bbbdaf4f199dbb7bba958dde1ef8b9e86 | 4,776 | package staffstutorial7;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Alexandre Ravaux
*/
public class StaffsTutorial7 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/* Part 1 Writing a Generic class */
System.out.println("Integer stack");
GenericStack<Integer> integerStack = new GenericStack<Integer>();
integerStack.push(1);
integerStack.push(2);
integerStack.push(3);
System.out.println(integerStack);
System.out.println("Seek: "+integerStack.peek());
System.out.println("Remove first element (pop() method called)");
integerStack.pop();
System.out.println(integerStack);
System.out.println("Seek: "+integerStack.peek());
System.out.println("String stack");
GenericStack<String> strStack = new GenericStack<String>();
strStack.push("Ever");
strStack.push("Tutorial");
strStack.push("Best");
System.out.println(strStack);
System.out.println("Seek: "+strStack.peek());
System.out.println("Remove first element (pop() method called)");
strStack.pop();
System.out.println(strStack);
System.out.println("Seek: "+strStack.peek());
/* Part 2 Using Wrapper classes */
aMethod();
Double answer1 = add(2, 7);
Number answer2 = add(new Integer(4), new Double(5.2));
double answer3 = add(8, 1.3);
System.out.println(answer1 + " " + answer2 + " " + answer3);
/* Part 3 */
System.out.println("-- TREEMAP --");
TreeMap<Date,String> tm = new TreeMap<Date,String>();
tm.put(new Date(2012-1900, 1, 20),"appointment1");
tm.put(new Date(2012-1900, 1, 28), "appointment2");
tm.put(new Date(2012-1900, 2, 15), "appointment3");
tm.put(new Date(2012-1900, 2, 26), "appointment4");
// Displaying the treemap
System.out.println("-- Display tree map --");
displayTreeMap(tm);
// Navigable 1
System.out.println("-- Navigable --");
Navigable(tm, "January 20, 2012");
}
private static void aMethod() {
ArrayList<Double>list=new ArrayList<Double>();
Double temp=0.0;
Scanner input=new Scanner(System.in);
System.out.println("You'll have to enter 5 numbers (double)");
for(int i=0;i<5;i++){
try{
System.out.print("Enter a double : ");
temp=input.nextDouble();
list.add(temp);
}catch(Exception e){
System.out.println("Error input");
temp=0.0;
}
}
for(int i=list.size()-1;i>=0;i--){
System.out.println(list.get(i));
}
}
private static Double add(int i, int d) {
return (double)i+d;
}
private static Double add(int i, double d) {
return (double)i+d;
}
private static void displayTreeMap(TreeMap tm){
Set set = tm.entrySet();
Iterator i = set.iterator();
Date tmp=new Date();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
tmp=(Date) me.getKey();
System.out.print(tmp.getDate()+"/"+tmp.getMonth()+"/"+(tmp.getYear()+1900) +": ");
System.out.println(me.getValue());
}
}
private static void Navigable(TreeMap tm, String date){
DateFormat dateformat = DateFormat.getDateInstance(DateFormat.LONG, new Locale("EN","en"));
try {
Date mydate=dateformat.parse(date);
Set set = tm.entrySet();
Iterator i = set.iterator();
Date tmp=new Date();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
tmp=(Date) me.getKey();
if(tmp.getDate()==mydate.getDate() && tmp.getMonth()== (mydate.getMonth()+1) && tmp.getYear()== mydate.getYear()){
System.out.print(tmp.getDate()+"/"+tmp.getMonth()+"/"+(tmp.getYear()+1900) +": ");
System.out.println(me.getValue());
}
}
} catch (ParseException ex) {
Logger.getLogger(StaffsTutorial7.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 34.359712 | 130 | 0.56407 |
6f91d15529fbf26ac8d545ba5ad8b93e1c942510 | 5,954 | package io.github.caller79.numericrange;
import org.junit.Assert;
import org.junit.Test;
public class NumericRangeFactoryTest {
@Test
public void testContainsAsInReadmeFile() {
NumericRangeFactory factory = new NumericRangeFactory();
String expression = "(,0)[1,2](3.141592,4)[5,6)(7,8][9]";
MultipleNumericRange range = factory.parse(expression);
Assert.assertTrue(range.contains(-1));
Assert.assertFalse(range.contains(0));
Assert.assertTrue(range.contains(1));
Assert.assertTrue(range.contains(1.5));
Assert.assertTrue(range.contains(2));
Assert.assertFalse(range.contains(3.141592));
Assert.assertTrue(range.contains(3.5));
Assert.assertFalse(range.contains(4));
Assert.assertTrue(range.contains(5));
Assert.assertFalse(range.contains(6));
Assert.assertFalse(range.contains(7));
Assert.assertTrue(range.contains(8));
Assert.assertTrue(range.contains(9));
Assert.assertFalse(range.contains(10));
Assert.assertTrue(range.overlaps(factory.parse("(-1,0]")));
Assert.assertFalse(range.overlaps(factory.parse("[0,0.5]")));
Assert.assertTrue(range.overlaps(factory.parse("[0,1]")));
Assert.assertTrue(range.overlaps(factory.parse("[0,0.5][8,9)")));
Assert.assertEquals(range.toString(), expression);
String expectedSql = "(products.price_in_usd<0) OR (products.price_in_usd>=1 AND products.price_in_usd<=2) OR (products.price_in_usd>3.141592 AND products.price_in_usd<4) "
+ "OR (products.price_in_usd>=5 AND products.price_in_usd<6) OR (products.price_in_usd>7 AND products.price_in_usd<=8) OR (products.price_in_usd=9)";
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.sqlCustomizer("products.price_in_usd")), expectedSql);
}
@Test
public void testToString() {
NumericRangeFactory factory = new NumericRangeFactory();
String expression = "(,0)[1,2](3,4)[5,6)(7,8](9,]";
String expectedSQL = "(x<0) OR (x>=1 AND x<=2) OR (x>3 AND x<4) OR (x>=5 AND x<6) OR (x>7 AND x<=8) OR (x>9)";
String expectedJavascript = "(x<0) || (x>=1 && x<=2) || (x>3 && x<4) || (x>=5 && x<6) || (x>7 && x<=8) || (x>9)";
MultipleNumericRange range = factory.parse(expression);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.numericRangeCustomizer()), expression);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.sqlCustomizer("x")), expectedSQL);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.javascriptCustomizer("x")), expectedJavascript);
}
@Test
public void testEmptyToString() {
String expression = "(,)";
String expectedSQL = "(1=1)";
String expectedJavascript = "(true)";
MultipleNumericRange range = new MultipleNumericRange(null);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.numericRangeCustomizer()), expression);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.sqlCustomizer("x")), expectedSQL);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.javascriptCustomizer("x")), expectedJavascript);
NumericRangeFactory factory = new NumericRangeFactory();
range = factory.parse(expression);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.numericRangeCustomizer()), expression);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.sqlCustomizer("x")), expectedSQL);
Assert.assertEquals(range.toString(MultipleNumericRange.ToStringCustomizer.javascriptCustomizer("x")), expectedJavascript);
}
@Test
public void testContains() {
NumericRangeFactory factory = new NumericRangeFactory();
MultipleNumericRange parsed = factory.parse("(,-1)[-1,0)(0,1][" + Math.E + ",3](3.141592,4][5,]");
Assert.assertNotNull(parsed);
Assert.assertTrue(parsed.contains(-2));
Assert.assertTrue(parsed.contains(-1));
Assert.assertFalse(parsed.contains(0));
Assert.assertTrue(parsed.contains(1));
Assert.assertFalse(parsed.contains(2));
Assert.assertTrue(parsed.contains(Math.E));
Assert.assertTrue(parsed.contains(3));
Assert.assertTrue(parsed.contains(4));
Assert.assertFalse(parsed.contains(4.5));
Assert.assertTrue(parsed.contains(5));
Assert.assertTrue(parsed.contains(6));
}
@Test
public void testOverlaps() {
NumericRangeFactory factory = new NumericRangeFactory();
MultipleNumericRange parsed = factory.parse("(,-1)(0,1][" + Math.E + ",3](3.141592,4][5,]");
Assert.assertNotNull(parsed);
Assert.assertTrue(parsed.overlaps(factory.parse("(,)").getRanges().get(0)));
Assert.assertTrue(parsed.overlaps(factory.parse("(,]").getRanges().get(0)));
Assert.assertTrue(parsed.overlaps(factory.parse("[,)").getRanges().get(0)));
Assert.assertTrue(parsed.overlaps(factory.parse("[,]").getRanges().get(0)));
Assert.assertFalse(parsed.overlaps(factory.parse("(-0.5,-0.4)").getRanges().get(0)));
Assert.assertTrue(parsed.overlaps(factory.parse("(-1.5,0)").getRanges().get(0)));
}
@Test
public void testExactRanges() {
NumericRangeFactory factory = new NumericRangeFactory();
MultipleNumericRange parsed = factory.parse("[1][2,3][4]");
Assert.assertNotNull(parsed);
Assert.assertFalse(parsed.contains(0));
Assert.assertTrue(parsed.contains(1));
Assert.assertTrue(parsed.contains(2));
Assert.assertTrue(parsed.contains(2.5));
Assert.assertTrue(parsed.contains(3));
Assert.assertTrue(parsed.contains(4));
Assert.assertFalse(parsed.contains(5));
}
}
| 50.888889 | 180 | 0.6782 |
b75730c9453c7700f7c5678f77cb8d2db0e22c04 | 2,821 | package com.egoveris.te.ws.controller;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.egoveris.ccomplejos.base.model.AbstractCComplejoDTO;
import com.egoveris.ffdd.ws.service.ExternalCComplejosService;
import com.egoveris.te.base.util.ReflectionUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
@RestController
@RequestMapping("/api/ccEntity")
public class RemoteEndPointCCEntity {
private Log logger = LogFactory.getLog(RemoteEndPointCCEntity.class);
protected List<AbstractCComplejoDTO> entityDTOClassList;
@Autowired
private ExternalCComplejosService cComplejosService;
@RequestMapping(value = "/get", method = RequestMethod.GET)
public ResponseEntity<String> getCCEntityOperation(@RequestParam(value = "entity", required = true) String entity,
@RequestParam(value = "idOperation", required = true) Integer operation) {
HttpStatus httpStatus = HttpStatus.OK;
String json = "[]";
if (entityDTOClassList == null) {
entityDTOClassList = ReflectionUtil.searchClasses(AbstractCComplejoDTO.class);
}
AbstractCComplejoDTO entityDTO = null;
try {
for (Object entityDTOClass : entityDTOClassList) {
if (entityDTOClass instanceof AbstractCComplejoDTO
&& entityDTOClass.getClass().getSimpleName().toLowerCase().contains(entity.concat("DTO").toLowerCase())) {
entityDTO = (AbstractCComplejoDTO) entityDTOClass.getClass().newInstance();
break;
}
}
}
catch (Exception e) {
logger.debug("Error while searching for entity: ", e);
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
}
if (entityDTO != null) {
entityDTO.setIdOperacion(operation);
try {
List<AbstractCComplejoDTO> datosComponente = cComplejosService.buscarDatosComponente(entityDTO);
if (!datosComponente.isEmpty()) {
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(datosComponente);
}
}
catch (Exception e) {
logger.debug("Error getting entity data [Entity: " + entityDTO.getClass().getSimpleName() + " | Operation: "
+ operation + "] => ", e);
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
}
}
return ResponseEntity.status(httpStatus).body(json);
}
}
| 35.2625 | 118 | 0.719248 |
2d1921b608e71b25f764705eb0d5efed79608657 | 955 | package org.zjuwangg.crawl.webpage;
/**
* Created by wanggang on 2015/5/27.
*/
public class Question {
public String questionInfo;
public String questionDetail;
public Question(String questionInfo, String questionDetail) {
this.questionInfo = questionInfo;
this.questionDetail = questionDetail;
}
public Question(){
}
public String getQuestionInfo() {
return questionInfo;
}
public void setQuestionInfo(String questionInfo) {
this.questionInfo = questionInfo;
}
public String getQuestionDetail() {
return questionDetail;
}
public void setQuestionDetail(String questionDetail) {
this.questionDetail = questionDetail;
}
@Override
public String toString() {
return "Question{" +
"questionInfo='" + questionInfo + '\'' +
", questionDetail='" + questionDetail + '\'' +
'}';
}
}
| 22.738095 | 65 | 0.616754 |
6b9b584d580309726bd925a8c55c4219328874f1 | 1,753 | package cc.mrbird.febs.basicInfo.service;
import cc.mrbird.febs.basicInfo.entity.DeviceInfo;
import cc.mrbird.febs.common.entity.QueryRequest;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* Service接口
*
* @author psy
* @date 2019-08-16 16:50:43
*/
public interface IDeviceInfoService extends IService<DeviceInfo> {
DeviceInfo findDeviceById(Integer deviceId);
/**
* 查询(分页)
*
* @param request QueryRequest
* @param deviceInfo deviceInfo
* @return IPage<DeviceInfo>
*/
IPage<DeviceInfo> findDeviceInfos(QueryRequest request, DeviceInfo deviceInfo);
/**
* 查询(所有)
*
* @param deviceInfo deviceInfo
* @return List<DeviceInfo>
*/
List<DeviceInfo> findDeviceInfos(DeviceInfo deviceInfo);
/**
* 新增
*
* @param deviceInfo deviceInfo
*/
void createDeviceInfo(DeviceInfo deviceInfo);
/**
* 修改
*
* @param deviceInfo deviceInfo
*/
void updateDeviceInfo(DeviceInfo deviceInfo);
/**
* 删除
*
* @param deviceIds deviceIds
*/
void deleteDeviceInfo(String deviceIds);
/**
* 通过学校 id 删除
*
* @param schoolIds 学校id
*/
void deleteDeviceInfoByschoolId(List<String> schoolIds);
Integer countDeviceByDept(String deptName);
Integer countDeviceBySchool(String schoolName);
/**
* 按部门查询
* @param deviceInfo
* @param deptId
* @return
*/
IPage<DeviceInfo> findDeviceInfosByDept(QueryRequest request, DeviceInfo deviceInfo, String deptId);
/**
* 导入Excel信息
* @param successList
*/
void insertDeviceInfo(List<DeviceInfo> successList);
}
| 21.120482 | 101 | 0.657159 |
90e1147f10ae8dedb70c24605947183ebce525f8 | 1,172 | package org.batfish.datamodel.isp_configuration;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import com.google.common.testing.EqualsTester;
import java.io.IOException;
import org.batfish.common.util.BatfishObjectMapper;
import org.batfish.datamodel.collections.NodeInterfacePair;
import org.junit.Test;
/** Tests for {@link BorderInterfaceInfo} */
public class BorderInterfaceInfoTest {
@Test
public void testEquals() {
new EqualsTester()
.addEqualityGroup(
new BorderInterfaceInfo(new NodeInterfacePair("node", "interface")),
new BorderInterfaceInfo(new NodeInterfacePair("node", "interface")))
.addEqualityGroup(
new BorderInterfaceInfo(new NodeInterfacePair("diffNode", "diffInterface")))
.testEquals();
}
@Test
public void testJsonSerialization() throws IOException {
BorderInterfaceInfo borderInterfaceInfo =
new BorderInterfaceInfo(new NodeInterfacePair("node", "interface"));
assertThat(
BatfishObjectMapper.clone(borderInterfaceInfo, BorderInterfaceInfo.class),
equalTo(borderInterfaceInfo));
}
}
| 33.485714 | 88 | 0.744881 |
2f9bf9640f9d16b9fb113b339090649c7fa08a86 | 2,117 | package com.nsc.datastructures.queue.stackqueue;
import java.util.Stack;
import java.util.StringJoiner;
public class StackQueue<T> {
private Stack<T> stack1;
private Stack<T> stack2;
private int size;
public StackQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
size = 0;
}
/*************************** Approach 1 ***************************/
/*
By making enQueue operation costly
1. While stack1 is not empty, push everything from stack1 to stack2.
2. Push element to stack1 (assuming size of stacks is unlimited).
3. Push everything back to stack1
*/
public void enQueue(T element) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
stack1.push(element);
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
size++;
}
/*
If stack1 is empty then error
Pop an item from stack1 and return it
*/
public T deQueue() {
if (stack1.isEmpty()) {
throw new RuntimeException("queue is empty");
}
size--;
return stack1.pop();
}
/*************************** Approach 2 ***************************/
public void testApproach2() {
stack1.clear();
stack2.clear();
size = 0;
}
/*
Push element to stack1 (assuming size of stacks is unlimited)
*/
public void enQueueApproach2(T element) {
stack1.push(element);
size++;
}
/*
By making deQueue operation costly
1. If both stacks are empty then error
2. If stack2 is empty
While stack1 is not empty, push everything from stack1 to stack2.
3. Pop the element from stack2 and return it.
*/
public T deQueueApproach2() {
if (stack1.isEmpty() && stack2.isEmpty()) {
throw new RuntimeException("queue is empty");
}
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
size--;
return stack2.pop();
}
}
| 25.202381 | 72 | 0.531412 |
c3079b462ab44c4f55df1a4f620e37e4e366bede | 8,056 | package com.lvmoney.frame.core.util;/**
* 描述:
* 包名:com.chdriver.frame.core.util
* 版本信息: 版本1.0
* 日期:2021/9/23
* Copyright XXXXXX科技有限公司
*/
import com.lvmoney.frame.core.vo.PackageIndexVo;
import com.lvmoney.frame.core.vo.PackageVo;
import com.lvmoney.frame.core.vo.item.PackageVoItem;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @describe:问题描述: 一个背包的总容量为V, 现在有N类物品, 第i类物品的重量为weight[i], 价值为value[i]
* 那么往该背包里装东西,怎样装才能使得最终包内物品的总价值最大。这里装物品主要由三种装法:
* 1、0-1背包:每类物品最多只能装一次
* 2、多重背包:每类物品都有个数限制,第i类物品最多可以装num[i]次
* 3、完全背包:每类物品可以无限次装进包内
* @author: lvmoney/XXXXXX科技有限公司
* @version:v1.0 2021/9/23 16:25
*/
public class PackageUtil {
/**
* 0-1背包问题
*
* @param v 背包容量
* @param n 物品种类
* @param weight 物品重量
* @param value 物品价值
* @param v:
* @param n:
* @param weight:
* @param value:
* @throws
* @return: com.chdriver.frame.core.vo.PackageVo
* @author: lvmoney /XXXXXX科技有限公司
* @date: 2021/9/24 13:05
*/
public static PackageVo zeroOnePack(int v, int n, int[] weight, int[] value) {
//初始化动态规划数组
int[][] dp = new int[n + 1][v + 1];
//为了便于理解,将dp[i][0]和dp[0][j]均置为0,从1开始计算
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < v + 1; j++) {
//如果第i件物品的重量大于背包容量j,则不装入背包
//由于weight和value数组下标都是从0开始,故注意第i个物品的重量为weight[i-1],价值为value[i-1]
if (weight[i - 1] > j)
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i - 1]] + value[i - 1]);
}
}
//则容量为V的背包能够装入物品的最大值为
int maxValue = dp[n][v];
//逆推找出装入背包的所有商品的编号
int j = v;
List<PackageVoItem> data = new ArrayList<>();
List<PackageIndexVo> item = new ArrayList<>();
for (int i = n; i > 0; i--) {
//若果dp[i][j]>dp[i-1][j],这说明第i件物品是放入背包的
if (dp[i][j] > dp[i - 1][j]) {
item.add(new PackageIndexVo(i));
j = j - weight[i - 1];
}
if (j == 0)
break;
}
Map<Integer, List<PackageIndexVo>> itemMap = item.stream().collect(Collectors.groupingBy(PackageIndexVo::getNum));
itemMap.forEach((k, val) -> {
int itemNum = val.size();
PackageVoItem packageVoItem = new PackageVoItem();
packageVoItem.setNumber(itemNum);
packageVoItem.setWeight(weight[k - 1]);
packageVoItem.setValue(value[k - 1]);
data.add(packageVoItem);
});
PackageVo packageVo = new PackageVo();
packageVo.setValue(maxValue);
packageVo.setCount(itemMap.size());
packageVo.setData(data);
return packageVo;
}
/**
* 多重背包
* 每类物品都有个数限制,第i类物品最多可以装num[i]次
*
* @param v:
* @param n:
* @param weight:
* @param value:
* @param num:
* @throws
* @return: com.chdriver.frame.core.vo.PackageVo
* @author: lvmoney /XXXXXX科技有限公司
* @date: 2021/9/24 13:05
*/
public static PackageVo manyPack(int v, int n, int[] weight, int[] value, int[] num) {
//初始化动态规划数组
int[][] dp = new int[n + 1][v + 1];
//为了便于理解,将dp[i][0]和dp[0][j]均置为0,从1开始计算
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < v + 1; j++) {
//如果第i件物品的重量大于背包容量j,则不装入背包
//由于weight和value数组下标都是从0开始,故注意第i个物品的重量为weight[i-1],价值为value[i-1]
if (weight[i - 1] > j)
dp[i][j] = dp[i - 1][j];
else {
//考虑物品的件数限制
int maxV = Math.min(num[i - 1], j / weight[i - 1]);
for (int k = 0; k < maxV + 1; k++) {
dp[i][j] = dp[i][j] > Math.max(dp[i - 1][j], dp[i - 1][j - k * weight[i - 1]] + k * value[i - 1]) ? dp[i][j] : Math.max(dp[i - 1][j], dp[i - 1][j - k * weight[i - 1]] + k * value[i - 1]);
}
}
}
}
//则容量为V的背包能够装入物品的最大值为
int maxValue = dp[n][v];
int j = v;
List<PackageVoItem> data = new ArrayList<>();
List<PackageIndexVo> item = new ArrayList<>();
for (int i = n; i > 0; i--) {
//若果dp[i][j]>dp[i-1][j],这说明第i件物品是放入背包的
while (dp[i][j] > dp[i - 1][j]) {
item.add(new PackageIndexVo(i));
j = j - weight[i - 1];
}
if (j == 0)
break;
}
Map<Integer, List<PackageIndexVo>> itemMap = item.stream().collect(Collectors.groupingBy(PackageIndexVo::getNum));
itemMap.forEach((k, val) -> {
int itemNum = val.size();
PackageVoItem packageVoItem = new PackageVoItem();
packageVoItem.setNumber(itemNum);
packageVoItem.setWeight(weight[k - 1]);
packageVoItem.setValue(value[k - 1]);
data.add(packageVoItem);
});
PackageVo packageVo = new PackageVo();
packageVo.setValue(maxValue);
packageVo.setCount(itemMap.size());
packageVo.setData(data);
return packageVo;
}
/**
* 第二类背包:完全背包
* 思路分析:
* 01背包问题是在前一个子问题(i-1种物品)的基础上来解决当前问题(i种物品),
* 向i-1种物品时的背包添加第i种物品;而完全背包问题是在解决当前问题(i种物品)
* 向i种物品时的背包添加第i种物品。
* 推公式计算时,f[i][y] = max{f[i-1][y], (f[i][y-weight[i]]+value[i])},
* 注意这里当考虑放入一个物品 i 时应当考虑还可能继续放入 i,
* 因此这里是f[i][y-weight[i]]+value[i], 而不是f[i-1][y-weight[i]]+value[i]。
*
* @param v
* @param n
* @param weight
* @param value
* @param v:
* @param n:
* @param weight:
* @param value:
* @throws
* @return: com.chdriver.frame.core.vo.PackageVo
* @author: lvmoney /XXXXXX科技有限公司
* @date: 2021/9/24 13:05
*/
public static PackageVo completePack(int v, int n, int[] weight, int[] value) {
//初始化动态规划数组
int[][] dp = new int[n + 1][v + 1];
//为了便于理解,将dp[i][0]和dp[0][j]均置为0,从1开始计算
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < v + 1; j++) {
//如果第i件物品的重量大于背包容量j,则不装入背包
//由于weight和value数组下标都是从0开始,故注意第i个物品的重量为weight[i-1],价值为value[i-1]
if (weight[i - 1] > j)
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - weight[i - 1]] + value[i - 1]);
}
}
//则容量为V的背包能够装入物品的最大值为
int maxValue = dp[n][v];
int j = v;
List<PackageVoItem> data = new ArrayList<>();
List<PackageIndexVo> item = new ArrayList<>();
for (int i = n; i > 0; i--) {
//若果dp[i][j]>dp[i-1][j],这说明第i件物品是放入背包的
while (dp[i][j] > dp[i - 1][j]) {
item.add(new PackageIndexVo(i));
j = j - weight[i - 1];
}
if (j == 0)
break;
}
Map<Integer, List<PackageIndexVo>> itemMap = item.stream().collect(Collectors.groupingBy(PackageIndexVo::getNum));
itemMap.forEach((k, val) -> {
int itemNum = val.size();
PackageVoItem packageVoItem = new PackageVoItem();
packageVoItem.setNumber(itemNum);
packageVoItem.setWeight(weight[k - 1]);
packageVoItem.setValue(value[k - 1]);
data.add(packageVoItem);
});
PackageVo packageVo = new PackageVo();
packageVo.setValue(maxValue);
packageVo.setCount(itemMap.size());
packageVo.setData(data);
return packageVo;
}
/* public static void main(String[] args) {
int[] weight = {6, 3, 4, 5, 22};
int[] value = {6, 3, 4, 5, 22};
int[] num = {3, 3, 3, 3, 3};
// System.out.println(manyPack(100, 4, weight, value, num));
System.out.println(completePack(100, 4, weight, value));
System.out.println(zeroOnePack(100, 5, weight, value));
}*/
} | 34.575107 | 211 | 0.508813 |
38bd160589d41cb621ff8aa4a50150547c12ae47 | 223 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int word = sc.nextInt();
System.out.println(word * 32);
}
}
| 13.9375 | 44 | 0.587444 |
f0e6793e169910788b115cafb1a5f016dfc32c69 | 1,835 | /*
* 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.droids.exception;
/**
* Wrapper object to limit the number of different Exception we can throw.
*
* @version 1.0
*
*/
public class DroidsException extends Exception {
private static final long serialVersionUID = -6910418914635962957L;
/**
* Constructs a new exception with the specified detail message. The cause is
* not initialized, and may subsequently be initialized by a call to
* {@link #initCause}.
*
* @param message
* the detail message. The detail message is saved for later
* retrieval by the {@link #getMessage()} method.
*/
public DroidsException(String message) {
super(message);
}
/**
* For more information {@link Exception}
*
* @param message
* @param cause
*/
public DroidsException(String message, Throwable cause) {
super(message, cause);
}
/**
* For more information {@link Exception}
*
* @param cause
*/
public DroidsException(Throwable cause) {
super(cause);
}
}
| 30.081967 | 79 | 0.696458 |
542be00088b75ac670ea60fcc70cc9aeceb304c5 | 8,703 | // CheckStyle: start generated
package com.oracle.truffle.js.nodes.access;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.dsl.GeneratedBy;
import com.oracle.truffle.api.dsl.Introspection;
import com.oracle.truffle.api.dsl.UnsupportedSpecializationException;
import com.oracle.truffle.api.dsl.Introspection.Provider;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.NodeCost;
import com.oracle.truffle.api.nodes.UnexpectedResultException;
import com.oracle.truffle.js.nodes.JSTypesGen;
@GeneratedBy(JSReadCurrentFrameSlotNode.class)
final class JSReadCurrentFrameSlotNodeGen extends JSReadCurrentFrameSlotNode implements Introspection.Provider {
@CompilationFinal private int state_0_;
private JSReadCurrentFrameSlotNodeGen(FrameSlot slot) {
super(slot);
}
@Override
public Object execute(VirtualFrame frameValue) {
int state_0 = this.state_0_;
if ((state_0 & 0b1) != 0 /* is-state_0 doBoolean(VirtualFrame) */) {
if ((frameValue.isBoolean(frameSlot))) {
return doBoolean(frameValue);
}
}
if ((state_0 & 0b10) != 0 /* is-state_0 doInt(VirtualFrame) */) {
if ((frameValue.isInt(frameSlot))) {
return doInt(frameValue);
}
}
if ((state_0 & 0b100) != 0 /* is-state_0 doDouble(VirtualFrame) */) {
if ((frameValue.isDouble(frameSlot) || frameValue.isInt(frameSlot))) {
return doDouble(frameValue);
}
}
if ((state_0 & 0b1000) != 0 /* is-state_0 doObject(VirtualFrame) */) {
if ((frameValue.isObject(frameSlot))) {
return doObject(frameValue);
}
}
if ((state_0 & 0b10000) != 0 /* is-state_0 doSafeInteger(VirtualFrame) */) {
if ((frameValue.isLong(frameSlot))) {
return doSafeInteger(frameValue);
}
}
CompilerDirectives.transferToInterpreterAndInvalidate();
return executeAndSpecialize(frameValue);
}
@Override
public boolean executeBoolean(VirtualFrame frameValue) throws UnexpectedResultException {
int state_0 = this.state_0_;
if ((state_0 & 0b1000) != 0 /* is-state_0 doObject(VirtualFrame) */) {
return JSTypesGen.expectBoolean(execute(frameValue));
}
if ((state_0 & 0b1) != 0 /* is-state_0 doBoolean(VirtualFrame) */) {
if ((frameValue.isBoolean(frameSlot))) {
return doBoolean(frameValue);
}
}
CompilerDirectives.transferToInterpreterAndInvalidate();
return JSTypesGen.expectBoolean(executeAndSpecialize(frameValue));
}
@Override
public double executeDouble(VirtualFrame frameValue) throws UnexpectedResultException {
int state_0 = this.state_0_;
if ((state_0 & 0b1000) != 0 /* is-state_0 doObject(VirtualFrame) */) {
return JSTypesGen.expectDouble(execute(frameValue));
}
if ((state_0 & 0b100) != 0 /* is-state_0 doDouble(VirtualFrame) */) {
if ((frameValue.isDouble(frameSlot) || frameValue.isInt(frameSlot))) {
return doDouble(frameValue);
}
}
CompilerDirectives.transferToInterpreterAndInvalidate();
return JSTypesGen.expectDouble(executeAndSpecialize(frameValue));
}
@Override
public int executeInt(VirtualFrame frameValue) throws UnexpectedResultException {
int state_0 = this.state_0_;
if ((state_0 & 0b1000) != 0 /* is-state_0 doObject(VirtualFrame) */) {
return JSTypesGen.expectInteger(execute(frameValue));
}
if ((state_0 & 0b10) != 0 /* is-state_0 doInt(VirtualFrame) */) {
if ((frameValue.isInt(frameSlot))) {
return doInt(frameValue);
}
}
CompilerDirectives.transferToInterpreterAndInvalidate();
return JSTypesGen.expectInteger(executeAndSpecialize(frameValue));
}
@Override
public void executeVoid(VirtualFrame frameValue) {
int state_0 = this.state_0_;
try {
if ((state_0 & 0b11101) == 0 /* only-active doInt(VirtualFrame) */ && (state_0 != 0 /* is-not doBoolean(VirtualFrame) && doInt(VirtualFrame) && doDouble(VirtualFrame) && doObject(VirtualFrame) && doSafeInteger(VirtualFrame) */)) {
executeInt(frameValue);
return;
} else if ((state_0 & 0b11011) == 0 /* only-active doDouble(VirtualFrame) */ && (state_0 != 0 /* is-not doBoolean(VirtualFrame) && doInt(VirtualFrame) && doDouble(VirtualFrame) && doObject(VirtualFrame) && doSafeInteger(VirtualFrame) */)) {
executeDouble(frameValue);
return;
} else if ((state_0 & 0b11110) == 0 /* only-active doBoolean(VirtualFrame) */ && (state_0 != 0 /* is-not doBoolean(VirtualFrame) && doInt(VirtualFrame) && doDouble(VirtualFrame) && doObject(VirtualFrame) && doSafeInteger(VirtualFrame) */)) {
executeBoolean(frameValue);
return;
}
execute(frameValue);
return;
} catch (UnexpectedResultException ex) {
return;
}
}
private Object executeAndSpecialize(VirtualFrame frameValue) {
int state_0 = this.state_0_;
if ((frameValue.isBoolean(frameSlot))) {
this.state_0_ = state_0 = state_0 | 0b1 /* add-state_0 doBoolean(VirtualFrame) */;
return doBoolean(frameValue);
}
if ((frameValue.isInt(frameSlot))) {
this.state_0_ = state_0 = state_0 | 0b10 /* add-state_0 doInt(VirtualFrame) */;
return doInt(frameValue);
}
if ((frameValue.isDouble(frameSlot) || frameValue.isInt(frameSlot))) {
this.state_0_ = state_0 = state_0 | 0b100 /* add-state_0 doDouble(VirtualFrame) */;
return doDouble(frameValue);
}
if ((frameValue.isObject(frameSlot))) {
this.state_0_ = state_0 = state_0 | 0b1000 /* add-state_0 doObject(VirtualFrame) */;
return doObject(frameValue);
}
if ((frameValue.isLong(frameSlot))) {
this.state_0_ = state_0 = state_0 | 0b10000 /* add-state_0 doSafeInteger(VirtualFrame) */;
return doSafeInteger(frameValue);
}
throw new UnsupportedSpecializationException(this, new Node[] {});
}
@Override
public NodeCost getCost() {
int state_0 = this.state_0_;
if (state_0 == 0) {
return NodeCost.UNINITIALIZED;
} else {
if ((state_0 & (state_0 - 1)) == 0 /* is-single-state_0 */) {
return NodeCost.MONOMORPHIC;
}
}
return NodeCost.POLYMORPHIC;
}
@Override
public Introspection getIntrospectionData() {
Object[] data = new Object[6];
Object[] s;
data[0] = 0;
int state_0 = this.state_0_;
s = new Object[3];
s[0] = "doBoolean";
if ((state_0 & 0b1) != 0 /* is-state_0 doBoolean(VirtualFrame) */) {
s[1] = (byte)0b01 /* active */;
} else {
s[1] = (byte)0b00 /* inactive */;
}
data[1] = s;
s = new Object[3];
s[0] = "doInt";
if ((state_0 & 0b10) != 0 /* is-state_0 doInt(VirtualFrame) */) {
s[1] = (byte)0b01 /* active */;
} else {
s[1] = (byte)0b00 /* inactive */;
}
data[2] = s;
s = new Object[3];
s[0] = "doDouble";
if ((state_0 & 0b100) != 0 /* is-state_0 doDouble(VirtualFrame) */) {
s[1] = (byte)0b01 /* active */;
} else {
s[1] = (byte)0b00 /* inactive */;
}
data[3] = s;
s = new Object[3];
s[0] = "doObject";
if ((state_0 & 0b1000) != 0 /* is-state_0 doObject(VirtualFrame) */) {
s[1] = (byte)0b01 /* active */;
} else {
s[1] = (byte)0b00 /* inactive */;
}
data[4] = s;
s = new Object[3];
s[0] = "doSafeInteger";
if ((state_0 & 0b10000) != 0 /* is-state_0 doSafeInteger(VirtualFrame) */) {
s[1] = (byte)0b01 /* active */;
} else {
s[1] = (byte)0b00 /* inactive */;
}
data[5] = s;
return Provider.create(data);
}
public static JSReadCurrentFrameSlotNode create(FrameSlot slot) {
return new JSReadCurrentFrameSlotNodeGen(slot);
}
}
| 40.291667 | 254 | 0.589567 |
c0611c5096a537fc99fef027f2a5aedaaf405612 | 1,632 | package com.idmworks.bitbucket.relay.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.annotation.Generated;
@Generated("com.robohorse.robopojogenerator")
public class Links{
@JsonProperty("patch")
private Link patch;
@JsonProperty("comments")
private Link comments;
@JsonProperty("approve")
private Link approve;
@JsonProperty("self")
private Link self;
@JsonProperty("statuses")
private Link statuses;
@JsonProperty("html")
private Link html;
@JsonProperty("diff")
private Link diff;
public void setPatch(Link patch){
this.patch = patch;
}
public Link getPatch(){
return patch;
}
public void setComments(Link comments){
this.comments = comments;
}
public Link getComments(){
return comments;
}
public void setApprove(Link approve){
this.approve = approve;
}
public Link getApprove(){
return approve;
}
public void setSelf(Link self){
this.self = self;
}
public Link getSelf(){
return self;
}
public void setStatuses(Link statuses){
this.statuses = statuses;
}
public Link getStatuses(){
return statuses;
}
public void setHtml(Link html){
this.html = html;
}
public Link getHtml(){
return html;
}
public void setDiff(Link diff){
this.diff = diff;
}
public Link getDiff(){
return diff;
}
@Override
public String toString(){
return
"Links{" +
"patch = '" + patch + '\'' +
",comments = '" + comments + '\'' +
",approve = '" + approve + '\'' +
",self = '" + self + '\'' +
",statuses = '" + statuses + '\'' +
",html = '" + html + '\'' +
",diff = '" + diff + '\'' +
"}";
}
} | 16.32 | 53 | 0.64277 |
8a10368e645e292ac9582ad5c34313d5cac0798a | 2,166 | /*
* Copyright (c) 2020 Broadcom.
* The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Broadcom, Inc. - initial API and implementation
*
*/
package org.eclipse.lsp.cobol.core.model.variables;
import org.eclipse.lsp.cobol.core.model.Locality;
import com.google.common.collect.ImmutableList;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.Value;
import java.util.List;
import static org.eclipse.lsp.cobol.core.visitor.VariableDefinitionDelegate.LEVEL_88;
/**
* This value class represents a conditional data name entry, that has a level number 88. It cannot
* be a top element in the structure. It always contains a variable name and a value, but not PIC
* clause.
*/
@Value
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class ConditionDataName extends AbstractVariable {
String value;
String valueTo;
public ConditionDataName(String name, Locality definition, Variable parent, String value, String valueTo) {
super(LEVEL_88, name, definition, parent);
this.value = value;
this.valueTo = valueTo;
}
@Override
public boolean isConditional() {
return false;
}
@Override
public void addConditionName(ConditionDataName variable) {
throw new UnsupportedOperationException("This variable is not conditional");
}
@Override
public List<ConditionDataName> getConditionNames() {
return ImmutableList.of();
}
@Override
public Variable rename(RenameItem newParent) {
return new ConditionDataName(name, definition, newParent, value, valueTo);
}
@Override
public String getFormattedDisplayLine() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(String.format("%1$02d %2$s VALUE %3$s", levelNumber, name, value));
if (valueTo != null)
stringBuilder.append(" THRU ").append(valueTo);
return stringBuilder.append(".").toString();
}
}
| 28.88 | 109 | 0.738689 |
499cc1d7bf5f46d7512ecc03bedb9536ffdcddbe | 35,393 | package dev.kxxcn.app_squad.data.remote;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.iid.FirebaseInstanceId;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import dev.kxxcn.app_squad.data.DataSource;
import dev.kxxcn.app_squad.data.model.Battle;
import dev.kxxcn.app_squad.data.model.Chatting;
import dev.kxxcn.app_squad.data.model.Information;
import dev.kxxcn.app_squad.data.model.Notification;
import dev.kxxcn.app_squad.data.model.User;
import dev.kxxcn.app_squad.data.model.message.Data;
import dev.kxxcn.app_squad.data.model.message.Send;
import dev.kxxcn.app_squad.util.Constants;
import dev.kxxcn.app_squad.util.DialogUtils;
import dev.kxxcn.app_squad.util.SystemUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static dev.kxxcn.app_squad.data.remote.APIPersistence.TYPE_CHATTING;
import static dev.kxxcn.app_squad.data.remote.APIPersistence.TYPE_REQUEST;
import static dev.kxxcn.app_squad.data.remote.APIPersistence.TYPE_RESPONSE;
import static dev.kxxcn.app_squad.util.Constants.DEFAULT_NAME;
import static dev.kxxcn.app_squad.util.Constants.TYPE_COLLECTION;
/**
* Created by kxxcn on 2018-05-01.
*/
public class RemoteDataSource extends DataSource {
private static final String COLLECTION_NAME_CHATTING = "chatting";
private static final String INIT = "1";
public static final String COLLECTION_NAME_USER = "user";
public static final String COLLECTION_NAME_MATCH = "match";
public static final String COLLECTION_NAME_RECRUITMENT = "recruitment";
public static final String COLLECTION_NAME_PLAYER = "player";
public static final String COLLECTION_NAME_BATTLE = "battle";
public static final String COUNTRY_FORMAT = "+82";
public static final String DOCUMENT_NAME_MESSAGE = "message";
public static final String DOCUMENT_NAME_JOIN = "join";
public static final String DOCUMENT_NAME_NOTICE = "notice";
public static final String DOCUMENT_NAME_SQUAD = "squad";
public static final String DOCUMENT_NAME_EVENT = "event";
private static final int EXPIRATION_TIME = 60;
public static final int FLAG_MATCH_LIST = 0;
public static final int FLAG_RECRUITMENT_LIST = 1;
public static final int FLAG_PLAYER_LIST = 2;
private static RemoteDataSource remoteDataSource;
private FirebaseAuth mAuth;
private DatabaseReference mReference;
private boolean mIsDuplicate = false;
private boolean mIsExistRoom = false;
private APIService service;
public RemoteDataSource(FirebaseAuth auth, DatabaseReference reference) {
this.mAuth = auth;
this.mReference = reference;
this.service = APIService.Factory.create();
}
public static synchronized RemoteDataSource getInstance(FirebaseAuth firebaseAuth,
DatabaseReference databaseReference) {
if (remoteDataSource == null) {
remoteDataSource = new RemoteDataSource(firebaseAuth, databaseReference);
}
return remoteDataSource;
}
@Override
public void onSignup(final GetSignupCallback callback, final String email, final String phone, final String password, final String team) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
if (isDuplicate(team, user.getTeam())) {
callback.onDuplicatedTeam();
mIsDuplicate = true;
break;
} else {
mIsDuplicate = false;
}
}
onCreateUser(callback, email, phone, password, team);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
private void onCreateUser(final GetSignupCallback callback, final String email, final String contact, final String password, final String team) {
if (!mIsDuplicate) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String uid = mAuth.getCurrentUser().getUid();
String token = FirebaseInstanceId.getInstance().getToken();
User user = new User(email, contact, uid, team, token);
mReference.child(COLLECTION_NAME_USER).child(uid).setValue(user).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
} else {
callback.onFailure(task.getException());
}
}
});
}
}
@Override
public void onLogin(final GetCommonCallback callback, String email, String password) {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
callback.onSuccess();
} else {
callback.onFailure(task.getException());
}
}
});
}
@Override
public void onLogout(GetCommonCallback callback) {
if (mAuth.getCurrentUser() != null) {
remoteDataSource = null;
mAuth.signOut();
callback.onSuccess();
} else {
callback.onFailure(new Exception());
}
}
@Override
public void onLoadList(final GetLoadListCallback callback, Constants.ListsFilterType requestType, final String region, final String date) {
DatabaseReference reference = null;
switch (requestType) {
case MATCH_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_MATCH);
break;
case RECRUITMENT_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_RECRUITMENT);
break;
case PLAYER_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_PLAYER);
break;
}
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<Information> list = new ArrayList<>(0);
for (DataSnapshot parentSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot childSnapshot : parentSnapshot.getChildren()) {
SystemUtils.Dlog.i(childSnapshot.getValue().toString());
final Information information = childSnapshot.getValue(Information.class);
if (!information.isConnect()) {
if (Integer.parseInt(DialogUtils.getFormattedDate(DialogUtils.getDate(), TYPE_COLLECTION)) <=
Integer.parseInt(information.getDate().replace("-", ""))) {
if (region == null && date == null) {
list.add(information);
} else if (region != null && date != null) {
if (region.equals(information.getRegion()) && date.equals(information.getDate())) {
list.add(information);
}
} else if (region != null) {
if (region.equals(information.getRegion())) {
list.add(information);
}
} else if (date != null) {
if (date.equals(information.getDate())) {
list.add(information);
}
}
}
}
}
}
callback.onSuccess(list);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
@Override
public void onRegister(final GetCommonCallback callback, final Information information, final Constants.ListsFilterType requestType) {
List<String> joinList = new ArrayList<>(0);
joinList.add(DEFAULT_NAME);
information.setJoin(joinList);
String collection = null;
switch (requestType) {
case MATCH_LIST:
collection = COLLECTION_NAME_MATCH;
break;
case RECRUITMENT_LIST:
collection = COLLECTION_NAME_RECRUITMENT;
break;
case PLAYER_LIST:
collection = COLLECTION_NAME_PLAYER;
break;
}
mReference.child(collection).child(DialogUtils.getFormattedDate(information.getDate(), TYPE_COLLECTION)).child(mAuth.getCurrentUser().getUid()).setValue(information)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
}
@Override
public void onLoadRecord(final GetBattleCallback callback) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_BATTLE).child(mAuth.getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<Battle> battleList = new ArrayList<>(0);
for (DataSnapshot parentSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot childSnapshot : parentSnapshot.getChildren()) {
battleList.add(childSnapshot.getValue(Battle.class));
}
}
callback.onSuccess(battleList);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
@Override
public void onRequest(final GetSendMessageCallback callback, final String to, final String title, final String message, final String from, final String date, final Constants.ListsFilterType filterType) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final String token = getTokenOfRrecipient(dataSnapshot, to, Constants.TYPE_REQUEST);
if (token != null) {
String flag = null;
Data data = new Data();
data.setTitle(title);
data.setMessage(message);
data.setSender(from);
data.setDate(date);
data.setType(TYPE_REQUEST);
switch (filterType) {
case MATCH_LIST:
flag = String.valueOf(FLAG_MATCH_LIST);
break;
case RECRUITMENT_LIST:
flag = String.valueOf(FLAG_RECRUITMENT_LIST);
break;
case PLAYER_LIST:
flag = String.valueOf(FLAG_PLAYER_LIST);
break;
}
data.setFlag(flag);
Send send = new Send();
send.setTo(token);
send.setData(data);
Call<Void> call = service.sendMessage(send);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
if (response.isSuccessful()) {
callback.onSuccess();
} else {
callback.onError();
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
callback.onFailure(t);
}
});
} else {
callback.onError();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
@Override
public void onLoadAccount(final GetUserCallback callback) {
try {
DatabaseReference accountReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER).child(mAuth.getCurrentUser().getUid());
accountReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() != 0) {
callback.onSuccess(dataSnapshot.getValue(User.class));
} else {
callback.onFailure(new Exception());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
} catch (NullPointerException e) {
e.printStackTrace();
callback.onFailure(e);
}
}
@Override
public void onLoadNotification(final GetNotificationCallback callback) {
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER).child(mAuth.getCurrentUser().getUid()).child(DOCUMENT_NAME_MESSAGE);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<Notification> list = new ArrayList<>(0);
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
list.add(snapshot.getValue(Notification.class));
}
callback.onSuccess(list);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
@Override
public void onReadNotification(GetCommonCallback callback, final List<Notification> notifications) {
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER).child(mAuth.getCurrentUser().getUid()).child(DOCUMENT_NAME_MESSAGE);
for (int i = 0; i < notifications.size(); i++) {
reference.child(String.valueOf(notifications.get(i).getKey())).setValue(notifications.get(i));
}
}
@Override
public void onRemove(final GetCommonCallback callback, Constants.ListsFilterType filterType, final String date) {
DatabaseReference reference = null;
String tmp = null;
switch (filterType) {
case MATCH_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_MATCH).child(date).child(mAuth.getCurrentUser().getUid());
tmp = String.valueOf(FLAG_MATCH_LIST);
break;
case RECRUITMENT_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_RECRUITMENT).child(date).child(mAuth.getCurrentUser().getUid());
tmp = String.valueOf(FLAG_RECRUITMENT_LIST);
break;
case PLAYER_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_PLAYER).child(date).child(mAuth.getCurrentUser().getUid());
tmp = String.valueOf(FLAG_PLAYER_LIST);
break;
}
final String flag = tmp;
reference.setValue(null).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
final DatabaseReference userReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER).child(mAuth.getCurrentUser().getUid()).child(DOCUMENT_NAME_MESSAGE);
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Notification notification = childSnapshot.getValue(Notification.class);
if (notification.getDate().equals(date)) {
if (notification.getFlag().equals(flag)) {
userReference.child(String.valueOf(notification.getKey())).setValue(null).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e.getCause());
}
});
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e.getCause());
}
});
}
@Override
public void onLoadMatch(final GetInformationCallback callback, boolean isHome, final String date, final String enemy, final String flag) {
if (isHome) {
DatabaseReference reference = null;
if (flag != null) {
switch (Integer.parseInt(flag)) {
case FLAG_MATCH_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_MATCH).child(date).child(mAuth.getCurrentUser().getUid());
break;
case FLAG_RECRUITMENT_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_RECRUITMENT).child(date).child(mAuth.getCurrentUser().getUid());
break;
case FLAG_PLAYER_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_PLAYER).child(date).child(mAuth.getCurrentUser().getUid());
break;
}
} else {
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_MATCH).child(date).child(mAuth.getCurrentUser().getUid());
}
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
SystemUtils.Dlog.d(dataSnapshot.getValue().toString());
callback.onSuccess(dataSnapshot.getValue(Information.class));
} catch (NullPointerException e) {
callback.onFailure(e);
e.printStackTrace();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
} else {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
User user = childSnapshot.getValue(User.class);
if (enemy.equals(user.getTeam())) {
String uid = user.getUid();
DatabaseReference matchReference = null;
if (flag != null) {
switch (Integer.parseInt(flag)) {
case FLAG_MATCH_LIST:
matchReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_MATCH).child(date).child(uid);
break;
case FLAG_RECRUITMENT_LIST:
matchReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_RECRUITMENT).child(date).child(uid);
break;
case FLAG_PLAYER_LIST:
matchReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_PLAYER).child(date).child(uid);
break;
}
} else {
matchReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_MATCH).child(date).child(uid);
}
matchReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
SystemUtils.Dlog.d(dataSnapshot.getValue().toString());
callback.onSuccess(dataSnapshot.getValue(Information.class));
} catch (NullPointerException e) {
callback.onFailure(e);
e.printStackTrace();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
break;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
@Override
public void onLoadEnemyData(final GetUserCallback callback, final String enemy) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
User user = childSnapshot.getValue(User.class);
if (user.getTeam().equals(enemy)) {
callback.onSuccess(user);
break;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
@Override
public void onAgree(final GetSendMessageCallback callback, final Information information, final String title, final String message, final String flag) {
information.setConnect(true);
DatabaseReference reference = null;
switch (Integer.parseInt(flag)) {
case FLAG_MATCH_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_MATCH)
.child(DialogUtils.getFormattedDate(information.getDate(), TYPE_COLLECTION)).child(mAuth.getCurrentUser().getUid());
break;
case FLAG_RECRUITMENT_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_RECRUITMENT)
.child(DialogUtils.getFormattedDate(information.getDate(), TYPE_COLLECTION)).child(mAuth.getCurrentUser().getUid());
break;
case FLAG_PLAYER_LIST:
reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_PLAYER)
.child(DialogUtils.getFormattedDate(information.getDate(), TYPE_COLLECTION)).child(mAuth.getCurrentUser().getUid());
break;
}
reference.setValue(information).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final String token = getTokenOfRrecipient(dataSnapshot, information.getEnemy(), Constants.TYPE_RESPONSE);
if (token != null) {
Data data = new Data();
data.setTitle(title);
data.setMessage(message);
data.setSender(information.getTeam());
data.setDate(DialogUtils.getFormattedDate(information.getDate(), TYPE_COLLECTION));
data.setType(TYPE_RESPONSE);
data.setPlace(information.getPlace());
data.setFlag(flag);
Send send = new Send();
send.setTo(token);
send.setData(data);
Call<Void> call = service.sendMessage(send);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull final Call<Void> call, @NonNull Response<Void> response) {
if (response.isSuccessful()) {
DatabaseReference battleReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_BATTLE)
.child(mAuth.getCurrentUser().getUid()).child(DialogUtils.getFormattedDate(information.getDate(), TYPE_COLLECTION)).child(flag);
battleReference.setValue(new Battle(information.getEnemy(), DialogUtils.getFormattedDate(information.getDate(), TYPE_COLLECTION), information.getPlace(), true, flag))
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
} else {
callback.onError();
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
callback.onFailure(t);
}
});
} else {
callback.onError();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
}
@Override
public void onUpdateNotice(GetCommonCallback callback, boolean on, Constants.NoticeFilterType requestType) {
String type = null;
switch (requestType) {
case SQAUD:
type = DOCUMENT_NAME_SQUAD;
break;
case NOTICE:
type = DOCUMENT_NAME_NOTICE;
break;
case EVENT:
type = DOCUMENT_NAME_EVENT;
break;
}
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER).child(mAuth.getCurrentUser().getUid())
.child(DOCUMENT_NAME_NOTICE).child(type);
reference.setValue(on);
}
@Override
public void onRemoveNotification(final GetCommonCallback callback) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER).child(mAuth.getCurrentUser().getUid()).child(DOCUMENT_NAME_MESSAGE);
reference.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
}
@Override
public void onUpdateToken(final GetCommonCallback callback, final String token) {
try {
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
user.setToken(token);
reference.setValue(user).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
} catch (NullPointerException e) {
e.printStackTrace();
callback.onFailure(e);
}
}
@Override
public void onSubscribe(final GetChattingCallback callback, String date, String roomName) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_CHATTING).child(date).child(roomName);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<Chatting> chattingList = new ArrayList<>(0);
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
chattingList.add(snapshot.getValue(Chatting.class));
}
callback.onSuccess(chattingList);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
@Override
public void onChat(final GetCommonCallback callback, final Chatting chatting, final String title, final String date, final String roomName) {
final String to = roomName.replace(chatting.getUid(), "");
DatabaseReference sendReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER);
sendReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final String token = getTokenOfRrecipient(dataSnapshot, to, Constants.TYPE_CHATTING);
if (token != null) {
Data data = new Data();
data.setTitle(title);
data.setMessage(roomName);
data.setSender(chatting.getFrom());
data.setDate(date);
data.setType(TYPE_CHATTING);
Send send = new Send();
send.setTo(token);
send.setData(data);
Call<Void> call = service.sendMessage(send);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
if (response.isSuccessful()) {
callback.onSuccess();
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
callback.onFailure(t);
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
final DatabaseReference storeReference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_CHATTING).child(date).child(roomName);
storeReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String key = null;
if (dataSnapshot.getChildrenCount() == 0) {
key = INIT;
} else {
for (DataSnapshot parentSnapshot : dataSnapshot.getChildren()) {
key = String.valueOf(Integer.parseInt(parentSnapshot.getKey()) + 1);
}
}
chatting.setKey(Integer.parseInt(key));
chatting.setCheck(false);
storeReference.child(key).setValue(chatting).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public void onSaveIntroduce(final GetCommonCallback callback, User user) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_USER).child(mAuth.getCurrentUser().getUid());
reference.setValue(user).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
}
@Override
public void onUpdateReadMessages(final GetCommonCallback callback, List<Chatting> chattingList, String room, String date) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_CHATTING).child(date).child(room);
reference.setValue(chattingList).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
callback.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
callback.onFailure(e);
}
});
}
@Override
public void onQuickMatch(final GetQuickListCallback callback, final String team, final String uid, final String region, final String date, final String rule) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(COLLECTION_NAME_MATCH).child(date.replace("-", ""));
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<Information> list = new ArrayList<>(0);
List<Information> quickList = new ArrayList<>(0);
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
list.add(childSnapshot.getValue(Information.class));
}
for (int i = 0; i < list.size(); i++) {
if (!list.get(i).isConnect() && !list.get(i).getTeam().equals(team)) {
boolean isJoin = false;
for (int j = 0; j < list.get(i).getJoin().size(); j++) {
if (list.get(i).getJoin().get(j).equals(uid)) {
isJoin = !isJoin;
}
}
if (!isJoin) {
if (list.get(i).getRegion().equals(region)) {
if (rule != null) {
if (list.get(i).getRule().equals(rule)) {
quickList.add(list.get(i));
}
} else {
quickList.add(list.get(i));
}
}
}
}
}
if (quickList.size() != 0) {
int random = new Random().nextInt(quickList.size());
callback.onSuccess(quickList.get(random));
} else {
callback.onError();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
callback.onFailure(databaseError.toException());
}
});
}
@Override
public void onAuth(final GetAuthCallback callback, Activity activity, String phoneNumber, final String authCode) {
phoneNumber = COUNTRY_FORMAT + phoneNumber.substring(1, phoneNumber.length());
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
SystemUtils.Dlog.v("onVerificationCompleted : " + phoneAuthCredential.getSmsCode());
if (TextUtils.isEmpty(authCode)) {
callback.onSuccessfullyTransfer(phoneAuthCredential.getSmsCode());
} else {
if (phoneAuthCredential.getSmsCode().equals(authCode)) {
callback.onSuccessfullyAuth();
} else {
callback.onUnsuccessfullyAuth();
}
}
}
@Override
public void onVerificationFailed(FirebaseException e) {
SystemUtils.Dlog.e("onVerificationFailed : " + e.getMessage());
if (e instanceof FirebaseAuthInvalidCredentialsException) {
SystemUtils.Dlog.e("FirebaseAuthInvalidCredentialsException : " + e.getMessage());
} else if (e instanceof FirebaseTooManyRequestsException) {
SystemUtils.Dlog.e("FirebaseTooManyRequestsException : " + e.getMessage());
}
callback.onFailure(e);
}
};
PhoneAuthProvider.getInstance().verifyPhoneNumber(phoneNumber, EXPIRATION_TIME, TimeUnit.SECONDS, activity, mCallbacks);
}
/**
* 팀명 중복 체크
*
* @author kxxcn
* @since 2018-05-30 오후 5:55
*/
private boolean isDuplicate(String team, String fixedTeam) {
boolean rtn = false;
if (team.equals(fixedTeam)) {
rtn = true;
}
return rtn;
}
/**
* 상대방 토큰 획득
*
* @author kxxcn
* @since 2018-06-25 오후 12:43
*/
private String getTokenOfRrecipient(DataSnapshot dataSnapshot, String to, int type) {
List<User> userList = new ArrayList<>(0);
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
userList.add(childSnapshot.getValue(User.class));
}
User user = null;
for (int i = 0; i < userList.size(); i++) {
switch (type) {
case Constants.TYPE_REQUEST:
if (to.equals(userList.get(i).getEmail())) {
user = userList.get(i);
break;
}
break;
case Constants.TYPE_RESPONSE:
if (to.equals(userList.get(i).getTeam())) {
user = userList.get(i);
break;
}
break;
case Constants.TYPE_CHATTING:
if (to.equals(userList.get(i).getUid())) {
user = userList.get(i);
break;
}
break;
}
}
return user.getToken();
}
}
| 35.216915 | 204 | 0.710027 |
4e6edc07c40e61204ac065424414795aa39cce6c | 3,081 | /*
* 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.usergrid.rest;
import java.util.Map;
import javax.ws.rs.NotAllowedException;
import javax.ws.rs.ServerErrorException;
import org.junit.Test;
import org.apache.usergrid.persistence.Entity;
import org.apache.usergrid.persistence.index.utils.UUIDUtils;
import org.apache.usergrid.rest.test.resource.AbstractRestIT;
import org.apache.usergrid.rest.test.resource.model.Organization;
import org.apache.usergrid.rest.test.resource.model.Token;
import org.apache.usergrid.services.exceptions.UnsupportedServiceOperationException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ExceptionResourceIT extends AbstractRestIT{
@Test
public void testNonExistingEndpoint(){
try {
clientSetup.getRestClient()
.pathResource( getOrgAppPath( "non_existant_delete_endpoint" ) ).delete( );
fail("Should have thrown below exception");
}catch(NotAllowedException e){
assertEquals( 405,e.getResponse().getStatus());
}
}
//test uncovered endpoints
@Test
public void testNotImplementedException(){
try {
clientSetup.getRestClient().management().orgs().delete( true );
fail("Should have thrown below exception");
}catch(NotAllowedException e){
assertEquals( 405,e.getResponse().getStatus());
}
}
@Test
public void testDeleteFromWrongEndpoint(){
try {
clientSetup.getRestClient()
.pathResource( clientSetup.getOrganizationName() + "/" + clientSetup.getAppName() ).delete( );
fail("Should have thrown below exception");
}catch(NotAllowedException e){
assertEquals( 405,e.getResponse().getStatus());
}
}
@Test
public void testUnsupportedServiceOperation(){
try {
clientSetup.getRestClient()
.pathResource( getOrgAppPath( "users" ) ).delete( );
fail("Should have thrown below exception");
}catch(NotAllowedException e){
assertEquals( 405,e.getResponse().getStatus());
}
}
}
| 33.48913 | 118 | 0.689062 |
55d886ce3146df1d5cb668ba50690c798ce1c029 | 4,077 | /*
* Copyright 2018 Vrije Universiteit Amsterdam, The Netherlands
*
* 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 nl.junglecomputing.common_source_identification.device_mem_cache;
import org.slf4j.Logger;
import ibis.cashmere.constellation.Cashmere;
import ibis.cashmere.constellation.CashmereNotAvailable;
import ibis.cashmere.constellation.Device;
import ibis.constellation.util.MemorySizes;
// import sun.misc.VM; not possible since Java 9
import nl.junglecomputing.common_source_identification.GetMaxDirectMem;
@SuppressWarnings("restriction")
public class CacheConfig {
static Logger logger = CommonSourceIdentification.logger;
public static int nrNoisePatternsForSpace(long space, long sizeNoisePattern) {
return (int) Math.floor(space / (double) sizeNoisePattern);
}
// get the number of noise patterns that the many-core device can hold
public static int getNrNoisePatternsDevice(long sizeNoisePattern, long toBeReserved) {
try {
Device device = Cashmere.getDevice("grayscaleKernel");
long spaceDevice = device.getMemoryCapacity();
long spaceForNoisePatterns = spaceDevice - toBeReserved - 500 * MemorySizes.MB;
int nrNoisePatterns = nrNoisePatternsForSpace(spaceForNoisePatterns, sizeNoisePattern);
if (logger.isDebugEnabled()) {
logger.debug("device memory: " + MemorySizes.toStringBytes(spaceDevice));
logger.debug("to be reserved: " + MemorySizes.toStringBytes(toBeReserved));
logger.debug("space for patterns on device: " + MemorySizes.toStringBytes(spaceForNoisePatterns));
logger.debug("device holds a maximum of {} noise patterns", nrNoisePatterns);
}
return nrNoisePatterns;
} catch (CashmereNotAvailable e) {
throw new Error(e);
}
}
public static int getNrNoisePatternsMemory(int sizeNoisePattern, long spaceForGrayscale) {
// long spaceForNoisePatterns = VM.maxDirectMemory() - spaceForGrayscale;
long spaceForNoisePatterns = GetMaxDirectMem.maxDirectMemory() - spaceForGrayscale;
int nrNoisePatterns = nrNoisePatternsForSpace(spaceForNoisePatterns, sizeNoisePattern);
if (logger.isDebugEnabled()) {
logger.debug("space for noise patterns: " + MemorySizes.toStringBytes(spaceForNoisePatterns));
logger.debug(String.format("The memory will hold a maximum of " + "%d noise patterns", nrNoisePatterns));
}
return nrNoisePatterns;
}
public static int initializeCache(Device device, int height, int width, long toBeReserved, int nrThreads) {
int sizeNoisePattern = height * width * 4;
int sizeNoisePatternFreq = sizeNoisePattern * 2;
if (logger.isDebugEnabled()) {
logger.debug("Size of noise pattern: " + MemorySizes.toStringBytes(sizeNoisePattern));
logger.debug("Size of noise pattern freq: " + MemorySizes.toStringBytes(sizeNoisePatternFreq));
}
int nrNoisePatternsFreqDevice = getNrNoisePatternsDevice(sizeNoisePatternFreq, toBeReserved);
int memReservedForGrayscale = height * width * 3 * nrThreads;
int nrNoisePatternsMemory = getNrNoisePatternsMemory(sizeNoisePattern, memReservedForGrayscale);
NoisePatternCache.initialize(device, height, width, nrNoisePatternsFreqDevice, nrNoisePatternsMemory);
return nrNoisePatternsFreqDevice;
}
public static void clearCaches() {
NoisePatternCache.clear();
}
}
| 43.83871 | 117 | 0.719402 |
ed24a6345b2becfc6ae737e2a5a6c000aa895333 | 3,273 | /*
* $Id: XmlDefinitionsSet.java 471754 2006-11-06 14:55:09Z husted $
*
* 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.struts.tiles.xmlDefinition;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.struts.tiles.NoSuchDefinitionException;
/**
* A set of definitions read from XML definitions file.
*/
public class XmlDefinitionsSet
{
/** Defined definitions. */
protected Map definitions;
/**
* Constructor.
*/
public XmlDefinitionsSet()
{
definitions = new HashMap();
}
/**
* Put definition in set.
* @param definition Definition to add.
*/
public void putDefinition(XmlDefinition definition)
{
definitions.put( definition.getName(), definition );
}
/**
* Get requested definition.
* @param name Definition name.
*/
public XmlDefinition getDefinition(String name)
{
return (XmlDefinition)definitions.get( name );
}
/**
* Get definitions map.
*/
public Map getDefinitions()
{
return definitions;
}
/**
* Resolve extended instances.
*/
public void resolveInheritances() throws NoSuchDefinitionException
{
// Walk through all definitions and resolve individual inheritance
Iterator i = definitions.values().iterator();
while( i.hasNext() )
{
XmlDefinition definition = (XmlDefinition)i.next();
definition.resolveInheritance( this );
} // end loop
}
/**
* Add definitions from specified child definitions set.
* For each definition in child, look if it already exists in this set.
* If not, add it, if yes, overload parent's definition with child definition.
* @param child Definition used to overload this object.
*/
public void extend( XmlDefinitionsSet child )
{
if(child==null)
return;
Iterator i = child.getDefinitions().values().iterator();
while( i.hasNext() )
{
XmlDefinition childInstance = (XmlDefinition)i.next();
XmlDefinition parentInstance = getDefinition(childInstance.getName() );
if( parentInstance != null )
{
parentInstance.overload( childInstance );
}
else
putDefinition( childInstance );
} // end loop
}
/**
* Get String representation.
*/
public String toString()
{
return "definitions=" + definitions.toString() ;
}
}
| 27.737288 | 81 | 0.655668 |
d272b7bf9889328ecc3b09099c5b0518bcea38d8 | 3,235 | package com.sdgcrm.application.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity()
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String LOGIN_PROCESSING_URL = "/login";
private static final String LOGIN_FAILURE_URL = "/login?error";
private static final String LOGIN_URL = "/login";
private static final String LOGOUT_SUCCESS_URL = "/login";
private static final String LOGIN_SUCCESSFUL = "/dashboard";
@org.springframework.context.annotation.Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
private javax.sql.DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.requestCache().requestCache(new CustomRequestCache())
.and()
.authorizeRequests().antMatchers("/signup").permitAll()
.requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()
.anyRequest().authenticated()
.and().formLogin()
.loginPage(LOGIN_URL).permitAll()
.loginProcessingUrl(LOGIN_PROCESSING_URL)
.failureUrl(LOGIN_FAILURE_URL)
.and().logout().logoutSuccessUrl(LOGOUT_SUCCESS_URL);
}
@org.springframework.context.annotation.Bean
public CustomRequestCache requestCache() { //
return new CustomRequestCache();
}
@Value("${spring.queries.users-query}")
private String usersQuery;
@Value("${spring.queries.roles-query}")
private String rolesQuery;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.
jdbcAuthentication()
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource)
.passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers(
"/VAADIN/**",
"/favicon.ico",
"/robots.txt",
"/manifest.webmanifest",
"/sw.js",
"/offline.html",
"/icons/**",
"/images/**",
"/styles/**",
"/h2-console/**");
}
} | 35.549451 | 107 | 0.673879 |
11efbf0b92dcacdd131167ffd8060237f2f5a8b0 | 764 | package com.hotmail.or_dvir.easysettings_dialogs.events;
import com.hotmail.or_dvir.easysettings_dialogs.pojos.EditTextSettingsObject;
/**
* an event that is sent when the value of an {@link EditTextSettingsObject}
* is changed
*/
public class EditTextSettingsValueChangedEvent
{
private EditTextSettingsObject editTextSettingsObj;
/**
*
* @param editTextSettingsObj the {@link EditTextSettingsObject} whose value was changed
*/
public EditTextSettingsValueChangedEvent(EditTextSettingsObject editTextSettingsObj)
{
this.editTextSettingsObj = editTextSettingsObj;
}
/**
*
* @return the {@link EditTextSettingsObject} whose value was changed
*/
public EditTextSettingsObject getEditTextSettingsObj()
{
return editTextSettingsObj;
}
} | 25.466667 | 89 | 0.791885 |
a0c77277f68f42f18dbbfe3c2901285ef72a9b7e | 1,243 | package hellogbye.com.hellogbyeandroid.views;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by arisprung on 10/19/16.
*/
public class WrapContentViewPager extends ViewPager {
private int mCurrentPagePosition = 0;
public WrapContentViewPager(Context context) {
super(context);
}
public WrapContentViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
View child = getChildAt(mCurrentPagePosition);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
}
} catch (Exception e) {
e.printStackTrace();
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void reMeasureCurrentPage(int position) {
mCurrentPagePosition = position;
requestLayout();
}
} | 28.906977 | 105 | 0.666935 |
04a59a018874565a9fe22cecf298f2e961db23c8 | 1,389 | package org.jkva;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Jan-Kees van Andel - @jankeesvanandel
*/
public class Config {
private String parentPath;
private List<ProjectModule> modules = new ArrayList<ProjectModule>();
private String distPath;
private File projectBase;
private File basedir;
public List<ProjectModule> getModules() {
return modules;
}
public void setModules(List<ProjectModule> modules) {
this.modules = modules;
}
public String getParentPath() {
return parentPath;
}
public void setParentPath(String parentPath) {
if (parentPath == null || parentPath.isEmpty()) {
this.parentPath = null;
} else {
this.parentPath = parentPath;
}
}
public String getDistPath() {
return distPath;
}
public void setDistPath(String distPath) {
if (distPath == null) {
this.distPath = "";
} else {
this.distPath = distPath;
}
}
public File getProjectBase() {
return projectBase;
}
public void setProjectBase(File projectBase) {
this.projectBase = projectBase;
}
public File getBasedir() {
return basedir;
}
public void setBasedir(File basedir) {
this.basedir = basedir;
}
}
| 21.369231 | 73 | 0.605472 |
fa3643e2a5d51b0407022fc9d7083992299f64d1 | 4,381 | package org.agrs.jcuda;
import jcuda.Pointer;
import jcuda.Sizeof;
import jcuda.driver.*;
import java.io.IOException;
import static jcuda.driver.JCudaDriver.*;
public class CudaAnalyzer {
private static CUfunction bytePacketKernel;
private static CUdeviceptr dNumRepeats;
private static CUdeviceptr dPacketInputPointer;
private static CUdeviceptr dPacketIndices;
private static CUdeviceptr dNumHTTPPackets;
private static long totalComputeTime;
private static long totalAllocTime;
public static void init() throws IOException {
System.out.println("[CUDA] INITIALIZING");
totalComputeTime = 0;
totalAllocTime = 0;
// Enable exceptions and omit all subsequent error checks
JCudaDriver.setExceptionsEnabled(true);
// Initialize the driver and create a context for the first device.
cuInit(0);
CUdevice device = new CUdevice();
cuDeviceGet(device, 0);
CUcontext context = new CUcontext();
cuCtxCreate(context, 0, device);
// Load the ptx file.
CUmodule module = new CUmodule();
cuModuleLoad(module, "./target/kernels/JCudaPacketKernel.ptx");
bytePacketKernel = new CUfunction();
cuModuleGetFunction(bytePacketKernel, module, "bytePacketKernel");
dNumRepeats = new CUdeviceptr();
dPacketInputPointer = new CUdeviceptr();
dPacketIndices = new CUdeviceptr();
dNumHTTPPackets = new CUdeviceptr();
cuModuleGetGlobal(dNumRepeats, new long[1], module,
"numRepeats");
cuMemAlloc(dPacketInputPointer, Analyze.ABSOLUTE_MAXLEN * Sizeof.BYTE);
cuMemAlloc(dPacketIndices, Analyze.ABSOLUTE_MAXLEN * Sizeof.INT);
cuMemAlloc(dNumHTTPPackets, Analyze.ABSOLUTE_MAXLEN * Sizeof.BYTE);
cuMemcpyHtoD(dNumRepeats, Pointer.to(new int[]{Analyze.NUM_REPEATS}), Sizeof.INT);
}
public static long processSinglePointer(byte[] packets, int[] indices, int numPackets) {
long time0 = System.nanoTime();
System.out.print("[CUDA] ALLOCATING AND COPYING... ");
cuMemcpyHtoD(dPacketInputPointer,
Pointer.to(packets),
packets.length * Sizeof.BYTE);
cuMemcpyHtoD(dPacketIndices, Pointer.to(indices),
indices.length * Sizeof.INT);
// Set up the kernel parameters
Pointer kernelParams = Pointer.to(
Pointer.to(new int[]{numPackets}),
Pointer.to(dPacketInputPointer),
Pointer.to(dPacketIndices),
Pointer.to(dNumHTTPPackets)
);
long time1 = System.nanoTime();
totalAllocTime += (time1 - time0);
System.out.printf("%5.3fms%n", (time1 - time0) / 1e6);
System.out.print("[CUDA] COMPUTING... ");
// Call the kernel function.
int blockDimX = 256;
int gridDimX = (int) Math.ceil((double) numPackets / blockDimX);
time0 = System.nanoTime();
cuLaunchKernel(bytePacketKernel,
gridDimX, 1, 1, // Grid dimension
blockDimX, 1, 1, // Block dimension
0, null, // Shared memory size and stream
kernelParams, null // Kernel- and extra parameters
);
cuCtxSynchronize();
time1 = System.nanoTime();
totalComputeTime += (time1 - time0);
System.out.printf("%5.3fms%n", (time1 - time0) / 1e6);
byte[] numHTTPPackets = new byte[numPackets];
System.out.print("[CUDA] GATHERING RESULTS... ");
time0 = System.nanoTime();
cuMemcpyDtoH(Pointer.to(numHTTPPackets), dNumHTTPPackets, numPackets
* Sizeof.BYTE);
time1 = System.nanoTime();
System.out.printf("%5.3fms%n", (time1 - time0) / 1e6);
long sum = 0;
for (int i = 0; i < numPackets; i++) {
if (numHTTPPackets[i] > 0)
sum++;
}
return sum;
}
public static void close() {
System.out.println("[CUDA] CLOSING");
cuMemFree(dPacketInputPointer);
cuMemFree(dNumHTTPPackets);
cuMemFree(dPacketIndices);
System.out.printf("[CUDA] TOTAL ALLOCATION TIME: %5.3fms%n", totalAllocTime / 1e6);
System.out.printf("[CUDA] TOTAL COMPUTE TIME: %5.3fms%n", totalComputeTime / 1e6);
}
}
| 32.213235 | 92 | 0.619037 |
33de5429dda9ff1405a7f794a849eccc86ac8bb8 | 1,287 | module com.github.longkerdandy.viki.home.hap {
// for jackson only
opens com.github.longkerdandy.viki.home.hap.model to com.fasterxml.jackson.databind;
opens com.github.longkerdandy.viki.home.hap.model.property to com.fasterxml.jackson.databind;
opens com.github.longkerdandy.viki.home.hap.http.request to com.fasterxml.jackson.databind;
opens com.github.longkerdandy.viki.home.hap.http.response to com.fasterxml.jackson.databind;
// project api
requires com.github.longkerdandy.viki.home.api;
// database migration
requires org.flywaydb.core;
// mDNS
requires jmdns;
// encryption
requires srp6a; // TODO: Automatic Module Name
requires hkdf; // TODO: Automatic Module Name
requires net.i2p.crypto.eddsa;
requires curve25519.java; // TODO: Automatic Module Name
// netty
requires io.netty.buffer;
requires io.netty.codec;
requires io.netty.codec.http;
requires io.netty.common;
requires io.netty.handler;
requires io.netty.transport;
// url utils
requires org.apache.httpcomponents.httpcore;
requires org.apache.httpcomponents.httpclient;
// service
provides com.github.longkerdandy.viki.home.ext.ControllerExtFactory
with com.github.longkerdandy.viki.home.hap.HomeKitProtocolExtFactory;
} | 33 | 95 | 0.752137 |
afedbf146cf509f87e965907c55d8979d18df938 | 6,278 | import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
public static GamePanel instance = null;
public static final int PWIDTH = 800; // size of panel
public static final int PHEIGHT = 600;
private Thread animator; // for the animation
private boolean running = false; // stops the animation
private Graphics2D dbg;
private int FPS, SFPS;
private long CurrentSecond = 0;
private long NewSecond = 0;
private Canvas gui = null;
private BufferStrategy strategy = null;
public MyCanvas canvasDraw = null;
public Random rnd;
//TODO tirar isso daqui
public BufferedImage heroiImage;
public BufferedImage background;
public GamePanel() {
instance = this;
heroiImage = loadImage("logo_ckl_size.png");
background = loadImage("nebula.jpg");
rnd = new Random();
setBackground(Color.white); // white background
setPreferredSize(new Dimension(PWIDTH, PHEIGHT));
gui = new Canvas();
gui.setSize(WIDTH, HEIGHT);
setLayout(new BorderLayout());
add(gui, BorderLayout.CENTER);
setFocusable(true); // create game components
requestFocus(); // JPanel now receives key events
// Add KeyListner
gui.addKeyListener(new KeyAdapter() {
// listen for esc, q, end, ctrl-c
public void keyPressed(KeyEvent e) {
if(canvasDraw != null) {
canvasDraw.keyPressed(e);
}
}
public void keyReleased(KeyEvent e) {
if(canvasDraw != null) {
canvasDraw.keyReleased(e);
}
}
});
// Add MouseWheelListener
gui.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if(canvasDraw != null) {
canvasDraw.mouseWheelMoved(e);
}
}
});
// Add MouseMotionListener
gui.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
if(canvasDraw != null) {
canvasDraw.mouseMoved(e);
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(canvasDraw != null) {
canvasDraw.mouseDragged(e);
}
}
});
// Add MouseListener
gui.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if(canvasDraw != null) {
canvasDraw.mousePressed(e);
}
}
public void mouseReleased(MouseEvent e) {
if(canvasDraw != null) {
canvasDraw.mouseReleased(e);
}
}
public void mouseExited(MouseEvent e) {
if(canvasDraw != null) {
canvasDraw.mouseExited(e);
}
}
public void mouseEntered(MouseEvent e) {
if(canvasDraw != null) {
canvasDraw.mouseEntered(e);
}
}
public void mouseClicked(MouseEvent e) {
if(canvasDraw != null) {
canvasDraw.mouseClicked(e);
}
}
});
canvasDraw = new CanvasMain();
} // end of GamePanel()
public void addNotify() {
super.addNotify(); // creates the peer
startGame(); // start the thread
}
private void startGame()
// initialise and start the thread
{
if (animator == null || !running) {
animator = new Thread(this);
animator.start();
}
} // end of startGame()
public void stopGame()
// called by the user to stop execution
{
running = false;
}
public void run()
/* Repeatedly update, render, sleep */
{
running = true;
long diffTime, oldTime;
diffTime = 0;
oldTime = System.currentTimeMillis();
CurrentSecond = (long) (oldTime / 1000);
gui.createBufferStrategy(2);
strategy = gui.getBufferStrategy();
while (running) {
dbg = (Graphics2D) strategy.getDrawGraphics();
dbg.setClip(0, 0, PWIDTH, PHEIGHT);
dbg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
gameUpdate(diffTime);
gameRender();
dbg.dispose();
strategy.show();
try {
Thread.sleep(1); // sleep a bit
} catch (InterruptedException ex) {
}
diffTime = System.currentTimeMillis() - oldTime;
oldTime = System.currentTimeMillis();
NewSecond = (long) (oldTime / 1000);
if (NewSecond != CurrentSecond) {
FPS = SFPS;
CurrentSecond = NewSecond;
SFPS = 1;
} else {
SFPS++;
}
}
System.exit(0); // so enclosing JFrame/JApplet exits
} // end of run()
private void gameUpdate(long diffTime) {
// update game elements
if(canvasDraw != null) {
canvasDraw.gameUpdate(diffTime);
}
}
private void gameRender()
// draw the current frame to an image buffer
{
// clear the background
dbg.setColor(Color.black);
dbg.fillRect(0, 0, PWIDTH, PHEIGHT);
// draw game elements
if(canvasDraw != null) {
canvasDraw.gameRender(dbg);
}
dbg.setFont(new Font("Serif", Font.BOLD, 12));
// draw FPS
dbg.setColor(Color.WHITE);
dbg.drawString("FPS: " + FPS, 20, 20);
} // end of gameRender()
public static void main(String args[]) {
GamePanel ttPanel = new GamePanel();
// create a JFrame to hold the timer test JPanel
JFrame app = new JFrame("Game Core");
app.getContentPane().add(ttPanel, BorderLayout.CENTER);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.pack();
app.setResizable(false);
app.setVisible(true);
} // end of main()
public BufferedImage loadImage(String filename) {
try {
BufferedImage imgtmp = ImageIO.read(getClass().getResource(filename));
BufferedImage imgfinal = new BufferedImage(imgtmp.getWidth(), imgtmp.getHeight(),
BufferedImage.TYPE_INT_ARGB);
imgfinal.getGraphics().drawImage(imgtmp, 0, 0, null);
return imgfinal;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
} // end of GamePanel class
| 22.262411 | 102 | 0.682383 |
cb19bc172adb5f28bd2607946138338fcaed9365 | 700 | /**
*
*/
package com.tvd12.ezyfox.util;
import java.util.Map;
/**
* Each model in application should have properties, and we think key/value is good idea
*
* @author tavandung12
*
*/
public interface EzyProperties extends EzyRoProperties {
/**
* put key and value to map
*
* @param key key
* @param value value
*/
void setProperty(Object key, Object value);
/**
* put all
*
* @param map the map to put
*/
void setProperties(Map<? extends Object, ? extends Object> map);
/**
* removes the mapping for a key from the map
*
* @param key the key
*/
void removeProperty(Object key);
}
| 17.948718 | 88 | 0.582857 |
4c1930e3cc907d7e8e655991ff6fc73f19bb3090 | 2,075 | package com.epam.jdi.light.elements.interfaces.base;
import com.epam.jdi.light.common.JDIAction;
import com.epam.jdi.light.elements.common.UIElement;
import com.epam.jdi.light.elements.complex.WebList;
import com.epam.jdi.tools.map.MapArray;
import org.openqa.selenium.By;
import java.util.List;
public interface ICoreElement extends IBaseElement {
UIElement core();
@JDIAction("Hover to '{name}'")
default void hover() { core().hover(); }
@JDIAction("Check that '{name}' is enabled")
default boolean isEnabled() { return core().isEnabled(); }
@JDIAction("Check that '{name}' is disabled")
default boolean isDisabled() { return !isEnabled(); }
@JDIAction("Check that '{name}' is displayed")
default boolean isDisplayed() { return core().isDisplayed(); }
@JDIAction("Check that '{name}' is hidden")
default boolean isHidden() { return !isDisplayed(); }
default void highlight(String color) { core().highlight(); }
default void highlight() { core().highlight(); }
default void show() { core().show(); }
default String attr(String name) { return core().attr(name); }
default MapArray<String, String> attrs() { return core().attrs(); }
default String css(String prop) {
return core().css(prop);
}
default boolean hasClass(String className) { return core().hasClass(className); }
default boolean hasAttribute(String attrName) { return core().hasAttribute(attrName); }
default String printHtml() { return core().printHtml(); }
default List<String> classes() {return core().classes(); }
default UIElement find(String by) {
return core().find(by);
}
default UIElement find(By by) {
return core().find(by);
}
default WebList finds(String by) {
return core().finds(by);
}
default WebList finds(By by) { return core().finds(by); }
default UIElement firstChild() { return core().firstChild(); }
default WebList childs() { return core().childs(); }
default String getTagName() {
return core().getTagName();
}
}
| 39.150943 | 91 | 0.666024 |
bb1fa3e90dde7a792fa59b766bdd07ab5a1ae2b5 | 17,143 | package no.nav.foreldrepenger.regler.uttak.fastsetteperiode;
import static no.nav.foreldrepenger.regler.uttak.fastsetteperiode.ManglendeSøktPeriodeUtil.bareFarRett;
import static no.nav.foreldrepenger.regler.uttak.fastsetteperiode.ManglendeSøktPeriodeUtil.fjernPerioderFørDato;
import static no.nav.foreldrepenger.regler.uttak.fastsetteperiode.ManglendeSøktPeriodeUtil.fjernPerioderFørEndringsdatoVedRevurdering;
import static no.nav.foreldrepenger.regler.uttak.fastsetteperiode.ManglendeSøktPeriodeUtil.lagManglendeSøktPeriode;
import static no.nav.foreldrepenger.regler.uttak.fastsetteperiode.ManglendeSøktPeriodeUtil.slåSammenUttakForBeggeParter;
import static no.nav.foreldrepenger.regler.uttak.fastsetteperiode.ManglendeSøktPeriodeUtil.utledSenesteLovligeStartdatoVedAdopsjon;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import no.nav.foreldrepenger.regler.uttak.fastsetteperiode.grunnlag.OppgittPeriode;
import no.nav.foreldrepenger.regler.uttak.fastsetteperiode.grunnlag.RegelGrunnlag;
import no.nav.foreldrepenger.regler.uttak.fastsetteperiode.grunnlag.Søknadstype;
import no.nav.foreldrepenger.regler.uttak.felles.Virkedager;
import no.nav.foreldrepenger.regler.uttak.felles.grunnlag.LukketPeriode;
import no.nav.foreldrepenger.regler.uttak.felles.grunnlag.Periode;
import no.nav.foreldrepenger.regler.uttak.felles.grunnlag.Stønadskontotype;
import no.nav.foreldrepenger.regler.uttak.konfig.Konfigurasjon;
import no.nav.foreldrepenger.regler.uttak.konfig.Parametertype;
final class ManglendeSøktePerioderForSammenhengendeUttakTjeneste {
private ManglendeSøktePerioderForSammenhengendeUttakTjeneste() {
// Skal ikke instansieres
}
static List<OppgittPeriode> finnManglendeSøktePerioder(RegelGrunnlag grunnlag, Konfigurasjon konfigurasjon) {
var manglendePerioderIUkerForbeholdtMor = finnManglendeSøktIUkerForbeholdtMor(grunnlag, konfigurasjon);
var manglendePerioderIUkerFarMedAleneomsorg = finnManglendeSøktePerioderTilFarMedAleneomsorg(grunnlag);
List<OppgittPeriode> manglendePerioder = new ArrayList<>();
manglendePerioder.addAll(manglendePerioderIUkerFarMedAleneomsorg);
manglendePerioder.addAll(manglendePerioderIUkerForbeholdtMor);
var manglendeSøktePerioder = finnManglendeMellomliggendePerioder(
grunnlag, manglendePerioder);
manglendeSøktePerioder.addAll(manglendePerioderIUkerFarMedAleneomsorg);
manglendeSøktePerioder.addAll(finnPerioderVedAdopsjon(grunnlag));
manglendeSøktePerioder.addAll(manglendePerioderIUkerForbeholdtMor);
var trimmedePerioder = trimPerioder(grunnlag, manglendeSøktePerioder);
List<OppgittPeriode> samlet = new ArrayList<>();
for (var msp : trimmedePerioder) {
if (!contains(samlet, msp.getFom(), msp.getTom())) {
samlet.add(msp);
}
}
return samlet;
}
private static List<OppgittPeriode> trimPerioder(RegelGrunnlag grunnlag, List<OppgittPeriode> manglendeSøktePerioder) {
return manglendeSøktePerioder.stream()
.map(ManglendeSøktPeriodeUtil::fjernHelg)
.filter(Optional::isPresent)
.map(Optional::get)
.map(p -> fjernPerioderFørSkjæringstidspunktOpptjening(p, grunnlag))
.filter(Optional::isPresent)
.map(Optional::get)
.map(p -> fjernPerioderFørEndringsdatoVedRevurdering(p, grunnlag))
.filter(Optional::isPresent)
.map(Optional::get)
.sorted(Comparator.comparing(Periode::getFom))
.collect(Collectors.toList());
}
private static boolean contains(List<OppgittPeriode> list, LocalDate fom, LocalDate tom) {
return list.stream().anyMatch(item -> item.getFom().isEqual(fom) && item.getTom().isEqual(tom));
}
private static List<OppgittPeriode> finnPerioderVedAdopsjon(RegelGrunnlag grunnlag) {
if (grunnlag.getSøknad().gjelderAdopsjon()) {
var mspAdopsjon = utledManglendeSøktVedAdopsjon(grunnlag);
if (mspAdopsjon.isPresent()) {
return List.of(mspAdopsjon.get());
}
}
return Collections.emptyList();
}
private static List<OppgittPeriode> finnManglendeSøktIUkerForbeholdtMor(RegelGrunnlag grunnlag, Konfigurasjon konfigurasjon) {
if (grunnlag.getBehandling().isSøkerMor() && grunnlag.getSøknad().getType().gjelderTerminFødsel()) {
return utledManglendeForMorFraOppgittePerioder(grunnlag, konfigurasjon);
}
if (farSøkerFødselEllerTerminOgBareFarHarRett(grunnlag) && !grunnlag.getRettOgOmsorg().getAleneomsorg()) {
var oppholdFar = utledManglendeSøktForFar(grunnlag.getDatoer().getFamiliehendelse(),
grunnlag.getSøknad().getOppgittePerioder(), konfigurasjon);
if (oppholdFar.isPresent()) {
return List.of(oppholdFar.get());
}
}
return Collections.emptyList();
}
private static List<OppgittPeriode> finnManglendeSøktePerioderTilFarMedAleneomsorg(RegelGrunnlag grunnlag) {
if (isFarMedAleneomsorg(grunnlag)) {
var førstePeriode = grunnlag.getSøknad().getOppgittePerioder().get(0);
if (grunnlag.getDatoer().getFamiliehendelse().isBefore(førstePeriode.getFom())) {
var nyPeriode = lagManglendeSøktPeriode(grunnlag.getDatoer().getFamiliehendelse(),
førstePeriode.getFom().minusDays(1), Stønadskontotype.FORELDREPENGER);
return List.of(nyPeriode);
}
}
return Collections.emptyList();
}
private static Optional<OppgittPeriode> utledManglendeSøktVedAdopsjon(RegelGrunnlag grunnlag) {
var senesteLovligeStartdatoVedAdopsjon = utledSenesteLovligeStartdatoVedAdopsjon(grunnlag);
var førsteUttaksdatoSøknad = førsteUttaksdatoSøknad(grunnlag);
var førsteUttaksdatoAnnenpart = førsteUttaksdatoAnnenpart(grunnlag);
if (førsteUttaksdatoSøknad.isAfter(senesteLovligeStartdatoVedAdopsjon) && (førsteUttaksdatoAnnenpart.isEmpty()
|| førsteUttaksdatoAnnenpart.get().isAfter(senesteLovligeStartdatoVedAdopsjon))) {
LocalDate tom;
if (førsteUttaksdatoAnnenpart.isEmpty() || førsteUttaksdatoSøknad.isBefore(førsteUttaksdatoAnnenpart.get())) {
tom = førsteUttaksdatoSøknad.minusDays(1);
} else {
tom = førsteUttaksdatoAnnenpart.get().minusDays(1);
}
return Optional.of(lagManglendeSøktPeriode(senesteLovligeStartdatoVedAdopsjon, tom));
}
return Optional.empty();
}
private static Optional<LocalDate> førsteUttaksdatoAnnenpart(RegelGrunnlag grunnlag) {
if (grunnlag.getAnnenPart() == null || grunnlag.getAnnenPart().getUttaksperioder().isEmpty()) {
return Optional.empty();
}
return Optional.of(førsteFom(grunnlag.getAnnenPart().getUttaksperioder()));
}
private static LocalDate førsteUttaksdatoSøknad(RegelGrunnlag grunnlag) {
return førsteFom(grunnlag.getSøknad().getOppgittePerioder());
}
private static LocalDate førsteFom(List<? extends LukketPeriode> perioder) {
return perioder.stream().min(Comparator.comparing(LukketPeriode::getFom)).orElseThrow().getFom();
}
private static Optional<OppgittPeriode> utledManglendeSøktForFar(LocalDate familiehendelse,
List<OppgittPeriode> uttaksperioder,
Konfigurasjon konfigurasjon) {
var førstePeriode = uttaksperioder.get(0);
var ukerForbeholdtMor = konfigurasjon.getParameter(Parametertype.UTTAK_MØDREKVOTE_ETTER_FØDSEL_UKER, familiehendelse);
if (familiehendelse.plusWeeks(ukerForbeholdtMor).isBefore(førstePeriode.getFom())) {
var nyPeriode = lagManglendeSøktPeriode(familiehendelse.plusWeeks(ukerForbeholdtMor), førstePeriode.getFom().minusDays(1),
Stønadskontotype.FORELDREPENGER);
return Optional.of(nyPeriode);
}
return Optional.empty();
}
private static boolean farSøkerFødselEllerTermin(RegelGrunnlag grunnlag) {
return grunnlag.getBehandling().isSøkerFarMedMor() && erFødselEllerTermin(grunnlag);
}
private static boolean erFødselEllerTermin(RegelGrunnlag grunnlag) {
return grunnlag.getSøknad().getType().gjelderTerminFødsel();
}
private static List<OppgittPeriode> utledManglendeForMorFraOppgittePerioder(RegelGrunnlag grunnlag, Konfigurasjon konfigurasjon) {
var familiehendelseDato = grunnlag.getDatoer().getFamiliehendelse();
var uttakPerioder = slåSammenUttakForBeggeParter(grunnlag).stream()
.sorted(Comparator.comparing(Periode::getFom))
.collect(Collectors.toList());
var mspFørFødsel = finnManglendeSøktFørFødsel(uttakPerioder, familiehendelseDato,
grunnlag.getSøknad().getType(), grunnlag.getGyldigeStønadskontotyper(), konfigurasjon);
var mspEtterFødsel = finnPerioderEtterFødsel(uttakPerioder, familiehendelseDato,
grunnlag.getGyldigeStønadskontotyper(), konfigurasjon);
return Stream.of(mspFørFødsel, mspEtterFødsel)
.flatMap(Collection::stream)
.map(ManglendeSøktPeriodeUtil::fjernHelg)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
private static Optional<OppgittPeriode> fjernPerioderFørSkjæringstidspunktOpptjening(OppgittPeriode msp, RegelGrunnlag grunnlag) {
var skjæringstidspunkt = grunnlag.getOpptjening().getSkjæringstidspunkt();
// Skal ikke fjerne periode før skjæringstidspunkt for far med aleneomsorg eller enerett (fødsel eller adopsjon)
if ((farSøkerFødselEllerTerminOgBareFarHarRett(grunnlag)
|| isFarMedAleneomsorg(grunnlag)
&& skjæringstidspunkt.isAfter(grunnlag.getDatoer().getFamiliehendelse()))) {
return Optional.of(msp);
}
if (mspFyllerHullMellomForeldrene(msp, grunnlag)) {
return Optional.of(msp);
}
return fjernPerioderFørDato(msp, skjæringstidspunkt);
}
private static boolean isFarMedAleneomsorg(RegelGrunnlag grunnlag) {
return grunnlag.getBehandling().isSøkerFarMedMor() && grunnlag.getRettOgOmsorg().getAleneomsorg();
}
private static boolean mspFyllerHullMellomForeldrene(OppgittPeriode msp, RegelGrunnlag grunnlag) {
if (grunnlag.getAnnenPart() == null) {
return false;
}
var sisteDagAnnenpart = grunnlag.getAnnenPart().sisteUttaksdag();
var førsteDagSøknad = grunnlag.getSøknad().getOppgittePerioder().get(0).getFom();
if (sisteDagAnnenpart.isPresent() && sisteDagAnnenpart.get().isBefore(førsteDagSøknad)) {
return msp.overlapper(new LukketPeriode(sisteDagAnnenpart.get(), førsteDagSøknad));
}
return false;
}
private static boolean farSøkerFødselEllerTerminOgBareFarHarRett(RegelGrunnlag grunnlag) {
return farSøkerFødselEllerTermin(grunnlag) && bareFarRett(grunnlag);
}
private static List<OppgittPeriode> finnManglendeMellomliggendePerioder(RegelGrunnlag grunnlag,
List<OppgittPeriode> ekskludertePerioder) {
var allePerioder = slåSammenUttakForBeggeParter(grunnlag);
//legge inn ikke søkte perioder til uker som er Forbeholdt til Mor etter fødsel
allePerioder.addAll(ekskludertePerioder);
return finnManglendeMellomliggendePerioder(allePerioder).stream()
.map(ManglendeSøktPeriodeUtil::fjernHelg)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
private static List<OppgittPeriode> finnManglendeSøktFørFødsel(List<LukketPeriode> søktePerioder,
LocalDate familiehendelseDato,
Søknadstype søknadstype,
Set<Stønadskontotype> gyldigeStønadskontotyper,
Konfigurasjon konfigurasjon) {
if (Søknadstype.ADOPSJON.equals(søknadstype)) {
return List.of();
}
var antallUkerFpffFørFødsel = konfigurasjon.getParameter(Parametertype.UTTAK_FELLESPERIODE_FØR_FØDSEL_UKER,
familiehendelseDato);
var sorterteSøktePerioder = søktePerioder.stream().sorted(Comparator.comparing(Periode::getFom)).collect(Collectors.toList());
var førsteUttaksdagSøknad = sorterteSøktePerioder.get(0).getFom();
if (!førsteUttaksdagSøknad.isBefore(familiehendelseDato.minusWeeks(antallUkerFpffFørFødsel))) {
return List.of();
}
var startdatoBegingetFpff = førsteUttaksdagSøknad.isBefore(
familiehendelseDato.minusWeeks(antallUkerFpffFørFødsel)) ? familiehendelseDato.minusWeeks(
antallUkerFpffFørFødsel) : førsteUttaksdagSøknad;
var betingetFpffPeriode = new LukketPeriode(startdatoBegingetFpff, familiehendelseDato.minusDays(1));
var mspFørFødsel = ManglendeSøktPeriodeUtil.finnManglendeSøktePerioder(sorterteSøktePerioder, betingetFpffPeriode)
.stream()
.map(msp -> lagManglendeSøktPeriode(msp.getFom(), msp.getTom(), Stønadskontotype.FORELDREPENGER_FØR_FØDSEL))
.collect(Collectors.toList());
var betingetFellesperiode = new LukketPeriode(førsteUttaksdagSøknad,
familiehendelseDato.minusWeeks(antallUkerFpffFørFødsel).minusDays(1));
var mspForFellesperiodeFørFødsel = ManglendeSøktPeriodeUtil.finnManglendeSøktePerioder(sorterteSøktePerioder,
betingetFellesperiode).stream().map(msp -> {
var type = gyldigeStønadskontotyper.contains(
Stønadskontotype.FELLESPERIODE) ? Stønadskontotype.FELLESPERIODE : Stønadskontotype.FORELDREPENGER;
return lagManglendeSøktPeriode(msp.getFom(), msp.getTom(), type);
}).collect(Collectors.toList());
return Stream.of(mspForFellesperiodeFørFødsel, mspFørFødsel)
.flatMap(Collection::stream)
.filter(p -> p.virkedager() > 0)
.collect(Collectors.toList());
}
private static List<OppgittPeriode> finnManglendeMellomliggendePerioder(List<LukketPeriode> perioder) {
var sortertePerioder = perioder.stream()
.sorted(Comparator.comparing(LukketPeriode::getFom))
.collect(Collectors.toList());
List<OppgittPeriode> mellomliggendePerioder = new ArrayList<>();
LocalDate mspFom = null;
for (var lukketPeriode : sortertePerioder) {
if (mspFom == null) {
mspFom = lukketPeriode.getTom().plusDays(1);
} else if (mspFom.isBefore(lukketPeriode.getFom())) {
var mspTom = lukketPeriode.getFom().minusDays(1);
if (Virkedager.beregnAntallVirkedager(mspFom, mspTom) > 0) {
mellomliggendePerioder.add(lagManglendeSøktPeriode(mspFom, mspTom));
}
}
if (!lukketPeriode.getTom().isBefore(mspFom)) {
mspFom = lukketPeriode.getTom().plusDays(1);
}
}
return mellomliggendePerioder;
}
private static List<OppgittPeriode> finnPerioderEtterFødsel(List<LukketPeriode> søktePerioder,
LocalDate familiehendelseDato,
Set<Stønadskontotype> gyldigeStønadskontotyper,
Konfigurasjon konfigurasjon) {
var mødrekvoteEtterFødselUker = konfigurasjon.getParameter(Parametertype.UTTAK_MØDREKVOTE_ETTER_FØDSEL_UKER,
familiehendelseDato);
var betingetPeriodeEtterFødsel = new LukketPeriode(familiehendelseDato,
familiehendelseDato.plusWeeks(mødrekvoteEtterFødselUker).minusDays(1));
var stønadskontotype = gyldigeStønadskontotyper.contains(
Stønadskontotype.MØDREKVOTE) ? Stønadskontotype.MØDREKVOTE : Stønadskontotype.FORELDREPENGER;
return ManglendeSøktPeriodeUtil.finnManglendeSøktePerioder(søktePerioder, betingetPeriodeEtterFødsel)
.stream()
.map(msp -> lagManglendeSøktPeriode(msp.getFom(), msp.getTom(), stønadskontotype))
.collect(Collectors.toList());
}
}
| 54.769968 | 134 | 0.686169 |
8b0b61d92426556ec52d64eb98538f8c0344ca65 | 2,671 | package org.ega_archive.elixircore.repository;
import java.io.Serializable;
import java.util.List;
import org.ega_archive.elixircore.helper.CommonQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.QueryDslMongoRepository;
import org.springframework.data.querydsl.EntityPathResolver;
import org.springframework.data.querydsl.SimpleEntityPathResolver;
import com.mysema.query.types.EntityPath;
import com.mysema.query.types.Predicate;
import com.mysema.query.types.path.PathBuilder;
public class CustomQuerydslMongoRepositoryImpl<T, ID extends Serializable>
extends QueryDslMongoRepository<T, ID> implements CustomQuerydslMongoRepository<T, ID> {
// All instance variables are available in super, but they are private
private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER =
SimpleEntityPathResolver.INSTANCE;
private final EntityPath<T> path;
private final PathBuilder<T> pathBuilder;
private final MongoOperations mongoOperations;
public CustomQuerydslMongoRepositoryImpl(MongoEntityInformation<T, ID> entityInformation,
MongoOperations mongoOperations) {
this(entityInformation, mongoOperations, DEFAULT_ENTITY_PATH_RESOLVER);
}
public CustomQuerydslMongoRepositoryImpl(MongoEntityInformation<T, ID> entityInformation,
MongoOperations mongoOperations,
EntityPathResolver resolver) {
super(entityInformation, mongoOperations, resolver);
this.path = resolver.createPath(entityInformation.getJavaType());
this.pathBuilder = new PathBuilder<T>(path.getType(), path.getMetadata());
this.mongoOperations = mongoOperations;
}
public Page<T> findAll(Predicate predicate, CommonQuery commonQuery) {
Page<T> page = null;
if (commonQuery.getLimit() == 0 && commonQuery.getSkip() == 0) {
// Return ALL results
List<T> list = findAll(predicate);
page = new PageImpl<T>(list);
} else {
page = findAll(predicate, commonQuery.getPageable());
}
return page;
}
public Page<T> findAll(CommonQuery commonQuery) {
Page<T> page = null;
if (commonQuery.getLimit() == 0 && commonQuery.getSkip() == 0) {
// Return ALL results
List<T> list = findAll();
page = new PageImpl<T>(list);
} else {
page = findAll(null, commonQuery);
}
return page;
}
}
| 38.710145 | 92 | 0.72894 |
8952dbd01c53d0ec875dc08e8899141979d400cf | 7,804 | package com.bertilware.vault;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public final class VaultManager {
// Record that represents a user's saved data.
private record VaultUserData(ArrayList<Account> accounts, String notes, String theme) implements Serializable {
public ArrayList<Account> getAccounts() {
return accounts;
}
public String getNotes() {
return notes;
}
public String getTheme() {
return theme;
}
}
private static ArrayList<Account> accounts = null;
private static String notes = "";
private static String theme = VaultThemes.BERTILWARE;
private static String user = "";
private static byte[] hash;
private static final File vaultDirectory = new File(
System.getProperty("user.home") + File.separator +
".bertilware" + File.separator + "vault"
);
private static File userFile;
private static Key key;
private static Cipher cipher;
// Getters
public static ArrayList<Account> getAccounts() { return accounts; }
public static String getTheme() {
return theme;
}
public static String getNotes() {
return notes;
}
public static String getUser() {
return user;
}
public static byte[] getHash() {
return hash;
}
public static File getVaultDirectory() {
return vaultDirectory;
}
public static File getUserFile() {
return userFile;
}
// Setters
public static void setTheme(String theme) {
VaultManager.theme = theme;
}
public static void setNotes(String notes) {
VaultManager.notes = notes;
}
public static void setUser(String user) {
VaultManager.user = user;
}
public static void initialize(String username, String password)
throws NoSuchPaddingException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
// Run the password through SHA-256 to get a 256-bit key
byte[] raw = md.digest(password.getBytes(StandardCharsets.UTF_8));
userFile = new File(
vaultDirectory + File.separator +
username + ".vault"
);
user = username;
key = new SecretKeySpec(raw, "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Run both the username and password through SHA-256 for syncing
hash = md.digest((user + password).getBytes(StandardCharsets.UTF_8));
}
public static void encrypt()
throws IOException, InvalidAlgorithmParameterException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException {
// Read the user's data
VaultUserData data = new VaultUserData(
accounts == null ? new ArrayList<>() : accounts,
notes,
theme
);
// Serialize the vault object into a ByteArrayOutputStream,
// and read that output stream into a byte array
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objectOut = new ObjectOutputStream(byteOut);
objectOut.writeObject(data);
objectOut.close();
byte[] decrypted = byteOut.toByteArray();
// Create a new byte array and populate it using a SecureRandom generator
byte[] ivArray = new byte[16];
SecureRandom generator = new SecureRandom();
generator.nextBytes(ivArray);
// Use that random byte array as an IV for the cipher
IvParameterSpec iv = new IvParameterSpec(ivArray);
// Initialize cipher to encryption mode,
// and encrypt the serialized object
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] encrypted = cipher.doFinal(decrypted);
byte[] vaultFile = new byte[encrypted.length + ivArray.length];
// Add the encrypted object
System.arraycopy(encrypted, 0, vaultFile, 0, encrypted.length);
// Append the IV bytes
System.arraycopy(ivArray, 0,vaultFile, encrypted.length, ivArray.length);
// Write to disk
Files.write(userFile.toPath(), vaultFile);
saveSession();
}
public static void decrypt()
throws IOException, InvalidAlgorithmParameterException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, ClassNotFoundException {
// Read encrypted object and the IV bytes from the user's file
byte[] vaultFile = Files.readAllBytes(userFile.toPath());
// Copy the encrypted object from the read bytes
byte[] encrypted = new byte[vaultFile.length - 16];
System.arraycopy(vaultFile, 0, encrypted, 0, vaultFile.length - 16);
// Copy the IV bytes from read bytes
byte[] byteArray = new byte[16];
System.arraycopy(vaultFile, encrypted.length, byteArray, 0, 16);
// Create the IV
IvParameterSpec iv = new IvParameterSpec(byteArray);
// Try to decrypt the file
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decrypted = cipher.doFinal(encrypted);
// Create input streams and read serialized vault object
ByteArrayInputStream byteIn = new ByteArrayInputStream(decrypted);
ObjectInputStream objectIn = new ObjectInputStream(byteIn);
VaultUserData data = (VaultUserData) objectIn.readObject();
objectIn.close();
// Set the accounts and the theme
accounts = data.getAccounts();
notes = data.getNotes();
theme = data.getTheme();
saveSession();
}
public static Cipher getCipherForSync(int mode)
throws NoSuchPaddingException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException, InvalidKeyException {
// CTR instead of CBC because padding was giving issues during sync
Cipher syncCipher = Cipher.getInstance("AES/CTR/NoPadding");
byte[] nonce = Arrays.copyOf(hash, 12);
byte[] nonceAndCounter = new byte[16];
System.arraycopy(nonce, 0, nonceAndCounter, 0, nonce.length);
IvParameterSpec iv = new IvParameterSpec(nonceAndCounter);
syncCipher.init(mode, key, iv);
return syncCipher;
}
public static void readSession() throws FileNotFoundException {
File session = new File(vaultDirectory + File.separator + "session.txt");
if (!session.exists())
return;
// Count the lines within the session file,
// and exit if it does not have the required amount
Scanner in = new Scanner(session);
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
count++;
}
in.close();
if (count != 2)
return;
// Finally, read the last session's info
in = new Scanner(session);
user = in.nextLine();
theme = in.nextLine();
in.close();
}
private static void saveSession() throws FileNotFoundException {
// Retain some information about the current session
File session = new File(vaultDirectory + File.separator + "session.txt");
PrintWriter writer = new PrintWriter(session);
writer.println(user);
writer.println(theme);
writer.close();
}
} | 35.963134 | 115 | 0.642107 |
eafbb236d5c674f1570fe320186ed76318ecc705 | 1,465 | package com.dotmarketing.logConsole.model;
import com.dotmarketing.util.UtilMethods;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.builder.ToStringBuilder;
public class LogMapperRow implements Serializable {
private static final long serialVersionUID = 1L;
Boolean enabled;
String log_name;
String description;
public static long getSerialversionuid () {
return serialVersionUID;
}
public String getDescription () {
return description;
}
public void setDescription ( String description ) {
this.description = description;
}
public Boolean getEnabled () {
return enabled;
}
public void setEnabled ( Boolean enabled ) {
this.enabled = enabled;
}
public String getLog_name () {
return log_name;
}
public void setLog_name ( String log_name ) {
this.log_name = log_name;
}
@Override
public String toString () {
return ToStringBuilder.reflectionToString( this );
}
public Map<String, Object> getMap () {
Map<String, Object> oMap = new HashMap<String, Object>();
oMap.put( "description", this.getDescription() );
oMap.put( "log_name", this.getLog_name() );
oMap.put( "enabled", this.getEnabled() );
return oMap;
}
public boolean isNew () {
return UtilMethods.isSet( log_name );
}
} | 22.890625 | 65 | 0.649147 |
0e856ea90f55bc9864d6b51371b738e1ac2293e8 | 7,880 | /*
* Copyright (c) 2021 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.couchbase.client.java.util;
import com.couchbase.client.core.annotation.Stability;
import com.couchbase.client.core.config.BucketConfig;
import com.couchbase.client.core.config.ConfigurationProvider;
import com.couchbase.client.core.config.CouchbaseBucketConfig;
import com.couchbase.client.core.config.MemcachedBucketConfig;
import com.couchbase.client.core.config.NodeInfo;
import com.couchbase.client.core.error.CouchbaseException;
import com.couchbase.client.java.Bucket;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.zip.CRC32;
/**
* Helper class to provide direct access on how document IDs are mapped onto nodes.
*/
@Stability.Uncommitted
public class NodeLocatorHelper {
private final AtomicReference<BucketConfig> bucketConfig = new AtomicReference<>();
private NodeLocatorHelper(final Bucket bucket, final Duration waitUntilReadyDuration) {
if (waitUntilReadyDuration.getSeconds() > 0) {
bucket.waitUntilReady(waitUntilReadyDuration);
}
ConfigurationProvider configurationProvider = bucket.core().configurationProvider();
BucketConfig bc = configurationProvider.config().bucketConfig(bucket.name());
if (bc == null) {
throw new CouchbaseException("Bucket configuration not found, if waitUntilReadyDuration is set to 0 the call" +
"must be executed before initializing the NodeLocatorHelper!");
}
bucketConfig.set(configurationProvider.config().bucketConfig(bucket.name()));
configurationProvider
.configs()
.subscribe(cc -> {
BucketConfig newConfig = cc.bucketConfig(bucket.name());
if (newConfig != null) {
bucketConfig.set(newConfig);
}
});
}
/**
* Creates a new {@link NodeLocatorHelper}, mapped on to the given {@link Bucket}.
*
* To make sure that the helper has a bucket config to work with in the beginning, it will call
* {@link Bucket#waitUntilReady(Duration)} with the duration provided as an argument. If you already
* did call waitUntilReady before initializing the helper, you can pass a duration of 0 in which case
* it will be omitted.
*
* @param bucket the scoped bucket.
* @param waitUntilReadyDuration the duration used to call waitUntilReady (if 0 ignored).
* @return the created locator.
*/
public static NodeLocatorHelper create(final Bucket bucket, final Duration waitUntilReadyDuration) {
return new NodeLocatorHelper(bucket, waitUntilReadyDuration);
}
/**
* Returns the target active node address for a given document ID on the bucket.
*
* @param id the document id to convert.
* @return the node for the given document id.
*/
public String activeNodeForId(final String id) {
BucketConfig config = bucketConfig.get();
if (config instanceof CouchbaseBucketConfig) {
return nodeForIdOnCouchbaseBucket(id, (CouchbaseBucketConfig) config);
} else if (config instanceof MemcachedBucketConfig) {
return nodeForIdOnMemcachedBucket(id, (MemcachedBucketConfig) config);
} else {
throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
}
}
/**
* Returns all target replica nodes addresses for a given document ID on the bucket.
*
* @param id the document id to convert.
* @return the node for the given document id.
*/
public List<String> replicaNodesForId(final String id) {
BucketConfig config = bucketConfig.get();
if (config instanceof CouchbaseBucketConfig) {
CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
List<String> replicas = new ArrayList<>();
for (int i = 1; i <= cbc.numberOfReplicas(); i++) {
replicas.add(replicaNodeForId(id, i));
}
return replicas;
} else {
throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
}
}
/**
* Returns the target replica node address for a given document ID and replica number on the bucket.
*
* @param id the document id to convert.
* @param replicaNum the replica number.
* @return the node for the given document id.
*/
public String replicaNodeForId(final String id, int replicaNum) {
if (replicaNum < 1 || replicaNum > 3) {
throw new IllegalArgumentException("Replica number must be between 1 and 3.");
}
BucketConfig config = bucketConfig.get();
if (config instanceof CouchbaseBucketConfig) {
CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
int partitionId = (int) hashId(id) & cbc.numberOfPartitions() - 1;
int nodeId = cbc.nodeIndexForReplica(partitionId, replicaNum - 1, false);
if (nodeId == -1) {
throw new IllegalStateException("No partition assigned to node for Document ID: " + id);
}
if (nodeId == -2) {
throw new IllegalStateException("Replica not configured for this bucket.");
}
return cbc.nodeAtIndex(nodeId).hostname();
} else {
throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
}
}
/**
* Returns all nodes known in the current config.
*
* @return all currently known nodes.
*/
public List<String> nodes() {
return bucketConfig.get().nodes().stream().map(NodeInfo::hostname).collect(Collectors.toList());
}
private static String nodeForIdOnCouchbaseBucket(final String id, final CouchbaseBucketConfig config) {
int partitionId = (int) hashId(id) & config.numberOfPartitions() - 1;
int nodeId = config.nodeIndexForActive(partitionId, false);
if (nodeId == -1) {
throw new IllegalStateException("No partition assigned to node for Document ID: " + id);
}
return config.nodeAtIndex(nodeId).hostname();
}
private static String nodeForIdOnMemcachedBucket(final String id, final MemcachedBucketConfig config) {
long hash = ketamaHash(id);
if (!config.ketamaNodes().containsKey(hash)) {
SortedMap<Long, NodeInfo> tailMap = config.ketamaNodes().tailMap(hash);
if (tailMap.isEmpty()) {
hash = config.ketamaNodes().firstKey();
} else {
hash = tailMap.firstKey();
}
}
return config.ketamaNodes().get(hash).hostname();
}
private static long hashId(String id) {
CRC32 crc32 = new CRC32();
crc32.update(id.getBytes(StandardCharsets.UTF_8));
return (crc32.getValue() >> 16) & 0x7fff;
}
private static long ketamaHash(final String key) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(key.getBytes(StandardCharsets.UTF_8));
byte[] digest = md5.digest();
long rv = ((long) (digest[3] & 0xFF) << 24)
| ((long) (digest[2] & 0xFF) << 16)
| ((long) (digest[1] & 0xFF) << 8)
| (digest[0] & 0xFF);
return rv & 0xffffffffL;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Could not encode ketama hash - MD5 should be available in the JVM.", e);
}
}
}
| 37.52381 | 117 | 0.70368 |
f58bb0e27b5166736bcf3a693077da0a97127baf | 91 | package com.twu.biblioteca.action;
public interface Action {
void performAction();
}
| 13 | 34 | 0.736264 |
42a1b2f64fa1068328f6cb8bd9407276a144f342 | 1,444 | /*
* The spring-based xzixi framework simplifies development.
*
* Copyright (C) 2020 xuelingkang@163.com.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.relaxed.common.jsch.sftp.utils;
import com.relaxed.common.jsch.sftp.exception.SftpClientException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
* @author 薛凌康
*/
public class ByteUtil {
/**
* 输入流转字节数组
* @param in 输入流
* @return 字节数组
*/
public static byte[] inputStreamToByteArray(InputStream in) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n;
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
}
return out.toByteArray();
}
catch (Exception e) {
throw new SftpClientException("Error in input stream byte array", e);
}
}
}
| 27.245283 | 73 | 0.710526 |
b39da8e131513988964eb6987f7ff5769ca5cbb4 | 13,704 | package jet.bpm.engine.xml.activiti;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import jet.bpm.engine.model.AbstractElement;
import jet.bpm.engine.model.BoundaryEvent;
import jet.bpm.engine.model.CallActivity;
import jet.bpm.engine.model.EndEvent;
import jet.bpm.engine.model.EventBasedGateway;
import jet.bpm.engine.model.ExclusiveGateway;
import jet.bpm.engine.model.ProcessDefinition;
import jet.bpm.engine.model.SequenceFlow;
import jet.bpm.engine.model.ServiceTask;
import jet.bpm.engine.model.ExpressionType;
import jet.bpm.engine.model.InclusiveGateway;
import jet.bpm.engine.model.IntermediateCatchEvent;
import jet.bpm.engine.model.ParallelGateway;
import jet.bpm.engine.model.SequenceFlow.ExecutionListener;
import jet.bpm.engine.model.StartEvent;
import jet.bpm.engine.model.SubProcess;
import jet.bpm.engine.model.VariableMapping;
import jet.bpm.engine.xml.Parser;
import jet.bpm.engine.xml.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ActivitiParser implements Parser {
private static final Logger log = LoggerFactory.getLogger(ActivitiParser.class);
@Override
public ProcessDefinition parse(InputStream in) throws ParserException {
if (in == null) {
throw new NullPointerException("Input cannot be null");
}
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser p = spf.newSAXParser();
Handler h = new Handler();
p.parse(in, h);
return h.process;
} catch (IOException | ParserConfigurationException | SAXException e) {
throw new ParserException("Parsing error", e);
}
}
private static final class Handler extends DefaultHandler {
private static final class Item {
private final String name;
private final String processId;
private final Collection<AbstractElement> children;
public Item(String processId, String name, Collection<AbstractElement> children) {
this.processId = processId;
this.name = name;
this.children = children;
}
}
private String id;
private String name;
private String processId;
private String processName;
private String attachedToRef;
private String errorRef;
private String sourceRef;
private String targetRef;
private String messageRef;
private String timeDate;
private String timeDuration;
private String calledElement;
private StringBuilder text;
private ProcessDefinition process;
private Collection<AbstractElement> children;
private final Stack<Item> items = new Stack<>();
private Collection<ExecutionListener> listeners;
private Set<VariableMapping> in;
private Set<VariableMapping> out;
@Override
public void startElement(String uri, String qName, String localName, Attributes attributes) throws SAXException {
log.debug("startElement ['{}']", localName);
localName = stripNamespace(localName);
switch (localName) {
case "process":
processId = attributes.getValue("id");
processName = attributes.getValue("name");
children = new ArrayList<>();
break;
case "subProcess":
name = attributes.getValue("name");
items.push(new Item(processId, name, children));
processId = attributes.getValue("id");
children = new ArrayList<>();
break;
case "startEvent":
id = attributes.getValue("id");
StartEvent ev = new StartEvent(id);
children.add(ev);
break;
case "callActivity":
id = attributes.getValue("id");
name = attributes.getValue("name");
calledElement = attributes.getValue("calledElement");
break;
case "boundaryEvent":
id = attributes.getValue("id");
attachedToRef = attributes.getValue("attachedToRef");
break;
case "errorEventDefinition":
errorRef = attributes.getValue("errorRef");
break;
case "endEvent":
id = attributes.getValue("id");
break;
case "sequenceFlow":
id = attributes.getValue("id");
name = attributes.getValue("name");
sourceRef = attributes.getValue("sourceRef");
targetRef = attributes.getValue("targetRef");
break;
case "conditionExpression":
text = new StringBuilder();
break;
case "exclusiveGateway":
id = attributes.getValue("id");
ExclusiveGateway eg = new ExclusiveGateway(id, attributes.getValue("default"));
children.add(eg);
break;
case "parallelGateway":
id = attributes.getValue("id");
ParallelGateway pg = new ParallelGateway(id);
children.add(pg);
break;
case "inclusiveGateway":
id = attributes.getValue("id");
InclusiveGateway ig = new InclusiveGateway(id);
children.add(ig);
break;
case "serviceTask":
id = attributes.getValue("id");
name = attributes.getValue("name");
String simple = attributes.getValue("expression");
String delegate = attributes.getValue("delegateExpression");
ExpressionType type = ExpressionType.NONE;
String expr = null;
if (simple != null) {
type = ExpressionType.SIMPLE;
expr = simple;
} else if (delegate != null) {
type = ExpressionType.DELEGATE;
expr = delegate;
}
ServiceTask st = new ServiceTask(id, type, expr);
st.setName(name);
children.add(st);
break;
case "executionListener":
if (listeners == null) {
listeners = new ArrayList<>();
}
String event = attributes.getValue("event");
String s = null;
ExpressionType t = ExpressionType.NONE;
String expression = attributes.getValue("expression");
String delegateExpression = attributes.getValue("delegateExpression");
if (expression != null) {
s = expression;
t = ExpressionType.SIMPLE;
} else if (delegateExpression != null) {
s = delegateExpression;
t = ExpressionType.DELEGATE;
}
ExecutionListener sel = new ExecutionListener(event, t, s);
listeners.add(sel);
break;
case "in":
if (in == null) {
in = new HashSet<>();
}
in.add(parseVariableMapping(attributes));
break;
case "out":
if (out == null) {
out = new HashSet<>();
}
out.add(parseVariableMapping(attributes));
break;
case "eventBasedGateway":
id = attributes.getValue("id");
EventBasedGateway ebg = new EventBasedGateway(id);
children.add(ebg);
break;
case "messageEventDefinition":
messageRef = attributes.getValue("messageRef");
break;
case "intermediateCatchEvent":
id = attributes.getValue("id");
break;
case "timeDate":
text = new StringBuilder();
break;
case "timeDuration":
text = new StringBuilder();
break;
}
}
private VariableMapping parseVariableMapping(Attributes attributes) {
String source = attributes.getValue("source");
String sourceExpression = attributes.getValue("sourceExpression");
String target = attributes.getValue("target");
return new VariableMapping(source, sourceExpression, target);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (text != null) {
text.append(ch, start, length);
}
}
@Override
public void endElement(String uri, String qName, String localName) throws SAXException {
log.debug("endElement ['{}']", localName);
localName = stripNamespace(localName);
switch (localName) {
case "process":
process = new ProcessDefinition(processId, children);
process.setName(processName);
children = null;
break;
case "subProcess":
SubProcess p = new SubProcess(processId, children);
Item i = items.pop();
processId = i.processId;
children = i.children;
p.setName(i.name);
children.add(p);
break;
case "boundaryEvent":
BoundaryEvent be = new BoundaryEvent(id, attachedToRef, errorRef, timeDuration);
children.add(be);
attachedToRef = null;
errorRef = null;
timeDuration = null;
break;
case "sequenceFlow":
String expr = text != null ? text.toString().trim() : null;
ExecutionListener[] l = null;
if (listeners != null) {
l = listeners.toArray(new ExecutionListener[listeners.size()]);
}
SequenceFlow sf = new SequenceFlow(id, sourceRef, targetRef, expr, l);
sf.setName(name);
children.add(sf);
name = null;
sourceRef = null;
targetRef = null;
text = null;
listeners = null;
break;
case "endEvent":
EndEvent ee = new EndEvent(id, errorRef);
children.add(ee);
errorRef = null;
break;
case "callActivity":
CallActivity ca = new CallActivity(id, calledElement, in, out);
ca.setName(name);
children.add(ca);
calledElement = null;
in = null;
name = null;
out = null;
break;
case "intermediateCatchEvent":
IntermediateCatchEvent ice = new IntermediateCatchEvent(id, messageRef, timeDate, timeDuration);
children.add(ice);
messageRef = null;
timeDate = null;
timeDuration = null;
break;
case "timeDate":
timeDate = text.toString();
text = null;
break;
case "timeDuration":
timeDuration = text.toString();
text = null;
break;
}
}
}
private static String stripNamespace(String s) {
if (s == null) {
return s;
}
int i = s.indexOf(":");
if (i >= 0 && i + 1 < s.length()) {
return s.substring(i + 1);
}
return s;
}
}
| 36.063158 | 121 | 0.484092 |
beff885f77503f2e42a32036b48398b6c2c1c756 | 1,012 | package com.codechef.ezresume;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class TemplateSelectActivity extends AppCompatActivity
{
ViewPager2 viewPager;
TemplateSelectPagerAdapter pagerAdapter;
TabLayout tabLayout;
private String[] titles = {"Resume", "CV", "Cover Letter"};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_template_select);
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tab_layout);
pagerAdapter = new TemplateSelectPagerAdapter(this);
viewPager.setAdapter(pagerAdapter);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> tab.setText(titles[position])).attach();
}
} | 32.645161 | 75 | 0.737154 |
031f8adf9d1b4511deaa61d3d35c9e6fe4b7bee1 | 211 | package com.imooc.lib_common_ui.delegate.web.event;
import android.util.Log;
public class UndefinedEvent extends Event {
@Override
public String execute(String params) {
Log.d("","");
return null;
}
}
| 16.230769 | 51 | 0.729858 |
bac02ef6c6e9cbdd62df46ff8b44d8d6534d9269 | 2,284 | package com.murraywilliams.arduino.data;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.murraywilliams.arduino.data.ArduinoConversion;;
public class ArduinoMCP9808 extends ArduinoFloat {
public enum DataTypes { TempC, TempF }
private double temps[] = null;
DecimalFormat formatter = new DecimalFormat("###.00");
public ArduinoMCP9808(byte[] data) {
int offset = 0;
for (int i=0; i<data.length; i++) {
if (data[i]==0x3A) offset = i + 1;
}
this.temps = getMCP9808TempC(offset == 0 ? data : Arrays.copyOfRange(data, offset, data.length));
this.typeString = "MCP9808";
}
@Override
public double[] getValues() {
return temps;
}
@Override
public double[] getValues(Enum<?> type) {
if (type.equals(DataTypes.TempF)) {
double f[] = new double[temps.length];
for (int i=0; i<temps.length; i++) f[i] = temps[i] * 9.0 / 5.0 + 32.0;
return f;
} else return this.temps;
}
public static double[] getMCP9808TempC(byte[] source) throws IllegalArgumentException {
int[] rawValues = ArduinoConversion.readUnsignedInts(source);
double[] temps = new double[rawValues.length];
for (int i=0; i<rawValues.length; i++) {
temps[i] = (rawValues[i] & 0x0FFF) / 16.0;
if ((rawValues[i] & 0x1000) != 0) temps[i] -= 256.0;
}
return temps;
}
public static double[] getMCP9808TempF(byte[] source) throws IllegalArgumentException {
double t[] = getMCP9808TempC(source);
for (int i=0; i<t.length; i++) {
t[i] = t[i] * 9.0 / 5.0 + 32.0;
}
return t;
}
public static double[] parseDoubles(byte[] source) {
ArduinoMCP9808 d = new ArduinoMCP9808(source);
return d.getValues();
}
@Override
public String toString() {
List<String> values = new ArrayList<String>();
for (double f : getValues(DataTypes.TempF)){
values.add(formatter.format(f) + "\u00b0F");
}
return String.join(", ", values);
}
@Override
public int getSize() {
return temps.length;
}
@Override
public void printByDate() {
double[] ftemps = getValues(DataTypes.TempF);
for (int i=0; i<temps.length; i++) {
System.out.print(dates[i] + ", " + formatter.format(ftemps[i]) + "\u00b0F");
}
}
@Override
public String getLabel() {
return "MCP9808Temp";
}
}
| 24.55914 | 99 | 0.664186 |
38ed85971760d5b22615817400061eb9fa8aeb78 | 587 | package io.renren.modules.app.service;
import com.baomidou.mybatisplus.service.IService;
import io.renren.common.utils.PageUtils;
import io.renren.modules.app.entity.Wage;
import java.util.Map;
/**
*@ClassName:PoiService
*@Description:TODO
*@author: Yophy.W
*@Date 2018/7/30--18:26
*/
public interface PoiService extends IService<Wage> {
/**
* 保存薪资信息
*/
public void save(Wage parmWage);
/**
* 分页查询薪资列表
* @param params
* @return
*/
PageUtils queryPage(Map<String, Object> params);
/**
* 删除方法
* @param excleId
*/
void deleteExcle(Integer excleId);
}
| 16.305556 | 52 | 0.691652 |
e2e25f4395feadadda99e1cff9b5265e67817f0e | 3,498 | /*
* Copyright 2006-2021 Prowide
*
* 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.prowidesoftware.swift.model.mt.mt5xx;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
import com.prowidesoftware.swift.SchemeConstantsS;
import com.prowidesoftware.swift.model.field.Field;
import com.prowidesoftware.swift.model.field.Field20C;
import com.prowidesoftware.swift.model.mt.AbstractMT;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class MT540Test {
public static final String MT_540_CANC =
"{1:F01AAAAFRPPAGSS0000000000}{2:O5401445211216BBBBFRPPAHCM5C3E1000002112161445N}{3:{108:5123C3E10}}{4:\n" +
":16R:GENL\n" +
":20C::SEME//TFH5436259-999\n" +
":23G:CANC\n" +
":98C::PREP//20211216144402\n" +
":16R:LINK\n" +
":20C::PREV//TFH5436259-999\n" +
":16S:LINK\n" +
":16S:GENL\n" +
":16R:TRADDET\n" +
":98A::SETT//20211216\n" +
":98A::TRAD//20211216\n" +
":35B:ISIN FR0099001N99\n" +
"FRTR 0 25 02 24 EUR\n" +
":16S:TRADDET\n" +
":16R:FIAC\n" +
":36B::SETT//FAMT/31000000,\n" +
":97A::SAFE//0528808067001999\n" +
":16S:FIAC\n" +
":16R:SETDET\n" +
":22F::SETR//TRAD\n" +
":16R:SETPRTY\n" +
":95P::DEAG//CCCCBEBEECL\n" +
":97A::SAFE//94999\n" +
":16S:SETPRTY\n" +
":16R:SETPRTY\n" +
":95P::SELL//DDDDFRPPHCM\n" +
":97A::SAFE//94999\n" +
":16S:SETPRTY\n" +
":16R:SETPRTY\n" +
":95P::PSET//EEEEFRPPXXX\n" +
":16S:SETPRTY\n" +
":16S:SETDET\n" +
"-}";
@Test
void field20C_should_be_returned_by_MT540_CANC() {
// Given
com.prowidesoftware.swift.model.mt.mt5xx.MT540 mt540;
// When
try {
mt540 = (com.prowidesoftware.swift.model.mt.mt5xx.MT540) AbstractMT.parse(MT_540_CANC);
// Then
assertThat(mt540.getField20C()).hasSize(2);
assertThat(mt540.getField20C().get(0).getReference()).isEqualTo("TFH5436259-999");
Field fieldByName = mt540.getSwiftMessage().getBlock4().getFieldByName(Field20C.NAME, SchemeConstantsS.SEME);
assertThat(fieldByName.getComponents()).hasSize(2);
assertThat(fieldByName.getComponent(1)).isEqualTo("SEME");
assertThat(fieldByName.getComponent(2)).isEqualTo("TFH5436259-999");
} catch (IOException exception) {
fail();
}
}
}
| 38.866667 | 121 | 0.551458 |
6d1942b3e540bf60ed25f930e90be15dd07d47d8 | 2,412 | package evan.org.vienhance.util;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
/**
* Create By yejiaquan in 2018/10/16 14:22
*/
public class Objects {
public static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
public static int hashCode(@Nullable Object... objects) {
return Arrays.hashCode(objects);
}
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
public static final class Strings{
public static boolean isNullOrEmpty(String s){
return s == null||s.isEmpty();
}
}
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
public static final class Lists{
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<E>(Collections2.cast(elements))
: newArrayList(elements.iterator());
}
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
ArrayList<E> list = newArrayList();
Iterators.addAll(list, elements);
return list;
}
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
}
public static final class Iterators{
public static <T> boolean addAll(
Collection<T> addTo, Iterator<? extends T> iterator) {
checkNotNull(addTo);
checkNotNull(iterator);
boolean wasModified = false;
while (iterator.hasNext()) {
wasModified |= addTo.add(iterator.next());
}
return wasModified;
}
}
public static final class Collections2{
static <T> Collection<T> cast(Iterable<T> iterable) {
return (Collection<T>) iterable;
}
}
}
| 29.777778 | 85 | 0.589967 |
e3611119cf39f3ee8cf579a6530e6afecb17695b | 3,162 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/retail/v2alpha/import_config.proto
package com.google.cloud.retail.v2alpha;
public interface ImportCompletionDataRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.retail.v2alpha.ImportCompletionDataRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Required. The catalog which the suggestions dataset belongs to.
* Format: `projects/1234/locations/global/catalogs/default_catalog`.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code>
* @return The parent.
*/
java.lang.String getParent();
/**
* <pre>
* Required. The catalog which the suggestions dataset belongs to.
* Format: `projects/1234/locations/global/catalogs/default_catalog`.
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for parent.
*/
com.google.protobuf.ByteString
getParentBytes();
/**
* <pre>
* Required. The desired input location of the data.
* </pre>
*
* <code>.google.cloud.retail.v2alpha.CompletionDataInputConfig input_config = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the inputConfig field is set.
*/
boolean hasInputConfig();
/**
* <pre>
* Required. The desired input location of the data.
* </pre>
*
* <code>.google.cloud.retail.v2alpha.CompletionDataInputConfig input_config = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The inputConfig.
*/
com.google.cloud.retail.v2alpha.CompletionDataInputConfig getInputConfig();
/**
* <pre>
* Required. The desired input location of the data.
* </pre>
*
* <code>.google.cloud.retail.v2alpha.CompletionDataInputConfig input_config = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
com.google.cloud.retail.v2alpha.CompletionDataInputConfigOrBuilder getInputConfigOrBuilder();
/**
* <pre>
* Pub/Sub topic for receiving notification. If this field is set,
* when the import is finished, a notification will be sent to
* specified Pub/Sub topic. The message data will be JSON string of a
* [Operation][google.longrunning.Operation].
* Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`.
* </pre>
*
* <code>string notification_pubsub_topic = 3;</code>
* @return The notificationPubsubTopic.
*/
java.lang.String getNotificationPubsubTopic();
/**
* <pre>
* Pub/Sub topic for receiving notification. If this field is set,
* when the import is finished, a notification will be sent to
* specified Pub/Sub topic. The message data will be JSON string of a
* [Operation][google.longrunning.Operation].
* Format of the Pub/Sub topic is `projects/{project}/topics/{topic}`.
* </pre>
*
* <code>string notification_pubsub_topic = 3;</code>
* @return The bytes for notificationPubsubTopic.
*/
com.google.protobuf.ByteString
getNotificationPubsubTopicBytes();
}
| 36.344828 | 132 | 0.696711 |
6b45242a27308fdeb8b16f4c6a3c72327970edac | 330 | package org.jxls.expression;
import java.util.Map;
/**
* An interface to evaluate expressions
*
* @author Leonid Vysochyn
*/
public interface ExpressionEvaluator {
Object evaluate(String expression, Map<String,Object> context);
Object evaluate(Map<String, Object> context);
String getExpression();
}
| 18.333333 | 67 | 0.709091 |
b9cdce56db52bfc3b39fb2357cce70accd917fc1 | 213 | package com.zerogdev.easyshorturl.service;
public class NaverConsts {
public static final String CLIENT_ID = "네이버 client id 를 입력해주세요";
public static final String CLIENT_SECRET = "네이버 secret 을 입력해주세요";
}
| 26.625 | 69 | 0.755869 |
0f060d22e905f623ddcb720c918904c2e26bb8d8 | 293 | package answers.designPatterns.observerPattern_own;
import answers.designPatterns.observerPattern_own.observers.SpyObserver;
public interface ObservableSpyAgency {
void addObserver(SpyObserver spyObserver);
void removeObserver(SpyObserver spyObserver);
void notifyObservers();
}
| 29.3 | 72 | 0.829352 |
a1322ce1bb0571c614920bc2bd894fd4f0f32ef6 | 38,131 | /*
* 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 bft;
import bftsmart.tom.MessageContext;
import bftsmart.tom.ServiceReplica;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.server.defaultservices.DefaultRecoverable;
import bftsmart.tom.server.defaultservices.DefaultReplier;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.hyperledger.fabric.protos.common.Common;
import org.hyperledger.fabric.protos.msp.Identities;
/**
*
* @author joao
*/
public class BFTNode extends DefaultRecoverable {
public final static String DEFAULT_CONFIG_FOLDER = "./config/";
private int id;
private ServiceReplica replica = null;
private CryptoPrimitives crypto;
private Log logger;
private String configFolder;
// MSP stuff
private String mspid = null;
private PrivateKey privKey = null;
private X509CertificateHolder certificate = null;
private byte[] serializedCert = null;
private Identities.SerializedIdentity ident;
//signature thread stuff
private int parallelism;
LinkedBlockingQueue<SignerSenderThread> queue;
private ExecutorService executor = null;
private int blocksPerThread;
private int sigIndex = 0;
private SignerSenderThread currentSST = null;
//measurements
private int interval = 10000;
private long envelopeMeasurementStartTime = -1;
private long blockMeasurementStartTime = -1;
private long sigsMeasurementStartTime = -1;
private int countEnvelopes = 0;
private int countBlocks = 0;
private int countSigs = 0;
//used to avoid the signing threads from accessing a null pointer in 'replica'
private Lock replicaLock;
private Condition replicaReady;
//these attributes are the state of this replicated state machine
private Set<Integer> receivers;
private BlockCutter blockCutter;
private int sequence = 0;
private long lastConfig = 0;
private Map<String,Common.BlockHeader> lastBlockHeaders;
private String sysChannel = "";
public BFTNode(int id, String configFolder) throws IOException, InvalidArgumentException, CryptoException, NoSuchAlgorithmException, NoSuchProviderException, InterruptedException, ClassNotFoundException, IllegalAccessException, InstantiationException {
this.replicaLock = new ReentrantLock();
this.replicaReady = replicaLock.newCondition();
this.id = id;
this.configFolder = (configFolder != null ? configFolder : BFTNode.DEFAULT_CONFIG_FOLDER);
loadConfig();
this.crypto = new CryptoPrimitives();
this.crypto.init();
this.logger = LogFactory.getLog(BFTNode.class);
this.queue = new LinkedBlockingQueue<>();
this.executor = Executors.newWorkStealingPool(this.parallelism);
for (int i = 0; i < parallelism; i++) {
this.executor.execute(new SignerSenderThread(this.queue));
}
this.sequence = 0;
this.lastBlockHeaders = new TreeMap<>();
//logger.info("This is the signature algorithm: " + this.crypto.getSignatureAlgorithm());
//logger.info("This is the hash algorithm: " + this.crypto.getHashAlgorithm());
this.replica = new ServiceReplica(this.id, this.configFolder, this, this, null, new NoopReplier());
this.replicaLock.lock();
this.replicaReady.signalAll();
this.replicaLock.unlock();
}
private String extractMSPID(byte[] bytes) {
try {
Common.Envelope env = Common.Envelope.parseFrom(bytes);
Common.Payload payload = Common.Payload.parseFrom(env.getPayload());
Common.SignatureHeader sigHeader = Common.SignatureHeader.parseFrom(payload.getHeader().getSignatureHeader());
Identities.SerializedIdentity ident = Identities.SerializedIdentity.parseFrom(sigHeader.getCreator());
return ident.getMspid();
} catch (InvalidProtocolBufferException ex) {
//ex.printStackTrace();
return null;
}
}
private void loadConfig() throws IOException {
LineIterator it = FileUtils.lineIterator(new File(this.configFolder + "node.config"), "UTF-8");
Map<String,String> configs = new TreeMap<>();
while (it.hasNext()) {
String line = it.nextLine();
if (!line.startsWith("#") && line.contains("=")) {
String[] params = line.split("\\=");
configs.put(params[0], params[1]);
}
}
it.close();
mspid = configs.get("MSPID");
privKey = getPemPrivateKey(configs.get("PRIVKEY"));
certificate = getCertificate(configs.get("CERTIFICATE"));
serializedCert = getSerializedCertificate(certificate);
ident = getSerializedIdentity(mspid, serializedCert);
parallelism = Integer.parseInt(configs.get("PARELLELISM"));
blocksPerThread = Integer.parseInt(configs.get("BLOCKS_PER_THREAD"));
String[] IDs = configs.get("RECEIVERS").split("\\,");
int[] receivers = Arrays.asList(IDs).stream().mapToInt(Integer::parseInt).toArray();
this.receivers = new TreeSet<>();
for (int o : receivers) {
this.receivers.add(o);
}
}
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Use: java BFTNode <processId> [<config folder>]");
System.exit(-1);
}
String configFolder = null;
if (args.length > 1) configFolder = args[1];
new BFTNode(Integer.parseInt(args[0]),configFolder);
}
@Override
public void installSnapshot(byte[] state) {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(state);
DataInputStream in = new DataInputStream(bis);
sysChannel = in.readUTF();
sequence = in.readInt();
lastConfig = in.readLong();
receivers = new TreeSet<Integer>();
int n = in.readInt();
for (int i = 0; i < n; i++) {
receivers.add(new Integer(in.readInt()));
}
byte[] headers = new byte[0];
n = in.readInt();
if (n > 0) {
headers = new byte[n];
in.read(headers);
}
blockCutter = null;
n = in.readInt();
if (n > 0) {
byte[] b = new byte[n];
in.read(b);
blockCutter = new BlockCutter();
blockCutter.deserialize(b);
}
//deserialize headers
ByteArrayInputStream b = new ByteArrayInputStream(headers);
ObjectInput i = new ObjectInputStream(b);
this.lastBlockHeaders = (Map<String,Common.BlockHeader>) i.readObject();
i.close();
b.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
@Override
public byte[] getSnapshot() {
try {
//serialize block headers
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutput o = new ObjectOutputStream(b);
o.writeObject(lastBlockHeaders);
o.flush();
byte[] headers = b.toByteArray();
b.close();
o.close();
//serialize receivers
Integer[] orderers;
if (this.receivers != null) {
orderers = new Integer[this.receivers.size()];
this.receivers.toArray(orderers);
} else {
orderers = new Integer[0];
}
//serialize block cutter
byte[] blockcutter = (blockCutter != null ? blockCutter.serialize() : new byte[0]);
//concatenate bytes
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeUTF(sysChannel);
out.writeInt(sequence);
out.writeLong(lastConfig);
out.writeInt(orderers.length);
out.flush();
bos.flush();
for (int i = 0; i < orderers.length; i++) {
out.writeInt(orderers[i].intValue());
out.flush();
bos.flush();
}
out.writeInt(headers.length);
if (headers.length > 0) out.write(headers);
out.flush();
bos.flush();
out.writeInt(blockcutter.length);
if (blockcutter.length > 0) out.write(blockcutter);
out.flush();
bos.flush();
out.close();
bos.close();
return bos.toByteArray();
} catch (IOException ex) {
ex.printStackTrace();
}
return new byte[0];
}
@Override
public byte[][] appExecuteBatch(byte[][] commands, MessageContext[] msgCtxs, boolean fromConsensus) {
byte[][] replies = new byte[commands.length][];
for (int i = 0; i < commands.length; i++) {
if (msgCtxs != null && msgCtxs[i] != null) {
try {
replies[i] = executeSingle(commands[i], msgCtxs[i], fromConsensus);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return replies;
}
private byte[] executeSingle(byte[] command, MessageContext msgCtx, boolean fromConsensus) throws IOException {
if (receivers.contains(msgCtx.getSender())) {
if (msgCtx.getSequence() == 0) {
if (blockCutter == null) {
logger.info("Initializing blockcutter");
blockCutter = new BlockCutter(command);
}
byte[][] reply = new byte[2][];
reply[0] = "SEQUENCE".getBytes();
reply[1] = ByteBuffer.allocate(4).putInt(this.sequence).array();
return serializeContents(reply);
}
if (Arrays.equals("GETVIEW".getBytes(), command)) {
logger.info("A proxy is trying to fetch the most current view");
return new byte[0];
}
RequestTuple tuple = deserializeRequest(command);
if (tuple.type.equals("NEWCHANNEL")) {
if (tuple.channelID != null && lastBlockHeaders.get(tuple.channelID) == null) {
Common.BlockHeader header = null;
header = Common.BlockHeader.parseFrom(tuple.payload);
lastBlockHeaders.put(tuple.channelID, header);
logger.info("New channel ID: " + tuple.channelID);
logger.info("Genesis header number: " + lastBlockHeaders.get(tuple.channelID).getNumber());
logger.info("Genesis header previous hash: " + Arrays.toString(lastBlockHeaders.get(tuple.channelID).getPreviousHash().toByteArray()));
logger.info("Genesis header data hash: " + Arrays.toString(lastBlockHeaders.get(tuple.channelID).getDataHash().toByteArray()));
logger.info("Genesis header ASN1 encoding: " + Arrays.toString(encodeBlockHeaderASN1(lastBlockHeaders.get(tuple.channelID))));
if (msgCtx.getSequence() == 1) {
logger.info("Setting system channel to " + tuple.channelID);
sysChannel = tuple.channelID;
}
}
return new byte[0];
}
if (tuple.type.equals("TIMEOUT") && (blockCutter != null)) {
logger.info("Purging blockcutter for channel " + tuple.channelID);
byte[][] batch = blockCutter.cut(tuple.channelID);
if (batch.length > 0) {
assembleAndSend(batch, msgCtx, fromConsensus, tuple.channelID, false);
}
return new byte[0];
}
return new byte[0];
}
if (envelopeMeasurementStartTime == -1) {
envelopeMeasurementStartTime = System.currentTimeMillis();
}
countEnvelopes++;
if (countEnvelopes % interval == 0) {
float tp = (float) (interval * 1000 / (float) (System.currentTimeMillis() - envelopeMeasurementStartTime));
logger.info("Throughput = " + tp + " envelopes/sec");
envelopeMeasurementStartTime = System.currentTimeMillis();
}
logger.debug("Envelopes received: " + countEnvelopes);
List<byte[][]> batches = null;
RequestTuple tuple = deserializeRequest(command);
boolean isConfig = tuple.type.equals("CONFIG");
logger.debug("Received envelope" + Arrays.toString(tuple.payload) + " for channel id " + tuple.channelID + (isConfig ? " (type config)" : " (type normal)"));
String mspid = extractMSPID(tuple.payload);
if (mspid != null && this.mspid.equals(mspid)) {
batches = blockCutter.ordered(tuple.channelID, tuple.payload, isConfig);
if (batches != null) {
for (int i = 0; i < batches.size(); i++) {
assembleAndSend(batches.get(i), msgCtx, fromConsensus, tuple.channelID, isConfig);
}
}
}
else {
logger.info((mspid == null ? "Malformed envelope" : "Envelope's MSPID is unknown")+", discarding");
}
return "ACK".getBytes();
}
private void assembleAndSend(byte[][] batch, MessageContext msgCtx, boolean fromConsensus, String channel, boolean config) {
try {
if (blockMeasurementStartTime == -1) {
blockMeasurementStartTime = System.currentTimeMillis();
}
Common.Block block = createNextBlock(lastBlockHeaders.get(channel).getNumber() + 1, crypto.hash(encodeBlockHeaderASN1(lastBlockHeaders.get(channel))), batch);
if (config) {
Common.Envelope env = Common.Envelope.parseFrom(batch[0]);
Common.Payload payload = Common.Payload.parseFrom(env.getPayload());
Common.ChannelHeader chanHeader = Common.ChannelHeader.parseFrom(payload.getHeader().getChannelHeader());
if (chanHeader.getType() == Common.HeaderType.CONFIG_VALUE)
lastConfig = block.getHeader().getNumber();
}
countBlocks++;
if (countBlocks % interval == 0) {
float tp = (float) (interval * 1000 / (float) (System.currentTimeMillis() - blockMeasurementStartTime));
logger.info("Throughput = " + tp + " blocks/sec");
blockMeasurementStartTime = System.currentTimeMillis();
}
lastBlockHeaders.put(channel, block.getHeader());
if ((lastBlockHeaders.get(channel).getNumber() % 100) == 0)
System.out.println("[" + channel + "] Genesis header hash for header #" + lastBlockHeaders.get(channel).getNumber() + ": " + Arrays.toString(lastBlockHeaders.get(channel).getDataHash().toByteArray()));
//optimization to parellise signatures and sending
if (fromConsensus) { //if this is from the state transfer, there is no point in signing and sending yet again
if (sigIndex % blocksPerThread == 0) {
if (currentSST != null) {
currentSST.input(null, null, -1, null, false, -1);
}
currentSST = this.queue.take(); // fetch the first SSThread that is idle
}
currentSST.input(block, msgCtx, this.sequence, channel, config, lastConfig);
sigIndex++;
}
//Runnable SSThread = new SignerSenderThread(block, msgCtx, this.sequence);
//this.executor.execute(SSThread);
this.sequence++; // because of parelisation, I need to increment the sequence number in this method
//standard code for sequential signing and sending (with debbuging prints)
/*CommonProtos.Metadata blockSig = createMetadataSignature(("BFT-SMaRt::"+id).getBytes(), msgCtx.getNonces(), null, lastBlockHeader);
byte[] dummyConf= {0,0,0,0,0,0,0,1}; //TODO: find a way to implement the check that is done in the golang code
CommonProtos.Metadata configSig = createMetadataSignature(("BFT-SMaRt::"+id).getBytes(), msgCtx.getNonces(), dummyConf, lastBlockHeader);
sendToOrderers(block, blockSig, configSig, msgCtx);*/
} catch (NoSuchAlgorithmException | NoSuchProviderException | IOException | InterruptedException ex) {
Logger.getLogger(BFTNode.class.getName()).log(Level.SEVERE, null, ex);
}
}
/*private void sendToOrderers(Common.Block block, Common.Metadata blockSig, Common.Metadata configSig, MessageContext msgCtx) throws IOException {
byte[][] contents = new byte[3][];
contents[0] = block.toByteArray();
contents[1] = blockSig.toByteArray();
contents[2] = configSig.toByteArray();
TOMMessage reply = null;
reply = new TOMMessage(id,
msgCtx.getSession(),
sequence, //change sequence because the message is going to be received by all clients, not just the original sender
msgCtx.getOperationId(),
serializeContents(contents),
replica.getReplicaContext().getCurrentView().getId(),
msgCtx.getType());
if (reply == null) {
return;
}
int[] clients = replica.getReplicaContext().getServerCommunicationSystem().getClientsConn().getClients();
replica.getReplicaContext().getServerCommunicationSystem().send(clients, reply);
sequence++;
}*/
private byte[] serializeContents(byte[][] contents) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(contents.length);
out.flush();
bos.flush();
for (int i = 0; i < contents.length; i++) {
out.writeInt(contents[i].length);
out.write(contents[i]);
out.flush();
bos.flush();
}
out.close();
bos.close();
return bos.toByteArray();
}
private byte[] encodeBlockHeaderASN1(Common.BlockHeader header) throws IOException {
//convert long to byte array
//ByteArrayOutputStream bos = new ByteArrayOutputStream();
//ObjectOutput out = new ObjectOutputStream(bos);
//out.writeLong(header.getNumber());
//out.flush();
//bos.flush();
//out.close();
//bos.close();
//byte[] number = bos.toByteArray();
// encode the header in ASN1 format
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ASN1OutputStream asnos = new ASN1OutputStream(bos);
asnos.writeObject(new ASN1Integer((int) header.getNumber()));
//asnos.writeObject(new DERInteger((int) header.getNumber()));
asnos.writeObject(new DEROctetString(header.getPreviousHash().toByteArray()));
asnos.writeObject(new DEROctetString(header.getDataHash().toByteArray()));
asnos.flush();
bos.flush();
asnos.close();
bos.close();
byte[] buffer = bos.toByteArray();
//Add golang idiosyncrasies
byte[] bytes = new byte[buffer.length + 2];
bytes[0] = 48; // no idea what this means, but golang's encoding uses it
bytes[1] = (byte) buffer.length; // length of the rest of the octet string, also used by golang
for (int i = 0; i < buffer.length; i++) { // concatenate
bytes[i + 2] = buffer[i];
}
return bytes;
}
private Common.Block createNextBlock(long number, byte[] previousHash, byte[][] envs) throws NoSuchAlgorithmException, NoSuchProviderException {
//initialize
Common.BlockHeader.Builder blockHeaderBuilder = Common.BlockHeader.newBuilder();
Common.BlockData.Builder blockDataBuilder = Common.BlockData.newBuilder();
Common.BlockMetadata.Builder blockMetadataBuilder = Common.BlockMetadata.newBuilder();
Common.Block.Builder blockBuilder = Common.Block.newBuilder();
//create header
blockHeaderBuilder.setNumber(number);
blockHeaderBuilder.setPreviousHash(ByteString.copyFrom(previousHash));
blockHeaderBuilder.setDataHash(ByteString.copyFrom(crypto.hash(concatenate(envs))));
//create metadata
int numIndexes = Common.BlockMetadataIndex.values().length;
for (int i = 0; i < numIndexes; i++) {
blockMetadataBuilder.addMetadata(ByteString.EMPTY);
}
//create data
for (int i = 0; i < envs.length; i++) {
blockDataBuilder.addData(ByteString.copyFrom(envs[i]));
}
//crete block
blockBuilder.setHeader(blockHeaderBuilder.build());
blockBuilder.setMetadata(blockMetadataBuilder.build());
blockBuilder.setData(blockDataBuilder.build());
return blockBuilder.build();
}
private Common.Metadata createMetadataSignature(byte[] creator, byte[] nonce, byte[] plaintext, Common.BlockHeader blockHeader) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, IOException, CryptoException {
Common.Metadata.Builder metadataBuilder = Common.Metadata.newBuilder();
Common.MetadataSignature.Builder metadataSignatureBuilder = Common.MetadataSignature.newBuilder();
Common.SignatureHeader.Builder signatureHeaderBuilder = Common.SignatureHeader.newBuilder();
signatureHeaderBuilder.setCreator(ByteString.copyFrom(creator));
signatureHeaderBuilder.setNonce(ByteString.copyFrom(nonce));
Common.SignatureHeader sigHeader = signatureHeaderBuilder.build();
metadataSignatureBuilder.setSignatureHeader(sigHeader.toByteString());
byte[][] concat = {plaintext, sigHeader.toByteString().toByteArray(), encodeBlockHeaderASN1(blockHeader)};
//byte[] sig = sign(concatenate(concat));
byte[] sig = crypto.sign(privKey, concatenate(concat));
logger.debug("Signature for block #" + blockHeader.getNumber() + ": " + Arrays.toString(sig) + "\n");
//parseSig(sig);
metadataSignatureBuilder.setSignature(ByteString.copyFrom(sig));
metadataBuilder.setValue((plaintext != null ? ByteString.copyFrom(plaintext) : ByteString.EMPTY));
metadataBuilder.addSignatures(metadataSignatureBuilder);
return metadataBuilder.build();
}
private byte[] concatenate(byte[][] bytes) {
int totalLength = 0;
for (byte[] b : bytes) {
if (b != null) {
totalLength += b.length;
}
}
byte[] concat = new byte[totalLength];
int last = 0;
for (int i = 0; i < bytes.length; i++) {
if (bytes[i] != null) {
for (int j = 0; j < bytes[i].length; j++) {
concat[last + j] = bytes[i][j];
}
last += bytes[i].length;
}
}
return concat;
}
/*private void parseSig(byte[] sig) throws IOException {
ASN1InputStream input = new ASN1InputStream(sig);
ASN1Primitive p;
while ((p = input.readObject()) != null) {
ASN1Sequence asn1 = ASN1Sequence.getInstance(p);
ASN1Integer r = ASN1Integer.getInstance(asn1.getObjectAt(0));
ASN1Integer s = ASN1Integer.getInstance(asn1.getObjectAt(1));
logger.info("r (int): " + r.getValue().toString());
logger.info("s (int): " + s.getValue().toString());
logger.info("r (bytes): " + Arrays.toString(r.getValue().toByteArray()));
logger.info("s (bytes): " + Arrays.toString(s.getValue().toByteArray()));
}
}
public static byte[] sha256(byte[] bytes) throws NoSuchAlgorithmException, NoSuchProviderException {
MessageDigest digestEngine = MessageDigest.getInstance("SHA-256","SUN");
return digestEngine.digest(bytes);
}
private byte[] sign(byte[] text) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException, CryptoException {
Signature signEngine = Signature.getInstance("SHA256withECDSA", BouncyCastleProvider.PROVIDER_NAME);
signEngine.initSign(privKey);
signEngine.update(text);
return signEngine.sign();
}
private boolean verify(byte[] text, byte[] signature) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException, PEMException {
PublicKey k = new JcaPEMKeyConverter().getPublicKey(certificate.getSubjectPublicKeyInfo());
Signature signEngine = Signature.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
signEngine.initVerify(k);
signEngine.update(text);
return signEngine.verify(signature);
}*/
private PrivateKey getPemPrivateKey(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
PEMParser pp = new PEMParser(br);
Object obj = pp.readObject();
pp.close();
br.close();
if (obj instanceof PrivateKeyInfo) {
PrivateKeyInfo keyInfo = (PrivateKeyInfo) obj;
return (new JcaPEMKeyConverter().getPrivateKey(keyInfo));
} else {
PEMKeyPair pemKeyPair = (PEMKeyPair) obj;
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
return kp.getPrivate();
}
}
private X509CertificateHolder getCertificate(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
PEMParser pp = new PEMParser(br);
X509CertificateHolder ret = (X509CertificateHolder) pp.readObject();
br.close();
pp.close();
return ret;
}
private byte[] getSerializedCertificate(X509CertificateHolder certificate) throws IOException {
PemObject pemObj = (new PemObject("", certificate.getEncoded()));
StringWriter strWriter = new StringWriter();
PemWriter writer = new PemWriter(strWriter);
writer.writeObject(pemObj);
writer.close();
strWriter.close();
return strWriter.toString().getBytes();
}
private Identities.SerializedIdentity getSerializedIdentity(String Mspid, byte[] serializedCert) {
Identities.SerializedIdentity.Builder ident = Identities.SerializedIdentity.newBuilder();
ident.setMspid(Mspid);
ident.setIdBytes(ByteString.copyFrom(serializedCert));
return ident.build();
}
private RequestTuple deserializeRequest(byte[] request) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(request);
DataInput in = new DataInputStream(bis);
String type = in.readUTF();
String channelID = in.readUTF();
int l = in.readInt();
byte[] payload = new byte[l];
in.readFully(payload);
bis.close();
return new RequestTuple(type, channelID, payload);
}
@Override
public byte[] appExecuteUnordered(byte[] command, MessageContext msgCtx) {
return new byte[0];
}
private class SignerSenderThread implements Runnable {
private LinkedBlockingQueue<BFTTuple> input;
LinkedBlockingQueue<SignerSenderThread> queue;
private final Lock inputLock;
private final Condition notEmptyInput;
SignerSenderThread(LinkedBlockingQueue<SignerSenderThread> queue) throws NoSuchAlgorithmException, NoSuchProviderException, InterruptedException {
this.queue = queue;
this.input = new LinkedBlockingQueue<>();
this.inputLock = new ReentrantLock();
this.notEmptyInput = inputLock.newCondition();
this.queue.put(this);
}
public void input(Common.Block block, MessageContext msgContext, int seq, String channel, boolean config, long lastConfig) throws InterruptedException {
this.inputLock.lock();
this.input.put(new BFTTuple(block, msgContext, seq, channel, config, lastConfig));
this.notEmptyInput.signalAll();
this.inputLock.unlock();
}
@Override
public void run() {
while (true) {
try {
LinkedList<BFTTuple> list = new LinkedList<>();
this.inputLock.lock();
if (this.input.isEmpty()) {
this.notEmptyInput.await();
}
this.input.drainTo(list);
this.inputLock.unlock();
for (BFTTuple tuple : list) {
if (tuple.sequence == -1) {
this.queue.put(this);
break;
}
if (sigsMeasurementStartTime == -1) {
sigsMeasurementStartTime = System.currentTimeMillis();
}
//create signatures
Common.Metadata blockSig = createMetadataSignature(ident.toByteArray(), tuple.msgContext.getNonces(), null, tuple.block.getHeader());
Common.LastConfig.Builder last = Common.LastConfig.newBuilder();
last.setIndex(tuple.lastConf);
Common.Metadata configSig = createMetadataSignature(ident.toByteArray(), tuple.msgContext.getNonces(), last.build().toByteArray(), tuple.block.getHeader());
countSigs++;
if (countSigs % interval == 0) {
float tp = (float) (interval * 1000 / (float) (System.currentTimeMillis() - sigsMeasurementStartTime));
logger.info("Throughput = " + tp + " sigs/sec");
sigsMeasurementStartTime = System.currentTimeMillis();
}
//serialize contents
byte[][] contents = new byte[5][];
contents[0] = tuple.block.toByteArray();
contents[1] = blockSig.toByteArray();
contents[2] = configSig.toByteArray();
contents[3] = tuple.channelID.getBytes();
contents[4] = new byte[] { (tuple.config ? (byte) 1 :(byte) 0) };
byte[] serialized = serializeContents(contents);
// send contents to the orderers
TOMMessage reply = new TOMMessage(id,
tuple.msgContext.getSession(),
tuple.sequence, //change sequence because the message is going to be received by all clients, not just the original sender
tuple.msgContext.getOperationId(),
serialized,
tuple.msgContext.getViewID(),
tuple.msgContext.getType());
while (replica == null) {
replicaLock.lock();
replicaReady.await(1000, TimeUnit.MILLISECONDS);
replicaLock.lock();
}
int[] clients = replica.getServerCommunicationSystem().getClientsConn().getClients();
List<Integer> activeOrderers = new LinkedList<>();
for (Integer c : clients) {
if (receivers.contains(c)) {
activeOrderers.add(c);
}
}
int[] array = new int[activeOrderers.size()];
for (int i = 0; i < array.length; i++) {
array[i] = activeOrderers.get(i);
}
replica.getServerCommunicationSystem().send(array, reply);
}
} catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException | IOException | CryptoException | InterruptedException ex) {
Logger.getLogger(BFTNode.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private class BFTTuple {
Common.Block block = null;
MessageContext msgContext = null;
int sequence = -1;
String channelID = null;
boolean config = false;
long lastConf = -1;
BFTTuple(Common.Block block, MessageContext msgCtx, int sequence, String channelID, boolean config, long lastConf) {
this.block = block;
this.msgContext = msgCtx;
this.sequence = sequence;
this.channelID = channelID;
this.config = config;
this.lastConf = lastConf;
}
}
private class RequestTuple {
String type = null;
String channelID = null;
byte[] payload = null;
RequestTuple(String type, String channelID, byte[] payload) {
this.type = type;
this.channelID = channelID;
this.payload = payload;
}
}
private class NoopReplier extends DefaultReplier {
@Override
public void manageReply(TOMMessage tomm, MessageContext mc) {
// send reply only if it is one of the clients from the connection pool or if it is the first message of the proxy
if (!receivers.contains(tomm.getSender()) || (receivers.contains(tomm.getSender()) && tomm.getSequence() == 0)) {
super.manageReply(tomm, mc);
}
}
}
}
| 36.488995 | 261 | 0.580814 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.