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 |
|---|---|---|---|---|---|
b69423f093e5a7edadb44af0ed526874545dd985 | 1,229 | package me.joshmcfarlin.cryptocompareapi.api;
import com.google.gson.Gson;
import me.joshmcfarlin.cryptocompareapi.CryptoCompareAPIConstant;
import me.joshmcfarlin.cryptocompareapi.Exceptions.OutOfCallsException;
import me.joshmcfarlin.cryptocompareapi.models.social.SocialStats;
import me.joshmcfarlin.cryptocompareapi.utils.Connection;
import java.io.IOException;
import java.io.Reader;
/**
* Contains methods for requesting information about social media accounts for cryptocurrencies and exchanges
* @author Josh McFarlin
*/
public class Social {
/**
* Gets social media information about a provided cryptocurrency or exchange
* @param id The CryptoCompare ID to find information for
* @return SocialStats a object containing different API data
* @throws IOException when a connection cannot be made
* @throws OutOfCallsException when no more API calls are available
*/
public SocialStats getStats(int id) throws IOException, OutOfCallsException {
String formattedUrl = CryptoCompareAPIConstant.CRYPTO_API_URL + "/socialstats/?id=" + id;
Reader r = Connection.getJSONWithLimitVerif(formattedUrl);
return new Gson().fromJson(r, SocialStats.class);
}
}
| 38.40625 | 109 | 0.7738 |
dd0e2983979d4ad8b3da0d828f6984d0d271c2fa | 2,879 | package org.kairosdb.client.testUtils;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.gson.*;
import org.kairosdb.client.builder.Grouper;
import org.kairosdb.client.builder.QueryBuilder;
import org.kairosdb.client.builder.grouper.TagGrouper;
import org.kairosdb.client.builder.grouper.TimeGrouper;
import org.kairosdb.client.builder.grouper.ValueGrouper;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.TimeZone;
public class QueryParser
{
private final Gson gson;
public QueryParser()
{
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(ListMultimap.class, new ListMuliMapDeserializer());
gsonBuilder.registerTypeAdapter(TimeZone.class, new TimeZoneDeserializer());
gsonBuilder.registerTypeAdapter(Grouper.class, new GrouperDeserializer());
gson = gsonBuilder.create();
}
public QueryBuilder parse(String json)
{
return gson.fromJson(json, QueryBuilder.class);
}
private class ListMuliMapDeserializer implements JsonDeserializer<ListMultimap<String, String>>
{
@Override
public ListMultimap<String, String> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException
{
ListMultimap<String, String> map = ArrayListMultimap.create();
JsonObject asJsonObject = jsonElement.getAsJsonObject();
for (Map.Entry<String, JsonElement> entry : asJsonObject.entrySet())
{
map.put(entry.getKey(), entry.getValue().getAsString());
}
return map;
}
}
private class TimeZoneDeserializer implements JsonDeserializer<TimeZone> {
@Override
public TimeZone deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException
{
return TimeZone.getTimeZone(jsonElement.getAsString());
}
}
private class GrouperDeserializer implements JsonDeserializer<Grouper> {
@Override
public Grouper deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException
{
JsonObject jsGroupBy = jsonElement.getAsJsonObject();
JsonElement nameElement = jsGroupBy.get("name");
if (nameElement == null || nameElement.getAsString().isEmpty())
{
throw new JsonParseException("name cannot be null");
}
String name = nameElement.getAsString();
if (name.equals("tag"))
{
return jsonDeserializationContext.deserialize(jsonElement, TagGrouper.class);
}
else if (name.equals("time"))
{
return jsonDeserializationContext.deserialize(jsonElement, TimeGrouper.class);
}
else if (name.equals("value"))
{
return jsonDeserializationContext.deserialize(jsonElement, ValueGrouper.class);
}
else
{
throw new JsonParseException("Invalid group_by: " + name);
}
}
}
}
| 31.637363 | 166 | 0.77388 |
cf1b0efc6532c9b176ed63c26e55cb43022bb233 | 1,329 | /*
* Copyright 2021 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.imagemgmt.services;
import azkaban.imagemgmt.dto.ImageVersionMetadataResponseDTO;
import azkaban.imagemgmt.exception.ImageMgmtException;
import java.util.Map;
public interface ImageVersionMetadataService {
/**
* Method for getting image version metadata such as version specific details, rampup information.
* This method provides image version information and rampup details in
* ImageVersionMetadataResponseDTO format and used as a response for dispaying on /status API
* page.
* @return Map<String, ImageVersionMetadataResponseDTO>
* @throws ImageMgmtException
*/
public Map<String, ImageVersionMetadataResponseDTO> getVersionMetadataForAllImageTypes()
throws ImageMgmtException;
}
| 37.971429 | 100 | 0.776524 |
d9aa7b318f78bbe3bcd2a47e6f29a63b0a78318d | 4,737 | /*
* Copyright 2016-2017 Lukhnos Liu. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lukhnos.nnio.file.spi;
import org.lukhnos.nnio.channels.AsynchronousFileChannel;
import org.lukhnos.nnio.file.AccessMode;
import org.lukhnos.nnio.file.CopyOption;
import org.lukhnos.nnio.file.DirectoryStream;
import org.lukhnos.nnio.file.FileStore;
import org.lukhnos.nnio.file.FileSystem;
import org.lukhnos.nnio.file.LinkOption;
import org.lukhnos.nnio.file.OpenOption;
import org.lukhnos.nnio.file.Path;
import org.lukhnos.nnio.file.attribute.BasicFileAttributes;
import org.lukhnos.nnio.file.attribute.FileAttribute;
import org.lukhnos.nnio.file.attribute.FileAttributeView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
/**
* Substitute for {@link java.nio.file.spi.FileSystemProvider}.
*/
public abstract class FileSystemProvider {
public abstract void checkAccess(Path var1, AccessMode... var2) throws IOException;
public abstract void copy(Path p1, Path p2, CopyOption... options) throws IOException;
public abstract void createDirectory(Path path, FileAttribute<?>... attrs) throws IOException;
public void createLink(Path p1, Path p2) throws IOException {
throw new UnsupportedOperationException();
}
public void createSymbolicLink(Path p1, Path p2, FileAttribute<?>... attrs) throws IOException {
throw new UnsupportedOperationException();
}
public abstract void delete(Path path) throws IOException;
public boolean deleteIfExists(Path path) throws IOException {
throw new UnsupportedOperationException();
}
public abstract <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> cls, LinkOption... options);
public abstract FileStore getFileStore(Path var1) throws IOException;
public abstract FileSystem getFileSystem(URI uri);
public abstract Path getPath(URI var1);
public abstract String getScheme();
public abstract boolean isHidden(Path var1) throws IOException;
public abstract boolean isSameFile(Path var1, Path var2) throws IOException;
public abstract void move(Path p1, Path p2, CopyOption... options) throws IOException;
public AsynchronousFileChannel newAsynchronousFileChannel(Path path, Set<? extends OpenOption> options,
ExecutorService executor, FileAttribute<?>... attrs)
throws IOException {
throw new UnsupportedOperationException();
}
public abstract SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options,
FileAttribute<?>... attrs) throws IOException;
public abstract DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter)
throws IOException;
public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws
IOException {
throw new UnsupportedOperationException();
}
public abstract FileSystem newFileSystem(URI var1, Map<String, ?> var2) throws IOException;
public FileSystem newFileSystem(Path var1, Map<String, ?> var2) throws IOException {
throw new UnsupportedOperationException();
}
public InputStream newInputStream(Path path, OpenOption... options) throws IOException {
throw new UnsupportedOperationException();
}
public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
throw new UnsupportedOperationException();
}
public abstract <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> cls, LinkOption... options)
throws IOException;
public abstract Map<String, Object> readAttributes(Path path, String str, LinkOption... options) throws IOException;
public Path readSymbolicLink(Path path) throws IOException {
throw new UnsupportedOperationException();
}
public abstract void setAttribute(Path path, String str, Object obj, LinkOption... options) throws IOException;
}
| 38.201613 | 119 | 0.759341 |
b43078499e93daff96341acda17447509d38e104 | 3,905 | package com.fanxin.huangfangyi.main.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fanxin.huangfangyi.R;
import com.fanxin.huangfangyi.main.FXConstant;
import com.fanxin.huangfangyi.main.db.ACache;
import com.fanxin.huangfangyi.main.fragment.ChatFragment;
import com.fanxin.huangfangyi.main.fragment.MainActivity;
import com.fanxin.huangfangyi.main.utils.OkHttpManager;
import com.fanxin.huangfangyi.main.utils.Param;
import com.fanxin.huangfangyi.runtimepermissions.PermissionsManager;
import com.fanxin.huangfangyi.ui.BaseActivity;
import com.fanxin.easeui.EaseConstant;
import com.fanxin.easeui.ui.EaseChatFragment;
import com.hyphenate.util.EasyUtils;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class ChatActivity extends BaseActivity {
public static ChatActivity activityInstance;
private EaseChatFragment chatFragment;
public String toChatUsername;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.em_activity_chat);
activityInstance = this;
//get user id or group id
toChatUsername = getIntent().getExtras().getString("userId");
//use EaseChatFratFragment
chatFragment = new ChatFragment();
//pass parameters to chat fragment
chatFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();
int chatTypeTemp = getIntent().getIntExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
if(chatTypeTemp==EaseConstant.CHATTYPE_GROUP){
getGroupMembersInServer(toChatUsername);
}
}
private void getGroupMembersInServer(final String groupId) {
List<Param> params = new ArrayList<>();
params.add(new Param("groupId", groupId));
OkHttpManager.getInstance().post(params, FXConstant.URL_GROUP_MEMBERS, new OkHttpManager.HttpCallBack() {
@Override
public void onResponse(JSONObject jsonObject) {
if (jsonObject.containsKey("code")) {
int code = Integer.parseInt(jsonObject.getString("code"));
if (code == 1000) {
if (jsonObject.containsKey("data") && jsonObject.get("data") instanceof JSONArray) {
JSONArray jsonArray = jsonObject.getJSONArray("data");
ACache.get(getApplicationContext()).put(groupId, jsonArray);
}
}
}
}
@Override
public void onFailure(String errorMsg) {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
activityInstance = null;
}
@Override
protected void onNewIntent(Intent intent) {
// make sure only one chat activity is opened
String username = intent.getStringExtra("userId");
if (toChatUsername.equals(username))
super.onNewIntent(intent);
else {
finish();
startActivity(intent);
}
}
@Override
public void onBackPressed() {
chatFragment.onBackPressed();
if (EasyUtils.isSingleActivity(this)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
public String getToChatUsername(){
return toChatUsername;
}
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
}
}
| 32.272727 | 113 | 0.659667 |
188574f57ab1bc4599644f22788fb8acd6dd4b29 | 1,946 | /*
* Copyright 2017-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.yang.runtime.impl;
import org.onosproject.yang.compiler.datamodel.TraversalType;
import org.onosproject.yang.compiler.datamodel.YangNode;
/**
* Represents model converter Traversal info which is needed every time the traversal of
* a YANG node happens. This contains YANG node and its corresponding traversal
* type information.
*/
class ModelConverterTraversalInfo {
/**
* YANG node of the current traversal.
*/
private final YangNode yangNode;
/**
* Traverse type of the current traversal.
*/
private final TraversalType traverseType;
/**
* Creates model converter traversal info by taking the traversal type and the YANG
* node.
*
* @param yangNode YANG node
* @param traverseType traversal type
*/
ModelConverterTraversalInfo(YangNode yangNode, TraversalType traverseType) {
this.yangNode = yangNode;
this.traverseType = traverseType;
}
/**
* Returns the YANG node of the current traversal.
*
* @return YANG node
*/
YangNode getYangNode() {
return yangNode;
}
/**
* Returns the traversal type of the current traversal.
*
* @return traversal type
*/
TraversalType getTraverseType() {
return traverseType;
}
}
| 28.202899 | 89 | 0.690647 |
76bc8181c30db12dc1aa9269eabd74a3de32d2ad | 2,734 | package es.upm.miw.apaw_practice.adapters.mongodb.school.entities;
import es.upm.miw.apaw_practice.domain.models.school.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.LocalDateTime;
@Document
public class SubjectEntity {
@DBRef
private TeacherEntity teacherEntity;
@Id
private String id;
private String name;
private LocalDateTime creationDate;
private String knowledgeArea;
public SubjectEntity() {
//empty for framework
}
public static Builder builder(TeacherEntity teacherEntity, String name) {
return new Builder(teacherEntity, name);
}
public TeacherEntity getTeacherEntity() {
return teacherEntity;
}
public void setTeacherEntity(TeacherEntity teacherEntity) {
this.teacherEntity = teacherEntity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDateTime getCreationDate() {
return creationDate;
}
public void setCreationDate(LocalDateTime creationDate) {
this.creationDate = creationDate;
}
public String getKnowledgeArea() {
return knowledgeArea;
}
public void setKnowledgeArea(String knowledgeArea) {
this.knowledgeArea = knowledgeArea;
}
public Subject toSubject() {
Subject subject = new Subject();
BeanUtils.copyProperties(this, subject);
return subject;
}
@Override
public String toString() {
return "SubjectEntity{" +
"teacherEntity=" + teacherEntity +
", id='" + id + '\'' +
", name='" + name + '\'' +
", creationDate=" + creationDate +
", knowledgeArea='" + knowledgeArea + '\'' +
'}';
}
public static class Builder {
private final SubjectEntity subject;
private Builder(TeacherEntity teacherEntity, String name) {
this.subject = new SubjectEntity();
this.subject.teacherEntity = teacherEntity;
this.subject.name = name;
this.subject.creationDate = LocalDateTime.now();
}
public Builder knowledgeArea(String knowledgeArea) {
this.subject.knowledgeArea = knowledgeArea;
return this;
}
public SubjectEntity build() {
return this.subject;
}
}
}
| 25.551402 | 77 | 0.626554 |
bdce66860977038d0f0195acb47d81207f822c36 | 3,445 | package com.oktaice.scim.model.scim;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ScimGroupPatchOp extends ScimPatchOp {
/**
* The body of an HTTP PATCH request MUST contain the attribute "Operations",
* whose value is an array of one or more PATCH operations.
*/
@JsonProperty("Operations")
private List<Operation> operations = new ArrayList<>();
// sets patch op schema
public ScimGroupPatchOp() {
super();
}
public List<Operation> getOperations() {
return operations;
}
public void setOperations(List<Operation> operations) {
this.operations = operations;
}
/**
* The Operation object contains six attributes.
* The string attribute op, and the value attribute is similar to ScimUserPatchOp.
* You modify the memberValues to make change of group members,
* and modify the groupValue to make change to the group itself.
*/
public static class Operation {
private String op;
private String path;
private Object value;
@JsonIgnore
private ObjectMapper mapper = new ObjectMapper();
private List<MemberValue> memberValues = new ArrayList<>();
private GroupValue groupValue;
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
if (value instanceof Map) {
groupValue = mapper.convertValue(value, GroupValue.class);
} else if (value instanceof List) {
memberValues = mapper.convertValue(value, new TypeReference<List<MemberValue>>(){});
}
}
public List<MemberValue> getMemberValues() {
return memberValues;
}
public GroupValue getGroupValue() {
return groupValue;
}
public static class MemberValue {
private String value;
private String display;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDisplay() {
return display;
}
public void setDisplay(String display) {
this.display = display;
}
}
public static class GroupValue {
private String id;
private String displayName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
}
}
| 25.330882 | 100 | 0.570392 |
3c8975b52e7649be6cdc0c376351dbd7d9bcca1d | 1,685 | /**
* Copyright (c) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trustedanalytics.platformoperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.trustedanalytics.platformoperations.repository.PlatformSummaryMongoRepository;
@Component
public class ApplicationStartedFilter implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationStartedFilter.class);
private final PlatformSummaryMongoRepository repository;
@Autowired
public ApplicationStartedFilter(PlatformSummaryMongoRepository repository) {
this.repository = repository;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
LOGGER.info("State of database: " + repository.count() + " items");
LOGGER.info("Clearing database");
repository.deleteAll();
}
}
| 34.387755 | 97 | 0.775668 |
6f282dbde041cba0891ae23a875e3e3a59c37619 | 168 | package com.notronix.etsy.api.model;
public enum ReceiptAssociations
{
Country,
Buyer,
GuestBuyer,
Seller,
Transactions,
Listings
}
| 14 | 37 | 0.636905 |
93d4bb8a8a1478bdf9f0a0e90fc0fc194a6efffc | 1,632 | package mdhim;
import org.bridj.BridJ;
import org.bridj.Pointer;
import org.bridj.StructObject;
import org.bridj.ann.Field;
import org.bridj.ann.Library;
/**
* <i>native declaration : mdhim-tng-ycsb/src/range_server.h:1368</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> or <a href="http://bridj.googlecode.com/">BridJ</a> .
*/
@Library("mdhim")
public abstract class out_req extends StructObject {
static {
BridJ.register();
}
/** C type : out_req* */
@Field(0)
public Pointer<out_req > next() {
return this.io.getPointerField(this, 0);
}
/** C type : out_req* */
@Field(0)
public out_req next(Pointer<out_req > next) {
this.io.setPointerField(this, 0, next);
return this;
}
/** C type : out_req* */
@Field(1)
public Pointer<out_req > prev() {
return this.io.getPointerField(this, 1);
}
/** C type : out_req* */
@Field(1)
public out_req prev(Pointer<out_req > prev) {
this.io.setPointerField(this, 1, prev);
return this;
}
/** C type : void* */
@Field(2)
public Pointer<? > req() {
return this.io.getPointerField(this, 2);
}
/** C type : void* */
@Field(2)
public out_req req(Pointer<? > req) {
this.io.setPointerField(this, 2, req);
return this;
}
/** Conversion Error : MPI_Request* (failed to convert type to Java (undefined type)) */
}
| 30.792453 | 183 | 0.675245 |
5276e73f7eaf164fe9767fba69da4819484f9b56 | 2,098 | package com.hyd.jfapps.httprequest;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.web.WebView;
import lombok.Getter;
import java.util.Map;
@Getter
public abstract class HttpToolView implements Initializable {
@FXML
protected TextField urlTextField;
@FXML
protected ChoiceBox<String> methodChoiceBox;
@FXML
protected Button sendButton;
@FXML
protected Button toBrowerButton;
@FXML
protected CheckBox paramsDataCheckBox;
@FXML
private Button addParamsDataButton;
@FXML
protected CheckBox paramsDataIsStringCheckBox;
@FXML
protected TextArea paramsDataTextArea;
@FXML
protected TableView<Map<String, String>> paramsDataTableView;
@FXML
protected TableColumn<Map<String, String>, String> paramsDataNameTableColumn;
@FXML
protected TableColumn<Map<String, String>, String> paramsDataValueTableColumn;
@FXML
protected TableColumn<Map<String, String>, String> paramsDataRemarkTableColumn;
@FXML
protected CheckBox paramsHeaderCheckBox;
@FXML
private Button addParamsHeaderButton;
@FXML
protected TableView<Map<String, String>> paramsHeaderTableView;
@FXML
protected TableColumn<Map<String, String>, String> paramsHeaderNameTableColumn;
@FXML
protected TableColumn<Map<String, String>, String> paramsHeaderValueTableColumn;
@FXML
protected TableColumn<Map<String, String>, String> paramsHeaderRemarkTableColumn;
@FXML
protected CheckBox paramsCookieCheckBox;
@FXML
private Button addParamsCookieButton;
@FXML
protected TableView<Map<String, String>> paramsCookieTableView;
@FXML
protected TableColumn<Map<String, String>, String> paramsCookieNameTableColumn;
@FXML
protected TableColumn<Map<String, String>, String> paramsCookieValueTableColumn;
@FXML
protected TableColumn<Map<String, String>, String> paramsCookieRemarkTableColumn;
@FXML
protected TextArea ResponseBodyTextArea;
@FXML
protected TextArea ResponseHeaderTextArea;
@FXML
protected WebView ResponseHtmlWebView;
@FXML
protected ImageView ResponseImgImageView;
} | 29.549296 | 82 | 0.811249 |
d34ebf24b3c09f0be21d246271302b9941b4549b | 580 | package br.com.zup.mercadolivre.compra.data.repository;
import br.com.zup.mercadolivre.compra.data.domain.Compra;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface CompraRepository extends JpaRepository<Compra,Long> {
@Query("SELECT c FROM Compra c JOIN c.produtos p JOIN p.produto prod JOIN prod.caracteristicas LEFT JOIN prod.imagens WHERE c.id = ?1")
Optional<Compra> findByIdFetch(Long id);
}
| 38.666667 | 139 | 0.808621 |
ff6f7a90eea4612b52087b370884666866481f01 | 3,761 | /**
* Copyright (c) 2016-2018, the Alpha Team.
* All rights reserved.
*
* Additional changes made by Siemens.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package at.ac.tuwien.kr.alpha.grounder.atoms;
import at.ac.tuwien.kr.alpha.common.Predicate;
import at.ac.tuwien.kr.alpha.common.atoms.Atom;
import at.ac.tuwien.kr.alpha.common.atoms.Literal;
import at.ac.tuwien.kr.alpha.common.rule.InternalRule;
import at.ac.tuwien.kr.alpha.common.terms.ConstantTerm;
import at.ac.tuwien.kr.alpha.common.terms.Term;
import at.ac.tuwien.kr.alpha.grounder.Substitution;
import java.util.Arrays;
import java.util.List;
import static at.ac.tuwien.kr.alpha.common.terms.ConstantTerm.getInstance;
/**
* Atoms corresponding to rule bodies use this predicate, first term is rule number,
* second is a term containing variable substitutions.
*/
public class RuleAtom extends Atom {
public static final Predicate PREDICATE = Predicate.getInstance("_R_", 2, true, true);
private final List<ConstantTerm<String>> terms;
private RuleAtom(List<ConstantTerm<String>> terms) {
if (terms.size() != 2) {
throw new IllegalArgumentException();
}
this.terms = terms;
}
public RuleAtom(InternalRule nonGroundRule, Substitution substitution) {
this(Arrays.asList(
getInstance(Integer.toString(nonGroundRule.getRuleId())),
getInstance(substitution.toString())
)
);
}
@Override
public Predicate getPredicate() {
return PREDICATE;
}
@Override
public List<Term> getTerms() {
return Arrays.asList(terms.get(0), terms.get(1));
}
@Override
public boolean isGround() {
// NOTE: Both terms are ConstantTerms, which are ground by definition.
return true;
}
@Override
public Literal toLiteral(boolean positive) {
throw new UnsupportedOperationException("RuleAtom cannot be literalized");
}
@Override
public Atom substitute(Substitution substitution) {
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RuleAtom that = (RuleAtom) o;
return terms.equals(that.terms);
}
@Override
public int hashCode() {
return 31 * PREDICATE.hashCode() + terms.hashCode();
}
@Override
public String toString() {
return PREDICATE.getName() + "(" + terms.get(0) + "," + terms.get(1) + ')';
}
@Override
public Atom withTerms(List<Term> terms) {
throw new UnsupportedOperationException("RuleAtoms do not support setting of terms!");
}
}
| 30.577236 | 88 | 0.738633 |
bed5efac815ca3dd56be0c6de8c689a059646422 | 276 | package com.sampa.camerax.arch.camera;
public interface ICameraModel {
void validatePath(String path, ICameraModel.ICameraModelCallback callback);
interface ICameraModelCallback {
void onValidatePathSuccess();
void onValidatePathFailure(Throwable t);
}
}
| 17.25 | 76 | 0.775362 |
442b3240e9f04bbe46842cfcaf354b2adafec0d2 | 12,215 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.slice;
import static android.app.slice.Slice.HINT_ACTIONS;
import static android.app.slice.Slice.HINT_PARTIAL;
import static android.app.slice.Slice.HINT_SHORTCUT;
import static android.app.slice.SliceItem.FORMAT_ACTION;
import static android.app.slice.SliceItem.FORMAT_IMAGE;
import static android.app.slice.SliceItem.FORMAT_REMOTE_INPUT;
import static android.app.slice.SliceItem.FORMAT_SLICE;
import static android.app.slice.SliceItem.FORMAT_TEXT;
import static androidx.slice.SliceMetadata.LOADED_ALL;
import static androidx.slice.SliceMetadata.LOADED_NONE;
import static androidx.slice.SliceMetadata.LOADED_PARTIAL;
import static androidx.slice.core.SliceHints.HINT_KEYWORDS;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.slice.core.SliceQuery;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.util.ArrayList;
import java.util.List;
/**
* Utilities for dealing with slices.
*/
public class SliceUtils {
private SliceUtils() {
}
/**
* Serialize a slice to an OutputStream.
* <p>
* The slice can later be read into slice form again with {@link #parseSlice}.
* Some slice types cannot be serialized, their handling is controlled by
* {@link SerializeOptions}.
*
* @param s The slice to serialize.
* @param context Context used to load any resources in the slice.
* @param output The output of the serialization.
* @param encoding The encoding to use for serialization.
* @param options Options defining how to handle non-serializable items.
* @throws IllegalArgumentException if the slice cannot be serialized using the given options.
*/
public static void serializeSlice(@NonNull Slice s, @NonNull Context context,
@NonNull OutputStream output, @NonNull String encoding,
@NonNull SerializeOptions options) throws IOException, IllegalArgumentException {
SliceXml.serializeSlice(s, context, output, encoding, options);
}
/**
* Parse a slice that has been previously serialized.
* <p>
* Parses a slice that was serialized with {@link #serializeSlice}.
* <p>
* Note: Slices returned by this cannot be passed to {@link SliceConvert#unwrap(Slice)}.
*
* @param input The input stream to read from.
* @param encoding The encoding to read as.
* @param listener Listener used to handle actions when reconstructing the slice.
* @throws SliceParseException if the InputStream cannot be parsed.
*/
public static @NonNull Slice parseSlice(@NonNull Context context, @NonNull InputStream input,
@NonNull String encoding, @NonNull SliceActionListener listener)
throws IOException, SliceParseException {
return SliceXml.parseSlice(context, input, encoding, listener);
}
/**
* Holds options for how to handle SliceItems that cannot be serialized.
*/
public static class SerializeOptions {
/**
* Constant indicating that the an {@link IllegalArgumentException} should be thrown
* when this format is encountered.
*/
public static final int MODE_THROW = 0;
/**
* Constant indicating that the SliceItem should be removed when this format is encountered.
*/
public static final int MODE_REMOVE = 1;
/**
* Constant indicating that the SliceItem should be serialized as much as possible.
* <p>
* For images this means they will be attempted to be serialized. For actions, the
* action will be removed but the content of the action will be serialized. The action
* may be triggered later on a de-serialized slice by binding the slice again and activating
* a pending-intent at the same location as the serialized action.
*/
public static final int MODE_CONVERT = 2;
@IntDef({MODE_THROW, MODE_REMOVE, MODE_CONVERT})
@Retention(SOURCE)
@interface FormatMode {
}
private int mActionMode = MODE_THROW;
private int mImageMode = MODE_THROW;
private int mMaxWidth = 1000;
private int mMaxHeight = 1000;
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public void checkThrow(String format) {
switch (format) {
case FORMAT_ACTION:
case FORMAT_REMOTE_INPUT:
if (mActionMode != MODE_THROW) return;
break;
case FORMAT_IMAGE:
if (mImageMode != MODE_THROW) return;
break;
default:
return;
}
throw new IllegalArgumentException(format + " cannot be serialized");
}
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public @FormatMode int getActionMode() {
return mActionMode;
}
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public @FormatMode int getImageMode() {
return mImageMode;
}
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public int getMaxWidth() {
return mMaxWidth;
}
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public int getMaxHeight() {
return mMaxHeight;
}
/**
* Sets how {@link android.app.slice.SliceItem#FORMAT_ACTION} items should be handled.
*
* The default mode is {@link #MODE_THROW}.
* @param mode The desired mode.
*/
public SerializeOptions setActionMode(@FormatMode int mode) {
mActionMode = mode;
return this;
}
/**
* Sets how {@link android.app.slice.SliceItem#FORMAT_IMAGE} items should be handled.
*
* The default mode is {@link #MODE_THROW}.
* @param mode The desired mode.
*/
public SerializeOptions setImageMode(@FormatMode int mode) {
mImageMode = mode;
return this;
}
/**
* Set the maximum width of an image to use when serializing.
* <p>
* Will only be used if the {@link #setImageMode(int)} is set to {@link #MODE_CONVERT}.
* Any images larger than the maximum size will be scaled down to fit within that size.
* The default value is 1000.
*/
public SerializeOptions setMaxImageWidth(int width) {
mMaxWidth = width;
return this;
}
/**
* Set the maximum height of an image to use when serializing.
* <p>
* Will only be used if the {@link #setImageMode(int)} is set to {@link #MODE_CONVERT}.
* Any images larger than the maximum size will be scaled down to fit within that size.
* The default value is 1000.
*/
public SerializeOptions setMaxImageHeight(int height) {
mMaxHeight = height;
return this;
}
}
/**
* Indicates this slice is empty and waiting for content to be loaded.
*
* @deprecated TO BE REMOVED: use {@link SliceMetadata#LOADED_NONE}
*/
@Deprecated
public static final int LOADING_ALL = 0;
/**
* Indicates this slice has some content but is waiting for other content to be loaded.
*
* @deprecated TO BE REMOVED: use {@link SliceMetadata#LOADED_PARTIAL}
*/
@Deprecated
public static final int LOADING_PARTIAL = 1;
/**
* Indicates this slice has fully loaded and is not waiting for other content.
*
* @deprecated TO BE REMOVED: use {@link SliceMetadata#LOADED_ALL}
*/
@Deprecated
public static final int LOADING_COMPLETE = 2;
/**
* @return the current loading state of the provided {@link Slice}.
*
* @deprecated TO BE REMOVED: use {@link SliceMetadata#getLoadingState()}
*/
@Deprecated
public static int getLoadingState(@NonNull Slice slice) {
// Check loading state
boolean hasHintPartial =
SliceQuery.find(slice, null, HINT_PARTIAL, null) != null;
if (slice.getItems().size() == 0) {
// Empty slice
return LOADED_NONE;
} else if (hasHintPartial) {
// Slice with specific content to load
return LOADED_PARTIAL;
} else {
// Full slice
return LOADED_ALL;
}
}
/**
* @return the group of actions associated with the provided slice, if they exist.
*
* @deprecated TO BE REMOVED; use {@link SliceMetadata#getSliceActions()}
*/
@Deprecated
@Nullable
public static List<SliceItem> getSliceActions(@NonNull Slice slice) {
SliceItem actionGroup = SliceQuery.find(slice, FORMAT_SLICE, HINT_ACTIONS, null);
String[] hints = new String[] {HINT_ACTIONS, HINT_SHORTCUT};
return (actionGroup != null)
? SliceQuery.findAll(actionGroup, FORMAT_SLICE, hints, null)
: null;
}
/**
* @return the list of keywords associated with the provided slice, null if no keywords were
* specified or an empty list if the slice was specified to have no keywords.
*
* @deprecated TO BE REMOVED; use {@link SliceMetadata#getSliceKeywords()}
*/
@Deprecated
@Nullable
public static List<String> getSliceKeywords(@NonNull Slice slice) {
SliceItem keywordGroup = SliceQuery.find(slice, FORMAT_SLICE, HINT_KEYWORDS, null);
if (keywordGroup != null) {
List<SliceItem> itemList = SliceQuery.findAll(keywordGroup, FORMAT_TEXT);
if (itemList != null) {
ArrayList<String> stringList = new ArrayList<>();
for (int i = 0; i < itemList.size(); i++) {
String keyword = (String) itemList.get(i).getText();
if (!TextUtils.isEmpty(keyword)) {
stringList.add(keyword);
}
}
return stringList;
}
}
return null;
}
/**
* A listener used to receive events on slices parsed with
* {@link #parseSlice(Context, InputStream, String, SliceActionListener)}.
*/
public interface SliceActionListener {
/**
* Called when an action is triggered on a slice parsed with
* {@link #parseSlice(Context, InputStream, String, SliceActionListener)}.
* @param actionUri The uri of the action selected.
*/
void onSliceAction(Uri actionUri);
}
/**
* Exception thrown during
* {@link #parseSlice(Context, InputStream, String, SliceActionListener)}.
*/
public static class SliceParseException extends Exception {
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public SliceParseException(String s, Throwable e) {
super(s, e);
}
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public SliceParseException(String s) {
super(s);
}
}
}
| 35 | 100 | 0.625706 |
f790aa7a39ec7c7739c37b3c51c8389172fca756 | 5,161 | package tv.dyndns.kishibe.qmaclone.client.game.input;
import java.util.Collections;
import java.util.List;
import tv.dyndns.kishibe.qmaclone.client.constant.Constant;
import tv.dyndns.kishibe.qmaclone.client.game.AnswerView;
import tv.dyndns.kishibe.qmaclone.client.game.SessionData;
import tv.dyndns.kishibe.qmaclone.client.game.panel.QuestionPanel;
import tv.dyndns.kishibe.qmaclone.client.packet.PacketProblem;
import tv.dyndns.kishibe.qmaclone.client.util.Random;
import com.allen_sauer.gwt.dnd.client.PickupDragController;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
public class InputWidgetGroup extends InputWidget implements ClickHandler {
private static final String STYLE_NAME_GROUP = "gwt-Button-group";
private static final String STYLE_NAME_GROUP_HEADER = "gwt-Button-group-header";
private static final String STYLE_NAME_GROUP_CONTROL = "gwt-Button-group-control";
private static final int draggableOffsetHeight = 30;
private AbsolutePanel gridConstrainedDropTarget;
private final List<Label> labelChoices = Lists.newArrayList();
private final Button buttonOk = new Button("OK", this);
private PickupDragController dragController;
public InputWidgetGroup(PacketProblem problem, AnswerView answerView,
QuestionPanel questionPanel, SessionData sessionData) {
super(problem, answerView, questionPanel, sessionData);
// 解答フォーム表示位置の予約
int numberOfGroups = ImmutableSet.copyOf(problem.getAnswerList()).size();
int numberOfChoices = problem.getNumberOfShuffledChoices();
// 解答フォームの表示
gridConstrainedDropTarget = new AbsolutePanel();
gridConstrainedDropTarget.setPixelSize(getDraggableOffsetWidth() * numberOfGroups + 8,
draggableOffsetHeight * (numberOfChoices + 1) + 8);
add(gridConstrainedDropTarget);
// 表示先のDOMのサイズが確定しておらず、ラベルを追加すると左上に表示されてしまうため、追加タイミングを遅らせる
Scheduler.get().scheduleDeferred(cmd);
// OKボタン
buttonOk.setStyleName(STYLE_NAME_GROUP_CONTROL);
add(buttonOk);
}
private int getDraggableOffsetWidth() {
int numberOfGroups = ImmutableSet.copyOf(problem.getAnswerList()).size();
return numberOfGroups == 2 ? 275 : 200;
}
private final Scheduler.ScheduledCommand cmd = new Scheduler.ScheduledCommand() {
@Override
public void execute() {
dragController = new PickupDragController(gridConstrainedDropTarget, false);
dragController.setBehaviorScrollIntoView(false);
final GridHorizontalMoveDropController dropController = new GridHorizontalMoveDropController(
gridConstrainedDropTarget, getDraggableOffsetWidth(), draggableOffsetHeight);
dragController.registerDropController(dropController);
int numberOfGroups = ImmutableSet.copyOf(problem.getAnswerList()).size();
int numberOfChoices = problem.getNumberOfShuffledChoices();
// header
List<String> groups = Lists.newArrayList(ImmutableSet.copyOf(problem.getAnswerList()));
Collections.sort(groups);
for (int i = 0; i < numberOfGroups; ++i) {
Label label = new Label(groups.get(i));
label.addStyleName(STYLE_NAME_GROUP_HEADER);
label.setPixelSize(getDraggableOffsetWidth(), draggableOffsetHeight);
gridConstrainedDropTarget.add(label, getDraggableOffsetWidth() * i, 0);
}
// choices
for (int i = 0; i < numberOfChoices; ++i) {
Label label = new Label(problem.shuffledChoices[i]);
label.addMouseDownHandler(new MouseDownHandler() {
@Override
public void onMouseDown(MouseDownEvent event) {
dropController.setStartY(event.getRelativeElement().getAbsoluteTop());
}
});
label.addStyleName(STYLE_NAME_GROUP);
label.setPixelSize(getDraggableOffsetWidth(), draggableOffsetHeight);
labelChoices.add(label);
dragController.makeDraggable(label);
dropController.drop(label, Random.get().nextInt(numberOfGroups)
* getDraggableOffsetWidth(), draggableOffsetHeight * (i + 1));
}
}
};
@Override
public void enable(boolean b) {
buttonOk.setEnabled(b);
}
@Override
public void onClick(ClickEvent event) {
Object source = event.getSource();
if (source == buttonOk) {
List<String> groups = Lists.newArrayList(ImmutableSet.copyOf(problem.getAnswerList()));
Collections.sort(groups);
StringBuilder sb = new StringBuilder();
for (Label label : labelChoices) {
if (sb.length() != 0) {
sb.append(Constant.DELIMITER_GENERAL);
}
int x = gridConstrainedDropTarget.getWidgetLeft(label);
int groupIndex = (x + getDraggableOffsetWidth() / 2) / getDraggableOffsetWidth();
sb.append(label.getText()).append(Constant.DELIMITER_KUMIAWASE_PAIR)
.append(groups.get(groupIndex));
}
sendAnswer(sb.toString());
}
}
@Override
protected void onUnload() {
dragController.unregisterDropControllers();
super.onUnload();
}
}
| 37.671533 | 96 | 0.7702 |
59be46c2ce05408d23c8eaa1e6c263c6af3b9425 | 1,558 | package com.alibaba.jstorm.message.zeroMq;
import java.nio.ByteBuffer;
import backtype.storm.serialization.KryoTupleDeserializer;
/**
* virtualport send message
*
* @author yannian/Longda
*
*/
public class PacketPair {
private int port;
private byte[] message;
public PacketPair(int port, byte[] message) {
this.port = port;
this.message = message;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public byte[] getMessage() {
return message;
}
public void setMessage(byte[] message) {
this.message = message;
}
public static byte[] mk_packet(int virtual_port, byte[] message) {
ByteBuffer buff = ByteBuffer.allocate((Integer.SIZE / 8)
+ message.length);
buff.putInt(virtual_port);
buff.put(message);
byte[] rtn = buff.array();
return rtn;
}
public static PacketPair parse_packet(byte[] packet) {
ByteBuffer buff = ByteBuffer.wrap(packet);
int port = buff.getInt();
/**
* @@@ Attention please, in order to reduce memory copy
*
* Here directly PacketPair.message use the packet buffer
*
* so need get rid of the target target taskid in
* KryoTupleDeserializer.deserialize
*
*
* The better design should tuple includes targetTaskId
*/
byte[] message = null;
if (KryoTupleDeserializer.USE_RAW_PACKET ) {
message = packet;
} else {
message = new byte[buff.array().length - (Integer.SIZE / 8)];
buff.get(message);
}
PacketPair pair = new PacketPair(port, message);
return pair;
}
}
| 21.054054 | 67 | 0.675225 |
b0d1528a4c8d795d09d7f66a01d67b4785172714 | 9,861 | /*
* 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.flink.table.client.config;
import org.apache.flink.table.client.SqlClientException;
import org.apache.flink.table.descriptors.DescriptorProperties;
import org.apache.flink.table.descriptors.TableDescriptor;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.apache.flink.table.client.config.ConfigUtil.extractEarlyStringProperty;
/**
* Environment configuration that represents the content of an environment file. Environment files
* define tables, execution, and deployment behavior. An environment might be defined by default or
* as part of a session. Environments can be merged or enriched with properties (e.g. from CLI command).
*
* <p>In future versions, we might restrict the merging or enrichment of deployment properties to not
* allow overwriting of a deployment by a session.
*/
public class Environment {
private Map<String, TableDescriptor> tables;
private Map<String, String> views;
private Map<String, UserDefinedFunction> functions;
private Execution execution;
private Deployment deployment;
private static final String TABLE_NAME = "name";
private static final String TABLE_TYPE = "type";
private static final String TABLE_TYPE_VALUE_SOURCE = "source";
private static final String TABLE_TYPE_VALUE_SINK = "sink";
private static final String TABLE_TYPE_VALUE_BOTH = "both";
private static final String VIEW_NAME = "name";
private static final String VIEW_QUERY = "query";
public Environment() {
this.tables = Collections.emptyMap();
this.views = Collections.emptyMap();
this.functions = Collections.emptyMap();
this.execution = new Execution();
this.deployment = new Deployment();
}
public Map<String, TableDescriptor> getTables() {
return tables;
}
public void setTables(List<Map<String, Object>> tables) {
this.tables = new HashMap<>(tables.size());
tables.forEach(config -> {
final String name = extractEarlyStringProperty(config, TABLE_NAME, "table");
final Map<String, Object> properties = new HashMap<>(config);
properties.remove(TABLE_NAME);
if (this.tables.containsKey(name) || this.views.containsKey(name)) {
throw new SqlClientException("Cannot create table '" + name + "' because a table or " +
"view with this name is already registered.");
}
this.tables.put(name, createTableDescriptor(name, properties));
});
}
public Map<String, String> getViews() {
return views;
}
public void setViews(List<Map<String, Object>> views) {
// the order of how views are registered matters because
// they might reference each other
this.views = new LinkedHashMap<>(views.size());
views.forEach(config -> {
final String name = extractEarlyStringProperty(config, VIEW_NAME, "view");
final String query = extractEarlyStringProperty(config, VIEW_QUERY, "view");
if (this.tables.containsKey(name) || this.views.containsKey(name)) {
throw new SqlClientException("Cannot create view '" + name + "' because a table or " +
"view with this name is already registered.");
}
this.views.put(name, query);
});
}
public Map<String, UserDefinedFunction> getFunctions() {
return functions;
}
public void setFunctions(List<Map<String, Object>> functions) {
this.functions = new HashMap<>(functions.size());
functions.forEach(config -> {
final UserDefinedFunction f = UserDefinedFunction.create(config);
if (this.tables.containsKey(f.getName())) {
throw new SqlClientException("Duplicate function name '" + f.getName() + "'.");
}
this.functions.put(f.getName(), f);
});
}
public void setExecution(Map<String, Object> config) {
this.execution = Execution.create(config);
}
public Execution getExecution() {
return execution;
}
public void setDeployment(Map<String, Object> config) {
this.deployment = Deployment.create(config);
}
public Deployment getDeployment() {
return deployment;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("===================== Tables =====================\n");
tables.forEach((name, table) -> {
sb.append("- name: ").append(name).append("\n");
final DescriptorProperties props = new DescriptorProperties(true);
table.addProperties(props);
props.asMap().forEach((k, v) -> sb.append(" ").append(k).append(": ").append(v).append('\n'));
});
sb.append("===================== Views =====================\n");
views.forEach((name, query) -> {
sb.append("- name: ").append(name).append("\n");
sb.append(" ").append(VIEW_QUERY).append(": ").append(query).append('\n');
});
sb.append("=================== Functions ====================\n");
functions.forEach((name, function) -> {
sb.append("- name: ").append(name).append("\n");
final DescriptorProperties props = new DescriptorProperties(true);
function.addProperties(props);
props.asMap().forEach((k, v) -> sb.append(" ").append(k).append(": ").append(v).append('\n'));
});
sb.append("=================== Execution ====================\n");
execution.toProperties().forEach((k, v) -> sb.append(k).append(": ").append(v).append('\n'));
sb.append("=================== Deployment ===================\n");
deployment.toProperties().forEach((k, v) -> sb.append(k).append(": ").append(v).append('\n'));
return sb.toString();
}
// --------------------------------------------------------------------------------------------
/**
* Parses an environment file from an URL.
*/
public static Environment parse(URL url) throws IOException {
return new ConfigUtil.LowerCaseYamlMapper().readValue(url, Environment.class);
}
/**
* Parses an environment file from an String.
*/
public static Environment parse(String content) throws IOException {
return new ConfigUtil.LowerCaseYamlMapper().readValue(content, Environment.class);
}
/**
* Merges two environments. The properties of the first environment might be overwritten by the second one.
*/
public static Environment merge(Environment env1, Environment env2) {
final Environment mergedEnv = new Environment();
// merge tables
final Map<String, TableDescriptor> tables = new HashMap<>(env1.getTables());
tables.putAll(env2.getTables());
mergedEnv.tables = tables;
// merge views
final LinkedHashMap<String, String> views = new LinkedHashMap<>(env1.getViews());
views.putAll(env2.getViews());
mergedEnv.views = views;
// merge functions
final Map<String, UserDefinedFunction> functions = new HashMap<>(env1.getFunctions());
functions.putAll(env2.getFunctions());
mergedEnv.functions = functions;
// merge execution properties
mergedEnv.execution = Execution.merge(env1.getExecution(), env2.getExecution());
// merge deployment properties
mergedEnv.deployment = Deployment.merge(env1.getDeployment(), env2.getDeployment());
return mergedEnv;
}
/**
* Enriches an environment with new/modified properties or views and returns the new instance.
*/
public static Environment enrich(
Environment env,
Map<String, String> properties,
Map<String, String> views) {
final Environment enrichedEnv = new Environment();
// merge tables
enrichedEnv.tables = new HashMap<>(env.getTables());
// merge functions
enrichedEnv.functions = new HashMap<>(env.getFunctions());
// enrich execution properties
enrichedEnv.execution = Execution.enrich(env.execution, properties);
// enrich deployment properties
enrichedEnv.deployment = Deployment.enrich(env.deployment, properties);
// enrich views
enrichedEnv.views = new LinkedHashMap<>(env.getViews());
enrichedEnv.views.putAll(views);
return enrichedEnv;
}
// --------------------------------------------------------------------------------------------
/**
* Creates a table descriptor from a YAML config map.
*
* @param name name of the table
* @param config YAML config map
* @return table descriptor describing a source, sink, or both
*/
private static TableDescriptor createTableDescriptor(String name, Map<String, Object> config) {
final Object typeObject = config.get(TABLE_TYPE);
if (typeObject == null || !(typeObject instanceof String)) {
throw new SqlClientException("Invalid 'type' attribute for table '" + name + "'.");
}
final String type = (String) typeObject;
final Map<String, Object> configCopy = new HashMap<>(config);
configCopy.remove(TABLE_TYPE);
final Map<String, String> normalizedConfig = ConfigUtil.normalizeYaml(configCopy);
switch (type) {
case TABLE_TYPE_VALUE_SOURCE:
return new Source(name, normalizedConfig);
case TABLE_TYPE_VALUE_SINK:
return new Sink(name, normalizedConfig);
case TABLE_TYPE_VALUE_BOTH:
return new SourceSink(name, normalizedConfig);
default:
throw new SqlClientException(String.format("Invalid 'type' attribute for table '%s'. " +
"Only 'source', 'sink', and 'both' are supported. But was '%s'.", name, type));
}
}
}
| 35.728261 | 108 | 0.692932 |
f193e4c8db38f28f2b425857396327a24756d398 | 1,768 | package ru.itis.servlets;
import ru.itis.entities.Event;
import ru.itis.entities.User;
import ru.itis.models.ConnectionCreator;
import ru.itis.DAO.ParticipantsDAO;
import ru.itis.repositories.EventsRepository;
import ru.itis.repositories.EventsRepositoryJdbcImpl;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;
@WebServlet(name = "addParticipant", urlPatterns = "/participate")
public class ParticipateServlet extends HttpServlet {
private ParticipantsDAO participantsRepositoryJdbc;
private EventsRepository eventsRepository;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
Event event = (Event) session.getAttribute("event");
participantsRepositoryJdbc.save(event.getId(), user.getId());
Optional<Event> ev = eventsRepository.find(event.getId());
if (ev.isPresent()) {
event = ev.get();
session.setAttribute("event", event);
}
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/view/event.jsp");
requestDispatcher.forward(req, resp);
}
@Override
public void init() {
participantsRepositoryJdbc = new ParticipantsDAO(ConnectionCreator.getConnection());
eventsRepository = new EventsRepositoryJdbcImpl(ConnectionCreator.getConnection());
}
}
| 38.434783 | 113 | 0.751697 |
1eb2e2c571c393359f9a4347958d6942cb159d1f | 1,853 | package com.example.models;
// Generated 09/05/2017 05:06:06 PM by Hibernate Tools 4.0.1.Final
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Home object for domain model class ClaseHibernate1.
* @see com.example.models.ClaseHibernate1
* @author Hibernate Tools
*/
@Stateless
public class ClaseHibernate1Home {
private static final Log log = LogFactory.getLog(ClaseHibernate1Home.class);
@PersistenceContext
private EntityManager entityManager;
public void persist(ClaseHibernate1 transientInstance) {
log.debug("persisting ClaseHibernate1 instance");
try {
entityManager.persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void remove(ClaseHibernate1 persistentInstance) {
log.debug("removing ClaseHibernate1 instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
} catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}
public ClaseHibernate1 merge(ClaseHibernate1 detachedInstance) {
log.debug("merging ClaseHibernate1 instance");
try {
ClaseHibernate1 result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public ClaseHibernate1 findById(int id) {
log.debug("getting ClaseHibernate1 instance with id: " + id);
try {
ClaseHibernate1 instance = entityManager.find(ClaseHibernate1.class, id);
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
| 26.855072 | 77 | 0.740961 |
9aab20e8807c6163bc7b24b0be77ed9d3d0bd169 | 2,732 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.profilers.cpu;
import com.android.tools.adtui.model.DataSeries;
import com.android.tools.adtui.model.Range;
import com.android.tools.adtui.model.SeriesData;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.NotNull;
/**
* Implementers of this class should implement {@link #inMemoryDataList}, which should return all the {@link DataSeries} that would be
* returned if {@link #getDataForRange(Range)} receives a range with maximum length.
*/
abstract class InMemoryDataSeries<T> implements DataSeries<T> {
@Override
public List<SeriesData<T>> getDataForRange(Range range) {
long min = (long)range.getMin();
long max = (long)range.getMax();
List<SeriesData<T>> series = new ArrayList<>();
List<SeriesData<T>> seriesDataList = inMemoryDataList();
if (seriesDataList.isEmpty()) {
return series;
}
for (int i = 0; i < seriesDataList.size() - 1; i++) {
SeriesData<T> data = seriesDataList.get(i);
SeriesData<T> nextData = seriesDataList.get(i + 1);
// If our series overlaps with the start of the range upto excluding the end. We add the series.
if (data.x >= max) {
break;
}
// If our next series is greater than our min then we add our current element to the return set. This works because
// we want to add the element just before our range starts so checking the next element gives us that.
// After that point all elements will be greater than our min until our current element is > than our max in which case
// we break out of the loop.
if (nextData.x > min) {
series.add(data);
}
}
SeriesData<T> lastElement = seriesDataList.get(seriesDataList.size() - 1);
// Always add the last element if it is less than the max.
if (lastElement.x < max) {
series.add(lastElement);
}
return series;
}
/**
* Returns all the {@link SeriesData} stored in memory, to be filtered by range in {@link #getDataForRange(Range)}
*/
@NotNull
protected abstract List<SeriesData<T>> inMemoryDataList();
}
| 39.028571 | 134 | 0.699122 |
9e07ad4dfa59cca1859647d58c48df6cb9a8eeab | 1,461 | package io.vertx.core.impl;
import io.vertx.core.Handler;
import io.vertx.core.spi.metrics.PoolMetrics;
import com.newrelic.api.agent.NewRelic;
import com.newrelic.api.agent.Segment;
import com.newrelic.api.agent.Token;
import com.newrelic.api.agent.Trace;
import com.newrelic.api.agent.weaver.MatchType;
import com.newrelic.api.agent.weaver.Weave;
import com.newrelic.api.agent.weaver.Weaver;
import com.nr.instrumentation.vertx.NRRunnableWrapper;
import com.nr.instrumentation.vertx.NRTaskHandler;
@Weave(type=MatchType.BaseClass)
public abstract class ContextImpl {
@Trace
protected void executeAsync(Handler<Void> task) {
Weaver.callOriginal();
}
@Trace
public void runOnContext(Handler<Void> hTask) {
Token token = NewRelic.getAgent().getTransaction().getToken();
Segment segment = NewRelic.getAgent().getTransaction().startSegment("runOnContext");
if(hTask != null) {
NRTaskHandler wrapper = new NRTaskHandler(token, segment, hTask);
hTask = wrapper;
}
Weaver.callOriginal();
}
@Trace
public void executeFromIO(ContextTask task) {
Weaver.callOriginal();
}
@SuppressWarnings("rawtypes")
@Trace
protected Runnable wrapTask(ContextTask cTask, Handler<Void> hTask, boolean checkThread, PoolMetrics metrics) {
Token token = NewRelic.getAgent().getTransaction().getToken();
Runnable runnable = Weaver.callOriginal();
NRRunnableWrapper wrapper = new NRRunnableWrapper(runnable,token);
return wrapper;
}
}
| 28.647059 | 112 | 0.767967 |
4d3b49881413af1c447a1dec5dda9929f92da01d | 5,651 | /*
* 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.ozone.s3;
import javax.annotation.PreDestroy;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.PrivilegedExceptionAction;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ozone.OzoneSecurityUtil;
import org.apache.hadoop.ozone.client.OzoneClient;
import org.apache.hadoop.ozone.client.OzoneClientFactory;
import org.apache.hadoop.ozone.s3.exception.OS3Exception;
import org.apache.hadoop.ozone.security.OzoneTokenIdentifier;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import com.google.common.annotations.VisibleForTesting;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.OMTokenProto.Type.S3AUTHINFO;
import static org.apache.hadoop.ozone.s3.exception.S3ErrorTable.INTERNAL_ERROR;
import static org.apache.hadoop.ozone.s3.exception.S3ErrorTable.MALFORMED_HEADER;
import static org.apache.hadoop.ozone.s3.exception.S3ErrorTable.S3_AUTHINFO_CREATION_ERROR;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class creates the OzoneClient for the Rest endpoints.
*/
@RequestScoped
public class OzoneClientProducer {
private static final Logger LOG =
LoggerFactory.getLogger(OzoneClientProducer.class);
private OzoneClient client;
@Inject
private SignatureProcessor signatureParser;
@Inject
private OzoneConfiguration ozoneConfiguration;
@Inject
private Text omService;
@Inject
private String omServiceID;
@Produces
public OzoneClient createClient() throws OS3Exception, IOException {
client = getClient(ozoneConfiguration);
return client;
}
@PreDestroy
public void destory() throws IOException {
client.close();
}
private OzoneClient getClient(OzoneConfiguration config)
throws OS3Exception {
OzoneClient ozoneClient = null;
try {
// Check if any error occurred during creation of signatureProcessor.
if (signatureParser.getException() != null) {
throw signatureParser.getException();
}
String awsAccessId = signatureParser.getAwsAccessId();
validateAccessId(awsAccessId);
UserGroupInformation remoteUser =
UserGroupInformation.createRemoteUser(awsAccessId);
if (OzoneSecurityUtil.isSecurityEnabled(config)) {
LOG.debug("Creating s3 auth info for client.");
try {
OzoneTokenIdentifier identifier = new OzoneTokenIdentifier();
identifier.setTokenType(S3AUTHINFO);
identifier.setStrToSign(signatureParser.getStringToSign());
identifier.setSignature(signatureParser.getSignature());
identifier.setAwsAccessId(awsAccessId);
identifier.setOwner(new Text(awsAccessId));
if (LOG.isTraceEnabled()) {
LOG.trace("Adding token for service:{}", omService);
}
Token<OzoneTokenIdentifier> token = new Token(identifier.getBytes(),
identifier.getSignature().getBytes(UTF_8),
identifier.getKind(),
omService);
remoteUser.addToken(token);
} catch (OS3Exception | URISyntaxException ex) {
throw S3_AUTHINFO_CREATION_ERROR;
}
}
ozoneClient =
remoteUser.doAs((PrivilegedExceptionAction<OzoneClient>)() -> {
if (omServiceID == null) {
return OzoneClientFactory.getRpcClient(ozoneConfiguration);
} else {
// As in HA case, we need to pass om service ID.
return OzoneClientFactory.getRpcClient(omServiceID,
ozoneConfiguration);
}
});
} catch (OS3Exception ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("Error during Client Creation: ", ex);
}
throw ex;
} catch (Throwable t) {
// For any other critical errors during object creation throw Internal
// error.
if (LOG.isDebugEnabled()) {
LOG.debug("Error during Client Creation: ", t);
}
throw INTERNAL_ERROR;
}
return ozoneClient;
}
// ONLY validate aws access id when needed.
private void validateAccessId(String awsAccessId) throws Exception {
if (awsAccessId == null || awsAccessId.equals("")) {
LOG.error("Malformed s3 header. awsAccessID: ", awsAccessId);
throw MALFORMED_HEADER;
}
}
public void setOzoneConfiguration(OzoneConfiguration config) {
this.ozoneConfiguration = config;
}
@VisibleForTesting
public void setSignatureParser(SignatureProcessor signatureParser) {
this.signatureParser = signatureParser;
}
}
| 35.765823 | 109 | 0.720757 |
1e054a16920cd10ba799676aba01bb99c367eea7 | 6,206 | /*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.util.command;
import java.net.MalformedURLException;
import org.hamcrest.core.Is;
import org.hamcrest.core.IsNot;
import org.hamcrest.core.StringContains;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
public class UrlArgumentTest {
private static final String URL_WITH_PASSWORD = "http://username:password@somehere";
private CommandArgument argument;
@Before
public void setup() throws MalformedURLException {
argument = new UrlArgument(URL_WITH_PASSWORD);
}
@Test public void shouldReturnStringValueForCommandLine() throws Exception {
Assert.assertThat(argument.forCommandline(), Is.is(URL_WITH_PASSWORD));
}
@Test public void shouldReturnStringValueForReporting() throws Exception {
Assert.assertThat(argument.forDisplay(), Is.is("http://username:******@somehere"));
}
@Test public void shouldReturnValueForToString() throws Exception {
Assert.assertThat(argument.toString(), Is.is("http://username:******@somehere"));
}
@Test public void shouldNotChangeNormalURL() throws Exception {
String normal = "http://normal/foo/bar/baz?a=b&c=d#fragment";
UrlArgument url = new UrlArgument(normal);
Assert.assertThat(url.toString(), Is.is(normal));
}
@Test public void shouldWorkWithSvnSshUrl() throws Exception {
String normal = "svn+ssh://user:password@10.18.7.51:8153";
UrlArgument url = new UrlArgument(normal);
Assert.assertThat(url.toString(), Is.is("svn+ssh://user:******@10.18.7.51:8153"));
}
@Test public void shouldWorkWithJustUser() throws Exception {
String normal = "svn+ssh://user@10.18.7.51:8153";
UrlArgument url = new UrlArgument(normal);
Assert.assertThat(url.forDisplay(), Is.is("svn+ssh://******@10.18.7.51:8153"));
}
@Test public void shouldIgnoreArgumentsThatAreNotRecognisedUrls() throws Exception {
String notAUrl = "C:\\foo\\bar\\baz";
UrlArgument url = new UrlArgument(notAUrl);
Assert.assertThat(url.toString(), Is.is(notAUrl));
}
@Test public void shouldBeEqualBasedOnCommandLine() throws Exception {
UrlArgument url1 = new UrlArgument("svn+ssh://user:password@10.18.7.51:8153");
UrlArgument url3 = new UrlArgument("svn+ssh://user:password@10.18.7.51:8153");
Assert.assertThat(url1, is(url3));
}
@Test public void shouldBeEqualBasedOnCommandLineForHttpUrls() throws Exception {
UrlArgument url1 = new UrlArgument("http://user:password@10.18.7.51:8153");
UrlArgument url2 = new UrlArgument("http://user:other@10.18.7.51:8153");
UrlArgument url3 = new UrlArgument("http://user:password@10.18.7.51:8153");
Assert.assertThat(url1, is(url3));
Assert.assertThat(url1, Is.is(not(url2)));
}
@Test public void shouldIgnoreTrailingSlashesOnURIs() throws Exception {
UrlArgument url1 = new UrlArgument("file:///not-exist/svn/trunk/");
UrlArgument url2 = new UrlArgument("file:///not-exist/svn/trunk");
Assert.assertThat(url1, is(url2));
}
@Test
public void shouldMaskPasswordInHgUrlWithBranch(){
UrlArgument url = new UrlArgument("http://cce:password@10.18.3.171:8080/hg/connect4/trunk#foo");
Assert.assertThat(url.hostInfoForCommandline(), Is.is("http://cce:password@10.18.3.171:8080"));
Assert.assertThat(url.hostInfoForDisplay(), Is.is("http://cce:******@10.18.3.171:8080"));
}
@Test //BUG #2973
public void shouldReplaceAllThePasswordsInSvnInfo() throws Exception {
String output = "<?xml version=\"1.0\"?>\n"
+ "<info>\n"
+ "<entry\n"
+ " kind=\"dir\"\n"
+ " path=\".\"\n"
+ " revision=\"294\">\n"
+ "<url>http://cce:password@10.18.3.171:8080/svn/connect4/trunk</url>\n"
+ "<repository>\n"
+ "<root>http://cce:password@10.18.3.171:8080/svn/connect4</root>\n"
+ "<uuid>b7cc39fa-2f96-0d44-9079-2001927d4b22</uuid>\n"
+ "</repository>\n"
+ "<wc-info>\n"
+ "<schedule>normal</schedule>\n"
+ "<depth>infinity</depth>\n"
+ "</wc-info>\n"
+ "<commit\n"
+ " revision=\"294\">\n"
+ "<author>cce</author>\n"
+ "<date>2009-06-09T06:13:05.109375Z</date>\n"
+ "</commit>\n"
+ "</entry>\n"
+ "</info>";
UrlArgument url = new UrlArgument("http://cce:password@10.18.3.171:8080/svn/connect4/trunk");
String result = url.replaceSecretInfo(output);
Assert.assertThat(result, StringContains.containsString("<url>http://cce:******@10.18.3.171:8080/svn/connect4/trunk</url>"));
Assert.assertThat(result, StringContains.containsString("<root>http://cce:******@10.18.3.171:8080/svn/connect4</root>"));
Assert.assertThat(result, IsNot.not(StringContains.containsString("cce:password")));
}
@Test //BUG #5471
public void shouldMaskAuthTokenInUrl() {
UrlArgument url = new UrlArgument("https://9bf58jhrb32f29ad0c3983a65g594f1464jgf9a3@somewhere");
Assert.assertThat(url.forDisplay(), Is.is("https://******@somewhere"));
}
}
| 43.704225 | 133 | 0.628746 |
e534e22e9d32a40dbb1590cb0d6176f2a5d02095 | 894 | package org.tt.admin.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import org.tt.admin.po.User;
import javax.annotation.Resource;
import static org.junit.Assert.*;
/**
* Created by zangzhonghua on 2017/5/11.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={"classpath:spring.xml"})
public class UserServiceTest {
private UserService userService;
@Resource
public void setUserService(UserService userService) {
this.userService = userService;
}
@Test
public void findUserById() throws Exception {
User user = this.userService.findUserById(1);
//System.out.println(user.toString());
Assert.isNull(user);
}
} | 27.090909 | 71 | 0.746085 |
c2faa4b553312ae0dd14f2343909cf52cb2f4826 | 7,081 | package util;
import java.io.*;
import org.assertj.core.util.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import ch.aaap.harvestclient.core.Harvest;
import ch.aaap.harvestclient.domain.*;
import ch.aaap.harvestclient.domain.reference.GenericReference;
import ch.aaap.harvestclient.domain.reference.Reference;
public class ExistingData {
/**
* https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
*/
private static class LazyHolder1 {
static final ExistingData INSTANCE = new ExistingData(TestSetupUtil.getAdminAccess(), 1);
}
private static class LazyHolder2 {
static final ExistingData ANOTHER_INSTANCE = new ExistingData(TestSetupUtil.getAnotherAdminAccess(), 2);
}
private static final Logger log = LoggerFactory.getLogger(ExistingData.class);
private final Reference<Task> taskReference;
private final Reference<Task> anotherTaskReference;
private final Reference<Client> clientReference;
private final Reference<Client> anotherClientReference;
private final Reference<Project> projectReference;
private final Reference<Project> anotherProjectReference;
private final Reference<User> userReference;
private final Reference<User> anotherUserReference;
private final Reference<TimeEntry> timeEntryReference;
private final EstimateItem.Category estimateItemCategory;
private final EstimateItem.Category anotherEstimateItemCategory;
private final InvoiceItem.Category invoiceItemCategory;
private final InvoiceItem.Category anotherInvoiceItemCategory;
private final ProjectAssignment projectAssignment;
private final Reference<ExpenseCategory> expenseCategory;
private ExistingData(Harvest harvest, int accountNumber) {
try {
log.debug("Getting Existing Data for tests");
TestData data = loadFromFile(accountNumber);
new TestDataCreator(harvest).getOrCreateAll(data);
log.info("TestData is {}", data);
saveToFile(accountNumber, data);
taskReference = GenericReference.of(data.getTaskId());
anotherTaskReference = GenericReference.of(data.getAnotherTaskId());
clientReference = GenericReference.of(data.getClientId());
anotherClientReference = GenericReference.of(data.getAnotherClientId());
projectReference = GenericReference.of(data.getProjectId());
anotherProjectReference = GenericReference.of(data.getAnotherProjectId());
userReference = GenericReference.of(data.getUserId());
anotherUserReference = GenericReference.of(data.getAnotherUserId());
timeEntryReference = GenericReference.of(data.getTimeEntryId());
// default categories
estimateItemCategory = ImmutableEstimateItem.Category.builder().name("Product").build();
anotherEstimateItemCategory = ImmutableEstimateItem.Category.builder().name("Service").build();
// default categories
invoiceItemCategory = ImmutableInvoiceItem.Category.builder().name("Product").build();
anotherInvoiceItemCategory = ImmutableInvoiceItem.Category.builder().name("Service").build();
expenseCategory = GenericReference.of(data.getExpenseCategoryId());
// create assignment
harvest.userAssignments().create(projectReference, ImmutableUserAssignment.builder()
.user(userReference).build());
projectAssignment = harvest.projectAssignments().list(userReference).get(0);
} catch (Throwable t) {
log.error("", t);
throw t;
}
}
private void saveToFile(int accountNumber, TestData data) {
Gson gson = new Gson();
File testDataFile = findTestDataFile(accountNumber);
try (FileWriter writer = new FileWriter(testDataFile)) {
gson.toJson(data, writer);
} catch (IOException e) {
log.error("Problem writing test data file", e);
}
}
private TestData loadFromFile(int accountNumber) {
File testDataFile = findTestDataFile(accountNumber);
Gson gson = new Gson();
try (FileReader reader = new FileReader(testDataFile)) {
log.debug("Loading data for account {}", accountNumber);
TestData parsedData = gson.fromJson(reader, TestData.class);
if (parsedData == null) {
parsedData = new TestData();
}
return parsedData;
} catch (FileNotFoundException e) {
log.info("test data file not present");
return new TestData();
} catch (IOException e) {
log.error("Problem reading test file", e);
return new TestData();
}
}
private File findTestDataFile(int accountNumber) {
String tmpFolder = Files.temporaryFolderPath();
File testDataFile = new File(String.format("%sharvest-client-e2etest%s.json", tmpFolder, accountNumber));
log.info("Using testdata file at {}", testDataFile.toString());
return testDataFile;
}
public static ExistingData getInstance() {
return LazyHolder1.INSTANCE;
}
public static ExistingData getAnotherInstance() {
return LazyHolder2.ANOTHER_INSTANCE;
}
public Reference<User> getUnassignedUser() {
return anotherUserReference;
}
public Reference<Task> getUnassignedTask() {
return anotherTaskReference;
}
public Reference<Task> getTaskReference() {
return taskReference;
}
public Reference<Task> getAnotherTaskReference() {
return anotherTaskReference;
}
public Reference<Client> getClientReference() {
return clientReference;
}
public Reference<Client> getAnotherClientReference() {
return anotherClientReference;
}
public Reference<Project> getProjectReference() {
return projectReference;
}
public Reference<TimeEntry> getTimeEntryReference() {
return timeEntryReference;
}
public EstimateItem.Category getEstimateItemCategory() {
return estimateItemCategory;
}
public Reference<User> getUserReference() {
return userReference;
}
public Reference<User> getAnotherUserReference() {
return anotherUserReference;
}
public ProjectAssignment getProjectAssignment() {
return projectAssignment;
}
public InvoiceItem.Category getInvoiceItemCategory() {
return invoiceItemCategory;
}
public InvoiceItem.Category getAnotherInvoiceItemCategory() {
return anotherInvoiceItemCategory;
}
public EstimateItem.Category getAnotherEstimateItemCategory() {
return anotherEstimateItemCategory;
}
public Reference<ExpenseCategory> getExpenseCategory() {
return expenseCategory;
}
public Reference<Project> getAnotherProjectReference() {
return anotherProjectReference;
}
}
| 32.934884 | 113 | 0.685496 |
e3ec037dac3201e3c6e4febfeeab88a3a5031874 | 396 |
package net.eduard.spawn.event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import net.eduard.spawn.Main;
public class SpawnEvent implements Listener {
@EventHandler
public void event(PlayerJoinEvent e) {
if (Main.config.contains("spawn")){
e.getPlayer().teleport(Main.config.getLocation("spawn"));
}
}
}
| 20.842105 | 60 | 0.762626 |
9fea5a12b9fa641c67b5f8b7336ebd3d8fa1883f | 1,102 | package cspace.render2d;
import javax.media.opengl.GL2;
import jgl.math.vector.Vec3f;
import cspace.scene.CSArc.Arc;
import cspace.scene.Scene;
import cspace.scene.Sub;
import cspace.util.CachedRenderer;
public class SubRenderer extends CachedRenderer {
private Scene scene;
private Camera camera;
public SubRenderer(Scene scene, Camera camera) {
this.scene = scene;
this.camera = camera;
}
@Override
protected void beginDraw(GL2 gl) {
Vec3f c = scene.view.subs.color;
gl.glColor3f(c.x, c.y, c.z);
}
@Override
protected void updateGeometry(GL2 gl) {
double theta = scene.view.robot.rotation.anglePi();
float width = scene.view.subs.edgeWidth;
if (scene.view.renderer.fixedWidthEdges)
width /= camera.getScale();
for (Sub sub : scene.cspace.subs) {
if (sub != null && sub.isActive(theta)) {
Arc arc = sub.arc(scene.view.robot.rotation);
new ArcGeometry(arc).draw(gl, width, scene.view.subs.edgeDetail);
}
}
}
@Override
protected boolean isVisible() {
return scene.view.subs.visible2d;
}
}
| 22.489796 | 73 | 0.681488 |
f453eac4a350d8a3f3d9f4530bd531ead24cd82a | 1,821 | package com.example.android.sunshine.app.wearsupport;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import com.example.android.sunshine.app.sync.SunshineSyncAdapter;
/**
* Created by Jim on 5/9/2016.
*/
public class WxProvider extends BroadcastReceiver {
private static final String TAG = "WxProvider";
@Override
public void onReceive(Context context, Intent intent) {
if(SunshineSyncAdapter.ACTION_DATA_UPDATED.equals(SunshineSyncAdapter.ACTION_DATA_UPDATED)) {
Log.d(TAG, "received SunshineSyncAdapter update ");
//SunshineSyncAdapter.syncImmediately(context); for msg receive
SharedPreferences prefs = context.getSharedPreferences("WX_DATA", Context.MODE_PRIVATE);
String high = prefs.getString("high_temp", "-99");
String low = prefs.getString("low_temp","-99");
String desc = prefs.getString("desc","-99");
Long time = prefs.getLong("update_time", 1);
Log.d(TAG, "Send to watch:");
Log.d(TAG, "high: " + high + " low: " + low + " desc: " + desc);
Intent sendWxData = new Intent(context, SendWearDataService.class);
sendWxData.putExtra(SendWearDataService.HIGH_TEMP, high );
sendWxData.putExtra(SendWearDataService.LOW_TEMP, low );
sendWxData.putExtra(SendWearDataService.WX_DESC, desc);
sendWxData.putExtra(SendWearDataService.WX_TIME, time);
ComponentName serviceName = context.startService(sendWxData);
if(serviceName == null){
Log.d(TAG, "SendWearDataService failed to start!" );
}
}
}
}
| 40.466667 | 101 | 0.673806 |
37a141be945569bbf57cb993f8da194da3ae773f | 15,892 | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.util;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.jboss.logging.Logger;
import org.jboss.util.loading.ContextClassLoaderSwitcher;
/** An implementation of a timed cache. This is a cache whose entries have a
limited lifetime with the ability to refresh their lifetime. The entries
managed by the cache implement the TimedCachePolicy.TimedEntry interface. If
an object inserted into the cache does not implement this interface, it will
be wrapped in a DefaultTimedEntry and will expire without the possibility of
refresh after getDefaultLifetime() seconds.
This is a lazy cache policy in that objects are not checked for expiration
until they are accessed.
@author <a href="mailto:Scott.Stark@jboss.org">Scott Stark</a>.
@version $Revision$
*/
@SuppressWarnings("unchecked")
public class TimedCachePolicy
extends TimerTask /* A legacy base class that is no longer used as this level */
implements CachePolicy
{
/**
* Name of system property that this class consults to determine what
* classloader to assign to its static {@link Timer}'s thread.
*/
public static final String TIMER_CLASSLOADER_PROPERTY = "jboss.common.timedcachepolicy.timer.classloader";
/**
* Value for {@link #TIMER_CLASSLOADER_PROPERTY} indicating the
* {@link ClassLoader#getSystemClassLoader() system classloader} should
* be used. This is the default value if the system property is not set.
*/
public static final String TIMER_CLASSLOADER_SYSTEM = "system";
/**
* Value for {@link #TIMER_CLASSLOADER_PROPERTY} indicating the
* {@link Class#getClassLoader() classloader that loaded this class} should
* be used.
*/
public static final String TIMER_CLASSLOADER_CURRENT = "current";
/**
* Value for {@link #TIMER_CLASSLOADER_PROPERTY} indicating the
* {@link Thread#getContextClassLoader() thread context classloader}
* in effect when this class is loaded should be used.
*/
public static final String TIMER_CLASSLOADER_CONTEXT = "context";
/** The interface that cache entries support.
*/
public static interface TimedEntry
{
/** Initializes an entry with the current cache time. This is called when
the entry is first inserted into the cache so that entries do not
have to know the absolute system time.
* @param now
*/
public void init(long now);
/** Is the entry still valid basis the current time
* @param now
@return true if the entry is within its lifetime, false if it is expired.
*/
public boolean isCurrent(long now);
/** Attempt to extend the entry lifetime by refreshing it.
@return true if the entry was refreshed successfully, false otherwise.
*/
public boolean refresh();
/** Notify the entry that it has been removed from the cache.
*/
public void destroy();
/** @return the value component of the TimedEntry. This may or may not
be the TimedEntry implementation.
*/
public Object getValue();
}
private static final Logger log = Logger.getLogger(TimedCachePolicy.class);
protected static Timer resolutionTimer;
static
{
// Don't leak the TCCL to the resolutionTimer thread
ContextClassLoaderSwitcher.SwitchContext clSwitchContext = null;
try
{
// See if the user configured what classloader they want
String timerCl = AccessController.doPrivileged(new PrivilegedAction<String>()
{
public String run()
{
return System.getProperty(TIMER_CLASSLOADER_PROPERTY, TIMER_CLASSLOADER_SYSTEM);
}
});
if (TIMER_CLASSLOADER_CONTEXT.equalsIgnoreCase(timerCl) == false)
{
ContextClassLoaderSwitcher clSwitcher = (ContextClassLoaderSwitcher) AccessController.doPrivileged(ContextClassLoaderSwitcher.INSTANTIATOR);
if (TIMER_CLASSLOADER_CURRENT.equalsIgnoreCase(timerCl))
{
// Switches the TCCL to this class' classloader
clSwitchContext = clSwitcher.getSwitchContext(TimedCachePolicy.class.getClassLoader());
}
else
{
if (TIMER_CLASSLOADER_SYSTEM.equalsIgnoreCase(timerCl) == false)
{
log.warn("Unknown value " + timerCl + " found for property " +
TIMER_CLASSLOADER_PROPERTY + " -- using the system classloader");
}
clSwitchContext = clSwitcher.getSwitchContext(ClassLoader.getSystemClassLoader());
}
}
resolutionTimer = new Timer(true);
}
catch (SecurityException e)
{
// For backward compatibility, don't blow up, just risk leaking the TCCL
// TODO log a WARN or something?
resolutionTimer = new Timer(true);
}
finally
{
// Restores the TCCL
if (clSwitchContext != null)
clSwitchContext.reset();
}
}
/** The map of cached TimedEntry objects. */
protected Map entryMap;
/** The lifetime in seconds to use for objects inserted
that do not implement the TimedEntry interface. */
protected int defaultLifetime;
/** A flag indicating if entryMap should be synchronized */
protected boolean threadSafe;
/** The caches notion of the current time */
protected long now;
/** The resolution in seconds of the cach current time */
protected int resolution;
/** */
protected ResolutionTimer theTimer;
/** Creates a new TimedCachePolicy with a default entry lifetime of 30 mins
that does not synchronized access to its policy store and uses a 60
second resolution.
*/
public TimedCachePolicy()
{
this(30*60, false, 0);
}
/** Creates a new TimedCachePolicy with the given default entry lifetime
that does not synchronized access to its policy store and uses a 60
second resolution.
* @param defaultLifetime
*/
public TimedCachePolicy(int defaultLifetime)
{
this(defaultLifetime, false, 0);
}
/** Creates a new TimedCachePolicy with the given default entry lifetime
that does/does not synchronized access to its policy store depending
on the value of threadSafe.
@param defaultLifetime - the lifetime in seconds to use for objects inserted
that do not implement the TimedEntry interface.
@param threadSafe - a flag indicating if the cach store should be synchronized
to allow correct operation under multi-threaded access. If true, the
cache store is synchronized. If false the cache store is unsynchronized and
the cache is not thread safe.
@param resolution - the resolution in seconds of the cache timer. A cache does
not query the system time on every get() invocation. Rather the cache
updates its notion of the current time every 'resolution' seconds.
*/
public TimedCachePolicy(int defaultLifetime, boolean threadSafe, int resolution)
{
this.defaultLifetime = defaultLifetime;
this.threadSafe = threadSafe;
if( resolution <= 0 )
resolution = 60;
this.resolution = resolution;
}
// Service implementation ----------------------------------------------
/** Initializes the cache for use. Prior to this the cache has no store.
*/
public void create()
{
if( threadSafe )
entryMap = Collections.synchronizedMap(new HashMap());
else
entryMap = new HashMap();
now = System.currentTimeMillis();
}
/** Schedules this with the class resolutionTimer Timer object for
execution every resolution seconds.
*/
public void start()
{
theTimer = new ResolutionTimer();
resolutionTimer.scheduleAtFixedRate(theTimer, 0, 1000*resolution);
}
/** Stop cancels the resolution timer and flush()es the cache.
*/
public void stop()
{
theTimer.cancel();
flush();
}
/** Clears the cache of all entries.
*/
public void destroy()
{
entryMap.clear();
}
// --- Begin CachePolicy interface methods
/** Get the cache value for key if it has not expired. If the TimedEntry
is expired its destroy method is called and then removed from the cache.
@return the TimedEntry value or the original value if it was not an
instance of TimedEntry if key is in the cache, null otherwise.
*/
public Object get(Object key)
{
TimedEntry entry = (TimedEntry) entryMap.get(key);
if( entry == null )
return null;
if( entry.isCurrent(now) == false )
{ // Try to refresh the entry
if( entry.refresh() == false )
{ // Failed, remove the entry and return null
entry.destroy();
entryMap.remove(key);
return null;
}
}
Object value = entry.getValue();
return value;
}
/** Get the cache value for key. This method does not check to see if
the entry has expired.
@return the TimedEntry value or the original value if it was not an
instancee of TimedEntry if key is in the cache, null otherwise.
*/
public Object peek(Object key)
{
TimedEntry entry = (TimedEntry) entryMap.get(key);
Object value = null;
if( entry != null )
value = entry.getValue();
return value;
}
/** Insert a value into the cache. In order to have the cache entry
reshresh itself value would have to implement TimedEntry and
implement the required refresh() method logic.
@param key - the key for the cache entry
@param value - Either an instance of TimedEntry that will be inserted without
change, or an abitrary value that will be wrapped in a non-refreshing
TimedEntry.
*/
public void insert(Object key, Object value)
{
if( entryMap.containsKey(key) )
throw new IllegalStateException("Attempt to insert duplicate entry");
TimedEntry entry = null;
if( (value instanceof TimedEntry) == false )
{ // Wrap the value in a DefaultTimedEntry
entry = new DefaultTimedEntry(defaultLifetime, value);
}
else
{
entry = (TimedEntry) value;
}
entry.init(now);
entryMap.put(key, entry);
}
/** Remove the entry associated with key and call destroy on the entry
if found.
*/
public void remove(Object key)
{
TimedEntry entry = (TimedEntry) entryMap.remove(key);
if( entry != null )
entry.destroy();
}
/** Remove all entries from the cache.
*/
public void flush()
{
Map tmpMap = null;
synchronized( this )
{
tmpMap = entryMap;
if( threadSafe )
entryMap = Collections.synchronizedMap(new HashMap());
else
entryMap = new HashMap();
}
// Notify the entries of their removal
Iterator iter = tmpMap.values().iterator();
while( iter.hasNext() )
{
TimedEntry entry = (TimedEntry) iter.next();
entry.destroy();
}
tmpMap.clear();
}
public int size()
{
return entryMap.size();
}
// --- End CachePolicy interface methods
/** Get the list of keys for entries that are not expired.
*
* @return A List of the keys corresponding to valid entries
*/
public List getValidKeys()
{
ArrayList validKeys = new ArrayList();
synchronized( entryMap )
{
Iterator iter = entryMap.entrySet().iterator();
while( iter.hasNext() )
{
Map.Entry entry = (Map.Entry) iter.next();
TimedEntry value = (TimedEntry) entry.getValue();
if( value.isCurrent(now) == true )
validKeys.add(entry.getKey());
}
}
return validKeys;
}
/** Get the default lifetime of cache entries.
@return default lifetime in seconds of cache entries.
*/
public int getDefaultLifetime()
{
return defaultLifetime;
}
/** Set the default lifetime of cache entries for new values added to the cache.
@param defaultLifetime - lifetime in seconds of cache values that do
not implement TimedEntry.
*/
public synchronized void setDefaultLifetime(int defaultLifetime)
{
this.defaultLifetime = defaultLifetime;
}
/**
* Get the frequency of the current time snapshot.
* @return the current timer resolution in seconds.
*/
public int getResolution()
{
return resolution;
}
/** Set the cache timer resolution
*
@param resolution - the resolution in seconds of the cache timer. A cache does
not query the system time on every get() invocation. Rather the cache
updates its notion of the current time every 'resolution' seconds.
*/
public synchronized void setResolution(int resolution)
{
if( resolution <= 0 )
resolution = 60;
if( resolution != this.resolution )
{
this.resolution = resolution;
theTimer.cancel();
theTimer = new ResolutionTimer();
resolutionTimer.scheduleAtFixedRate(theTimer, 0, 1000*resolution);
}
}
/** The TimerTask run method. It updates the cache time to the
current system time.
*/
public void run()
{
now = System.currentTimeMillis();
}
/** Get the cache time.
@return the cache time last obtained from System.currentTimeMillis()
*/
public long currentTimeMillis()
{
return now;
}
/** Get the raw TimedEntry for key without performing any expiration check.
* @param key
@return the TimedEntry value associated with key if one exists, null otherwise.
*/
public TimedEntry peekEntry(Object key)
{
TimedEntry entry = (TimedEntry) entryMap.get(key);
return entry;
}
/** The default implementation of TimedEntry used to wrap non-TimedEntry
objects inserted into the cache.
*/
static class DefaultTimedEntry implements TimedEntry
{
long expirationTime;
Object value;
DefaultTimedEntry(long lifetime, Object value)
{
this.expirationTime = 1000 * lifetime;
this.value = value;
}
public void init(long now)
{
expirationTime += now;
}
public boolean isCurrent(long now)
{
return expirationTime > now;
}
public boolean refresh()
{
return false;
}
public void destroy()
{
}
public Object getValue()
{
return value;
}
}
/**
*/
private class ResolutionTimer extends TimerTask
{
public void run()
{
TimedCachePolicy.this.run();
}
}
}
| 32.834711 | 152 | 0.644727 |
b8ee91250b0883b30a2ea703c78352cbdebeb654 | 907 | package View;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
public class BackButtonView {
protected Button backToMainButton;
protected VBox mainView, backToMainVBox;
public BackButtonView() {
mainView = new VBox();
backToMainVBox = new VBox();
assignAll();
}
private void assignAll() {
assignBackToMainButton();
}
private void assignBackToMainButton() {
backToMainButton = new Button("");
backToMainButton.getStyleClass().add("button-back");
backToMainVBox.getChildren().add(backToMainButton);
}
public void eventBackToMainButton(EventHandler<ActionEvent> event) {
backToMainButton.setOnAction(event);
}
public VBox update() {
mainView.getChildren().clear();
return mainView;
}
}
| 23.25641 | 72 | 0.674752 |
24327cd6f4c67391a6496f499e38e1bc1553ca25 | 1,662 | package ir.apend.slidersample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.List;
import ir.apend.slider.model.Slide;
import ir.apend.slider.ui.Slider;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Slider slider = findViewById(R.id.slider);
List<Slide> slideList = new ArrayList<>();
slideList.add(new Slide(0,"http://cssslider.com/sliders/demo-20/data1/images/picjumbo.com_img_4635.jpg" , getResources().getDimensionPixelSize(R.dimen.slider_image_corner)));
slideList.add(new Slide(1,"http://cssslider.com/sliders/demo-12/data1/images/picjumbo.com_hnck1995.jpg" , getResources().getDimensionPixelSize(R.dimen.slider_image_corner)));
slideList.add(new Slide(2,"http://cssslider.com/sliders/demo-19/data1/images/picjumbo.com_hnck1588.jpg" , getResources().getDimensionPixelSize(R.dimen.slider_image_corner)));
slideList.add(new Slide(3,"http://wowslider.com/sliders/demo-18/data1/images/shanghai.jpg" , getResources().getDimensionPixelSize(R.dimen.slider_image_corner)));
slider.setItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//do what you want
}
});
slider.addSlides(slideList);
}
}
| 41.55 | 182 | 0.72864 |
5903d1d10dbee835af0b1e5cf3893c71c192e945 | 2,548 | //Chapter 12 - Exercise 12.12
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CircleCenterRadiusViewer extends JComponent implements ActionListener
{
private JTextField xField;
private JTextField yField;
private JTextField nField;
private CircleCenterRadius shape;
public CircleCenterRadiusViewer()
{
shape = new CircleCenterRadius();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
shape.paint(g);
}
private Component createControlPanel()
{
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout (new BoxLayout (buttonPanel, BoxLayout.Y_AXIS));
JPanel drawPanel = new JPanel();
drawPanel.add (new JLabel ("Enter value X"));
xField = new JTextField(5);
drawPanel.add(xField);
drawPanel.add (new JLabel ("Enter value Y"));
yField = new JTextField(5);
drawPanel.add(yField);
drawPanel.add (new JLabel ("Enter value radius"));
nField = new JTextField(5);
drawPanel.add(nField);
buttonPanel.add(drawPanel);
JButton drawButton = new JButton("Draw");
drawButton.addActionListener(this);
buttonPanel.add(drawButton);
return buttonPanel;
}
public void actionPerformed (ActionEvent event)
{
int x;
String xText = xField.getText();
if (xText.equals(""))
{
x = 0;
}
else
{
x = Integer.parseInt(xText);
}
int y;
String yText = yField.getText();
if (yText.equals(""))
{
y = 0;
}
else
{
y = Integer.parseInt(yText);
}
int n;
String nText = nField.getText();
if (nText.equals(""))
{
n = 0;
}
else
{
n = Integer.parseInt(nText);
}
shape.setValue(x, y, n);
repaint();
}
public static void main (String[] args)
{
JFrame frame = new JFrame();
frame.setTitle("Circle with center radius");
CircleCenterRadiusViewer component = new CircleCenterRadiusViewer();
Container contentPane = frame.getContentPane();
contentPane.add(component, BorderLayout.CENTER);
contentPane.add(component.createControlPanel(), BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension (800, 800));
frame.setVisible(true);
}
}
| 21.411765 | 82 | 0.700942 |
76a903e6656cd3578dcf6eb300eb3ebb79526f56 | 5,363 | // Generated from graphql_java_gen gem with template Input.java.erb
package com.contentbig.kgdatalake.graphql.generated;
import com.shopify.graphql.support.ID;
import com.shopify.graphql.support.Input;
import com.shopify.graphql.support.Tuery;
import java.io.Serializable;
import java.util.List;
public class MessageFilter implements Serializable {
private Input<List<ID>> id = Input.undefined();
private Input<StringHashFilter> name = Input.undefined();
private Input<MessageFilter> and = Input.undefined();
private Input<MessageFilter> or = Input.undefined();
private Input<MessageFilter> not = Input.undefined();
public List<ID> getId() {
return id.getValue();
}
public Input<List<ID>> getIdInput() {
return id;
}
public MessageFilter setId(List<ID> id) {
this.id = Input.optional(id);
return this;
}
public MessageFilter setIdInput(Input<List<ID>> id) {
if (id == null) {
throw new IllegalArgumentException("Input can not be null");
}
this.id = id;
return this;
}
public StringHashFilter getName() {
return name.getValue();
}
public Input<StringHashFilter> getNameInput() {
return name;
}
public MessageFilter setName(StringHashFilter name) {
this.name = Input.optional(name);
return this;
}
public MessageFilter setNameInput(Input<StringHashFilter> name) {
if (name == null) {
throw new IllegalArgumentException("Input can not be null");
}
this.name = name;
return this;
}
public MessageFilter getAnd() {
return and.getValue();
}
public Input<MessageFilter> getAndInput() {
return and;
}
public MessageFilter setAnd(MessageFilter and) {
this.and = Input.optional(and);
return this;
}
public MessageFilter setAndInput(Input<MessageFilter> and) {
if (and == null) {
throw new IllegalArgumentException("Input can not be null");
}
this.and = and;
return this;
}
public MessageFilter getOr() {
return or.getValue();
}
public Input<MessageFilter> getOrInput() {
return or;
}
public MessageFilter setOr(MessageFilter or) {
this.or = Input.optional(or);
return this;
}
public MessageFilter setOrInput(Input<MessageFilter> or) {
if (or == null) {
throw new IllegalArgumentException("Input can not be null");
}
this.or = or;
return this;
}
public MessageFilter getNot() {
return not.getValue();
}
public Input<MessageFilter> getNotInput() {
return not;
}
public MessageFilter setNot(MessageFilter not) {
this.not = Input.optional(not);
return this;
}
public MessageFilter setNotInput(Input<MessageFilter> not) {
if (not == null) {
throw new IllegalArgumentException("Input can not be null");
}
this.not = not;
return this;
}
public void appendTo(StringBuilder _queryBuilder) {
String separator = "";
_queryBuilder.append('{');
if (this.id.isDefined()) {
_queryBuilder.append(separator);
separator = ",";
_queryBuilder.append("id:");
if (id.getValue() != null) {
_queryBuilder.append('[');
{
String listSeperator1 = "";
for (ID item1 : id.getValue()) {
_queryBuilder.append(listSeperator1);
listSeperator1 = ",";
Tuery.appendQuotedString(_queryBuilder, item1.toString());
}
}
_queryBuilder.append(']');
} else {
_queryBuilder.append("null");
}
}
if (this.name.isDefined()) {
_queryBuilder.append(separator);
separator = ",";
_queryBuilder.append("name:");
if (name.getValue() != null) {
name.getValue().appendTo(_queryBuilder);
} else {
_queryBuilder.append("null");
}
}
if (this.and.isDefined()) {
_queryBuilder.append(separator);
separator = ",";
_queryBuilder.append("and:");
if (and.getValue() != null) {
and.getValue().appendTo(_queryBuilder);
} else {
_queryBuilder.append("null");
}
}
if (this.or.isDefined()) {
_queryBuilder.append(separator);
separator = ",";
_queryBuilder.append("or:");
if (or.getValue() != null) {
or.getValue().appendTo(_queryBuilder);
} else {
_queryBuilder.append("null");
}
}
if (this.not.isDefined()) {
_queryBuilder.append(separator);
separator = ",";
_queryBuilder.append("not:");
if (not.getValue() != null) {
not.getValue().appendTo(_queryBuilder);
} else {
_queryBuilder.append("null");
}
}
_queryBuilder.append('}');
}
}
| 26.949749 | 82 | 0.543353 |
48997ace726aff62cd913bbeaf7cf5ec2bbe9f35 | 513 | package macbury.forge.promises;
import com.badlogic.gdx.utils.Disposable;
/**
* Created by macbury on 16.03.15.
*/
public class GdxPromiseFrameTicker implements Disposable {
private GdxFutureTask target;
public void setTarget(GdxFutureTask target) {
this.target = target;
}
public GdxFutureTask getTarget() {
return target;
}
public void update(float delta) {
if (target != null) {
target.tick(delta);
}
}
@Override
public void dispose() {
target = null;
}
}
| 17.1 | 58 | 0.674464 |
b0eda8e765066a1011f7199c1d6a79e54bcc435c | 762 | package com.horvat.dragutin.survey.controllers;
import com.horvat.dragutin.survey.exception.SurveyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(SurveyException.class)
public void springHandleSurveyException(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.NOT_FOUND.value());
}
} | 38.1 | 94 | 0.843832 |
7e4b4056b95f12151d0f4df234b0c12d56d2a54f | 158 | package devos.jlsl;
import devos.jlsl.fragments.*;
@FunctionalInterface
public interface CodeFilter
{
public CodeFragment filter(CodeFragment fragment);
}
| 15.8 | 51 | 0.810127 |
61b4544b04a4a1d430f02f730497cf5003803a13 | 1,122 | package abapci.coloredProject.model.projectColor;
import static org.junit.Assert.*;
import org.eclipse.swt.graphics.RGB;
import org.junit.Test;
public class ProjectColorFactoryTest {
private static final RGB RED_COLOR = new RGB(255,0,0);
@Test
public void testCreateRGB() {
ProjectColorFactory projectColorFactory = new ProjectColorFactory();
RGB nullRGB = null;
assertTrue(projectColorFactory.create(nullRGB) instanceof DefaultEclipseProjectColor);
assertTrue(projectColorFactory.create(RED_COLOR) instanceof StandardProjectColor);
}
@Test
public void testCreateRGBBoolean() {
ProjectColorFactory projectColorFactory = new ProjectColorFactory();
IProjectColor suppressedColor = projectColorFactory.create(RED_COLOR, true);
assertTrue( suppressedColor instanceof StandardProjectColor);
assertTrue(suppressedColor.isSuppressed());
assertTrue(projectColorFactory.create(RED_COLOR, false) instanceof StandardProjectColor);
RGB nullRGB = null;
assertTrue(projectColorFactory.create(nullRGB, false) instanceof DefaultEclipseProjectColor);
}
}
| 33 | 97 | 0.778966 |
6037289be2e76d4b8d1a65ceffcac364ccb58a60 | 116 | package ms.springframework.bean.tx;
public class BookService {
public void checkout(String name, int age){
}
}
| 12.888889 | 44 | 0.741379 |
c7bcad6347cbaacd3ea0d8a0ddc879e39d84113e | 1,632 | package org.numbercounter;
import java.util.NavigableMap;
import java.util.TreeMap;
/**
* Class to be used for capturing data points and calculating statistics on those data points.
*/
public class DataCapture {
final NavigableMap<Integer, Long> pointCounts = new TreeMap<>();
long totalPointCount = 0;
/**
* Add a data point to the data capture. This function records a count of each data
* point it has observed, and a total count. It can record as many as Long.MAX_VALUE
* instances of each data point
*
* Time complexity is O(m) where m is the number of unique elements and will not exceed 1000.
* Memory complexity is also O(m).
*
* @param dataPoint a number between [0, 1000]
*/
public void add(int dataPoint) {
//This is O(log(m)) where
// m is the maximum number of *unique* elements.
// The maximum number of unique elements in the list is given in the problem as 1000
// therefore this is O(log(1000)) -> O(1)
final Long pointCount = pointCounts.computeIfAbsent(dataPoint, x -> 0L)+1;
pointCounts.put(dataPoint, pointCount);
totalPointCount++;
}
/**
* Create an object capable of efficiently calculating statistics on the observed data points.
* If you continue adding data points after calling build_stats, the StatisticsCalculator this
* generates will operate on the set of points captured at the time build_stats was called.
*
* Implementation is not thread safe.
*
* @return StatisticsCalculator
*/
public StatisticsCalculator build_stats() {
return new StatisticsCalculator(pointCounts, totalPointCount);
}
}
| 35.478261 | 96 | 0.715074 |
51b198503b7949f677c3ded1ece0d3b79f44741e | 1,594 | package com.luckypeng.mock.core.util;
import java.io.*;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
/**
* @author coalchan
* @since 1.0
*/
public class ObjectUtils {
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}
public static <T> T coalesce(T... objs) {
for (T obj: objs) {
if (obj != null) {
return obj;
}
}
return null;
}
/**
* 读取文件到字符串
* @param fileName relative path of file
* @return string of file
*/
public static String fromFile(String fileName) {
InputStream inputStream = ObjectUtils.class.getClassLoader().getResourceAsStream(fileName);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return sb.toString();
}
}
| 24.90625 | 99 | 0.534504 |
9d54f3daf0b0717210e1e826403fed9f8b2467ef | 1,064 | package com.github.serializepojo;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import com.github.serializepojo.api.Formatter;
import com.github.serializepojo.api.Serializer;
/**
* Base class to facilitate different implementations.
*
* @see ReflectionCsvSerializer
*/
public abstract class BaseSerializer<P, F extends Formatter> implements Serializer<P>, Closeable {
protected final F formatter;
/**
* Specifies the formatter to be used {@link Formatter}
*
* @param formatter
* @throws IOException
*/
public BaseSerializer(F formatter) throws IOException {
this.formatter = formatter;
}
/*
* (non-Javadoc)
*
* @see com.github.serializepojo.api.Serializer#serialize(java.lang.Object)
*/
@Override
public OutputStream serialize(final P pojo) throws IOException {
return this.serialize(Arrays.asList(pojo));
}
/*
* (non-Javadoc)
*
* @see java.io.Closeable#close()
*/
@Override
public void close() throws IOException {
this.formatter.end();
}
}
| 20.862745 | 98 | 0.726504 |
ab54f572d328c54c128cf8c3d48646984e2d098a | 974 | /*
* @(#)TabColorProvider.java 4/1/2011
*
* Copyright 2002 - 2011 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import java.awt.*;
/**
* A Color Provider to provide background and foreground for both {@link JideTabbedPane} and {@link SidePaneItem}.
* <p/>
* It has higher priority than {@link com.jidesoft.swing.JideTabbedPane#getTabColorProvider()}. However, if {@link SidePaneItem#setBackground(java.awt.Color)}
* or {@link SidePaneItem#setForeground(java.awt.Color)} is invoked, the settings in {@link SidePaneItem} will be respected
* instead of the color returned by this class.
*/
public interface TabColorProvider {
/**
* Gets the background color the tab.
*
* @return the background color.
*/
public Color getTabBackground();
/**
* Gets the foreground color the tab.
*
* @return the foreground color.
*/
public Color getTabForeground();
}
| 29.515152 | 159 | 0.666324 |
6c27ef9acbc6d10b5abac4efa1ac5dae29cafa35 | 1,975 | package samples;
import com.slack.api.bolt.App;
import com.slack.api.bolt.AppConfig;
import com.slack.api.methods.response.views.ViewsOpenResponse;
import com.slack.api.model.view.View;
import util.ResourceLoader;
import util.TestSlackAppServer;
import java.net.URLDecoder;
public class ViewDefaultToCurrentConversationSample {
public static void main(String[] args) throws Exception {
AppConfig config = ResourceLoader.loadAppConfig("appConfig_defaultToCurrentConversation.json");
App app = new App(config);
app.use((req, resp, chain) -> {
String body = req.getRequestBodyAsString();
String payload = body.startsWith("payload=") ? URLDecoder.decode(body.split("payload=")[1], "UTF-8") : body;
req.getContext().logger.info(payload);
return chain.next(req);
});
// src/test/resources
app.command("/view", (req, ctx) -> {
String view = ResourceLoader.load("views/view5.json");
ViewsOpenResponse apiResponse = ctx.client().viewsOpen(r ->
r.triggerId(ctx.getTriggerId()).viewAsString(view));
if (apiResponse.isOk()) {
return ctx.ack();
} else {
return ctx.ackWithJson(apiResponse);
}
});
app.viewSubmission("view-callback-id", (req, ctx) -> {
View view = req.getPayload().getView();
ctx.logger.info("state - {}, private_metadata - {}", view.getState(), view.getPrivateMetadata());
String conversationId = view.getState().getValues().get("b1").get("a").getSelectedConversation();
ctx.say(r -> r.channel(conversationId).text("Thank you for submitting the data!"));
return ctx.ack(); // just close the view
});
app.viewClosed("view-callback-id", (req, ctx) -> ctx.ack());
TestSlackAppServer server = new TestSlackAppServer(app);
server.start();
}
}
| 38.72549 | 120 | 0.618734 |
9d1bc88e8a5a4a01078bd9a8aeab10add4b8e184 | 4,254 | /*
* 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.commons.rng.core.source64;
import org.apache.commons.rng.core.RandomAssert;
import org.junit.jupiter.api.Test;
class XorShift1024StarPhiTest {
/** The size of the array SEED. */
private static final int SEED_SIZE = 16;
/*
* Data from running the executable compiled from the author's C code:
* http://xorshift.di.unimi.it/xorshift1024star.c
*/
private static final long[] SEED = {
0x012de1babb3c4104L, 0xa5a818b8fc5aa503L, 0xb124ea2b701f4993L, 0x18e0374933d8c782L,
0x2af8df668d68ad55L, 0x76e56f59daa06243L, 0xf58c016f0f01e30fL, 0x8eeafa41683dbbf4L,
0x7bf121347c06677fL, 0x4fd0c88d25db5ccbL, 0x99af3be9ebe0a272L, 0x94f2b33b74d0bdcbL,
0x24b5d9d7a00a3140L, 0x79d983d781a34a3cL, 0x582e4a84d595f5ecL, 0x7316fe8b0f606d20L,
};
private static final long[] EXPECTED_SEQUENCE = {
0xc9351be6ae9af4bbL, 0x2696a1a51e3040cbL, 0xdcbbc38b838b4be8L, 0xc989eee03351a25cL,
0xc4ad829b653ada72L, 0x1cff4000cc0118dfL, 0x988f3aaf7bfb2852L, 0x3a621d4d5fb27bf2L,
0x0153d81cf33ff4a7L, 0x8a1b5adb974750c1L, 0x182799e238df6de2L, 0x92d9bda951cd6377L,
0x601f077d2a659728L, 0x90536cc64ad5bc49L, 0x5d99d9e84e3d7fa9L, 0xfc66f4610240613aL,
0x0ff67da640cdd6b6L, 0x973c7a6afbb41751L, 0x5089cb5236ac1b5bL, 0x7ed6edc1e4d7e261L,
0x3e37630df0c00b63L, 0x49ec234a0d03bcc4L, 0x2bcbe2fa4b80fa33L, 0xbaafc47b960baefaL,
0x1855fa47be98c84fL, 0x8d59cb57e34a73e0L, 0x256b15bb001bf641L, 0x28ad378895f5615dL,
0x865547335ba2a571L, 0xfefe4c356e154585L, 0xeb87f7a74e076680L, 0x990d2f5d1e60b914L,
0x3bf0f6864688af2fL, 0x8c6304df9b945d58L, 0x63bc09c335b63666L, 0x1038139f53734ad2L,
0xf41b58faf5680868L, 0xa50ba830813c163bL, 0x7dc1ca503ae39817L, 0xea3d0f2f37f5ce95L,
};
private static final long[] EXPECTED_SEQUENCE_AFTER_JUMP = {
0x07afdab6d38bddd2L, 0x7bb8f1495d6aaa58L, 0x00f583e9eb57bf12L, 0x694e972ba626f7b6L,
0x0f7017b991b531dbL, 0x702fc8e6791b530cL, 0xf62322eab2db2526L, 0xe6bdc2cffeeae3ffL,
0xa0cb7cb78c2e3918L, 0x53fa4d1ee744ee74L, 0x5f0bcdebaf4b4af0L, 0xec23017af16e9040L,
0x2d1119530d4f4e06L, 0x75b721c9942eea60L, 0x6aab166dbc9d553bL, 0xcfa59b433d647154L,
0x687a4f5aa4bfd161L, 0xcc954692756486f1L, 0xcfa57a42ae5e8285L, 0xe290ecfae5d74436L,
0x0adb47de60db796fL, 0xee4e161668406ee0L, 0xe7f5beb82ec63004L, 0x5ee1ed818be7d7c0L,
0xb1aa1517d646c3c3L, 0x31ab29451adf8b7dL, 0x2612a880abf60efdL, 0xa7679f88450d8d9cL,
0xee3b07f323a85a69L, 0xac7e0039bb81e9a5L, 0x5b454710e237ab6dL, 0xdd6c4ac09653d161L,
0xc03e09a39f5e8c24L, 0x4a8352f76f7c3e94L, 0xebeb6e56c67fc377L, 0x3726d52cb3cda75bL,
0x3f6c00e368b97361L, 0xc49b806ba04c8ef4L, 0xf396608b186fdf27L, 0xe0c7f13ba319779fL,
};
@Test
void testReferenceCode() {
RandomAssert.assertEquals(EXPECTED_SEQUENCE, new XorShift1024StarPhi(SEED));
}
@Test
void testConstructorWithZeroSeedIsNonFunctional() {
RandomAssert.assertNextIntZeroOutput(new XorShift1024StarPhi(new long[SEED_SIZE]), 2 * SEED_SIZE);
}
@Test
void testConstructorWithSingleBitSeedIsFunctional() {
RandomAssert.assertLongArrayConstructorWithSingleBitSeedIsFunctional(XorShift1024StarPhi.class, SEED_SIZE);
}
@Test
void testJump() {
RandomAssert.assertJumpEquals(EXPECTED_SEQUENCE, EXPECTED_SEQUENCE_AFTER_JUMP, new XorShift1024StarPhi(SEED));
}
}
| 50.642857 | 118 | 0.780207 |
8eeac2c056f8bfa0d0ae0d89393d1bbf5ff6c8c6 | 1,744 | package net.fortytwo.ripple.model.types;
import net.fortytwo.ripple.RippleException;
import net.fortytwo.ripple.io.RipplePrintStream;
import net.fortytwo.ripple.model.ModelConnection;
import net.fortytwo.ripple.model.RippleType;
import net.fortytwo.ripple.model.StackMapping;
import net.fortytwo.ripple.model.StackMappingWrapper;
import org.openrdf.model.Value;
/**
* The data type of a wrapper for a stack mapping with a settable RDF equivalent
*
* @author Joshua Shinavier (http://fortytwo.net)
*/
public class StackMappingWrapperType extends SimpleType<StackMappingWrapper> {
public StackMappingWrapperType() {
super(StackMappingWrapper.class);
}
@Override
public boolean isInstance(StackMappingWrapper instance) {
return true;
}
@Override
public Value toRDF(StackMappingWrapper instance, ModelConnection mc) throws RippleException {
return instance.getRDFEquivalent();
}
@Override
public StackMapping getMapping(StackMappingWrapper instance) {
return null;
}
@Override
public void print(StackMappingWrapper instance, RipplePrintStream p, ModelConnection mc) throws RippleException {
p.print("[StackMappingWrapper: ");
p.print(instance.getInnerMapping());
p.print("]");
}
@Override
public Category getCategory() {
return RippleType.Category.OTHER_RESOURCE;
}
@Override
public int compare(StackMappingWrapper o1, StackMappingWrapper o2, ModelConnection mc) {
Value o1r = o1.getRDFEquivalent(), o2r = o2.getRDFEquivalent();
return null == o1r
? null == o2r ? 0 : -1
: null == o2r ? 1 : o1r.stringValue().compareTo(o2r.stringValue());
}
}
| 30.596491 | 117 | 0.704702 |
2fe9a06470feb62522b0cef22b640f9676872a75 | 533 | package lista05;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
public class ExportadorFormatoB implements Exportador {
public void exportar(File destino, List<Conta> contas) throws IOException {
PrintWriter out = new PrintWriter(destino);
for (Conta conta: contas) {
out.printf("%s;%s;%s;%.2f\n",
conta.getCpf(), conta.getBanco(), conta.getAgencia(), conta.getSaldo()
);
}
out.close();
}
}
| 24.227273 | 90 | 0.624765 |
52a53eb38da21c36d2f1706ccb051a80b18445ca | 6,383 | /*
* Copyright 2020 Horstexplorer @ https://www.netbeacon.de
*
* 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 de.netbeacon.jstorage.server.tools.exceptions;
/**
* This exception should be thrown when a direct feedback to a web client is required
*
* @author horstexplorer
*/
public class HTTPException extends Exception{
private final int statusCode;
private String additionalInformation;
/**
* Instantiates a new Http exception.
*
* @param statusCode the status code
*/
public HTTPException(int statusCode){
super("generic_placeholder");
this.statusCode = statusCode;
}
/**
* Instantiates a new Http exception.
*
* @param statusCode the status code
* @param additionalInformation the additional information
*/
public HTTPException(int statusCode, String additionalInformation){
super("generic_placeholder");
this.statusCode = statusCode;
this.additionalInformation = additionalInformation;
}
/**
* Get status code int.
*
* @return the int
*/
public int getStatusCode(){ return statusCode; }
/**
* Get additional information string.
*
* @return the string
*/
public String getAdditionalInformation(){ return additionalInformation; }
@Override
public String getMessage(){
switch(statusCode){
case 100:
return "Continue";
case 101:
return "Switching Protocols";
case 102:
return "Processing";
case 200:
return "OK";
case 201:
return "Created";
case 202:
return "Accepted";
case 203:
return "Non-Authoritative Information";
case 204:
return "No Content";
case 205:
return "Reset Content";
case 206:
return "Partial Content";
case 207:
return "Multi-Status";
case 208:
return "Already Reported";
case 226:
return "IM Used";
case 300:
return "Multiple Choices";
case 301:
return "Moved Permanently";
case 302:
return "Found (Moved Temporarily)";
case 303:
return "See Other";
case 304:
return "Not Modified";
case 305:
return "Use Proxy";
case 307:
return "Temporary Redirect";
case 308:
return "Permanent Redirect";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 402:
return "Payment Required";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 405:
return "Method Not Allowed";
case 406:
return "Not Acceptable";
case 407:
return "Proxy Authentication Required";
case 408:
return "Request Timeout";
case 409:
return "Conflict";
case 410:
return "Gone";
case 411:
return "Length Required";
case 412:
return "Precondition Failed";
case 413:
return "Request Entity Too Large";
case 414:
return "URI Too Long";
case 415:
return "Unsupported Media Type";
case 416:
return "Requested range not satisfiable";
case 417:
return "Expectation Failed";
case 420:
return "Policy Not Fulfilled";
case 421:
return "Misdirected Request";
case 422:
return "Unprocessable Entity";
case 423:
return "Locked";
case 424:
return "Failed Dependency";
case 426:
return "Upgrade Required";
case 428:
return "Precondition Required";
case 429:
return "Too Many Requests";
case 431:
return "Request Header Fields Too Large";
case 451:
return "\tUnavailable For Legal Reasons";
case 418:
return "I’m a teapot";
case 425:
return "Unordered Collection";
case 444:
return "No Response";
case 449:
return "The request should be retried after doing the appropriate action";
case 499:
return "Client Closed Request";
case 500:
return "Internal Server Error";
case 501:
return "Not Implemented";
case 502:
return "Bad Gateway";
case 503:
return "Service Unavailable";
case 504:
return "Gateway Timeout";
case 505:
return "HTTP Version not supported";
case 506:
return "Variant Also Negotiates";
case 507:
return "Insufficient Storage";
case 508:
return "Loop Detected";
case 509:
return "Bandwidth Limit Exceeded";
case 510:
return "Not Extended";
case 511:
return "Network Authentication Required";
default:
return "Internal Server Error";
}
}
}
| 30.251185 | 90 | 0.506032 |
1265f40620651a37520c0924ff0c3f2857c4ac5f | 4,926 | package com.github.badoualy.telegram.tl.api;
import static com.github.badoualy.telegram.tl.StreamUtils.*;
import static com.github.badoualy.telegram.tl.TLObjectUtils.*;
import com.github.badoualy.telegram.tl.TLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
/**
* @author Yannick Badoual yann.badoual@gmail.com
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
public class TLWallPaper extends TLAbsWallPaper {
public static final int CONSTRUCTOR_ID = 0xa437c3ed;
protected long id;
protected boolean creator;
protected boolean pattern;
protected long accessHash;
protected String slug;
protected TLAbsDocument document;
private final String _constructor = "wallPaper#a437c3ed";
public TLWallPaper() {
}
public TLWallPaper(long id, boolean creator, boolean isDefault, boolean pattern, boolean dark, long accessHash, String slug, TLAbsDocument document, TLWallPaperSettings settings) {
this.id = id;
this.creator = creator;
this.isDefault = isDefault;
this.pattern = pattern;
this.dark = dark;
this.accessHash = accessHash;
this.slug = slug;
this.document = document;
this.settings = settings;
}
private void computeFlags() {
flags = 0;
flags = creator ? (flags | 1) : (flags & ~1);
flags = isDefault ? (flags | 2) : (flags & ~2);
flags = pattern ? (flags | 8) : (flags & ~8);
flags = dark ? (flags | 16) : (flags & ~16);
flags = settings != null ? (flags | 4) : (flags & ~4);
}
@Override
public void serializeBody(OutputStream stream) throws IOException {
computeFlags();
writeLong(id, stream);
writeInt(flags, stream);
writeLong(accessHash, stream);
writeString(slug, stream);
writeTLObject(document, stream);
if ((flags & 4) != 0) {
if (settings == null) throwNullFieldException("settings", flags);
writeTLObject(settings, stream);
}
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public void deserializeBody(InputStream stream, TLContext context) throws IOException {
id = readLong(stream);
flags = readInt(stream);
creator = (flags & 1) != 0;
isDefault = (flags & 2) != 0;
pattern = (flags & 8) != 0;
dark = (flags & 16) != 0;
accessHash = readLong(stream);
slug = readTLString(stream);
document = readTLObject(stream, context, TLAbsDocument.class, -1);
settings = (flags & 4) != 0 ? readTLObject(stream, context, TLWallPaperSettings.class, TLWallPaperSettings.CONSTRUCTOR_ID) : null;
}
@Override
public int computeSerializedSize() {
computeFlags();
int size = SIZE_CONSTRUCTOR_ID;
size += SIZE_INT64;
size += SIZE_INT32;
size += SIZE_INT64;
size += computeTLStringSerializedSize(slug);
size += document.computeSerializedSize();
if ((flags & 4) != 0) {
if (settings == null) throwNullFieldException("settings", flags);
size += settings.computeSerializedSize();
}
return size;
}
@Override
public String toString() {
return _constructor;
}
@Override
public int getConstructorId() {
return CONSTRUCTOR_ID;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean getCreator() {
return creator;
}
public void setCreator(boolean creator) {
this.creator = creator;
}
public boolean getIsDefault() {
return isDefault;
}
public void setIsDefault(boolean isDefault) {
this.isDefault = isDefault;
}
public boolean getPattern() {
return pattern;
}
public void setPattern(boolean pattern) {
this.pattern = pattern;
}
public boolean getDark() {
return dark;
}
public void setDark(boolean dark) {
this.dark = dark;
}
public long getAccessHash() {
return accessHash;
}
public void setAccessHash(long accessHash) {
this.accessHash = accessHash;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public TLAbsDocument getDocument() {
return document;
}
public void setDocument(TLAbsDocument document) {
this.document = document;
}
public TLWallPaperSettings getSettings() {
return settings;
}
public void setSettings(TLWallPaperSettings settings) {
this.settings = settings;
}
}
| 26.202128 | 184 | 0.620382 |
453d8c1342774a1779bda6e7d361468220b39d46 | 1,834 | package com.lvonce.logicweaver.persistent;
import com.lvonce.logicweaver.interfaces.ILogicNode;
/**
* Created by WangWei on 2017/3/16.
*/
public class BehaviorDumper {
public static String dump(Object entity, ILogicNode unit) {
/*
IBehaviorUnit.TYPE type = unit.getType();
LogicDebug.incLevel();
String dumpString = "";
switch (type) {
case UNIT:
IBehaviorFunction func = ((BehaviorUnit)unit).getFunc();
dumpString = String.format("{\"type\":\"unit\", \"func\":\"%s\", \"config\":%s}", entity.getBehaviorName(func), "null");
break;
case SELECTOR:
dumpString = "{ \"type\":\"selector\", \"list\":[";
break;
case SEQUENCE:
dumpString = "{ \"type\":\"sequence\", \"list\":[";
break;
case PARALLEL_SELECTOR:
LogicDebug.debug("PARALLEL_SELECTOR");
break;
case PARALLEL_SEQUENCE:
LogicDebug.debug("PARALLEL_SEQUENCE");
break;
case PROBABILITY:
LogicDebug.debug("PROBABILITY");
break;
}
if (type != IBehaviorUnit.TYPE.UNIT) {
LogicList list = (LogicList)unit;
for (int i=0; i<list.list.length; ++i) {
IBehaviorUnit u = list.list[i];
if (i!=0) {
dumpString = dumpString.concat(",");
}
dumpString = dumpString.concat(dump(entity, u));
}
}
if (type != IBehaviorUnit.TYPE.UNIT) {
dumpString = dumpString.concat("]}");
}
return dumpString;
*/
return null;
}
}
| 32.75 | 137 | 0.47928 |
048b4537f364e8a6c37e6c4d1e5f1b2869537790 | 959 | package com.dante.tedd.extraction;
public class DependencyGraphExtractionConfig {
private String dependencyGraphOptimized;
private String fixedSelectedTestSuite;
public void setParetoFrontSolution(String dependencyGraphOptimized) {
this.dependencyGraphOptimized = dependencyGraphOptimized
.replaceAll("\\s+","-");
}
public String getParetoFrontSolution() {
if(dependencyGraphOptimized == null)
throw new UnsupportedOperationException("Pareto front solution not set!");
return dependencyGraphOptimized;
}
public void setFixedSelectedTestSuite(String fixedSelectedTestSuite) {
this.fixedSelectedTestSuite = fixedSelectedTestSuite;
}
public String getFixedSelectedTestSuite() {
if(fixedSelectedTestSuite == null)
throw new UnsupportedOperationException("Fixed minimized test suite not set!");
return fixedSelectedTestSuite;
}
}
| 33.068966 | 91 | 0.72367 |
764517b2da51edcda21de9abedc0cba113727431 | 509 | package com.zhaoq.spring3.demo2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfig {
@Bean(name="mycar")
public Car showCar(){
Car car = new Car();
car.setName("长安");
car.setPrice(40000d);
return car;
}
@Bean(name="product")
public Product initProduct(){
Product product = new Product();
product.setName("空调");
product.setPrice(3000d);
return product;
}
}
| 20.36 | 61 | 0.689587 |
4efeb87cf9afca3832ae12d8b37ce8c632df7119 | 443 | package io.gomint.server.inventory.item;
import io.gomint.inventory.item.ItemType;
import io.gomint.server.registry.RegisterInfo;
import io.gomint.taglib.NBTTagCompound;
/**
* @author geNAZt
* @version 1.0
*/
@RegisterInfo(sId = "minecraft:lever", id = 69)
public class ItemLever extends ItemStack implements io.gomint.inventory.item.ItemLever {
@Override
public ItemType getItemType() {
return ItemType.LEVER;
}
}
| 21.095238 | 88 | 0.733634 |
be1e958b56925aae4bc963997cf8449044bcabe4 | 1,046 | package enhancedbooks.client.core;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.client.registry.RenderingRegistry;
import enhancedbooks.client.models.ModelFlyingBook;
import enhancedbooks.client.renderers.RenderFlyingBook;
import enhancedbooks.client.renderers.StorageShelfRenderer;
import enhancedbooks.common.core.CommonProxy;
import enhancedbooks.common.entities.EntityFlyingBook;
import enhancedbooks.common.tileentities.TileEntityStorageShelf;
/**
* Created with IntelliJ IDEA.
* User: Ari
* Date: 02/01/13
* Time: 3:31 AM
*/
public class ClientProxy extends CommonProxy {
@Override
public void registerRenderInformation() {
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityStorageShelf.class, new StorageShelfRenderer());
RenderingRegistry.registerBlockHandler(StorageShelfRenderer.storageShelfModelID, new StorageShelfRenderer());
RenderingRegistry.registerEntityRenderingHandler(EntityFlyingBook.class, new RenderFlyingBook(new ModelFlyingBook(), 0.5F));
}
} | 36.068966 | 132 | 0.813576 |
f8c66440f0f22e234167facd1f15a760133ca993 | 2,489 | /*
* Copyright (c) 2020 John Mayfield
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.simolecule.centres;
public class Edge<A, B> {
private Node<A, B> beg, end;
private final B bond;
private Descriptor aux;
public Edge(Node<A, B> beg, Node<A, B> end, B bond)
{
this.beg = beg;
this.end = end;
this.bond = bond;
}
public Node<A, B> getOther(Node<A, B> node)
{
if (node.equals(getBeg()))
return getEnd();
else if (node.equals(getEnd()))
return getBeg();
else
throw new IllegalArgumentException("Not an end-point of this edge!");
}
public Node<A, B> getBeg()
{
return beg;
}
public Node<A, B> getEnd()
{
return end;
}
public Descriptor getAux()
{
return aux;
}
public void setAux(Descriptor aux)
{
this.aux = aux;
}
public void flip()
{
Node<A, B> tmp = end;
end = beg;
beg = tmp;
}
public B getBond()
{
return bond;
}
public boolean isBeg(Node<A, B> node)
{
return node.equals(beg);
}
public boolean isEnd(Node<A, B> node)
{
return node.equals(end);
}
@Override
public String toString()
{
return beg.toString() + "->" + end.toString();
}
}
| 24.89 | 79 | 0.679791 |
7e19b7f799e8076cdb13726fefebc0c422e26e7a | 329 | package cn.orgid.message.domain.dao.message;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import cn.orgid.message.domain.model.message.ReportMessage;
public interface ReportMessageDAO extends JpaRepository<ReportMessage, Long>{
List<ReportMessage> findTop200ByOrderByIdAsc();
}
| 20.5625 | 78 | 0.817629 |
f0dc3554dd781fecbaf5eab3775e79f4618ac4ad | 4,117 | package org.usergrid.rest.applications.collection.activities;
import org.codehaus.jackson.JsonNode;
import org.junit.Rule;
import org.junit.Test;
import org.usergrid.rest.AbstractRestIT;
import org.usergrid.rest.TestContextSetup;
import org.usergrid.rest.test.resource.CustomCollection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.usergrid.utils.MapUtils.hashMap;
/**
* // TODO: Document this
*
* @author ApigeeCorporation
* @since 4.0
*/
public class OrderByTest extends AbstractRestIT
{
@Rule
public TestContextSetup context = new TestContextSetup( this );
@Test
// USERGRID-1400
public void orderByShouldNotAffectResults() {
CustomCollection activities = context.collection("activities");
long created = 0;
Map actor = hashMap("displayName", "Erin");
Map props = new HashMap();
props.put("actor", actor);
props.put("verb", "go");
props.put("content", "bragh");
for (int i = 0; i < 20; i++) {
props.put("ordinal", i);
JsonNode activity = activities.create(props);
if (i == 5) {
created = activity.findValue("created").getLongValue();
}
}
String query = "select * where created > " + created;
JsonNode node = activities.withQuery(query).get();
assertEquals(10, node.get("entities").size());
query = query + " order by created desc";
node = activities.withQuery(query).get();
assertEquals(10, node.get("entities").size());
}
@Test
// USERGRID-1520
public void orderByComesBeforeLimitResult() {
CustomCollection activities = context.collection("activities");
Map actor = hashMap("displayName", "Erin");
Map props = new HashMap();
int checkResultsNum = 0;
props.put("actor", actor);
props.put("verb", "go");
props.put("content", "bragh");
for (int i = 0; i < 20; i++) {
props.put("ordinal", i);
JsonNode activity = activities.create(props);
}
String query = "select * where created > " + 1 + " order by created desc";
JsonNode incorrectNode = activities.withQuery(query).withLimit(5).get();
assertEquals(5, incorrectNode.get("entities").size());
while (checkResultsNum < 5)
{
assertEquals(activities.entityIndex(query, checkResultsNum),
activities.entityIndexLimit(query, 5, checkResultsNum));
checkResultsNum++;
}
}
/*
* public JsonNode entityIndex(JsonNode container, int index) { return
* container.get("entities").get(index); }
*/
@Test
// USERGRID-1521
public void orderByReturnCorrectResults() {
CustomCollection activities = context.collection("activities");
int size = 200;
Map<String, String> actor = hashMap("displayName", "Erin");
Map<String, Object> props = new HashMap<String, Object>();
props.put("actor", actor);
props.put("verb", "go");
props.put("content", "bragh");
List<JsonNode> activites = new ArrayList<JsonNode>(size);
for (int i = 0; i < size; i++) {
props.put("ordinal", i);
JsonNode activity = activities.create(props).get("entities").get(0);
activites.add(activity);
}
long lastCreated = activites.get(activites.size() - 1).get("created").asLong();
String errorQuery = String.format("select * where created <= %d order by created desc", lastCreated);
String cursor = null;
int index = size-1;
do {
JsonNode response = activities.withQuery(errorQuery).get();
JsonNode cursorNode = response.get("cursor");
cursor = cursorNode != null ? cursorNode.asText() : null;
JsonNode entities = response.get("entities");
int returnSize = entities.size();
for(int i = 0; i < returnSize; i ++, index--){
assertEquals(activites.get(index), entities.get(i));
}
activities = activities.withCursor(cursor);
} while (cursor != null && cursor.length() > 0);
assertEquals("Paged to last result", -1, index);
}
}
| 27.817568 | 105 | 0.653145 |
ce950b2176b5535742fe3f95935f8d6835bbd7df | 8,885 | package com.alauda.jenkins.plugins;
import com.alauda.jenkins.plugins.cluster.ClusterRegistryExtension;
import com.alauda.jenkins.plugins.cluster.DefaultClusterRegistry;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.util.ListBoxModel;
import io.alauda.jenkins.devops.support.KubernetesCluster;
import io.alauda.jenkins.devops.support.KubernetesClusterConfiguration;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.StaplerRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Devops extends AbstractDescribableImpl<Devops> {
public static final String DEFAULT_CLUSTER = "default";
private static final Logger LOGGER = Logger.getLogger(Devops.class.getName());
public static final String DEFAULT_LOGLEVEL = "0";
@Extension
@Symbol("alaudaDevOpsClientConfiguration")
public static class DescriptorImpl extends Descriptor<Devops> {
private static final long serialVersionUID = 1L;
// Store a config version so we're able to migrate config.
public Long configVersion;
public List<ClusterConfig> clusterConfigs;
public String tool = "kubectl";
private String proxy;
private String namespace = "system";
public DescriptorImpl() {
configVersion = 1L;
load();
}
@Override
public String getDisplayName() {
return "Devops Configuration";
}
public String getClientToolName() {
return tool;
}
public void removeClusterConfig(ClusterConfig clusterConfig) throws IllegalArgumentException {
if (clusterConfigs == null || clusterConfigs.size() <= 0) {
throw new IllegalArgumentException("ClusterConfigs is null or empty");
}
clusterConfigs.remove(clusterConfig);
}
public void addClusterConfig(ClusterConfig clusterConfig) {
if (clusterConfigs == null) {
clusterConfigs = new ArrayList<>(1);
}
clusterConfigs.add(clusterConfig);
}
@Override
public boolean configure(StaplerRequest req, JSONObject json)
throws FormException {
/**
* If all cluster configurations are deleted in the UI and saved,
* binJSON does not set the list. So clear out the list before bind.
*/
clusterConfigs = null;
req.bindJSON(this, json.getJSONObject("alaudaDevops"));
KubernetesClusterConfiguration config = KubernetesClusterConfiguration.get();
if(config != null) {
KubernetesCluster cluster = config.getCluster();
ClusterConfig clusterConfig = getLocalClusterConfig(Devops.DEFAULT_CLUSTER);
if(clusterConfig == null) {
clusterConfig = new ClusterConfig(Devops.DEFAULT_CLUSTER);
addClusterConfig(clusterConfig);
}
clusterConfig.setServerUrl(cluster.getMasterUrl());
clusterConfig.setSkipTlsVerify(cluster.isSkipTlsVerify());
clusterConfig.setCredentialsId(cluster.getCredentialsId());
clusterConfig.setServerCertificateAuthority(cluster.getServerCertificateAuthority());
ManagerClusterCache.getInstance().setCredentialId(cluster.getCredentialsId());
}
save();
// should re-watch cluster
ExtensionList<DefaultClusterRegistry> defaultClusterRegistry =
Jenkins.getInstance().getExtensionList(DefaultClusterRegistry.class);
if(defaultClusterRegistry != null && defaultClusterRegistry.size() > 0) {
if(defaultClusterRegistry.get(0) != null) {
defaultClusterRegistry.get(0).watch();
LOGGER.info("DefaultClusterRegistry is reloaded.");
}
}
return true;
}
// Creates a model that fills in logLevel options in configuration UI
public ListBoxModel doFillLogLevelItems() {
ListBoxModel items = new ListBoxModel();
items.add("0 - Least Logging", "0");
for (int i = 1; i < 10; i++) {
items.add("" + i, "" + i);
}
items.add("10 - Most Logging", "10");
return items;
}
public List<ClusterConfig> getClusterConfigs() {
if (clusterConfigs == null) {
return new ArrayList<>(0);
}
return Collections.unmodifiableList(clusterConfigs);
}
@DataBoundSetter
public void setClusterConfigs(List<ClusterConfig> clusterConfigs) {
this.clusterConfigs = clusterConfigs;
}
public String getProxy() {
return proxy;
}
@DataBoundSetter
public void setProxy(String proxy) {
this.proxy = proxy;
}
public String getNamespace() {
return namespace;
}
@DataBoundSetter
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public ClusterConfig getLocalClusterConfig(String name) {
final String clusterName = Util.fixEmptyAndTrim(name);
Optional<ClusterConfig> clusterConfigOpt = Optional.empty();
if (clusterConfigs != null) {
clusterConfigOpt = clusterConfigs.stream()
.filter(cc -> cc.getName().equalsIgnoreCase(clusterName))
.findFirst();
}
if (!clusterConfigOpt.isPresent()) {
LOGGER.log(Level.WARNING, "Cannot find cluster %s from both system configuration and clusterregistry");
return null;
}
return clusterConfigOpt.get();
}
/**
* Determines if a cluster has been configured with a given name. If a
* cluster has been configured with the name, its definition is
* returned.
*
* @param name
* The name of the cluster config to find
* @return A ClusterConfig for the supplied parameters OR null.
*/
public ClusterConfig getClusterConfig(String name) {
final String clusterName = Util.fixEmptyAndTrim(name);
Optional<ClusterConfig> clusterConfigOpt = Optional.empty();
if (clusterConfigs != null) {
clusterConfigOpt = clusterConfigs.stream()
.filter(cc -> cc.getName().equalsIgnoreCase(clusterName))
.findFirst();
}
if (!clusterConfigOpt.isPresent()) {
LOGGER.info(String.format("Cannot find %s from system configuration, try to find from cluster registry.", name));
clusterConfigOpt = Optional.ofNullable(findFromClusterRegistry(clusterName));
}
if (!clusterConfigOpt.isPresent()) {
LOGGER.log(Level.WARNING, "Cannot find cluster %s from both system configuration and clusterregistry");
return null;
}
return clusterConfigOpt.get();
}
private ClusterConfig findFromClusterRegistry(String clusterName) {
ClusterRegistryExtension extension = ClusterRegistryExtension.findByName(clusterName);
if(extension == null) {
LOGGER.fine(String.format("no matched ClusterRegistryExtension for cluster: %s", clusterName));
return null;
}
ClusterRegistryExtension.ClusterRegistry clusterRegistry = extension.getClusterRegistry(clusterName);
if(clusterRegistry == null) {
LOGGER.fine(String.format("no matched ClusterRegistry for cluster: %s", clusterName));
return null;
}
ClusterConfig clusterConfig = new ClusterConfig(clusterName);
clusterConfig.setCredentialsId(clusterRegistry.getToken());
clusterConfig.setServerUrl(getProxy() + "/" + clusterRegistry.getName());
clusterConfig.setServerCertificateAuthority(clusterRegistry.getServerCertificateAuthority());
clusterConfig.setSkipTlsVerify(clusterRegistry.isSkipTlsVerify());
clusterConfig.setProxy(true);
LOGGER.fine(String.format("cluster server url is: %s", clusterConfig.getServerUrl()));
return clusterConfig;
}
}
}
| 37.331933 | 129 | 0.619471 |
e195fd73d75d6c2ab0732ad837866a85c669296b | 1,381 | package us.davidandersen.tyche.random;
import java.lang.reflect.Field;
import us.davidandersen.tyche.Randomize;
public class ObjectRandomizer
{
final Randomizer randomizer;
public ObjectRandomizer()
{
randomizer = new BasicRandomizer();
}
ObjectRandomizer(final Randomizer randomizer)
{
this.randomizer = randomizer;
}
public void randomize(final Object object)
{
for (final Field field : object.getClass().getDeclaredFields())
{
if (field.isAnnotationPresent(Randomize.class))
{
try
{
final Randomize randomizeAnnotation = field.getAnnotation(Randomize.class);
final String value = randomizeAnnotation.value();
final int min = randomizeAnnotation.min();
final int max = randomizeAnnotation.max();
field.setAccessible(true);
if ("".equals(value) && (min != 0 || max != 0))
{
field.set(object, randomizer.between(min, max));
}
else if (field.getType().isAssignableFrom(String.class) && (min != 0 || max != 0))
{
field.set(object, randomizer.randomize(value, min, max));
}
else if (field.getType().isAssignableFrom(String.class))
{
field.set(object, randomizer.randomize(value));
}
else
{
field.set(object, randomizer.between(0, 9999));
}
}
catch (final Exception e)
{
throw new RuntimeException(e);
}
}
}
}
}
| 23.40678 | 87 | 0.655322 |
4eea41723f7d9ccccf1c782793154245fb4c56bd | 1,004 | package org.odata4j.producer.server;
import javax.ws.rs.core.Application;
import org.odata4j.producer.resources.AbstractODataApplication;
import org.odata4j.producer.resources.DefaultODataApplication;
import org.odata4j.producer.resources.RootApplication;
/**
* Generic OData server
*/
public interface ODataServer {
/**
* Starts the OData server.
*
* @return this server
*/
ODataServer start();
/**
* Stops the OData server.
*
* @return this server
*/
ODataServer stop();
/**
* Sets the OData application.
*
* @param odataApp the OData application class
* @return this server
* @see AbstractODataApplication
* @see DefaultODataApplication
*/
ODataServer setODataApplication(Class<? extends Application> odataApp);
/**
* Sets the root application.
*
* @param rootApp the root application class
* @return this server
* @see RootApplication
*/
ODataServer setRootApplication(Class<? extends Application> rootApp);
}
| 21.361702 | 73 | 0.705179 |
1f39bea043916e24f5efff772fddf1bf0a8372dc | 1,621 | package br.com.zer0framework.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.zer0framework.utils.security.SecurityUtil;
import br.com.zer0framework.utils.HttpHeaders;
// TODO RegisterUserSevlet
@WebFilter(filterName = "userAuthFilter", urlPatterns = "/api/*")
public class UserAuthFilter implements Filter {
protected FilterConfig filterConfig;
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
final HttpServletResponse res = (HttpServletResponse) response;
final HttpServletRequest req = (HttpServletRequest) request;
String token = req.getHeader(HttpHeaders.AUTHORIZATION);
if (token == null) {
token = request.getParameter("token");
}
if (token == null || token.trim().isEmpty()) {
res.setStatus(401);
return;
}
try {
if (SecurityUtil.validateToken(token)) {
res.setStatus(200);
filterChain.doFilter(request, response);
} else {
res.setStatus(401);
}
}catch (NumberFormatException e){
res.setStatus(401);
}
}
@Override
public void destroy() {
}
} | 27.948276 | 135 | 0.727329 |
11b0a328478e8b11023e9647316f3669a7404b1b | 1,140 |
package mage.game.permanent.token;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.MageInt;
import mage.abilities.keyword.FlyingAbility;
import java.util.Arrays;
/**
*
* @author spjspj
*/
public final class ThopterToken extends TokenImpl {
public ThopterToken() {
super("Thopter Token", "1/1 blue Thopter artifact creature token with flying");
cardType.add(CardType.CREATURE);
cardType.add(CardType.ARTIFACT);
color.setBlue(true);
subtype.add(SubType.THOPTER);
power = new MageInt(1);
toughness = new MageInt(1);
this.addAbility(FlyingAbility.getInstance());
availableImageSetCodes = Arrays.asList("ALA", "C16", "C18", "2XM");
}
@Override
public void setExpansionSetCodeForImage(String code) {
super.setExpansionSetCodeForImage(code);
if (getOriginalExpansionSetCode().equals("2XM")) {
this.setTokenType(2);
}
}
public ThopterToken(final ThopterToken token) {
super(token);
}
public ThopterToken copy() {
return new ThopterToken(this);
}
}
| 24.255319 | 87 | 0.657895 |
8018de4b4f8c00aa2206e2ac07268dcf240f3590 | 3,724 | package org.ljrobotics.lib.util.motion;
import static org.junit.Assert.*;
import org.junit.Test;
public class SetpointGeneratorTest {
public MotionState followProfile(SetpointGenerator spg, MotionProfileConstraints constraints,
MotionProfileGoal goal, MotionState start_state, double dt, int max_iterations) {
MotionState prev_state = start_state;
System.out.println("Goal: " + goal);
System.out.println("Start state: " + prev_state);
int i = 0;
for (; i < max_iterations; ++i) {
SetpointGenerator.Setpoint setpoint = spg.getSetpoint(constraints, goal, prev_state, prev_state.t() + dt);
prev_state = setpoint.motion_state;
System.out.println(prev_state);
if (setpoint.final_setpoint) {
System.out.println("Goal reached");
break;
}
}
if (i == max_iterations) {
System.out.println("Iteration limit reached");
}
return prev_state;
}
@Test
public void testStationaryToStationary() {
MotionProfileConstraints constraints = new MotionProfileConstraints(10.0, 10.0);
MotionProfileGoal goal = new MotionProfileGoal(100.0);
MotionState start_state = new MotionState(0.0, 0.0, 0.0, 0.0);
final double dt = 0.01;
SetpointGenerator spg = new SetpointGenerator();
MotionState final_setpoint = followProfile(spg, constraints, goal, start_state, dt, 1500);
assertTrue(goal.atGoalState(final_setpoint));
}
@Test
public void testUpdateGoal() {
MotionProfileConstraints constraints = new MotionProfileConstraints(10.0, 10.0);
MotionProfileGoal goal = new MotionProfileGoal(100.0);
MotionState start_state = new MotionState(0.0, 0.0, 0.0, 0.0);
final double dt = 0.01;
SetpointGenerator spg = new SetpointGenerator();
MotionState final_setpoint = followProfile(spg, constraints, goal, start_state, dt, 500);
assertTrue(!goal.atGoalState(final_setpoint));
goal = new MotionProfileGoal(0.0);
final_setpoint = followProfile(spg, constraints, goal, final_setpoint, dt, 1000);
assertTrue(goal.atGoalState(final_setpoint));
}
@Test
public void testUpdateState() {
MotionProfileConstraints constraints = new MotionProfileConstraints(10.0, 10.0);
MotionProfileGoal goal = new MotionProfileGoal(100.0);
MotionState start_state = new MotionState(0.0, 0.0, 0.0, 0.0);
final double dt = 0.01;
SetpointGenerator spg = new SetpointGenerator();
MotionState final_setpoint = followProfile(spg, constraints, goal, start_state, dt, 500);
assertTrue(!goal.atGoalState(final_setpoint));
start_state = new MotionState(5.0, 50.0, 0.0, 0.0);
final_setpoint = followProfile(spg, constraints, goal, start_state, dt, 1500);
assertTrue(goal.atGoalState(final_setpoint));
}
@Test
public void testUpdateConstraints() {
MotionProfileConstraints constraints = new MotionProfileConstraints(10.0, 10.0);
MotionProfileGoal goal = new MotionProfileGoal(100.0);
MotionState start_state = new MotionState(0.0, 0.0, 0.0, 0.0);
final double dt = 0.01;
SetpointGenerator spg = new SetpointGenerator();
MotionState final_setpoint = followProfile(spg, constraints, goal, start_state, dt, 500);
assertTrue(!goal.atGoalState(final_setpoint));
constraints = new MotionProfileConstraints(20.0, 20.0);
final_setpoint = followProfile(spg, constraints, goal, final_setpoint, dt, 1500);
assertTrue(goal.atGoalState(final_setpoint));
}
}
| 40.923077 | 118 | 0.66783 |
6d4d03360f4d804edc51ece9b6bed42a68024071 | 6,064 | /*
* Copyright 2004-2014 ICEsoft Technologies Canada Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icefaces.mobi.component.pagepanel;
import java.io.IOException;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.icefaces.mobi.renderkit.BaseLayoutRenderer;
import org.icefaces.mobi.utils.HTML;
import org.icefaces.mobi.utils.JSFUtils;
import org.icefaces.mobi.utils.PassThruAttributeWriter;
public class PagePanelRenderer extends BaseLayoutRenderer {
private static final Logger logger = Logger.getLogger(PagePanelRenderer.class.getName());
@Override
public void encodeEnd(FacesContext facesContext, UIComponent component) throws IOException {
PagePanel pagePanel = (PagePanel) component;
ResponseWriter writer = facesContext.getResponseWriter();
String clientId = component.getClientId(facesContext);
// render a top level div and apply the style and style class pass through attributes
writer.startElement(HTML.DIV_ELEM, pagePanel);
String styleClass = "mobi-pagePanel";
if( pagePanel.isFixedHeader()){
styleClass += " mobi-fixed-header";
}
if( pagePanel.isFixedFooter()){
styleClass += " mobi-fixed-footer";
}
writer.writeAttribute(HTML.CLASS_ATTR, styleClass, null);
PassThruAttributeWriter.renderNonBooleanAttributes(writer, pagePanel,
pagePanel.getCommonAttributeNames());
writer.writeAttribute(HTML.ID_ATTR, clientId + "_pgPnl", HTML.ID_ATTR);
if (pagePanel.getStyle()!=null){
writer.writeAttribute(HTML.STYLE_ATTR, pagePanel.getStyle(), HTML.STYLE_ATTR);
}
StringBuilder headerClass = new StringBuilder(PagePanel.HEADER_CLASS + " ui-bar-a");
StringBuilder bodyClass = new StringBuilder(PagePanel.BODY_CLASS);
StringBuilder footerClass = new StringBuilder(PagePanel.FOOTER_CLASS +"ui-bar-a");
StringBuilder headerFooterContentsClass = new StringBuilder(PagePanel.CTR_CLASS);
// find out if header and/or footer facets are present as this will directly
// effect which style classes to apply
UIComponent headerFacet = pagePanel.getFacet(PagePanel.HEADER_FACET);
UIComponent bodyFacet = pagePanel.getFacet(PagePanel.BODY_FACET);
UIComponent footerFacet = pagePanel.getFacet(PagePanel.FOOTER_FACET);
if (bodyFacet == null) {
logger.warning("PagePanel body was not defined, " +
"no content will be rendered by this component.");
}
if (headerFacet==null) {
bodyClass.append(" ").append(PagePanel.BODY_NO_HEADER_CLASS);
}
if (footerFacet ==null){
bodyClass.append(" ").append(PagePanel.BODY_NO_FOOTER_CLASS);
}
String userDefStyle = pagePanel.getStyleClass();
if (userDefStyle!=null){
headerClass.append(" ").append(userDefStyle);
bodyClass.append(" ").append(userDefStyle);
footerClass.append(" ").append(userDefStyle);
headerFooterContentsClass.append(" ").append(userDefStyle);
}
// write header if present
if (headerFacet != null) {
writer.startElement(HTML.DIV_ELEM, pagePanel);
writer.writeAttribute(HTML.CLASS_ATTR, headerClass.toString(), HTML.CLASS_ATTR);
writer.writeAttribute(HTML.ID_ATTR, clientId + "_pgPnlHdr", HTML.ID_ATTR);
writer.startElement(HTML.DIV_ELEM, component);
writer.writeAttribute(HTML.CLASS_ATTR, headerFooterContentsClass.toString(), HTML.STYLE_CLASS_ATTR);
JSFUtils.renderLayoutChild(facesContext, headerFacet);
writer.endElement(HTML.DIV_ELEM);
writer.endElement(HTML.DIV_ELEM);
}
/// write body with no-footer or no-header considerations
if (bodyFacet != null) {
// build out style class depending on header footer visibility
writer.startElement(HTML.DIV_ELEM, pagePanel);
writer.writeAttribute(HTML.CLASS_ATTR, bodyClass.toString(), HTML.CLASS_ATTR);
writer.writeAttribute(HTML.ID_ATTR, clientId + "_pgPnlBdy", HTML.ID_ATTR);
JSFUtils.renderLayoutChild(facesContext, bodyFacet);
writer.endElement(HTML.DIV_ELEM);
}
// write footer f present
if (footerFacet != null) {
writer.startElement(HTML.DIV_ELEM, pagePanel);
writer.writeAttribute(HTML.CLASS_ATTR, footerClass.toString(), HTML.CLASS_ATTR);
writer.writeAttribute(HTML.ID_ATTR, clientId + "_pgPnlFtr", HTML.ID_ATTR);
writer.startElement(HTML.DIV_ELEM, component);
writer.writeAttribute(HTML.CLASS_ATTR, headerFooterContentsClass, HTML.STYLE_CLASS_ATTR);
JSFUtils.renderLayoutChild(facesContext, footerFacet);
writer.endElement(HTML.DIV_ELEM);
writer.endElement(HTML.DIV_ELEM);
}
// close the top level div
writer.endElement(HTML.DIV_ELEM);
}
@Override
public void encodeChildren(FacesContext facesContext, UIComponent component) throws IOException {
//Rendering happens on encodeEnd
}
@Override
public boolean getRendersChildren() {
return true;
}
}
| 45.939394 | 113 | 0.671669 |
3446b64ef07b74c34ba453eddcc9d15dca296c83 | 397 | package com.bonvio.staff.dao;
import com.bonvio.staff.models.Ticket;
import java.util.List;
/**
* Created by mil on 04.06.15.
*/
public interface TicketDAO {
public List<Ticket> getAllTickets();
public Ticket getTicketById(Integer id);
public Integer insertTicket(Ticket ticket);
public Integer deleteTicketById(Integer id);
public Integer updateTicket(Ticket ticket);
}
| 22.055556 | 48 | 0.738035 |
dff6488df860825359a1b42026718362366b068f | 91 | package pr04.interfaces;
public interface Callable {
void calling(String address);
}
| 13 | 33 | 0.747253 |
79a27f49179c8bf4b9f017d6b7c6bd45ede95bfb | 2,917 | package com.swagger.yaml;
import com.swagger.yaml.utils.RefUtil;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Created by dpujari on 11/11/16.
*/
public class MergeYaml {
Path sourceFilePath;
Path destFilePath;
public MergeYaml() {
}
public MergeYaml(final Path sourceFile, Path destinationFile) {
this.sourceFilePath = sourceFile;
this.destFilePath = destinationFile;
}
/**
* Merge the yaml files starting with sourceFilePath
*
* @return
*/
public void merge() throws IOException {
//check if dest file exists
Path destParentDir = destFilePath.getParent();
//create missing directories
Files.createDirectories(destParentDir);
Files.deleteIfExists(destFilePath);
Files.createFile(destFilePath);
Path parentDir = sourceFilePath.getParent();
FileWriter fw = new FileWriter(destFilePath.toFile());
resolve(parentDir, sourceFilePath, fw, "");
fw.close();
}
/**
* start reading the source file line by line
* if line starts with $ref.
* get the parentDir and file name
* call resolve()
* else
* write to dest file.
*
* @param parentDir
* @param sourceFilePath
*/
private void resolve(Path parentDir, Path sourceFilePath, final FileWriter fw, String indentation) throws IOException {
Files.lines(sourceFilePath).forEach(line -> {
//String indent="";
if (RefUtil.isStartWithRef(line) && RefUtil.isRemoteFilepath(line)) {
String indent = indentation + RefUtil.getIndentation(line);
//get the abs file path
String remoteRefValue = RefUtil.getRemoteRelativeFilePath(line);
Path remoteFilePath = getAbsolutePath(parentDir, remoteRefValue);
//get the new parent Directory
Path newParentDir = remoteFilePath.getParent();
try {
resolve(newParentDir, remoteFilePath, fw, indent);
} catch (IOException e) {
e.printStackTrace();
}
}
else {
try {
//fw.write(line, 0, line.length());
fw.write(String.format("%s%s%n", indentation, line));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
/**
* this method returns the absolute path for the remote value.
* @param parentDir
* @param remoteRefValue
* @return
*/
private Path getAbsolutePath(Path parentDir, String remoteRefValue ) {
String absFileStr = parentDir.toString() + remoteRefValue;
return Paths.get(absFileStr);
}
}
| 28.048077 | 123 | 0.58999 |
4c3c0d0ae1e5947dee900eba9a7e6b86d211d795 | 6,641 | // Copyright 2011, 2014 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.jpa;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import java.net.URL;
import java.util.Map;
/**
* Tapestry's mutable extension of {@link PersistenceUnitInfo} interface used for XML-less configuration
* of persistence units.
*
* @since 5.3
*/
public interface TapestryPersistenceUnitInfo extends PersistenceUnitInfo
{
/**
* Set the the fully qualified name of the persistence provider implementation class.
* Corresponds to the <code>provider</code> element in the <code>persistence.xml</code> file.
*
* @param persistenceProviderClassName
* persistence provider's class name
*/
TapestryPersistenceUnitInfo persistenceProviderClassName(String persistenceProviderClassName);
/**
* Set the transaction type of the entity managers. Corresponds to
* the <code>transaction-type</code> attribute in the <code>persistence.xml</code> file.
*
* @param transactionType
* transition type to set
*/
TapestryPersistenceUnitInfo transactionType(PersistenceUnitTransactionType transactionType);
/**
* Set the non-JTA-enabled data source to be used by the persistence provider for accessing data outside a JTA
* transaction. Corresponds to the named <code>non-jta-data-source</code> element in the
* <code>persistence.xml</code> file.
*
* @param nonJtaDataSource
* data source to set
*/
TapestryPersistenceUnitInfo nonJtaDataSource(String nonJtaDataSource);
/**
* Set the JTA-enabled data source to be used by the persistence provider for accessing data outside a JTA
* transaction. Corresponds to the named <code>jta-data-source</code> element in the
* <code>persistence.xml</code> file.
*
* @param jtaDataSource
* data source to set
*/
TapestryPersistenceUnitInfo jtaDataSource(String jtaDataSource);
/**
* Add a managed class name to be used by persistence provider.
* Corresponds to a named <code>class</code> element in the <code>persistence.xml</code> file.
*
* @param className
* class name to add
* @see #addManagedClass(Class)
*/
TapestryPersistenceUnitInfo addManagedClassName(String className);
/**
* Add a managed class to be used by persistence provider.
* Corresponds to a named <code>class</code> element in the <code>persistence.xml</code> file.
*
* @param clazz
* class to add
* @see #addManagedClassName(String)
*/
TapestryPersistenceUnitInfo addManagedClass(Class<?> clazz);
/**
* Defines how the persistence provider must use a second-level cache for the persistence unit.
* Corresponds to the <code>shared-cache-mode</code> element in the <code>persistence.xml</code> file.
*
* @param cacheMode
* cache mode to set
*/
TapestryPersistenceUnitInfo sharedCacheMode(SharedCacheMode cacheMode);
/**
* Set the validation mode to be used by the persistence provider for the persistence unit.
* Corresponds to the <code>validation-mode</code> element in the <code>persistence.xml</code> file.
*
* @param validationMode
* validation mode to set
*/
TapestryPersistenceUnitInfo validationMode(ValidationMode validationMode);
/**
* Add a mapping file to be loaded by the persistence provider to determine the mappings for
* the entity classes. Corresponds to a <code>mapping-file</code> element in the <code>persistence.xml</code> file.
*
* @param fileName
* mapping file name to add
*/
TapestryPersistenceUnitInfo addMappingFileName(String fileName);
/**
* Add a URLs for the jar file or exploded jar file directory that the persistence provider must examine
* for managed classes of the persistence unit. Corresponds to a <code>jar-file</code> element in the
* <code>persistence.xml</code> file.
*
* @param url
* url to add
*/
TapestryPersistenceUnitInfo addJarFileUrl(URL url);
/**
* Add a URLs for the jar file or exploded jar file directory that the persistence provider must examine
* for managed classes of the persistence unit. Corresponds to a <code>jar-file</code> element in the
* <code>persistence.xml</code> file.
*
* @param url
* url to add
*/
TapestryPersistenceUnitInfo addJarFileUrl(String url);
/**
* Add a property. Corresponds to a <code>property</code> element in the <code>persistence.xml</code> file.
*
* @param name
* property's name
* @param value
* property's value
*/
TapestryPersistenceUnitInfo addProperty(String name, String value);
/**
* Defines whether classes in the root of the persistence unit that have not been explicitly listed
* are to be included in the set of managed classes. Corresponds to the <code>exclude-unlisted-classes</code>
* element in the <code>persistence.xml</code> file.
*
* @param exclude
* defines whether to exclude or not
*/
TapestryPersistenceUnitInfo excludeUnlistedClasses(boolean exclude);
/**
* {@link javax.persistence.spi.PersistenceProvider} allows creating an {@link javax.persistence.EntityManagerFactory}
* with a default EntityManager properties map. This operation allows contributing default properties for
* EntityManager.
*
* @param properties
* properties to initialize EntityManagerFactory with
* @since 5.4
*/
TapestryPersistenceUnitInfo setEntityManagerProperties(Map properties);
/**
* @return Returns the supplied EntityManagerFactory properties. Returns null if not set.
* @since 5.4
*/
Map getEntityManagerProperties();
}
| 38.166667 | 122 | 0.692667 |
30bd075ca65fb2f338e4d121d3a41e7845d4b8d4 | 4,833 | package com.teamb6.shop.controller.front;
import com.teamb6.shop.domain.*;
import com.teamb6.shop.service.GoodsService;
import com.teamb6.shop.service.ShopCartService;
import com.teamb6.shop.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
public class ShopCartController {
@Autowired
private ShopCartService shopCartService;
@Autowired
private GoodsService goodsService;
@RequestMapping("/showcart")
public String showCart(HttpSession session) {
User user = (User) session.getAttribute("user");
// User user = new User();
// user.setUserid(1);
if(user == null) {
return "redirect:/users/login";
}
return "cart";
}
@RequestMapping("/cartjson")
@ResponseBody
public Msg getCart(HttpSession session) {
User user = (User) session.getAttribute("user");
List<Goods> goods = new ArrayList<>();
int goodsSum = 0;
// User user = new User();
// user.setUserid(1);
if(user == null) {
return Msg.fail("请先登录");
}
//获取当前用户的购物车信息
ShopCartExample shopCartExample = new ShopCartExample();
shopCartExample.or().andUseridEqualTo(user.getUserid());
List<ShopCart> shopCart = shopCartService.selectByExample(shopCartExample);
//获取购物车中的商品信息
List<Goods> goodsAndImage = new ArrayList<>();
for (ShopCart cart:shopCart) {
Goods good = goodsService.selectById(cart.getGoodsid());
List<ImagePath> imagePathList = goodsService.findImagePath(good.getGoodsid());
good.setImagePaths(imagePathList);
good.setNum(cart.getGoodsnum());
goodsAndImage.add(good);
goodsSum++;
}
session.setAttribute("goodsSum",goodsSum);
return Msg.success("查询成功").add("shopcart",goodsAndImage);
}
@RequestMapping(value = "/deleteCart/{goodsid}", method = RequestMethod.DELETE)
@ResponseBody
public Msg deleteCart(@PathVariable("goodsid")Integer goodsid, HttpSession session) {
User user = (User) session.getAttribute("user");
int goodsSum = (int)session.getAttribute("goodsSum");
// User user = new User();
// user.setUserid(1);
if(user == null) {
return Msg.fail("请先登录");
}
goodsSum--;
session.setAttribute("goodsSum",goodsSum);
ShopCart shopCart = shopCartService.selectCartByKey(new ShopCartKey(user.getUserid(),goodsid));
Goods goods = goodsService.selectById(goodsid);
shopCartService.deleteByKey(new ShopCartKey(user.getUserid(), goodsid));
return Msg.success("查询成功").add("good_price",shopCart.getGoodsnum()*goods.getPrice());
}
@RequestMapping("/cart/update")
@ResponseBody
public Msg updateCart(Integer goodsid,Integer num,HttpSession session) {
User user = (User) session.getAttribute("user");
// User user = new User();
// user.setUserid(1);
if(user == null) {
return Msg.fail("请先登录");
}
ShopCart shopCart = new ShopCart();
shopCart.setUserid(user.getUserid());
shopCart.setGoodsid(goodsid);
shopCart.setGoodsnum(num);
shopCartService.updateCartByKey(shopCart);
return Msg.success("更新购物车成功");
}
@RequestMapping("/addCart")
@ResponseBody
public Msg addCart(Integer goodsId, HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
// User user = new User();
// user.setUserid(7);
if(user == null) {
return Msg.fail("请先登录");
}
//判断是否已经加入购物车
ShopCart shopCart = shopCartService.selectCartByKey(new ShopCartKey(user.getUserid(), goodsId));
if (shopCart != null) {
shopCart.setGoodsnum(shopCart.getGoodsnum()+1);
shopCartService.updateCartByKey(shopCart);
}else{
shopCart = new ShopCart();
//用户
shopCart.setUserid(user.getUserid());
//加入时间
shopCart.setCatedate(new Date());
shopCart.setGoodsnum(1);
shopCart.setGoodsid(goodsId);
shopCartService.addShopCart(shopCart);
}
return Msg.success("加入购物车成功");
}
}
| 34.035211 | 104 | 0.643493 |
de44e0179305db914e3a279844ce5230f44a8bdb | 752 | package com.zsw.orm.utils;
import lombok.*;
/**
* @author ZhangShaowei on 2019/7/15 16:56
**/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TestDto {
private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String g;
private String h;
private String i;
private String j;
private String k;
private String l;
private String m;
private String n;
private String o;
private String p;
private String q;
private String r;
private String s;
private String t;
private String u;
private String v;
private String w;
private String x;
private String y;
private String z;
}
| 17.904762 | 42 | 0.655585 |
1d06ad208e4c695293193c71853b52984bcb6a7f | 1,561 | // Developer:
// ======================================================
//
// Date Created: December 28,2013
//
// Program Description:
// This program implements the doubly iterator object.
// It iterates over a doubly linkedlist.
//
// ======================================================
package datastructures;
public class DIterator<DataType>{
private DNode<DataType> m_starting_node;
private DNode<DataType> m_iterator;
// ==================================================
// Constructor
public DIterator(DNode<DataType> p_start_node){
m_starting_node = m_iterator = p_start_node;
}
public DIterator(DIterator<DataType> p_iterator){
m_starting_node = p_iterator.GetStartNode();
m_iterator = p_iterator.GetNode();
}
// ==================================================
// Doubly Iterator Functions
public void Start(){
m_iterator = m_starting_node;
}
public void Reset(DNode<DataType> p_start_node){
m_starting_node = p_start_node;
}
public void Forth(){
m_iterator = m_iterator.GetNextNode();
}
public void Back(){
m_iterator = m_iterator.GetPrevNode();
}
public DNode<DataType> GetStartNode(){
return m_starting_node;
}
public DataType GetItem(){
return m_iterator.GetData();
}
public DNode<DataType> GetNode(){
return m_iterator;
}
public boolean Valid(){
return (m_iterator != null);
}
}
| 24.015385 | 59 | 0.532992 |
c7cdfd5e1ac4362104724e33ff7512a3e50be7a1 | 1,581 | package eu.nullstack.kidlike.kyu6;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class VasyaClerkTest {
@Test
public void test1() {
assertEquals("YES", VasyaClerk.Tickets(new int[]{25, 25, 50}));
}
@Test
public void test2() {
assertEquals("NO", VasyaClerk.Tickets(new int[]{25, 100}));
}
@Test
public void test3() {
assertEquals("YES", VasyaClerk.Tickets(new int[]{25, 25, 25, 25, 25, 25, 25, 25, 25, 25}));
}
@Test
public void test4() {
assertEquals("NO", VasyaClerk.Tickets(new int[]{50, 50, 50, 50, 50, 50, 50, 50, 50, 50}));
}
@Test
public void test5() {
assertEquals("NO", VasyaClerk.Tickets(new int[]{100, 100, 100, 100, 100, 100, 100, 100, 100, 100}));
}
@Test
public void test6() {
assertEquals("YES", VasyaClerk.Tickets(new int[]{25, 25, 25, 25, 50, 100, 50}));
}
@Test
public void test7() {
assertEquals("NO", VasyaClerk.Tickets(new int[]{50, 100, 100}));
}
@Test
public void test8() {
assertEquals("NO", VasyaClerk.Tickets(new int[]{25, 25, 100}));
}
@Test
public void test9() {
assertEquals("NO", VasyaClerk.Tickets(new int[]{25, 25, 25, 25, 25, 25, 25, 50, 50, 50, 100, 100, 100, 100}));
}
@Test
public void test10() {
assertEquals("NO", VasyaClerk.Tickets(new int[]{25, 25, 50, 50, 100}));
}
@Test
public void test11() {
assertEquals("NO", VasyaClerk.Tickets(new int[]{25, 25, 25, 25, 25, 100, 100}));
}
} | 25.5 | 118 | 0.569892 |
f07a1cc6cffbb9c2d709870a5fba382e0039589d | 3,826 | /**
* Copyright 2009-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.metaeffekt.dcc.commons.mapping;
import java.io.File;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import org.metaeffekt.dcc.commons.domain.Id;
public class ConfigurationMappingCasesTest {
private static final File ORIGIN = new File("ConfigurationMappingCasesTest.class");
private static final String DESCRIPTION = "description";
@Test
public void testMulitpleRequiredCapabilitiesOfSameDefinition() throws Exception {
CapabilityDefinition def = new CapabilityDefinition("a").
add(new AttributeKey("key01", ORIGIN, DESCRIPTION, false)).
add(new AttributeKey("key02", ORIGIN, DESCRIPTION, false));
ConfigurationUnit unit = new ConfigurationUnit("test-unit");
RequiredCapability capabilityR1 = new RequiredCapability(Id.createCapabilityId("a1"), def, unit);
RequiredCapability capabilityR2 = new RequiredCapability(Id.createCapabilityId("a2"), def, unit);
RequiredCapability capabilityP = new RequiredCapability(Id.createCapabilityId("ap"), def, unit);
unit.getRequiredCapabilities().add(capabilityR1);
unit.getRequiredCapabilities().add(capabilityR2);
unit.getProvidedCapabilities().add(capabilityP);
Mapping mapping = new Mapping(capabilityP.getId());
mapping.add(new ExpressionAttributeMapper("key01", "${a1[key01]}"));
mapping.add(new ExpressionAttributeMapper("key02", "${a2[key02]}"));
unit.add(mapping);
unit.afterPropertiesSet();
ConfigurationUnit sourceUnit1 = new ConfigurationUnit("source-unit-01");
sourceUnit1.add(new Attribute("key01", "value_01-01", ORIGIN));
sourceUnit1.add(new Attribute("key02", "value_01-02", ORIGIN));
Capability capabilitySource1 = new Capability(Id.createCapabilityId("a"), def, sourceUnit1);
sourceUnit1.getProvidedCapabilities().add(capabilitySource1);
sourceUnit1.afterPropertiesSet();
ConfigurationUnit sourceUnit2 = new ConfigurationUnit("source-unit-02");
sourceUnit2.add(new Attribute("key01", "value_02-01", ORIGIN));
sourceUnit2.add(new Attribute("key02", "value_02-02", ORIGIN));
Capability capabilitySource2 = new Capability(Id.createCapabilityId("a"), def, sourceUnit2);
sourceUnit2.getProvidedCapabilities().add(capabilitySource2);
sourceUnit2.afterPropertiesSet();
Profile p = new Profile();
p.add(unit);
p.add(sourceUnit1);
p.add(sourceUnit2);
p.add(new Binding(capabilitySource1, capabilityR1));
p.add(new Binding(capabilitySource2, capabilityR2));
p.setDeploymentProperties(new Properties(), null);
p.setSolutionProperties(new Properties(), null);
PropertiesHolder propertiesHolder = p.createPropertiesHolder(false);
p.evaluate(propertiesHolder);
Properties properties = propertiesHolder.getProperties(capabilityP);
// check cross-mapping key01 for source 01 and key2 from source 02
Assert.assertEquals("value_01-01", properties.getProperty("key01"));
Assert.assertEquals("value_02-02", properties.getProperty("key02"));
}
}
| 42.511111 | 105 | 0.710925 |
34179d36c44acc352c88c02ac4983fe69191be17 | 1,838 | package com.github.florent37.myyoutube.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by florentchampigny on 17/06/15.
*/
public class Snippet implements Parcelable{
String title;
String description;
Thumbnails thumbnails;
String channelTitle;
public Snippet(){}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Thumbnails getThumbnails() {
return thumbnails;
}
public void setThumbnails(Thumbnails thumbnails) {
this.thumbnails = thumbnails;
}
public String getChannelTitle() {
return channelTitle;
}
public void setChannelTitle(String channelTitle) {
this.channelTitle = channelTitle;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(description);
dest.writeParcelable(thumbnails, flags);
dest.writeString(channelTitle);
}
protected Snippet(Parcel in) {
title = in.readString();
description = in.readString();
thumbnails = in.readParcelable(Thumbnails.class.getClassLoader());
channelTitle = in.readString();
}
public static final Creator<Snippet> CREATOR = new Creator<Snippet>() {
@Override
public Snippet createFromParcel(Parcel in) {
return new Snippet(in);
}
@Override
public Snippet[] newArray(int size) {
return new Snippet[size];
}
};
}
| 22.414634 | 75 | 0.631121 |
525aa2ff1bfb6dfbf989317296d87f3ed8a9dc63 | 63,645 | /*
* 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.geode.cache.query.dunit;
import static org.apache.geode.test.dunit.Assert.*;
import static org.apache.geode.test.dunit.Invoke.*;
import static org.apache.geode.test.dunit.LogWriterUtils.*;
import static org.apache.geode.test.dunit.NetworkUtils.*;
import java.io.Serializable;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.query.CacheUtils;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.SelectResults;
import org.apache.geode.cache.query.data.PortfolioPdx;
import org.apache.geode.cache.query.data.PositionPdx;
import org.apache.geode.cache.query.internal.CompiledValue;
import org.apache.geode.cache.query.internal.QueryObserver;
import org.apache.geode.cache.query.internal.QueryObserverAdapter;
import org.apache.geode.cache.query.internal.QueryObserverHolder;
import org.apache.geode.cache.query.internal.StructImpl;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.VMCachedDeserializable;
import org.apache.geode.pdx.PdxInstance;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.SerializableCallable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
import org.apache.geode.test.junit.categories.DistributedTest;
/**
* Test for #44807 to eliminate unnecessary serialization/deserialization in select * queries
*/
@Category(DistributedTest.class)
public class SelectStarQueryDUnitTest extends JUnit4CacheTestCase {
/** Used for saving & restoring oldObserver without serialization */
private static volatile QueryObserver oldObserver;
private final String regName = "exampleRegion";
private final String regName2 = "exampleRegion2";
private final String[] queries = {"SELECT * FROM /" + regName, // 0
"SELECT * FROM /" + regName + " limit 5", // 1
"SELECT p from /" + regName + " p", // 2
"SELECT count(*) FROM /" + regName, // 3
"SELECT ALL * from /" + regName, // 4
"SELECT * from /" + regName + ".values", // 5
"SELECT distinct * FROM /" + regName, // 6
"SELECT distinct * FROM /" + regName + " p order by p.ID", // 7
"SELECT * from /" + regName + " r, positions.values pos"// 8
};
private final int[] resultSize = {20, 5, 20, 1, 20, 20, 20, 20, 40};
private final String[] multipleRegionQueries = {" SELECT * FROM /" + regName + ", /" + regName2,
"SELECT * FROM /" + regName + ", /" + regName2 + " limit 5",
"SELECT distinct * FROM /" + regName + ", /" + regName2,
"SELECT distinct * FROM /" + regName + " p1, /" + regName2 + " p2 order by p1.ID",
"SELECT count(*) FROM /" + regName + ", /" + regName2,
"SELECT p, q from /" + regName + " p, /" + regName2 + " q",
"SELECT ALL * from /" + regName + " p, /" + regName2 + " q",
"SELECT * from /" + regName + ".values" + ", /" + regName2 + ".values",
"SELECT * from /" + regName + " p, p.positions.values pos" + ", /" + regName2
+ " q, q.positions.values pos",};
private final int[] resultSize2 = {400, 5, 400, 400, 1, 400, 400, 400, 1600};
@Override
public final void preTearDownCacheTestCase() throws Exception {
invokeInEveryVM(() -> oldObserver = null);
}
@Test
public void functionWithStructTypeInInnerQueryShouldNotThrowException() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM client = host.getVM(3);
PortfolioPdx[] portfolios = new PortfolioPdx[10];
for (int i = 0; i < portfolios.length; i++) {
portfolios[i] = new PortfolioPdx(i);
}
// create servers and regions
final int port1 = startPartitionedCacheServer(server1, portfolios);
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(regName);
return null;
}
});
// put serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
for (int i = 10; i < 100; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService remoteQS = null;
try {
remoteQS = ((ClientCache) getCache()).getQueryService();
SelectResults sr = (SelectResults) remoteQS
.newQuery("select distinct oP.ID, oP.status, oP.getType from /" + regName
+ " oP where element(select distinct p.ID, p.status, p.getType from /" + regName
+ " p where p.ID = oP.ID).status = 'inactive'")
.execute();
assertEquals(50, sr.size());
} catch (Exception e) {
fail("Exception getting query service ", e);
}
return null;
}
});
closeCache(client);
closeCache(server1);
}
@Test
public void functionWithStructTypeInInnerQueryShouldNotThrowExceptionWhenRunOnMultipleNodes()
throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM server2 = host.getVM(1);
final VM server3 = host.getVM(2);
final VM client = host.getVM(3);
PortfolioPdx[] portfolios = new PortfolioPdx[10];
for (int i = 0; i < portfolios.length; i++) {
portfolios[i] = new PortfolioPdx(i);
}
// create servers and regions
final int port1 = startPartitionedCacheServer(server1, portfolios);
final int port2 = startPartitionedCacheServer(server2, portfolios);
final int port3 = startPartitionedCacheServer(server3, portfolios);
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
cf.addPoolServer(getServerHostName(server2.getHost()), port2);
cf.addPoolServer(getServerHostName(server3.getHost()), port3);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(regName);
return null;
}
});
// put serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
for (int i = 10; i < 100; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService remoteQS = null;
try {
remoteQS = ((ClientCache) getCache()).getQueryService();
SelectResults sr = (SelectResults) remoteQS
.newQuery("select distinct oP.ID, oP.status, oP.getType from /" + regName
+ " oP where element(select distinct p.ID, p.status, p.getType from /" + regName
+ " p where p.ID = oP.ID).status = 'inactive'")
.execute();
assertEquals(50, sr.size());
} catch (Exception e) {
fail("Exception getting query service ", e);
}
return null;
}
});
closeCache(client);
closeCache(server1);
closeCache(server2);
closeCache(server3);
}
@Test
public void testSelectStarQueryForPartitionedRegion() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM server2 = host.getVM(1);
final VM server3 = host.getVM(2);
final VM client = host.getVM(3);
PortfolioPdx[] portfolios = new PortfolioPdx[10];
for (int i = 0; i < portfolios.length; i++) {
portfolios[i] = new PortfolioPdx(i);
}
// create servers and regions
final int port1 = startPartitionedCacheServer(server1, portfolios);
final int port2 = startPartitionedCacheServer(server2, portfolios);
final int port3 = startPartitionedCacheServer(server3, portfolios);
server1.invoke(new SerializableCallable("Set observer") {
@Override
public Object call() throws Exception {
oldObserver = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
return null;
}
});
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
cf.addPoolServer(getServerHostName(server2.getHost()), port2);
cf.addPoolServer(getServerHostName(server3.getHost()), port3);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
return null;
}
});
// put serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
for (int i = 10; i < 20; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults[][] sr = new SelectResults[1][2];
SelectResults res = null;
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) localQS.newQuery(queries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(queries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
return null;
}
});
// verify if objects iterated by query are serialized
server1.invoke(new SerializableCallable("Get observer") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertTrue(resultObserver.isObjectSerialized());
return null;
}
});
// verify if objects returned by local server query are not serialized
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
// reset observer
QueryObserverHolder.setInstance(oldObserver);
return null;
}
});
closeCache(client);
closeCache(server1);
closeCache(server2);
closeCache(server3);
}
@Test
public void testSelectStarQueryForReplicatedRegion() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(1);
final VM client = host.getVM(3);
// create servers and regions
final int port1 = startReplicatedCacheServer(server1);
server1.invoke(new SerializableCallable("Set observer") {
@Override
public Object call() throws Exception {
oldObserver = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
return null;
}
});
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName2);
return null;
}
});
// put serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
Region r2 = getRootRegion(regName2);
for (int i = 10; i < 20; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
r2.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < multipleRegionQueries.length; i++) {
try {
res = (SelectResults) localQS.newQuery(multipleRegionQueries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(multipleRegionQueries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + multipleRegionQueries[i], e);
}
assertEquals(resultSize2[i], res.size());
if (i == 4) {
int cnt = ((Integer) res.iterator().next());
assertEquals(400, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + multipleRegionQueries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + multipleRegionQueries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
return null;
}
});
// verify if objects iterated by query are serialized
server1.invoke(new SerializableCallable("Get observer") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertTrue(resultObserver.isObjectSerialized());
return null;
}
});
// verify if objects returned by local server query are not serialized
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < multipleRegionQueries.length; i++) {
try {
res = (SelectResults) qs.newQuery(multipleRegionQueries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + multipleRegionQueries[i], e);
}
assertEquals(resultSize2[i], res.size());
if (i == 4) {
int cnt = ((Integer) res.iterator().next());
assertEquals(400, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + multipleRegionQueries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + multipleRegionQueries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
// reset observer
QueryObserverHolder.setInstance(oldObserver);
return null;
}
});
closeCache(client);
closeCache(server1);
}
@Test
public void testByteArrayReplicatedRegion() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM client = host.getVM(3);
final byte[] ba = new byte[] {1, 2, 3, 4, 5};
// create servers and regions
final int port = (Integer) server1.invoke(new SerializableCallable("Create Server1") {
@Override
public Object call() throws Exception {
Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regName);
// put domain objects
for (int i = 0; i < 10; i++) {
r1.put("key-" + i, ba);
}
CacheServer server = getCache().addCacheServer();
int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
server.setPort(port);
server.start();
return port;
}
});
server1.invoke(new SerializableCallable("Set observer") {
@Override
public Object call() throws Exception {
oldObserver = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
return null;
}
});
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
return null;
}
});
// put serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
for (int i = 10; i < 20; i++) {
r1.put("key-" + i, ba);
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < 6; i++) {
try {
res = (SelectResults) localQS.newQuery(queries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(queries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object o : res) {
if (o instanceof byte[]) {
int j = 0;
for (byte b : ((byte[]) o)) {
if (b != ba[j++]) {
fail("Bytes in byte array are different when queried from client");
}
}
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + o.getClass());
}
}
}
}
return null;
}
});
// verify if objects iterated by query are serialized
server1.invoke(new SerializableCallable("Get observer") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
return null;
}
});
// verify if objects returned by local server query are not serialized
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < 6; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object o : res) {
if (o instanceof byte[]) {
int j = 0;
for (byte b : ((byte[]) o)) {
if (b != ba[j++]) {
fail("Bytes in byte array are different when queried locally on server");
}
}
} else {
fail("Result objects for server local query: " + queries[i]
+ " should be instance of byte array and not " + o.getClass());
}
}
}
}
observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
// reset observer
QueryObserverHolder.setInstance(oldObserver);
return null;
}
});
closeCache(client);
closeCache(server1);
}
@Test
public void testByteArrayPartitionedRegion() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM client = host.getVM(3);
final VM server2 = host.getVM(1);
final VM server3 = host.getVM(2);
final byte[][] objs = new byte[10][5];
for (int i = 0; i < objs.length; i++) {
objs[i] = new byte[] {1, 2, 3, 4, 5};
}
// create servers and regions
final int port1 = startPartitionedCacheServer(server1, objs);
final int port2 = startPartitionedCacheServer(server2, objs);
final int port3 = startPartitionedCacheServer(server3, objs);
server1.invoke(new SerializableCallable("Set observer") {
@Override
public Object call() throws Exception {
oldObserver = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
return null;
}
});
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
cf.addPoolServer(getServerHostName(server2.getHost()), port2);
cf.addPoolServer(getServerHostName(server3.getHost()), port3);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
return null;
}
});
// put serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
for (int i = 10; i < 20; i++) {
r1.put("key-" + i, new byte[] {1, 2, 3, 4, 5});
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < 6; i++) {
try {
res = (SelectResults) localQS.newQuery(queries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(queries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object o : res) {
if (o instanceof byte[]) {
int j = 0;
for (byte b : ((byte[]) o)) {
if (b != objs[0][j++]) {
fail("Bytes in byte array are different when queried from client");
}
}
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + o.getClass());
}
}
}
}
return null;
}
});
// verify if objects iterated by query are serialized
server1.invoke(new SerializableCallable("Get observer") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
return null;
}
});
// verify if objects returned by local server query are not serialized
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < 6; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object o : res) {
if (o instanceof byte[]) {
int j = 0;
for (byte b : ((byte[]) o)) {
if (b != objs[0][j++]) {
fail("Bytes in byte array are different when queried locally on server");
}
}
} else {
fail("Result objects for server local query: " + queries[i]
+ " should be instance of byte array and not " + o.getClass());
}
}
}
}
observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
// reset observer
QueryObserverHolder.setInstance(oldObserver);
return null;
}
});
closeCache(client);
closeCache(server1);
}
@Test
public void testSelectStarQueryForIndexes() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM client = host.getVM(3);
// create servers and regions
final int port1 = startReplicatedCacheServer(server1);
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName2);
return null;
}
});
// put serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
Region r2 = getRootRegion(regName2);
for (int i = 10; i < 20; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
r2.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// create index on exampleRegion1
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryService qs = null;
try {
qs = getCache().getQueryService();
qs.createIndex("status", "status", "/" + regName);
} catch (Exception e) {
fail("Exception getting query service ", e);
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < multipleRegionQueries.length; i++) {
try {
res = (SelectResults) localQS.newQuery(multipleRegionQueries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(multipleRegionQueries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + multipleRegionQueries[i], e);
}
assertEquals(resultSize2[i], res.size());
if (i == 4) {
int cnt = ((Integer) res.iterator().next());
assertEquals(400, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + multipleRegionQueries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + multipleRegionQueries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
return null;
}
});
// create index on exampleRegion2
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryService qs = null;
try {
qs = getCache().getQueryService();
qs.createIndex("status", "status", "/" + regName2);
} catch (Exception e) {
fail("Exception getting query service ", e);
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < multipleRegionQueries.length; i++) {
try {
res = (SelectResults) localQS.newQuery(multipleRegionQueries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(multipleRegionQueries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + multipleRegionQueries[i], e);
}
assertEquals(resultSize2[i], res.size());
if (i == 4) {
int cnt = ((Integer) res.iterator().next());
assertEquals(400, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + multipleRegionQueries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + multipleRegionQueries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
return null;
}
});
closeCache(client);
closeCache(server1);
}
@Test
public void testSelectStarQueryForPdxObjects() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM client = host.getVM(3);
// create servers and regions
final int port1 = startReplicatedCacheServer(server1);
server1.invoke(new SerializableCallable("Set observer") {
@Override
public Object call() throws Exception {
oldObserver = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
return null;
}
});
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
return null;
}
});
// Update with serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
for (int i = 0; i < 20; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) localQS.newQuery(queries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(queries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
return null;
}
});
// verify if objects iterated by query are serialized
server1.invoke(new SerializableCallable("Get observer") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertTrue(resultObserver.isObjectSerialized());
return null;
}
});
// verify if objects returned by local server query are not serialized
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
QueryObserverHolder.setInstance(oldObserver);
return null;
}
});
// verify if Pdx instances are returned by local server query
// if read-serialized is set true
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
cache.setReadSerialized(true);
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PdxInstance) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PdxInstance and not " + obj.getClass());
}
}
} else if (rs instanceof PdxInstance) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PdxInstance and not " + rs.getClass());
}
}
}
}
return null;
}
});
closeCache(client);
closeCache(server1);
}
@Test
public void testSelectStarQueryForPdxAndNonPdxObjects() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM client = host.getVM(3);
// create servers and regions
// put domain objects
final int port1 = startReplicatedCacheServer(server1);
server1.invoke(new SerializableCallable("Set observer") {
@Override
public Object call() throws Exception {
oldObserver = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
return null;
}
});
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port1);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
return null;
}
});
// Add some serialized PortfolioPdx objects
client.invoke(new SerializableCallable("Put objects") {
@Override
public Object call() throws Exception {
Region r1 = getRootRegion(regName);
for (int i = 10; i < 20; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) localQS.newQuery(queries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(queries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx or PortfolioPdx and not "
+ obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx || rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
return null;
}
});
// verify if objects iterated by query are serialized
server1.invoke(new SerializableCallable("Get observer") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertTrue(resultObserver.isObjectSerialized());
return null;
}
});
// verify if objects returned by local server query are not serialized
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
QueryObserver observer = QueryObserverHolder.setInstance(new QueryResultTrackingObserver());
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx or PortfolioPdx and not "
+ obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx || rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
observer = QueryObserverHolder.getInstance();
assertTrue(QueryObserverHolder.hasObserver());
assertTrue(observer instanceof QueryResultTrackingObserver);
QueryResultTrackingObserver resultObserver = (QueryResultTrackingObserver) observer;
assertFalse(resultObserver.isObjectSerialized());
QueryObserverHolder.setInstance(oldObserver);
return null;
}
});
server1.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
GemFireCacheImpl cache = (GemFireCacheImpl) getCache();
cache.setReadSerialized(true);
QueryService qs = null;
try {
qs = getCache().getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) qs.newQuery(queries[i]).execute();
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else if (obj instanceof PdxInstance) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PdxInstance and not " + obj.getClass());
}
}
} else if (rs instanceof PdxInstance || rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PdxInstance and not " + rs.getClass());
}
}
}
}
return null;
}
});
closeCache(client);
closeCache(server1);
}
@Test
public void testSelectStarQueryForPdxObjectsReadSerializedTrue() throws Exception {
final Host host = Host.getHost(0);
final VM server1 = host.getVM(0);
final VM client = host.getVM(3);
// create servers and regions
final int port = (Integer) server1.invoke(new SerializableCallable("Create Server1") {
@Override
public Object call() throws Exception {
((GemFireCacheImpl) getCache()).setReadSerialized(true);
Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regName);
CacheServer server = getCache().addCacheServer();
int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
server.setPort(port);
server.start();
return port;
}
});
// create client
client.invoke(new SerializableCallable("Create client") {
@Override
public Object call() throws Exception {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(getServerHostName(server1.getHost()), port);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY).create(regName);
Region r1 = getRootRegion(regName);
for (int i = 0; i < 20; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
}
return null;
}
});
// query remotely from client
client.invoke(new SerializableCallable("Query") {
@Override
public Object call() throws Exception {
getLogWriter().info("Querying remotely from client");
QueryService localQS = null;
QueryService remoteQS = null;
try {
localQS = ((ClientCache) getCache()).getLocalQueryService();
remoteQS = ((ClientCache) getCache()).getQueryService();
} catch (Exception e) {
fail("Exception getting query service ", e);
}
SelectResults res = null;
SelectResults[][] sr = new SelectResults[1][2];
for (int i = 0; i < queries.length; i++) {
try {
res = (SelectResults) localQS.newQuery(queries[i]).execute();
sr[0][0] = res;
res = (SelectResults) remoteQS.newQuery(queries[i]).execute();
sr[0][1] = res;
CacheUtils.compareResultsOfWithAndWithoutIndex(sr);
} catch (Exception e) {
fail("Error executing query: " + queries[i], e);
}
assertEquals(resultSize[i], res.size());
if (i == 3) {
int cnt = ((Integer) res.iterator().next());
assertEquals(20, cnt);
} else {
for (Object rs : res) {
if (rs instanceof StructImpl) {
for (Object obj : ((StructImpl) rs).getFieldValues()) {
if (obj instanceof PortfolioPdx || obj instanceof PositionPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + obj.getClass());
}
}
} else if (rs instanceof PortfolioPdx) {
} else {
fail("Result objects for remote client query: " + queries[i]
+ " should be instance of PortfolioPdx and not " + rs.getClass());
}
}
}
}
return null;
}
});
closeCache(client);
closeCache(server1);
}
private int startPartitionedCacheServer(VM vm, final Object[] objs) {
final int port = (Integer) vm.invoke(new SerializableCallable("Create Server1") {
@Override
public Object call() throws Exception {
Region r1 = getCache().createRegionFactory(RegionShortcut.PARTITION).create(regName);
// put domain objects
for (int i = 0; i < objs.length; i++) {
r1.put("key-" + i, objs[i]);
}
CacheServer server = getCache().addCacheServer();
int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
server.setPort(port);
server.start();
return port;
}
});
return port;
}
private int startReplicatedCacheServer(VM vm) {
final int port = (Integer) vm.invoke(new SerializableCallable("Create Server1") {
@Override
public Object call() throws Exception {
Region r1 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regName);
Region r2 = getCache().createRegionFactory(RegionShortcut.REPLICATE).create(regName2);
// put domain objects
for (int i = 0; i < 10; i++) {
r1.put("key-" + i, new PortfolioPdx(i));
r2.put("key-" + i, new PortfolioPdx(i));
}
CacheServer server = getCache().addCacheServer();
int port = AvailablePortHelper.getRandomAvailablePortForDUnitSite();
server.setPort(port);
server.start();
return port;
}
});
return port;
}
private void closeCache(VM vm) {
vm.invoke(new SerializableCallable() {
public Object call() throws Exception {
closeCache();
return null;
}
});
}
public class QueryResultTrackingObserver extends QueryObserverAdapter implements Serializable {
private boolean isObjectSerialized = false;
@Override
public void beforeIterationEvaluation(CompiledValue executer, Object currentObject) {
if (currentObject instanceof VMCachedDeserializable) {
getLogWriter().fine("currentObject is serialized object");
isObjectSerialized = true;
} else {
getLogWriter().fine("currentObject is deserialized object");
}
}
public boolean isObjectSerialized() {
return isObjectSerialized;
}
public void setObjectSerialized(boolean isObjectSerialized) {
this.isObjectSerialized = isObjectSerialized;
}
}
}
| 37.883929 | 100 | 0.585859 |
4f3b3f24c5d438939412bbfd194bf7ee970fb1a7 | 574 | package com.sourcegraph.lsp.domain.params;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class CacheGetParams {
private String key;
public static CacheGetParams of(String key) {
CacheGetParams p = new CacheGetParams();
p.key = key;
return p;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
| 21.259259 | 61 | 0.691638 |
eec4b1a5db39d18db85122005b35f97e68ed4eee | 471 | package io.connectedhealth_idaas.eventbuilder.dataobjects.clinical.fhir.r4.common;
public class Entry {
public String fullUrl;
public Resource resource;
public String getFullUrl() {
return fullUrl;
}
public void setFullUrl(String fullUrl) {
this.fullUrl = fullUrl;
}
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
}
| 19.625 | 82 | 0.66242 |
feda3842d7b579f6327deabb14498d0faa4f6f2a | 487 | package com.kevinlorenzo.learning.junit.payments;
public class PaymentProcessor {
private PaymentGateway paymentGateway;
public PaymentProcessor(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
public boolean makePayment(double amount) {
PaymentResponse paymentResponse = paymentGateway.requestPayment(new PaymentRequest(amount));
return paymentResponse.getPaymentStatus() == PaymentResponse.PaymentStatus.OK;
}
} | 28.647059 | 100 | 0.761807 |
7d6dc2f78004f617ada7c933090a0e3687b49740 | 5,316 | package com.thanple.little.boy.websocket;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thanple.little.boy.web.entity.msg.RedisPubBean;
import com.thanple.little.boy.web.entity.msg.RedisPubMsg;
import com.thanple.little.boy.websocket.redis.JedisAccess;
import com.thanple.little.boy.websocket.redis.JedisAccessFactory;
import com.thanple.little.boy.websocket.redis.RedisSerializer;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
/**
* Created by Thanple on 2018/5/25.
* 这个测试和RedisAccessTest的区别是,当前JedisAccess没有Spring环境(spring-data-jedis),不过原理一致,都是用jackson2JsonRedisSerializer序列化
*/
public class JedisAccessTest {
private static Logger log = LoggerFactory.getLogger(JedisAccessTest.class);
private JedisAccess jedisAccess = JedisAccessFactory.getJedisAccess();
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class ObjectClass1{
private int id;
private String name;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class ObjectClass2{
private int id;
private String name;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class ObjectClass3{
private ObjectClass2 obj2;
private int range;
}
/**
* 将JSON字符串动态转换成一个对象
*/
@Test
public void testJaskson(){
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\":1,\"name\":\"Tom2\"}";
try {
ObjectClass1 obj1 = mapper.readValue(jsonString, ObjectClass1.class);
Assert.assertEquals(1,obj1.getId());
Assert.assertEquals("Tom2",obj1.getName());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ObjectClass2 obj2 = new RedisSerializer<ObjectClass2>(ObjectClass2.class).deserialize(jsonString.getBytes());
Assert.assertEquals(1,obj2.getId());
Assert.assertEquals("Tom2",obj2.getName());
}
@Test
public void testObject(){
//测试ObjectClass1对象
ObjectClass1 obj1 = new ObjectClass1(1,"ObjectTim");
jedisAccess.set("testObject",obj1);
obj1 = jedisAccess.get(ObjectClass1.class,"testObject");
Assert.assertEquals(1,obj1.getId());
Assert.assertEquals("ObjectTim", obj1.getName());
//测试对象成员
ObjectClass2 obj2 = new ObjectClass2(2,"Object2");
ObjectClass3 obj3 = new ObjectClass3(obj2,100);
jedisAccess.set("testObject",obj3);
obj3 = jedisAccess.get(ObjectClass3.class,"testObject");
Assert.assertEquals(obj2, obj3.getObj2());
Assert.assertEquals(100, obj3.getRange());
}
@Test
public void testString(){
jedisAccess.set("testString","tom2");
String name = jedisAccess.<String>get(String.class,"testString");
Assert.assertEquals(name,"tom2");
}
@Test
public void testList(){
jedisAccess.del("testList");
jedisAccess.rightPush("testList","Tim2");
jedisAccess.rightPush("testList","Cindy2");
jedisAccess.leftPush("testList","Tommy2");
List<String> result = jedisAccess.<String>range(String.class,"testList",0,-1);
Assert.assertEquals(result.get(0),"Tommy2");
Assert.assertEquals(result.get(1),"Tim2");
Assert.assertEquals(result.get(2),"Cindy2");
}
@Test
public void testHash(){
jedisAccess.del("testHash");
jedisAccess.hash("testHash","name","Tom2");
Assert.assertEquals(jedisAccess.hashGet(String.class,"testHash","name"),"Tom2");
}
@Test
public void testSet(){
jedisAccess.del("testSet");
jedisAccess.setAdd("testSet","Timmy");
Assert.assertEquals(jedisAccess.setContains("testSet","Timmy"),true);
}
@Test
public void testZSet(){
jedisAccess.del("testZSet");
//这里根据后面的权值排序,9.2 < 9.6 < 9.7
Map<Object,Double> paramsMap = new HashMap<Object,Double>();
paramsMap.put("zset-1",9.6);
paramsMap.put("zset-2",9.2);
paramsMap.put("zset-3",9.7);
jedisAccess.zset("testZSet",paramsMap);
//上面已经排好序,这里直接验证
Set<String> zsets = jedisAccess.<String>zsetRange(String.class,"testZSet",0, -1);
Iterator<String> zsetIterator = zsets.iterator();
Assert.assertEquals(zsetIterator.next(),"zset-2");
Assert.assertEquals(zsetIterator.next(),"zset-1");
Assert.assertEquals(zsetIterator.next(),"zset-3");
}
/**
* 测试发布一条消息
*/
@Test
public void testPublish(){
RedisPubMsg pubMsg = new RedisPubMsg();
pubMsg.setId(1L);
pubMsg.setPubBean( new RedisPubBean("Tom","Hello, SpringBoot redis message!!!!") );
long result = jedisAccess.publish("sprinboot-redis-messaage", pubMsg);
log.info("Publish message......,result={}",result);
}
}
| 31.832335 | 117 | 0.657449 |
d1a609c5f35bcb1fd276b7cdbdf3300444633ce0 | 178 | package com.droidsonroids.workcation.common.model;
import com.google.gson.annotations.SerializedName;
public class Step {
@SerializedName("polyline") Polyline polyline;
}
| 19.777778 | 50 | 0.792135 |
b9334f9a1ad92f38180b7be92c1171936a2d8aaa | 5,909 | package com.catzhang.linkedlist.singlelinkedlist;
import java.util.Stack;
/**
* @author: crazycatzhang
* @date: 2020/7/27 8:11 下午
* @description: Simple implementation of a single linked list
*/
public class SingleLinkedListDemo {
public static void main(String[] args) {
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.addNodeOrder(new HeroNode(1, "宋江", "及时雨"));
singleLinkedList.addNodeOrder(new HeroNode(4, "鲁智深", "花和尚"));
singleLinkedList.addNodeOrder(new HeroNode(2, "林冲", "豹子头"));
singleLinkedList.addNodeOrder(new HeroNode(3, "吴用", "智多星"));
singleLinkedList.show();
System.out.println();
// singleLinkedList.modifyNode(new HeroNode(1,"小江","及时雨啊哈"));
// singleLinkedList.show();
// System.out.println();
// singleLinkedList.deleteNode(2);
// singleLinkedList.show();
// reverseList(singleLinkedList.getHead());
// singleLinkedList.show();
// System.out.println(getLength(singleLinkedList.getHead()));
// System.out.println(findLastNode(singleLinkedList.getHead(),3));
reversePrint(singleLinkedList.getHead());
}
//Reverse print the LinkedList
public static void reversePrint(HeroNode head) {
Stack<HeroNode> heroNodeStack = new Stack<>();
HeroNode temp = head.next;
while (temp != null) {
heroNodeStack.add(temp);
temp = temp.next;
}
while (heroNodeStack.size() > 0) {
System.out.println(heroNodeStack.pop());
}
}
//Reverse the LinkedList
public static void reverseList(HeroNode head) {
if (head.next == null || head.next.next == null) {
return;
}
HeroNode reverseHead = new HeroNode(0, "", "");
HeroNode current = head.next;
HeroNode next = null;
while (current != null) {
next = current.next;
current.next = reverseHead.next;
reverseHead.next = current;
current = next;
}
head.next = reverseHead.next;
}
//Find the K of the last node
public static HeroNode findLastNode(HeroNode head, int index) {
if (head.next == null || index > getLength(head)) {
return null;
}
HeroNode temp = head.next;
for (int i = 0; i < getLength(head) - index; i++) {
temp = temp.next;
}
return temp;
}
//Get the number of the LinkedList data
public static int getLength(HeroNode head) {
if (head.next == null){
return 0;
}
HeroNode temp = head.next;
int count = 0;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
}
//Define SingleLinkedList
class SingleLinkedList {
//Define HeadNode
private HeroNode head = new HeroNode(0, "", "");
public HeroNode getHead() {
return head;
}
//Add Node
public void addNode(HeroNode node) {
HeroNode temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = node;
}
//Add Node with Order
public void addNodeOrder(HeroNode node) {
HeroNode temp = head;
boolean flag = false;
while (true) {
if (temp.next == null) {
break;
}
if (temp.next.id > node.id) {
break;
} else if (temp.next.id == node.id) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
System.out.println("The Hero Id is existed...");
return;
} else {
node.next = temp.next;
temp.next = node;
}
}
//Modify the Node data
public void modifyNode(HeroNode node) {
HeroNode temp = head.next;
boolean flag = false;
while (true) {
if (temp == null) {
break;
}
if (temp.id == node.id) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
temp.name = node.name;
temp.nickname = node.nickname;
} else {
System.out.println("The Node Id is not existed in the LinkedList...");
}
}
//Delete Node
public void deleteNode(int id) {
HeroNode temp = head;
boolean flag = false;
while (true) {
if (temp.next == null) {
break;
}
if (temp.next.id == id) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
temp.next = temp.next.next;
} else {
System.out.println("The Node Id is not existed in the LinkedList...");
}
}
//Through LinkedList
public void show() {
if (head.next == null) {
throw new RuntimeException("The LinkedList is empty...");
}
HeroNode temp = head.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
//Define Node
class HeroNode {
public int id;
public String name;
public String nickname;
public HeroNode next;
public HeroNode(int id, String name, String nickname) {
this.id = id;
this.name = name;
this.nickname = nickname;
}
@Override
public String toString() {
return "HeroNode{" +
"id=" + id +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
| 27.483721 | 82 | 0.5055 |
bd7d75bc765564cb226cb4e94f1371b5a71033ea | 7,263 | package graph.hbase;
import com.carrotsearch.hppc.LongHashSet;
import com.carrotsearch.hppc.LongSet;
import org.janusgraph.diskstorage.BackendException;
import org.janusgraph.diskstorage.IDAuthority;
import org.janusgraph.diskstorage.IDBlock;
import org.janusgraph.diskstorage.common.DistributedStoreManager;
import org.janusgraph.diskstorage.configuration.BasicConfiguration;
import org.janusgraph.diskstorage.configuration.Configuration;
import org.janusgraph.diskstorage.configuration.ModifiableConfiguration;
import org.janusgraph.diskstorage.configuration.WriteConfiguration;
import org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration;
import org.janusgraph.diskstorage.hbase.HBaseStoreManager;
import org.janusgraph.diskstorage.idmanagement.ConflictAvoidanceMode;
import org.janusgraph.diskstorage.idmanagement.ConsistentKeyIDAuthority;
import org.janusgraph.diskstorage.keycolumnvalue.*;
import org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration;
import org.janusgraph.graphdb.database.StandardJanusGraph;
import org.janusgraph.graphdb.database.idassigner.IDBlockSizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.List;
import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.*;
import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID;
import static org.junit.Assert.*;
public class GraphHBaseStoreID {
private static final Logger log = LoggerFactory.getLogger(GraphHBaseStoreID.class);
private KeyColumnValueStoreManager manager;
private IDAuthority idAuthority;
private WriteConfiguration baseStoreConfiguration; //创建基本的WriteConfiguration
private final int uidBitWidth;
private final boolean hasFixedUid;
private final boolean hasEmptyUid;
private final long blockSize;
private final long idUpperBoundBitWidth;
private final long idUpperBound;
private Configuration config;
private static final Duration GET_ID_BLOCK_TIMEOUT = Duration.ofMillis(300000L);//获取ID的超时时间
public GraphHBaseStoreID() {
baseStoreConfiguration = new CommonsConfiguration();
config = new ModifiableConfiguration(ROOT_NS,baseStoreConfiguration, BasicConfiguration.Restriction.NONE);
blockSize = config.get(GraphDatabaseConfiguration.IDS_BLOCK_SIZE);
idUpperBoundBitWidth = 30;
idUpperBound = 1L <<idUpperBoundBitWidth;
uidBitWidth = config.get(IDAUTHORITY_CAV_BITS);//这个就是uniqueIdBitWidth = 4 uniqueIDUpperBound 则是1 << uniqueIdBitWidth = 16
//hasFixedUid = !config.get(IDAUTHORITY_RANDOMIZE_UNIQUEID);
hasFixedUid = !ConflictAvoidanceMode.GLOBAL_AUTO.equals(config.get(IDAUTHORITY_CONFLICT_AVOIDANCE));
hasEmptyUid = uidBitWidth==0;
}
public static void main(String[] args) {
/* Configuration config = ((StandardJanusGraph) GraphSingle.getGraphSingleInstance().getGraph()).getConfiguration().getConfiguration();
int uidBitWidth = config.get(IDAUTHORITY_CAV_BITS);
System.out.println(uidBitWidth);
*/
//HbaseStoreManagerUse();
try {
GraphHBaseStoreID hBaseStoreTest = new GraphHBaseStoreID();
hBaseStoreTest.open("");
hBaseStoreTest.idAcquire();
} catch (BackendException e) {
e.printStackTrace();
}
}
public void open(String tableName) throws BackendException {
ModifiableConfiguration sc = new ModifiableConfiguration(ROOT_NS,baseStoreConfiguration.copy(), BasicConfiguration.Restriction.NONE);
if (!sc.has(UNIQUE_INSTANCE_ID)) {//JanusGraph instance 唯一标识符
String uniqueGraphId = getOrGenerateUniqueInstanceId(sc);
log.warn("Setting unique instance id: {}", uniqueGraphId);
sc.set(UNIQUE_INSTANCE_ID, uniqueGraphId);
}
sc.set(GraphDatabaseConfiguration.CLUSTER_MAX_PARTITIONS,4);//设置最大分区4位, 默认是32位置的也就是2的5次方 32, 此处只需要2的2次方为4 所以partitionBitWidth = 2,
manager = openStorageManager(tableName);
KeyColumnValueStore idStore = manager.openDatabase("ids");
StoreFeatures storeFeatures = manager.getFeatures();
if(storeFeatures.isKeyConsistent()){
System.out.println(" yes we can open the id store");
idAuthority = new ConsistentKeyIDAuthority(idStore, manager, sc);
}else {
throw new IllegalArgumentException("Cannot open id store");
}
}
private void HbaseStoreManagerUse() {
HBaseStoreManager hBaseStoreManager = (HBaseStoreManager)openStorageManager("hiki");
try {
boolean exists = hBaseStoreManager.exists();
System.out.println("exists ? " + exists);
} catch (BackendException e) {
e.printStackTrace();
}
DistributedStoreManager.Deployment deployment = hBaseStoreManager.getDeployment();
System.out.println("deploy name ----" + deployment.name());
try {
List<KeyRange> localKeyPartition = hBaseStoreManager.getLocalKeyPartition();
System.out.println(localKeyPartition.size());
} catch (BackendException e) {
e.printStackTrace();
}
}
public KeyColumnValueStoreManager openStorageManager(String tableName) {
HBaseStoreManager hiki = null;
try {
hiki = new HBaseStoreManager(HbaseSetup.getHBaseConfiguration(tableName, null));
} catch (BackendException e) {
e.printStackTrace();
}
return hiki;
}
private class InnerIDBlockSizer implements IDBlockSizer {
@Override
public long getBlockSize(int idNamespace) {
return blockSize;
}
@Override
public long getIdUpperBound(int idNamespace) {
return idUpperBound;
}
}
public void idAcquire() throws BackendException{
final IDBlockSizer blockSizer = new InnerIDBlockSizer();
idAuthority.setIDBlockSizer(blockSizer);
int numTrials = 100;// 测试生产num个id
LongSet ids = new LongHashSet((int)blockSize*numTrials);
long previous = 0;
for(int i = 0; i< numTrials; i++){
IDBlock block = idAuthority.getIDBlock(0, 0, GET_ID_BLOCK_TIMEOUT);
checkBlock(block,ids);
if (hasEmptyUid) {
log.warn("now it has empty uid");
if (previous!=0)
assertEquals(previous+1, block.getId(0));
previous=block.getId(block.numIds()-1);
}
}
}
private void checkBlock(IDBlock block, LongSet ids) {
assertEquals(blockSize,block.numIds());
for (int i=0;i<blockSize;i++) {
long id = block.getId(i);
log.warn("get id {}", id );
assertEquals(id,block.getId(i));
assertFalse(ids.contains(id));
assertTrue(id<idUpperBound);
assertTrue(id>0);
ids.add(id);
}
if (hasEmptyUid) {
assertEquals(blockSize-1,block.getId(block.numIds()-1)-block.getId(0));
}
try {
block.getId(blockSize);
fail();
} catch (ArrayIndexOutOfBoundsException ignored) {}
}
}
| 40.127072 | 142 | 0.694066 |
449196ca18f1dc24efc1a629b3334e6d280318b4 | 6,133 | package org.kairosdb.plugin.prometheus;
import com.google.common.collect.ImmutableSortedMap;
import org.junit.Before;
import org.junit.Test;
import org.kairosdb.core.datapoints.DoubleDataPoint;
import org.kairosdb.eventbus.FilterEventBus;
import org.kairosdb.eventbus.Publisher;
import org.kairosdb.events.DataPointEvent;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.Properties;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class PrometheusServerTest
{
@Mock
private FilterEventBus mockEventBus;
@Mock
private Publisher<DataPointEvent> mockPublisher;
@Before
public void setup()
{
initMocks(this);
when(mockEventBus.createPublisher(DataPointEvent.class)).thenReturn(mockPublisher);
}
@Test
public void test() throws MalformedURLException, UnknownHostException
{
String cwd = System.getProperty("user.dir");
Properties properties = new Properties();
properties.put("kairosdb.prometheus-server.client.0.url", "file:///" + cwd + "/src/test/resources/timeseries.txt");
properties.put("kairosdb.prometheus-server.client.0.scrape-interval", "30s");
TestScheduledExecutorService executor = new TestScheduledExecutorService();
ConfigurationDiscovery discovery = new ConfigurationDiscovery(properties);
PrometheusServer server = new PrometheusServer(mockEventBus, discovery, executor);
server.start();
executor.execute();
// Quantiles
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"go_gc_duration_seconds",
ImmutableSortedMap.of("instance", "1.2.3.4", "quantile", "0.0"),
6.1708E-05))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"go_gc_duration_seconds",
ImmutableSortedMap.of("instance", "1.2.3.4", "quantile", "0.25"),
8.1063e-05))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"go_gc_duration_seconds",
ImmutableSortedMap.of("instance", "1.2.3.4", "quantile", "0.5"),
9.5992e-05))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"go_gc_duration_seconds",
ImmutableSortedMap.of("instance", "1.2.3.4", "quantile", "0.75"),
0.000127407))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"go_gc_duration_seconds_sum",
ImmutableSortedMap.of(),
10.254398459))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"go_gc_duration_seconds_count",
ImmutableSortedMap.of(),
52837))));
// Guage
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"go_goroutines",
ImmutableSortedMap.of(),
126))));
// Counter
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"go_memstats_alloc_bytes_total",
ImmutableSortedMap.of(),
1.52575345048e+11))));
// Histogram
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"http_request_duration_seconds",
ImmutableSortedMap.of("le", "0.05"),
24054))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"http_request_duration_seconds",
ImmutableSortedMap.of("le", "0.1"),
33444))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"http_request_duration_seconds",
ImmutableSortedMap.of("le", "0.2"),
100392))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"http_request_duration_seconds",
ImmutableSortedMap.of("le", "0.5"),
129389))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"http_request_duration_seconds",
ImmutableSortedMap.of("le", "1.0"),
133988))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"http_request_duration_seconds",
ImmutableSortedMap.of("le", "Infinity"),
144320))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"http_request_duration_seconds_sum",
ImmutableSortedMap.of(),
53423))));
verify(mockPublisher).post(argThat(new DataPointEventMatcher(newDataPointEvent(
"http_request_duration_seconds_count",
ImmutableSortedMap.of(),
144320))));
}
private DataPointEvent newDataPointEvent(String metricName, ImmutableSortedMap<String, String> tags, double dataPoint) throws UnknownHostException
{
ImmutableSortedMap.Builder<String, String> builder = ImmutableSortedMap.naturalOrder();
builder.put("host", getHostname()).putAll(tags).build();
return new DataPointEvent(
metricName,
builder.build(),
new DoubleDataPoint(System.currentTimeMillis(), dataPoint));
}
private static String getHostname()
throws UnknownHostException
{
return InetAddress.getLocalHost().getHostName();
}
private class DataPointEventMatcher implements ArgumentMatcher<DataPointEvent>
{
private DataPointEvent event;
private String errorMessage;
DataPointEventMatcher(DataPointEvent event)
{
this.event = event;
}
@Override
public boolean matches(DataPointEvent dataPointEvent)
{
if (!event.getMetricName().equals(dataPointEvent.getMetricName()))
{
errorMessage = "Metric names don't match: " + event.getMetricName() + " != " + dataPointEvent.getMetricName();
return false;
}
if (!event.getTags().equals(dataPointEvent.getTags()))
{
errorMessage = "Tags don't match: " + event.getTags() + " != " + dataPointEvent.getTags();
return false;
}
if (event.getDataPoint().getDoubleValue() != dataPointEvent.getDataPoint().getDoubleValue())
{
errorMessage = "Data points don't match: " + event.getDataPoint().getDoubleValue() + " != " + dataPointEvent.getDataPoint().getDoubleValue();
return false;
}
return true;
}
@Override
public String toString()
{
if (errorMessage != null)
{
return errorMessage;
}
return "";
}
}
} | 33.331522 | 147 | 0.745801 |
1964317471d46067abd8697e110de6969c3af8c0 | 2,059 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.12
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.vectorsearch.faiss.swig;
public class ITQMatrix extends LinearTransform {
private transient long swigCPtr;
protected ITQMatrix(long cPtr, boolean cMemoryOwn) {
super(swigfaissJNI.ITQMatrix_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
protected static long getCPtr(ITQMatrix obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
swigfaissJNI.delete_ITQMatrix(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setMax_iter(int value) {
swigfaissJNI.ITQMatrix_max_iter_set(swigCPtr, this, value);
}
public int getMax_iter() {
return swigfaissJNI.ITQMatrix_max_iter_get(swigCPtr, this);
}
public void setSeed(int value) {
swigfaissJNI.ITQMatrix_seed_set(swigCPtr, this, value);
}
public int getSeed() {
return swigfaissJNI.ITQMatrix_seed_get(swigCPtr, this);
}
public void setInit_rotation(DoubleVector value) {
swigfaissJNI.ITQMatrix_init_rotation_set(swigCPtr, this, DoubleVector.getCPtr(value), value);
}
public DoubleVector getInit_rotation() {
long cPtr = swigfaissJNI.ITQMatrix_init_rotation_get(swigCPtr, this);
return (cPtr == 0) ? null : new DoubleVector(cPtr, false);
}
public ITQMatrix(int d) {
this(swigfaissJNI.new_ITQMatrix__SWIG_0(d), true);
}
public ITQMatrix() {
this(swigfaissJNI.new_ITQMatrix__SWIG_1(), true);
}
public void train(int n, SWIGTYPE_p_float x) {
swigfaissJNI.ITQMatrix_train(swigCPtr, this, n, SWIGTYPE_p_float.getCPtr(x));
}
}
| 27.092105 | 97 | 0.646916 |
9871ba9984322b7658d1288aac4ada51fe944419 | 2,709 | package io.github.mewore.tsw.config;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.resource.ResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AngularUiResourceResolverTest {
private static final String NON_UI_PATH = "non/ui/path/";
private static final String RESOURCE_PATH = "path/to/resource";
private static final ResourceResolver RESOURCE_RESOLVER = new AngularUiResourceResolver(NON_UI_PATH);
@Mock
private Resource location;
@Mock
private Resource resource;
@Mock
private Resource indexHtmlResource;
@Mock
private ResourceResolverChain resolverChain;
@Test
void testResolveResource_nonUiPath() {
assertNull(RESOURCE_RESOLVER.resolveResource(null, "non/ui/path/resource", getLocationList(), resolverChain));
}
@Test
void testResolveResource() throws IOException {
when(location.createRelative(RESOURCE_PATH)).thenReturn(resource);
when(resource.exists()).thenReturn(true);
when(resource.isReadable()).thenReturn(true);
assertSame(resource, RESOURCE_RESOLVER.resolveResource(null, RESOURCE_PATH, getLocationList(), resolverChain));
}
@Test
void testResolveResource_nonExistent() throws IOException {
when(location.createRelative(RESOURCE_PATH)).thenReturn(resource);
when(location.createRelative("index.html")).thenReturn(indexHtmlResource);
when(resource.exists()).thenReturn(false);
assertSame(indexHtmlResource,
RESOURCE_RESOLVER.resolveResource(null, RESOURCE_PATH, getLocationList(), resolverChain));
}
@Test
void testResolveResource_unreadable() throws IOException {
when(location.createRelative(RESOURCE_PATH)).thenReturn(resource);
when(location.createRelative("index.html")).thenReturn(indexHtmlResource);
when(resource.exists()).thenReturn(true);
when(resource.isReadable()).thenReturn(false);
assertSame(indexHtmlResource,
RESOURCE_RESOLVER.resolveResource(null, RESOURCE_PATH, getLocationList(), resolverChain));
}
private List<Resource> getLocationList() {
return Collections.singletonList(location);
}
} | 36.12 | 119 | 0.749723 |
9082cbccfaac328abe0e9c53efc77d402105eabf | 896 | package com.hills.mcs_02.dataBeans;
public class BeanListViewMineMinor6Notification {
private int icon;
private String Id;
private String time;
private String content;
public BeanListViewMineMinor6Notification(int icon, String Id, String time, String content) {
this.icon = icon;
this.Id = Id;
this.time = time;
this.content = content;
}
public int getIcon() {
return icon;
}
public String getId() {
return Id;
}
public String getTime() {
return time;
}
public String getContent() {
return content;
}
public void setId(String id) {
this.Id = id;
}
public void setTime(String time) {
this.time = time;
}
public void setContent(String content) {
this.content = content;
}
}
| 19.478261 | 98 | 0.563616 |
0323386cf1feaad6787e3792aac57b4d799ef855 | 3,486 | package de.lyca.xml.res;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
public class MessagesTest {
// Just as example - Better scan your classpath for message_*.properties
private static String[] propertyFiles = new String[] { //
"de/lyca/xml/res/XmlError_ca.properties", //
"de/lyca/xml/res/XmlError_cs.properties", //
"de/lyca/xml/res/XmlError_de.properties", //
"de/lyca/xml/res/XmlError_es.properties", //
"de/lyca/xml/res/XmlError_fr.properties", //
"de/lyca/xml/res/XmlError_hu.properties", //
"de/lyca/xml/res/XmlError_it.properties", //
"de/lyca/xml/res/XmlError_ja.properties", //
"de/lyca/xml/res/XmlError_ko.properties", //
"de/lyca/xml/res/XmlError_pl.properties", //
"de/lyca/xml/res/XmlError_pt_BR.properties", //
"de/lyca/xml/res/XmlError_ru.properties", //
"de/lyca/xml/res/XmlError_sk.properties", //
"de/lyca/xml/res/XmlError_sl.properties", //
"de/lyca/xml/res/XmlError_sv.properties", //
"de/lyca/xml/res/XmlError_tr.properties", //
"de/lyca/xml/res/XmlError_zh_TW.properties", //
"de/lyca/xml/res/XmlError_zh.properties", //
"de/lyca/xml/res/XmlError.properties" //
};
private static List<String> methodNames = new ArrayList<String>();
private static Map<String, Properties> bundles = new HashMap<String, Properties>();
@BeforeClass
public static void prepare() throws Exception {
// Get Method-Names
Method[] methods = XmlErrorMessages.class.getDeclaredMethods();
for (Method method : methods) {
methodNames.add(method.getName());
}
// Get all messages
for (String propertyFile : propertyFiles) {
Properties properties = new Properties();
URL url = ClassLoader.getSystemResource(propertyFile);
properties.load(url.openStream());
bundles.put(propertyFile, properties);
}
}
/**
* Is there an interface-method for every entry in our properties?
*
* @throws IOException
* ignore
*/
@Test
public void shouldHaveMessagesForAllInterafaceMethods() throws IOException {
Set<String> error = new HashSet<String>();
for (String methodName : methodNames) {
for (String propertyFile : propertyFiles) {
if (!bundles.get(propertyFile).containsKey(methodName)) {
error.add(propertyFile + "#" + methodName);
}
}
}
if (!error.isEmpty()) {
fail("No translations for " + error);
}
}
/**
* Is there an entry in each message.properties for every method in the
* interface?
*
* @throws IOException
* ignore
*/
@Test
public void shouldHaveInterfaceMethodForAllMessages() throws IOException {
Set<String> error = new HashSet<String>();
for (String propertyFile : propertyFiles) {
Properties bundle = bundles.get(propertyFile);
for (Object messageObj : bundle.keySet()) {
String message = messageObj.toString();
if (!methodNames.contains(message)) {
error.add(propertyFile + "#" + message);
}
}
}
if (!error.isEmpty()) {
fail("No interface method for : " + error);
}
}
}
| 30.051724 | 85 | 0.657774 |
8b4d444736d6aaa5f93b514f011c80fb2dbc15ac | 2,771 | // The MIT License (MIT)
// Copyright © 2015 AppsLandia. All rights reserved.
// 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 com.appslandia.common.utils;
import java.util.Locale;
import java.util.regex.Pattern;
/**
*
* @author <a href="mailto:haducloc13@gmail.com">Loc Ha</a>
*
*/
public class BytesSizeUtils {
private static final Pattern BYTES_SIZE_PATTERN = Pattern.compile("((\\d+.\\d+|\\d+)(TB|GB|MB|KB|B)\\s*)+", Pattern.CASE_INSENSITIVE);
public static long translateToBytes(String sizeAmt) throws IllegalArgumentException {
return translateToBytes(sizeAmt, false);
}
public static long translateToBytes(String sizeAmt, boolean base10) throws IllegalArgumentException {
sizeAmt = StringUtils.trimToNull(sizeAmt);
AssertUtils.assertNotNull(sizeAmt, "sizeAmt is required.");
if (!BYTES_SIZE_PATTERN.matcher(sizeAmt).matches()) {
throw new IllegalArgumentException("sizeAmt is invalid (value=" + sizeAmt + ")");
}
double result = 0L;
int i = 0;
while (i < sizeAmt.length()) {
int j = i;
while (Character.isDigit(sizeAmt.charAt(j)) || (sizeAmt.charAt(j) == '.'))
j++;
int k = j;
while ((k <= sizeAmt.length() - 1) && (Character.isLetter(sizeAmt.charAt(k)) || sizeAmt.charAt(k) == (' ')))
k++;
double amt = Double.parseDouble(sizeAmt.substring(i, j));
String unit = sizeAmt.substring(j, k).trim().toUpperCase(Locale.ENGLISH);
switch (unit) {
case "GB":
result += amt * (base10 ? 1000_000_000 : 1_073_741_824);
break;
case "MB":
result += amt * (base10 ? 1000_000 : 1_048_576);
break;
case "KB":
result += amt * (base10 ? 1000 : 1024);
break;
default:
result += amt;
break;
}
i = k;
}
return (long) Math.ceil(result);
}
}
| 35.075949 | 135 | 0.702995 |
5be6cb18a511b6be3974afb6fca397683e767c1a | 2,040 | package at.ac.tuwien.big.xmlintelledit.intelledit.change.primitive;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class PrimitiveChanges {
private static Map<Class<?>, List<ValueGenerator<?>>> generatorsPerClass = new HashMap<>();
private static Map<Class<?>, List<ValueModificator<?>>> modificatorsPerClass = new HashMap<>();
private static Random random = new Random();
private static final String possibleCharsString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_0123456789";
private static final char[] possibleChars = possibleCharsString.toCharArray();
{
addGenerator(Integer.class, (x,y,z)->{return random.nextInt(20);});
addGenerator(Long.class, (x,y,z)->{return random.nextInt(20);});
addGenerator(Boolean.class, (x,y,z)->{return random.nextBoolean();});
addGenerator(String.class, (x,y,z)->{
int length = random.nextInt(10);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; ++i) {
builder.append(possibleChars[random.nextInt(possibleChars.length)]);
}
return builder.toString();});
}
public static void addGenerator(Class<?> cl, ValueGenerator<?> generator) {
List<ValueGenerator<?>> curList = generatorsPerClass.get(cl);
if (curList == null) {
generatorsPerClass.put(cl, curList = new ArrayList<ValueGenerator<?>>());
}
curList.add(generator);
}
public static void addModificator(Class<?> cl, ValueModificator<?> modificator) {
List<ValueModificator<?>> curList = modificatorsPerClass.get(cl);
if (curList == null) {
modificatorsPerClass.put(cl, curList = new ArrayList<ValueModificator<?>>());
}
curList.add(modificator);
}
public List<ValueGenerator<?>> getGenerators(Class<?> cl) {
return generatorsPerClass.getOrDefault(cl, Collections.emptyList());
}
public List<ValueModificator<?>> getModificators(Class<?> cl) {
return modificatorsPerClass.getOrDefault(cl, Collections.emptyList());
}
}
| 35.789474 | 118 | 0.730392 |
1b17ebebbde0fdbbea7c97ef4a416877e1215c87 | 619 | package com.cloud.dips.tag.service;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.cloud.dips.common.core.util.Query;
import com.cloud.dips.tag.api.entity.GovTagDescription;
import com.cloud.dips.tag.api.vo.GovTagDescriptionVO;
/**
* @author ZB
*/
public interface GovTagDescriptionService extends IService<GovTagDescription> {
/**
* 删除标签
* @param tagId 标签id
* @return 布尔值
*/
Boolean deleteByTagId(Integer tagId);
/**
* 分页查询描述
* @param query
* @return
*/
Page<GovTagDescriptionVO> selectAllPage(Query<GovTagDescriptionVO> query);
}
| 22.107143 | 79 | 0.751212 |
84e99c816785a25ff1e65ea00a05b82b9e8e4e67 | 5,026 | package info.ephyra.trec;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* A parser for the TREC 8-12 QA tracks.
*
* @author Nico Schlaefer
* @version 2007-05-25
*/
public class TREC8To12Parser {
/** Type of the TREC 8 to 11 questions. */
private static final String QTYPE = "FACTOID";
/**
* Loads the questions from a file.
*
* @param filename file that contains the questions
* @return questions or <code>null</code>, if the file could not be parsed
*/
public static TRECQuestion[] loadQuestions(String filename) {
File file = new File(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String id = "";
String type = "";
String line, questionString;
TRECQuestion question;
ArrayList<TRECQuestion> questions = new ArrayList<TRECQuestion>();
while (in.ready()) {
line = in.readLine();
if (line.matches("<num>.*")) {
id = line.split(": ")[1].trim();
type = QTYPE; // TREC 8 to 11
} else if (line.matches("<type>.*")) {
type = line.split(": ")[1].trim().toUpperCase(); // TREC 12
} else if (line.matches("<desc>.*")) {
questionString = in.readLine().trim();
question = new TRECQuestion(id, type, questionString);
questions.add(question);
}
}
in.close();
return questions.toArray(new TRECQuestion[questions.size()]);
} catch (IOException e) {
return null; // file could not be parsed
}
}
/**
* Loads the patterns from a file.
*
* @param filename file that contains the patterns
* @return patterns or <code>null</code>, if the file could not be parsed
*/
public static TRECPattern[] loadPatterns(String filename) {
TRECPattern[] aligned = loadPatternsAligned(filename);
if (aligned == null) return null;
// remove null-entries
ArrayList<TRECPattern> patterns = new ArrayList<TRECPattern>();
for (TRECPattern pattern : aligned)
if (pattern != null) patterns.add(pattern);
return patterns.toArray(new TRECPattern[patterns.size()]);
}
/**
* Loads the patterns from a file. For each skipped question ID in the input
* file, a <code>null</code> entry is added to the array of patterns.
*
* @param filename file that contains the patterns
* @return patterns aligned to question IDs or <code>null</code>, if the
* file could not be parsed
*/
public static TRECPattern[] loadPatternsAligned(String filename) {
File file = new File(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String[] line;
int id, lastId = -1;
String regex = "";
TRECPattern pattern;
ArrayList<TRECPattern> patterns = new ArrayList<TRECPattern>();
while (in.ready()) {
line = in.readLine().split(" ", 2);
id = Integer.parseInt(line[0]);
if (id == lastId)
// if still the same pattern, append the regular expression
regex += "|" + line[1].trim();
else { // next pattern
if (!(lastId == -1)) {
// if not first pattern, add previous pattern to results
regex += ")";
pattern = new TRECPattern(Integer.toString(lastId),
new String[] {regex});
patterns.add(pattern);
// some number might have been skipped
for (int i = lastId + 1; i < id; i++)
patterns.add(null);
}
// start new pattern
lastId = id;
regex = "(?i)(" + line[1].trim(); // case is ignored
}
}
// add last pattern to results
regex += ")";
pattern = new TRECPattern(Integer.toString(lastId),
new String[] {regex});
patterns.add(pattern);
in.close();
return patterns.toArray(new TRECPattern[patterns.size()]);
} catch (IOException e) {
return null; // file could not be parsed
}
}
/**
* Loads the answers to the TREC9 questions from a file.
*
* @param filename file that contains the answers
* @return answers or <code>null</code>, if the file could not be parsed
*/
public static TRECAnswer[] loadTREC9Answers(String filename) {
File file = new File(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String id;
String line, answerString;
TRECAnswer answer;
ArrayList<TRECAnswer> answers = new ArrayList<TRECAnswer>();
while (in.ready()) {
line = in.readLine();
if (line.matches("Question.*")) {
id = line.split(" ")[1];
in.readLine();
in.readLine();
answerString = in.readLine().trim();
answer = new TRECAnswer(id, answerString);
answers.add(answer);
}
}
in.close();
return answers.toArray(new TRECAnswer[answers.size()]);
} catch (IOException e) {
return null; // file could not be parsed
}
}
}
| 28.39548 | 78 | 0.607839 |
58587138498843468951846b6ff97934a5baceee | 8,631 | package org.firstinspires.ftc.teamcode.subsystem.positioning;
import com.qualcomm.robotcore.hardware.HardwareMap;
import org.apache.commons.io.IOUtils;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static org.firstinspires.ftc.robotcore.external.navigation.AngleUnit.DEGREES;
import static org.firstinspires.ftc.robotcore.external.navigation.AngleUnit.RADIANS;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.XYZ;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesOrder.YZX;
import static org.firstinspires.ftc.robotcore.external.navigation.AxesReference.EXTRINSIC;
import static org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.CameraDirection.BACK;
public class VuforiaSensor extends PositioningSensor {
// Configuration related to using a webcam
private static final VuforiaLocalizer.CameraDirection CAMERA_CHOICE = BACK;
private static final boolean PHONE_IS_PORTRAIT = false;
// Some other constants
private static String VUFORIA_KEY = "";
private static final float MM_PER_INCH = 25.4f;
private static final float MM_TARGET_HEIGHT = (6) * MM_PER_INCH; // the height of the center of the target image above the floor
private static final float HALF_FIELD = 72 * MM_PER_INCH;
private static final float QUAD_FIELD = 36 * MM_PER_INCH;
private final float phoneZRotate = 0;
VuforiaTrackables targetsUltimateGoal;
private OpenGLMatrix lastLocation;
private VuforiaLocalizer vuforia;
private WebcamName webcamName;
private List<VuforiaTrackable> allTrackables;
private boolean targetVisible = false;
private float phoneXRotate = 0;
private float phoneYRotate = 0;
private Position position;
@Override
public Supplier<Position> getPositionSupplier() {
return () -> position;
}
@Override
public Consumer<Position> getPositionReset() {
return (Position pos) -> {};
}
public void update() {
// check all the trackable targets to see which one (if any) is visible.
targetVisible = false;
for (VuforiaTrackable trackable : allTrackables) {
if (((VuforiaTrackableDefaultListener) trackable.getListener()).isVisible()) {
telemetry.addData("Visible Target", trackable.getName());
targetVisible = true;
// getUpdatedRobotLocation() will return null if no new information is available since
// the last time that call was made, or if the trackable is not currently visible.
OpenGLMatrix robotLocationTransform = ((VuforiaTrackableDefaultListener) trackable.getListener()).getUpdatedRobotLocation();
if (robotLocationTransform != null) {
lastLocation = robotLocationTransform;
}
break;
}
}
// Provide feedback as to where the robot is located (if we know).
if (targetVisible) {
// express position (translation) of robot in inches.
VectorF translation = lastLocation.getTranslation();
double xPos = translation.get(0) / MM_PER_INCH;
double yPos = translation.get(1) / MM_PER_INCH;
double zPos = translation.get(2) / MM_PER_INCH;
telemetry.addData("Vuforia Pos (in)", "{X, Y, Z} = %.1f, %.1f, %.1f", xPos, yPos, zPos);
// express the rotation of the robot in degrees.
Orientation rotation = Orientation.getOrientation(lastLocation, EXTRINSIC, XYZ, RADIANS);
double roll = rotation.firstAngle;
double pitch = rotation.secondAngle;
double heading = rotation.thirdAngle;
telemetry.addData("Vuforia Rot (rad)", "{Roll, Pitch, Heading} = %.2f, %.2f, %.2f", roll, pitch, heading);
position = new Position(xPos, yPos, heading);
} else {
telemetry.addData("Visible Target", "none");
position = new Position(null, null, null);
}
}
@Override
public void initialize(HardwareMap hardwareMap) {
super.initialize(hardwareMap);
try {
VUFORIA_KEY = new String(IOUtils.toCharArray(hardwareMap.appContext.getResources().openRawResource(
hardwareMap.appContext.getResources().getIdentifier("vuforiasecret", "raw", hardwareMap.appContext.getPackageName())
), Charset.defaultCharset()));
} catch (IOException e) {
e.printStackTrace();
}
webcamName = hardwareMap.get(WebcamName.class, "camera");
VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();
parameters.vuforiaLicenseKey = VUFORIA_KEY;
parameters.cameraName = webcamName;
parameters.useExtendedTracking = false; // TODO Check this behavior
vuforia = ClassFactory.getInstance().createVuforia(parameters);
targetsUltimateGoal = this.vuforia.loadTrackablesFromAsset("UltimateGoal");
VuforiaTrackable blueTowerGoalTarget = targetsUltimateGoal.get(0);
blueTowerGoalTarget.setName("Blue Tower Goal Target");
VuforiaTrackable redTowerGoalTarget = targetsUltimateGoal.get(1);
redTowerGoalTarget.setName("Red Tower Goal Target");
VuforiaTrackable redAllianceTarget = targetsUltimateGoal.get(2);
redAllianceTarget.setName("Red Alliance Target");
VuforiaTrackable blueAllianceTarget = targetsUltimateGoal.get(3);
blueAllianceTarget.setName("Blue Alliance Target");
VuforiaTrackable frontWallTarget = targetsUltimateGoal.get(4);
frontWallTarget.setName("Front Wall Target");
allTrackables = new ArrayList<VuforiaTrackable>();
allTrackables.addAll(targetsUltimateGoal);
//Set the position of the perimeter targets with relation to origin (center of field)
redAllianceTarget.setLocation(OpenGLMatrix
.translation(0, -HALF_FIELD, MM_TARGET_HEIGHT)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 180)));
blueAllianceTarget.setLocation(OpenGLMatrix
.translation(0, HALF_FIELD, MM_TARGET_HEIGHT)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 0)));
frontWallTarget.setLocation(OpenGLMatrix
.translation(-HALF_FIELD, 0, MM_TARGET_HEIGHT)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, 90)));
// The tower goal targets are located a quarter field length from the ends of the back perimeter wall.
blueTowerGoalTarget.setLocation(OpenGLMatrix
.translation(HALF_FIELD, QUAD_FIELD, MM_TARGET_HEIGHT)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, -90)));
redTowerGoalTarget.setLocation(OpenGLMatrix
.translation(HALF_FIELD, -QUAD_FIELD, MM_TARGET_HEIGHT)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, XYZ, DEGREES, 90, 0, -90)));
// We need to rotate the camera around it's long axis to bring the correct camera forward.
if (CAMERA_CHOICE == BACK) {
phoneYRotate = -90;
} else {
phoneYRotate = 90;
}
// Rotate the phone vertical about the X axis if it's in portrait mode
if (PHONE_IS_PORTRAIT) {
phoneXRotate = 90;
}
// TODO Change these values
final float CAMERA_FORWARD_DISPLACEMENT = 4.0f * MM_PER_INCH; // eg: Camera is 4 Inches in front of robot-center
final float CAMERA_VERTICAL_DISPLACEMENT = 8.0f * MM_PER_INCH; // eg: Camera is 8 Inches above ground
final float CAMERA_LEFT_DISPLACEMENT = 0; // eg: Camera is ON the robot's center line
OpenGLMatrix robotFromCamera = OpenGLMatrix
.translation(CAMERA_FORWARD_DISPLACEMENT, CAMERA_LEFT_DISPLACEMENT, CAMERA_VERTICAL_DISPLACEMENT)
.multiplied(Orientation.getRotationMatrix(EXTRINSIC, YZX, DEGREES, phoneYRotate, phoneZRotate, phoneXRotate));
/** Let all the trackable listeners know where the phone is. */
for (VuforiaTrackable trackable : allTrackables) {
((VuforiaTrackableDefaultListener) trackable.getListener()).setPhoneInformation(robotFromCamera, parameters.cameraDirection);
}
position = new Position();
targetsUltimateGoal.activate();
}
public VuforiaLocalizer getVuforiaLocalizer() {
return vuforia;
}
@Override
public void initPeriodic() {
update();
}
@Override
public void runPeriodic() {
update();
}
@Override
public void stop() {
targetsUltimateGoal.deactivate();
}
}
| 42.517241 | 138 | 0.773723 |
b04b7cae3840e157b833cd036226badfe88cc44a | 11,042 | package de.pxav.kelp.core.inventory.metadata;
import com.google.common.hash.HashCode;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Represents a color that can be used for dyeing items such
* as leather armor or represent colors inside minecraft in general.
*
* This class is a version independent alternative to bukkit's normal
* {@link org.bukkit.Color} class.
*
* You can use the color presets such as {@link Color#CHAT_GOLD} or {@link Color#PRESET_OLIVE}
* or create your own colors using rgb or hex values: {@link Color#fromRGB(int, int, int)}.
*
* You will need this color representation in classes like {@link LeatherArmorMetadata}.
*
* @author pxav
*/
public class Color implements Cloneable {
// all minecraft default chat colors in rgb notation
public static final Color CHAT_DARK_RED = fromRGB(170, 0, 0);
public static final Color CHAT_BLACK = fromRGB(0, 0, 0);
public static final Color CHAT_DARK_BLUE = fromRGB(170, 0, 170);
public static final Color CHAT_DARK_GREEN = fromRGB(0, 170, 0);
public static final Color CHAT_DARK_AQUA = fromRGB(0, 170, 170);
public static final Color CHAT_DARK_PURPLE = fromRGB(170, 0, 170);
public static final Color CHAT_GOLD = fromRGB(255, 170, 0);
public static final Color CHAT_GRAY = fromRGB(170, 170, 170);
public static final Color CHAT_DARK_GRAY = fromRGB(85, 85, 85);
public static final Color CHAT_BLUE = fromRGB(85, 85, 255);
public static final Color CHAT_GREEN = fromRGB(85, 255, 85);
public static final Color CHAT_AQUA = fromRGB(85, 255, 255);
public static final Color CHAT_RED = fromRGB(255, 85, 85);
public static final Color CHAT_LIGHT_PURPLE = fromRGB(255, 85, 255);
public static final Color CHAT_YELLOW = fromRGB(255, 255, 85);
public static final Color CHAT_WHITE = fromRGB(255, 255, 255);
// some preset colors provided by the bukkit library.
public static final Color PRESET_AQUA = fromRGB(0, 255, 255);
public static final Color PRESET_BLACK = fromRGB(0, 0, 0);
public static final Color PRESET_BLUE = fromRGB(0, 0, 255);
public static final Color PRESET_WHITE = fromRGB(255, 255, 255);
public static final Color PRESET_SILVER = fromRGB(192, 192, 192);
public static final Color PRESET_GRAY = fromRGB(128, 128, 128);
public static final Color PRESET_RED = fromRGB(255, 0, 0);
public static final Color PRESET_MAROON = fromRGB(128, 0, 0);
public static final Color PRESET_YELLOW = fromRGB(255, 255, 0);
public static final Color PRESET_OLIVE = fromRGB(128, 128, 0);
public static final Color PRESET_LIME = fromRGB(0, 255, 0);
public static final Color PRESET_GREEN = fromRGB(0, 128, 0);
public static final Color PRESET_TEAL = fromRGB(0, 128, 128);
public static final Color PRESET_NAVY = fromRGB(0, 0, 128);
public static final Color PRESET_FUCHSIA = fromRGB(255, 0, 255);
public static final Color PRESET_PURPLE = fromRGB(128, 0, 128);
public static final Color PRESET_ORANGE = fromRGB(255, 165, 0);
// colors that are created when crafting a dye together with a dyeable item such as
// leather armor or wool.
public static final Color DYE_PINK = fromRGB(243, 139, 170);
public static final Color DYE_LIME = fromRGB(128, 199, 31);
public static final Color DYE_YELLOW = fromRGB(254, 216, 61);
public static final Color DYE_LIGHT_BLUE = fromRGB(58, 179, 218);
public static final Color DYE_MAGENTA = fromRGB(199, 78, 189);
public static final Color DYE_ORANGE = fromRGB(249, 128, 29);
public static final Color DYE_WHITE = fromRGB(249, 255, 254);
public static final Color DYE_GRAY = fromRGB(71, 79, 82);
public static final Color DYE_RED = fromRGB(176, 46, 38);
public static final Color DYE_CACTUS = fromRGB(94, 124, 22);
public static final Color DYE_BROWN = fromRGB(131, 84, 50);
public static final Color DYE_BLUE = fromRGB(60, 68, 170);
public static final Color DYE_PURPLE = fromRGB(137, 50, 184);
public static final Color DYE_CYAN = fromRGB(22, 156, 156);
public static final Color DYE_BLACK = fromRGB(29, 29, 33);
/**
* Creates a new color instance based on the given red, green and blue value.
*
* @param red The amount of red in the desired color (from 0-255)
* @param green The amount of green in the desired color (from 0-255)
* @param blue The amount of blue in the desired color (from 0-255)
* @return The new color instance based on the given values.
*/
public static Color fromRGB(int red, int green, int blue) {
return new Color(red, green, blue);
}
/**
* Creates a new color instance based on the HEX value of the given color.
* The entered hex string has to have 6 chars representing the colors
* and optionally a {@code #} at the beginning to indicate that this is a
* HEX color value.
*
* @param hexValue The HEX value of the color you want to create.
* This value may contain a # at the beginning, but
* does not have to have one necessarily.
* @return The color based on the given HEX value.
*/
public static Color fromHEX(String hexValue) {
if (hexValue == null
|| ((hexValue.length() != 7 && hexValue.charAt(0) != '#')
&& hexValue.length() != 6)) {
return new Color(0, 0, 0);
}
if (hexValue.length() == 7) {
hexValue = hexValue.replace("#", "");
}
int red = Integer.parseInt(hexValue.substring(0, 2), 16);
int green = Integer.parseInt(hexValue.substring(2, 4), 16);
int blue = Integer.parseInt(hexValue.substring(4, 6), 16);
return fromRGB(red, green, blue);
}
/**
* Converts a bukkit color into a kelp color using its rgb values.
*
* @param color The bukkit color you want to convert.
* @return The kelp color instance equivalent to the bukkit color.
*/
public static Color fromBukkit(org.bukkit.Color color) {
return new Color(color.getRed(), color.getGreen(), color.getBlue());
}
/**
* Builds an array of all default colors available in this
* class. This includes (in order):
* - Dye colors (DYE_)
* - Chat colors (CHAT_)
* - Preset colors (PRESET_)
*
* @return An array of all default colors in this class.
*/
public static Color[] colorValues() {
return new Color[] {
DYE_PINK,
DYE_LIME,
DYE_YELLOW,
DYE_LIGHT_BLUE,
DYE_MAGENTA,
DYE_ORANGE,
DYE_WHITE,
DYE_GRAY,
DYE_RED,
DYE_CACTUS,
DYE_BROWN,
DYE_BLUE,
DYE_PURPLE,
DYE_CYAN,
DYE_BLACK,
CHAT_DARK_RED,
CHAT_BLACK,
CHAT_DARK_BLUE,
CHAT_DARK_GREEN,
CHAT_DARK_AQUA,
CHAT_DARK_PURPLE,
CHAT_GOLD,
CHAT_GRAY,
CHAT_DARK_GRAY,
CHAT_BLUE,
CHAT_GREEN,
CHAT_AQUA,
CHAT_RED,
CHAT_LIGHT_PURPLE,
CHAT_YELLOW,
CHAT_WHITE,
PRESET_ORANGE,
PRESET_PURPLE,
PRESET_FUCHSIA,
PRESET_NAVY,
PRESET_TEAL,
PRESET_GREEN,
PRESET_LIME,
PRESET_OLIVE,
PRESET_YELLOW,
PRESET_MAROON,
PRESET_RED,
PRESET_GRAY,
PRESET_SILVER,
PRESET_WHITE,
PRESET_BLUE,
PRESET_BLACK,
PRESET_AQUA,
};
}
// RGB color values
private int red;
private int green;
private int blue;
private Color(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
/**
* Sets the amount of red in this color.
*
* @param red The amount of red in this color.
* The value may range from 0 to 255.
* @return The instance of the current color for fluent builder design.
*/
public Color setRed(int red) {
this.red = red;
return this;
}
/**
* Gets the amount of red in this color (0-255)
*
* @return The amount of red in this color.
*/
public int getRed() {
return red;
}
/**
* Sets the amount of green in this color.
*
* @param green The amount of green in this color.
* The value may range from 0 to 255.
* @return The instance of the current color for fluent builder design.
*/
public Color setGreen(int green) {
this.green = green;
return this;
}
/**
* Gets the amount of green in this color (0-255)
*
* @return The amount of green in this color.
*/
public int getGreen() {
return green;
}
/**
* Sets the amount of blue in this color.
*
* @param blue The amount of blue in this color.
* The value may range from 0 to 255.
* @return The instance of the current color for fluent builder design.
*/
public Color setBlue(int blue) {
this.blue = blue;
return this;
}
/**
* Gets the amount of blue in this color (0-255)
*
* @return The amount of blue in this color.
*/
public int getBlue() {
return blue;
}
/**
* Converts the color values from RGB to a HEX string. This means it converts
* each color value for red, green and blue into their hex number, which is
* two characters long. Those characters are appended in the RGB order resulting
* in the six-chars long hex format of the current color. This method does not
* add a {@code #} in front of each color.
*
* @return The HEX notation of the current color.
*/
public String asHex() {
return (StringUtils.leftPad(Integer.toHexString(red), 2, '0') +
StringUtils.leftPad(Integer.toHexString(green), 2, '0') +
StringUtils.leftPad(Integer.toHexString(blue), 2, '0')).toUpperCase();
}
/**
* Generates an array containing the RGB color values in their
* regular order: [red, green, blue]
*
* @return The color values in RGB order.
*/
public int[] asRGB() {
return new int[] {
this.red,
this.green,
this.blue
};
}
/**
* Generates an array containing the color values in the format:
* [blue, green, red]
*
* @return The raw color values composing the current color in BGR format.
*/
public int[] asBGR() {
return new int[] {
this.blue,
this.green,
this.red
};
}
/**
* Converts this color to the equivalent bukkit color.
*
* @return The bukkit color equivalent to this color.
*/
public org.bukkit.Color getBukkitColor() {
return org.bukkit.Color.fromRGB(red, green, blue);
}
@Override
public Color clone() {
return Color.fromRGB(this.red, this.green, this.blue);
}
@Override
public String toString() {
return "Color{" +
"red=" + red +
", green=" + green +
", blue=" + blue +
'}';
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Color)) {
return false;
}
Color color = (Color) object;
return color.getRed() == this.red
&& color.getGreen() == this.green
&& color.getBlue() == this.blue;
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(this.red)
.append(this.blue)
.append(this.green)
.toHashCode();
}
}
| 31.104225 | 94 | 0.658305 |
fb97ac3a209768b3b5b8307a36c9c72e53ecb127 | 9,009 | /**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.cas.client.validation;
import java.io.IOException;
import java.util.*;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jasig.cas.client.proxy.*;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.ReflectUtils;
/**
* Creates either a CAS20ProxyTicketValidator or a CAS20ServiceTicketValidator depending on whether any of the
* proxy parameters are set.
* <p>
* This filter can also pass additional parameters to the ticket validator. Any init parameter not included in the
* reserved list {@link org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter#RESERVED_INIT_PARAMS}.
*
* @author Scott Battaglia
* @author Brad Cupit (brad [at] lsu {dot} edu)
* @version $Revision$ $Date$
* @since 3.1
*
*/
public class Cas20ProxyReceivingTicketValidationFilter extends AbstractTicketValidationFilter {
private static final String[] RESERVED_INIT_PARAMS = new String[] {"proxyGrantingTicketStorageClass", "proxyReceptorUrl", "acceptAnyProxy", "allowedProxyChains", "casServerUrlPrefix", "proxyCallbackUrl", "renew", "exceptionOnValidationFailure", "redirectAfterValidation", "useSession", "serverName", "service", "artifactParameterName", "serviceParameterName", "encodeServiceUrl", "millisBetweenCleanUps", "hostnameVerifier", "encoding", "config"};
private static final int DEFAULT_MILLIS_BETWEEN_CLEANUPS = 60 * 1000;
/**
* The URL to send to the CAS server as the URL that will process proxying requests on the CAS client.
*/
private String proxyReceptorUrl;
private Timer timer;
private TimerTask timerTask;
private int millisBetweenCleanUps;
/**
* Storage location of ProxyGrantingTickets and Proxy Ticket IOUs.
*/
private ProxyGrantingTicketStorage proxyGrantingTicketStorage = new ProxyGrantingTicketStorageImpl();
protected void initInternal(final FilterConfig filterConfig) throws ServletException {
setProxyReceptorUrl(getPropertyFromInitParams(filterConfig, "proxyReceptorUrl", null));
final String proxyGrantingTicketStorageClass = getPropertyFromInitParams(filterConfig, "proxyGrantingTicketStorageClass", null);
if (proxyGrantingTicketStorageClass != null) {
this.proxyGrantingTicketStorage = ReflectUtils.newInstance(proxyGrantingTicketStorageClass);
if (this.proxyGrantingTicketStorage instanceof AbstractEncryptedProxyGrantingTicketStorageImpl) {
final AbstractEncryptedProxyGrantingTicketStorageImpl p = (AbstractEncryptedProxyGrantingTicketStorageImpl) this.proxyGrantingTicketStorage;
final String cipherAlgorithm = getPropertyFromInitParams(filterConfig, "cipherAlgorithm", AbstractEncryptedProxyGrantingTicketStorageImpl.DEFAULT_ENCRYPTION_ALGORITHM);
final String secretKey = getPropertyFromInitParams(filterConfig, "secretKey", null);
p.setCipherAlgorithm(cipherAlgorithm);
try {
if (secretKey != null) {
p.setSecretKey(secretKey);
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
log.trace("Setting proxyReceptorUrl parameter: " + this.proxyReceptorUrl);
this.millisBetweenCleanUps = Integer.parseInt(getPropertyFromInitParams(filterConfig, "millisBetweenCleanUps", Integer.toString(DEFAULT_MILLIS_BETWEEN_CLEANUPS)));
super.initInternal(filterConfig);
}
public void init() {
super.init();
CommonUtils.assertNotNull(this.proxyGrantingTicketStorage, "proxyGrantingTicketStorage cannot be null.");
if (this.timer == null) {
this.timer = new Timer(true);
}
if (this.timerTask == null) {
this.timerTask = new CleanUpTimerTask(this.proxyGrantingTicketStorage);
}
this.timer.schedule(this.timerTask, this.millisBetweenCleanUps, this.millisBetweenCleanUps);
}
/**
* Constructs a Cas20ServiceTicketValidator or a Cas20ProxyTicketValidator based on supplied parameters.
*
* @param filterConfig the Filter Configuration object.
* @return a fully constructed TicketValidator.
*/
protected final TicketValidator getTicketValidator(final FilterConfig filterConfig) {
final String allowAnyProxy = getPropertyFromInitParams(filterConfig, "acceptAnyProxy", null);
final String allowedProxyChains = getPropertyFromInitParams(filterConfig, "allowedProxyChains", null);
final String casServerUrlPrefix = getPropertyFromInitParams(filterConfig, "casServerUrlPrefix", null);
final Cas20ServiceTicketValidator validator;
if (CommonUtils.isNotBlank(allowAnyProxy) || CommonUtils.isNotBlank(allowedProxyChains)) {
final Cas20ProxyTicketValidator v = new Cas20ProxyTicketValidator(casServerUrlPrefix);
v.setAcceptAnyProxy(parseBoolean(allowAnyProxy));
v.setAllowedProxyChains(CommonUtils.createProxyList(allowedProxyChains));
validator = v;
} else {
validator = new Cas20ServiceTicketValidator(casServerUrlPrefix);
}
validator.setProxyCallbackUrl(getPropertyFromInitParams(filterConfig, "proxyCallbackUrl", null));
validator.setProxyGrantingTicketStorage(this.proxyGrantingTicketStorage);
validator.setProxyRetriever(new Cas20ProxyRetriever(casServerUrlPrefix, getPropertyFromInitParams(filterConfig, "encoding", null)));
validator.setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false")));
validator.setEncoding(getPropertyFromInitParams(filterConfig, "encoding", null));
final Map<String,String> additionalParameters = new HashMap<String,String>();
final List<String> params = Arrays.asList(RESERVED_INIT_PARAMS);
for (final Enumeration<?> e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {
final String s = (String) e.nextElement();
if (!params.contains(s)) {
additionalParameters.put(s, filterConfig.getInitParameter(s));
}
}
validator.setCustomParameters(additionalParameters);
validator.setHostnameVerifier(getHostnameVerifier(filterConfig));
return validator;
}
public void destroy() {
super.destroy();
this.timer.cancel();
}
/**
* This processes the ProxyReceptor request before the ticket validation code executes.
*/
protected final boolean preFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
final String requestUri = request.getRequestURI();
if (CommonUtils.isEmpty(this.proxyReceptorUrl) || !requestUri.endsWith(this.proxyReceptorUrl)) {
return true;
}
try {
CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage);
} catch (final RuntimeException e) {
log.error(e.getMessage(), e);
throw e;
}
return false;
}
public final void setProxyReceptorUrl(final String proxyReceptorUrl) {
this.proxyReceptorUrl = proxyReceptorUrl;
}
public void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage storage) {
this.proxyGrantingTicketStorage = storage;
}
public void setTimer(final Timer timer) {
this.timer = timer;
}
public void setTimerTask(final TimerTask timerTask) {
this.timerTask = timerTask;
}
public void setMillisBetweenCleanUps(final int millisBetweenCleanUps) {
this.millisBetweenCleanUps = millisBetweenCleanUps;
}
}
| 43.73301 | 451 | 0.725164 |
38fa84d5845b7ebb4c8c9331bda3955e2b1be6bf | 3,380 | package com.joymain.jecs.pm.webapp.action;
import java.util.Locale;
import java.math.BigDecimal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.apache.commons.lang.StringUtils;
import com.joymain.jecs.util.data.CommonRecord;
import com.joymain.jecs.util.web.RequestUtil;
import com.joymain.jecs.webapp.action.BaseFormController;
import com.joymain.jecs.webapp.util.SessionLogin;
import com.joymain.jecs.pm.model.JmiMemberTeam;
import com.joymain.jecs.pm.service.JmiMemberTeamManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
public class JmiMemberTeamFormController extends BaseFormController {
private JmiMemberTeamManager jmiMemberTeamManager = null;
public void setJmiMemberTeamManager(JmiMemberTeamManager jmiMemberTeamManager) {
this.jmiMemberTeamManager = jmiMemberTeamManager;
}
public JmiMemberTeamFormController() {
setCommandName("jmiMemberTeam");
setCommandClass(JmiMemberTeam.class);
}
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
String code = request.getParameter("code");
JmiMemberTeam jmiMemberTeam = null;
String strAction = request.getParameter("strAction");
if ("editJmiMemberTeam".equals(strAction)) {
jmiMemberTeam = jmiMemberTeamManager.getJmiMemberTeam(code);
} else {
jmiMemberTeam = new JmiMemberTeam();
}
return jmiMemberTeam;
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command,
BindException errors)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering 'onSubmit' method...");
}
JmiMemberTeam jmiMemberTeam = (JmiMemberTeam) command;
boolean isNew = (jmiMemberTeam.getCode() == null);
Locale locale = request.getLocale();
String key=null;
String strAction = request.getParameter("strAction");
if ("deleteJmiMemberTeam".equals(strAction) ) {
jmiMemberTeamManager.removeJmiMemberTeam(jmiMemberTeam.getCode().toString());
key="jmiMemberTeam.delete";
}else if ("addJmiMemberTeam".equals(strAction) ) {
CommonRecord crm=RequestUtil.toCommonRecord(request);
crm.setValue("code", jmiMemberTeam.getCode());
//判断是否已经存在团队编码
boolean isExist = jmiMemberTeamManager.isExist(crm, "0");
if(isExist){
errors.rejectValue("code","error.jmimemberteam.existed");
return showForm(request, response, errors);
}
jmiMemberTeam.setCode(jmiMemberTeam.getCode().replace(" ", "").trim());
jmiMemberTeam.setName(jmiMemberTeam.getName().replace(" ", "").trim());
jmiMemberTeamManager.saveJmiMemberTeam(jmiMemberTeam);
key="jmiMemberTeam.add";
}else if ("editJmiMemberTeam".equals(strAction) ) {
jmiMemberTeamManager.saveJmiMemberTeam(jmiMemberTeam);
key="jmiMemberTeam.update";
}
saveMessage(request, getText(SessionLogin.getLoginUser(request)
.getDefCharacterCoding(), key));
return new ModelAndView(getSuccessView());
}
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {
// TODO Auto-generated method stub
// binder.setAllowedFields(allowedFields);
// binder.setDisallowedFields(disallowedFields);
// binder.setRequiredFields(requiredFields);
super.initBinder(request, binder);
}
}
| 35.578947 | 81 | 0.774556 |
6d42b3fa777d0152adec6c3db311d21ee6e8db78 | 4,159 | package com.alsan_grand_lyon.aslangrandlyon.service;
import android.content.Context;
import android.os.AsyncTask;
import com.alsan_grand_lyon.aslangrandlyon.R;
import com.alsan_grand_lyon.aslangrandlyon.dao.MessageDAO;
import com.alsan_grand_lyon.aslangrandlyon.model.DataSingleton;
import com.alsan_grand_lyon.aslangrandlyon.model.Message;
import com.alsan_grand_lyon.aslangrandlyon.model.MessageFactory;
import com.alsan_grand_lyon.aslangrandlyon.model.User;
import com.alsan_grand_lyon.aslangrandlyon.view.chat.ChatActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Nico on 24/04/2017.
*/
public class DownloadMessagesTask extends AsyncTask<User, String, List<Message>> {
private ChatActivity chatActivity = null;
private MessageDAO messageDAO = null;
public DownloadMessagesTask(ChatActivity chatActivity) {
this.chatActivity = chatActivity;
this.messageDAO = new MessageDAO(chatActivity);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected List<Message> doInBackground(User... params) {
User user = params[0];
String url = chatActivity.getString(R.string.server_url) + chatActivity.getString(R.string.server_message);
int timeToSleep = 2000;
int numberOfNewMessages = 0;
int maxAttempt = 0;
List<Message> messages = new ArrayList<>();
while(numberOfNewMessages == 0 && maxAttempt < 3) {
try {
Thread.sleep(timeToSleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
messageDAO.open();
messageDAO.lock();
Message lastMessage = messageDAO.selectMostRecentFromServer();
if (lastMessage != null) {
HttpResult httpResult = CallAPI.getMessages(url, user.getToken(), user.getServerId(), lastMessage.getServerId());
if (httpResult.getCode() == 200) {
try {
JSONObject jsonObject = new JSONObject(httpResult.getOutput());
JSONArray jsonArray = jsonObject.getJSONArray("messages");
System.out.println("--->DownloadMessagesTask.doInBackground : " + jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
Message message = MessageFactory.createMessageFromJson(jsonArray.getJSONObject(i));
if (!messageDAO.exists(message.getServerId())) {
messageDAO.insert(message);
messages.add(message);
System.out.println("--->DownloadMessagesTask.doInBackground : " + message);
}
}
} catch (JSONException e) {
httpResult.setCode(-1);
}
} else {
System.out.println("--->DownloadMessagesTask.doInBackground : ERROR - " + httpResult.toString());
}
}
messageDAO.unlock();
messageDAO.close();
timeToSleep = 1000;
maxAttempt++;
numberOfNewMessages = messages.size();
}
return messages;
}
@Override
protected void onPostExecute(List<Message> result) {
messageDAO.open();
messageDAO.lock();
DataSingleton.getInstance().removeAllMessages();
DataSingleton.getInstance().addAllMessages(messageDAO.selectAll());
DataSingleton.getInstance().sortMessages();
messageDAO.unlock();
messageDAO.close();
chatActivity.setAslanIsTyping(false);
chatActivity.refreshMessagesListView();
if(result.size() > 0) {
chatActivity.readMessages(result);
chatActivity.scrollToBottom();
} else {
chatActivity.showToast(chatActivity.getString(R.string.alsan_cant_answer));
}
}
} | 35.853448 | 129 | 0.606396 |
bfd271b89f5d0a15355c87bbdd1052d95b5b9f58 | 209 | package org.firstinspires.ftc.teamcode.Autonomous;
public class VuforiaTest extends AutoBase{
@Override
public void runOpMode() throws InterruptedException {
//encoderDrive(0.1 , 3);
}
}
| 20.9 | 57 | 0.712919 |
12c4582d546a807a4ffb09e53f749a77c2b1c052 | 252 | package com.afqa123.shareplay.common;
public abstract class StoppableThread extends Thread {
private volatile boolean stop = false;
protected boolean isStopped() {
return stop;
}
public synchronized void requestStop() {
stop = true;
}
}
| 16.8 | 54 | 0.738095 |
fc9470fdd6ab765912b8a3740c3cd40b28225c16 | 1,150 | package com.blackmorse.hattrick.api.matches.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class LeagueLevelUnit {
@JacksonXmlProperty(localName = "LeagueLevelUnitID")
private Integer leagueLevelUnitId;
@JacksonXmlProperty(localName = "LeagueLevelUnitName")
private String leagueLevelUnitName;
@JacksonXmlProperty(localName = "LeagueLevel")
private Integer leagueLevel;
public Integer getLeagueLevelUnitId() {
return leagueLevelUnitId;
}
public void setLeagueLevelUnitId(Integer leagueLevelUnitId) {
this.leagueLevelUnitId = leagueLevelUnitId;
}
public String getLeagueLevelUnitName() {
return leagueLevelUnitName;
}
public void setLeagueLevelUnitName(String leagueLevelUnitName) {
this.leagueLevelUnitName = leagueLevelUnitName;
}
public Integer getLeagueLevel() {
return leagueLevel;
}
public void setLeagueLevel(Integer leagueLevel) {
this.leagueLevel = leagueLevel;
}
}
| 29.487179 | 74 | 0.748696 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.