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
|
---|---|---|---|---|---|
96a3356fba7c4a8ceec25d1bf007fd24a48f6a9c | 441 | package com.regent.rpush.dto.enumration;
/**
* 方案值类型
*
* @author 钟宝林
* @since 2021/4/5/005 10:29
**/
public enum SchemeValueType {
AUTO,
INTEGER,
DECIMAL,
STRING,
BOOLEAN,
TEXTAREA,
// ===========以下为特殊处理的类型============
/**
* 接收人分组
*/
RECEIVER_GROUP,
/**
* 接收人
*/
RECEIVER,
/**
* 多对象输入
*/
MULTI_OBJ_INPUT,
/**
* 多选
*/
SELECT
;
}
| 11.605263 | 40 | 0.44898 |
a99662cadb164137308c3549742a407141a35f5b | 586 | package br.com.project.api.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.hateoas.RepresentationModel;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ProductDto extends RepresentationModel<ProductDto> {
@ApiModelProperty(hidden = true)
private Long id;
@NotNull
private String name;
@NotNull
private BigDecimal price;
}
| 21.703704 | 65 | 0.800341 |
ccb3bd845ae24d2b80af9436d171ebb5564e3f6e | 827 | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
int k = in.nextInt();
int prod = 0;
String num = in.next();
for (int index=0; index<(n-k); index++) {
String sub = num.substring(index, index+k);
int temp = 1;
for(int i=0; i<k; i++) {
temp *= Integer.parseInt(sub.substring(i, i+1));
}
if (temp > prod)
prod = temp;
}
System.out.println(prod);
}
}
}
| 27.566667 | 68 | 0.449819 |
e999b932b8b2f5e11b2c2af4a4614ac441b6b342 | 966 | package io.delta.sql.parser;
/**
* Fork from <code>org.apache.spark.sql.catalyst.parser.PostProcessor</code>.
* <p>
* @see https://github.com/apache/spark/blob/v2.4.4/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/ParseDriver.scala#L248
*/
public class PostProcessor$ extends io.delta.sql.parser.DeltaSqlBaseBaseListener implements scala.Product, scala.Serializable {
/**
* Static reference to the singleton instance of this Scala object.
*/
public static final PostProcessor$ MODULE$ = null;
public PostProcessor$ () { throw new RuntimeException(); }
/** Remove the back ticks from an Identifier. */
public void exitQuotedIdentifier (io.delta.sql.parser.DeltaSqlBaseParser.QuotedIdentifierContext ctx) { throw new RuntimeException(); }
/** Treat non-reserved keywords as Identifiers. */
public void exitNonReserved (io.delta.sql.parser.DeltaSqlBaseParser.NonReservedContext ctx) { throw new RuntimeException(); }
}
| 53.666667 | 139 | 0.755694 |
c6515dfb8941e0a960d1116c5433135ac1ab998b | 450 | package net.la.lega.mod.item;
import net.la.lega.mod.initializer.LItemGroups;
import net.la.lega.mod.loader.LLoader;
import net.minecraft.item.Item;
import net.minecraft.util.Identifier;
public class RiceOilBottle extends Item
{
public static final Identifier ID = new Identifier(LLoader.MOD_ID, "rice_oil_bottle");
public RiceOilBottle()
{
super(new Settings().group(LItemGroups.LALEGA_INGREDIENTS).maxCount(16));
}
}
| 26.470588 | 90 | 0.746667 |
ad7961bb12bdc0cded9b302a5fb9a884a9d01681 | 506 | package ml.sun.demo.controller;
import ml.sun.demo.common.CommonResult;
import ml.sun.demo.service.IStudentService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("stu")
public class StudentController {
@Resource
private IStudentService service;
@GetMapping("get/{id}")
public CommonResult<?> getEntityById(@PathVariable String id) {
return CommonResult.success(service.findById(Long.parseLong(id)));
}
}
| 25.3 | 74 | 0.756917 |
fe554e5d1bc4805164d27a95e4db28df5792a572 | 1,426 | package com.sap.olingo.jpa.processor.core.testmodel;
import java.util.List;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
@Entity
@Table(schema = "\"OLINGO\"", name = "\"Collections\"")
public class Collection {
@Id
@Column(name = "\"ID\"")
private String iD;
// Collection as part of complex
@Embedded
private CollectionPartOfComplex complex;
// Collection with nested complex
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(schema = "\"OLINGO\"", name = "\"NestedComplex\"",
joinColumns = @JoinColumn(name = "\"ID\""))
private List<CollcetionNestedComplex> nested; // Must not be assigned to an ArrayList
public String getID() {
return iD;
}
public void setID(String iD) {
this.iD = iD;
}
public CollectionPartOfComplex getComplex() {
return complex;
}
public void setComplex(CollectionPartOfComplex complex) {
this.complex = complex;
}
public List<CollcetionNestedComplex> getNested() {
return nested;
}
public void setNested(List<CollcetionNestedComplex> nested) {
this.nested = nested;
}
}
| 24.586207 | 88 | 0.699158 |
daefa57721841e15b1d1c0527a135b395e9debed | 298 | package com.csis3275.group4.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.csis3275.group4.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends MongoRepository<User, String>{
}
| 24.833333 | 71 | 0.812081 |
c117e632afe7280030f5bc3cb17da6229b47fb91 | 930 | package com.jason.se.simple.composite;
import java.util.Arrays;
import java.util.List;
public class CihSort {
public static void main(String[] args) {
int[] arr={2 , 17, 16, 16, 7, 31, 39, 32, 38 , 11};
List<?> list=bubbleSort(arr);
System.out.println(list.get(0));
}
//1.冒泡排序(找出每轮比较的最大的数,往上冒)
public static List<?> bubbleSort(int[] arr){
for(int i=0,len=arr.length;i<len;i++)
{
System.out.print("i:"+arr[i]);
for (int j = i+1; j < arr.length; j++) {
System.out.print(" j:"+arr[j]);
int temp;
if (arr[i]>arr[j]) {
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
System.out.println();
}
System.out.println(Arrays.asList( arr) );
return Arrays.asList(arr);
}
//2.选择排序(每轮找出最小的对号入座)
public static List<int[]> selectSort(int[] arr){
return Arrays.asList(arr);
}
}
| 23.846154 | 54 | 0.539785 |
c1a008c83e2acec6372e01773f9a238393c0072a | 588 | package b.m.a.t;
import b.m.a.r;
import java.util.Comparator;
public class n implements Comparator<r> {
/* renamed from: h reason: collision with root package name */
public final /* synthetic */ r f5976h;
/* renamed from: i reason: collision with root package name */
public final /* synthetic */ o f5977i;
public n(o oVar, r rVar) {
this.f5977i = oVar;
this.f5976h = rVar;
}
public int compare(Object obj, Object obj2) {
return Float.compare(this.f5977i.a((r) obj2, this.f5976h), this.f5977i.a((r) obj, this.f5976h));
}
}
| 25.565217 | 104 | 0.634354 |
397faeaeef060abaade74bfcf0b3c1b7bcab3c30 | 2,720 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.avs.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/** NSX DHCP Server. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "dhcpType")
@JsonTypeName("SERVER")
@Fluent
public final class WorkloadNetworkDhcpServer extends WorkloadNetworkDhcpEntity {
@JsonIgnore private final ClientLogger logger = new ClientLogger(WorkloadNetworkDhcpServer.class);
/*
* DHCP Server Address.
*/
@JsonProperty(value = "serverAddress")
private String serverAddress;
/*
* DHCP Server Lease Time.
*/
@JsonProperty(value = "leaseTime")
private Long leaseTime;
/**
* Get the serverAddress property: DHCP Server Address.
*
* @return the serverAddress value.
*/
public String serverAddress() {
return this.serverAddress;
}
/**
* Set the serverAddress property: DHCP Server Address.
*
* @param serverAddress the serverAddress value to set.
* @return the WorkloadNetworkDhcpServer object itself.
*/
public WorkloadNetworkDhcpServer withServerAddress(String serverAddress) {
this.serverAddress = serverAddress;
return this;
}
/**
* Get the leaseTime property: DHCP Server Lease Time.
*
* @return the leaseTime value.
*/
public Long leaseTime() {
return this.leaseTime;
}
/**
* Set the leaseTime property: DHCP Server Lease Time.
*
* @param leaseTime the leaseTime value to set.
* @return the WorkloadNetworkDhcpServer object itself.
*/
public WorkloadNetworkDhcpServer withLeaseTime(Long leaseTime) {
this.leaseTime = leaseTime;
return this;
}
/** {@inheritDoc} */
@Override
public WorkloadNetworkDhcpServer withDisplayName(String displayName) {
super.withDisplayName(displayName);
return this;
}
/** {@inheritDoc} */
@Override
public WorkloadNetworkDhcpServer withRevision(Long revision) {
super.withRevision(revision);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
@Override
public void validate() {
super.validate();
}
}
| 28.041237 | 102 | 0.681618 |
4218903baa6fd846851fb0259e6483900fd655b0 | 432 | package FlyWeight;
public class FlyWeightFactory {
private static Map<ReceiptEnum,,Receipt> listReceipe= new HashMap<ReceiptEnum,Receipt>();
public Receipt getReceipt(ReceiptType type) {
Receipt = new Receipt(type);
listReceipe.put(type,receipt);
return receipt;
/* switch(type) {
case:type:{
}
default:
throw new IllegalArgumentException();
}*/
}
}
| 24 | 94 | 0.625 |
e267a8d9402e25ad2f906d08661e87a9ebd2818d | 1,162 | package org.minijax.rs;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.MessageBodyWriter;
public class WidgetWriter implements MessageBodyWriter<Widget> {
@Override
public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
return type == Widget.class;
}
@Override
public void writeTo(
final Widget widget,
final Class<?> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders,
final OutputStream entityStream)
throws IOException, WebApplicationException {
entityStream.write(String.format("(widget %s %s)", widget.getId(), widget.getValue()).getBytes(StandardCharsets.UTF_8));
}
}
| 33.2 | 136 | 0.707401 |
0fce76441b2f54460ab97e2a4ddc53e7b34f8cd1 | 12,018 | package com.rainbow_umbrella.wopogo_medals;
import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.PixelFormat;
import android.media.projection.MediaProjectionManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.app.PendingIntent;
import android.os.RemoteException;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import java.util.ArrayList;
import android.graphics.Bitmap;
import com.google.android.gms.vision.text.TextRecognizer;
/**
* An overlay foregroud service which provides a button which can be used to screen grab the current
* screen and perform OCR on it.
*
*/
public class OverlayService extends Service implements View.OnTouchListener, OcrTask.IOwner {
private static final String TAG = OverlayService.class.getSimpleName();
ArrayList<Messenger> mClients = new ArrayList<Messenger>();
/** Holds last value set by a client. */
int mValue = 0;
/**
* Command to the service to register a client, receiving callbacks
* from the service. The Message's replyTo field must be a Messenger of
* the client where callbacks should be sent.
*/
static final int MSG_REGISTER_CLIENT = 1;
/**
* Command to the service to unregister a client, ot stop receiving callbacks
* from the service. The Message's replyTo field must be a Messenger of
* the client as previously given with MSG_REGISTER_CLIENT.
*/
static final int MSG_UNREGISTER_CLIENT = 2;
/**
* Command to service to set a new value. This can be sent to the
* service to supply a new value, and will be sent by the service to
* any registered clients with the new value.
*/
static final int MSG_SET_VALUE = 3;
static final int MSG_SEND_TEXT_BLOCK = 4;
static final int MSG_HIDE_BUTTON = 5;
static final int MSG_SHOW_BUTTON = 6;
static final int MSG_CLOSE_APP = 7;
ScreenGrabTask mScreenGrabTask = null;
static final int REQUEST_SCREEN_GRAB = 9010;
/**
* Handler of incoming messages from clients.
*/
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_VALUE:
mValue = msg.arg1;
for (int i=mClients.size()-1; i>=0; i--) {
try {
mClients.get(i).send(Message.obtain(null,
MSG_SET_VALUE, mValue, 0));
} catch (RemoteException e) {
// The client is dead. Remove it from the list;
// we are going through the list from back to front
// so this is safe to do inside the loop.
mClients.remove(i);
}
}
break;
case MSG_HIDE_BUTTON:
overlayButton.setVisibility(View.INVISIBLE);
break;
case MSG_SHOW_BUTTON:
overlayButton.setVisibility(View.VISIBLE);
default:
super.handleMessage(msg);
}
}
}
/**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger(new IncomingHandler());
private WindowManager windowManager;
private View floatyView;
public View overlayButton;
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private static int FOREGROUND_ID=1234;
public static int REQUEST_CLOSE=9999;
private DisplayMetrics mMetrics;
private MediaProjectionManager mMediaProjectionManager;
private TextRecognizer mTextRecognizer;
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mMetrics = new DisplayMetrics();
mMediaProjectionManager = (MediaProjectionManager) getSystemService
(Context.MEDIA_PROJECTION_SERVICE);
mTextRecognizer = new TextRecognizer.Builder(this).build();
MainActivity.instance().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
addOverlayView();
Notification.Builder b=new Notification.Builder(this);
/*
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
*/
Intent notificationIntent = new Intent("action_close_app");
PendingIntent contentIntent = PendingIntent.getBroadcast(
this, REQUEST_CLOSE,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
startForeground(FOREGROUND_ID,
b.setOngoing(true)
.setContentTitle(getString(R.string.title_activity_main))
.setContentText("Click me to stop WoPoGo Medals")
.setSmallIcon(R.drawable.icon_status)
.setTicker(getString(R.string.screen_cap))
.setContentIntent(contentIntent)
.setAutoCancel(true)
.build());
IntentFilter filter = new IntentFilter();
filter.addAction("action_close_app");
registerReceiver(receiver, filter);
}
private WindowManager.LayoutParams layoutParams;
private void addOverlayView() {
layoutParams =
new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
layoutParams.gravity = Gravity.TOP | Gravity.LEFT; //Gravity.NO_GRAVITY; // was Gravity.CENTER | Gravity.START;
DisplayMetrics displayMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
// TODO: 48 = icon size.
layoutParams.x = (displayMetrics.widthPixels - 48) / 2;
layoutParams.y = (displayMetrics.heightPixels - 48) / 2;
FrameLayout interceptorLayout = new FrameLayout(this) {
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Only fire on the ACTION_DOWN event, or you'll get two events (one for _DOWN, one for _UP)
if (event.getAction() == KeyEvent.ACTION_DOWN) {
// Check if the HOME button is pressed
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
Log.v(TAG, "BACK Button Pressed");
// As we've taken action, we'll return true to prevent other apps from consuming the event as well
return true;
}
}
// Otherwise don't intercept the event
return super.dispatchKeyEvent(event);
}
};
floatyView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
inflate(R.layout.floating_view, interceptorLayout);
overlayButton = floatyView.findViewById(R.id.overlay_button);
overlayButton.setOnTouchListener(this);
overlayButton.setVisibility(View.INVISIBLE);
windowManager.addView(floatyView, layoutParams);
}
@Override
public void onDestroy() {
super.onDestroy();
if (floatyView != null) {
windowManager.removeView(floatyView);
floatyView = null;
}
unregisterReceiver(receiver);
}
private void sendMessage(String text) {
Message msg = Message.obtain(null, MSG_SET_VALUE, 0, 0);
msg.obj = text;
for (int i=mClients.size()-1; i>=0; i--) {
try {
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list;
// we are going through the list from back to front
// so this is safe to do inside the loop.
mClients.remove(i);
}
}
}
private float downRawX, downRawY, dX, dY;
private final float CLICK_DRAG_TOLERANCE = 10.0f;
public boolean performClick() {
if (mScreenGrabTask == null) {
overlayButton.setVisibility(View.INVISIBLE);
mScreenGrabTask = new ScreenGrabTask(this, MainActivity.instance().mResultCode,
MainActivity.instance().mScreenCapResultData, mMetrics, mMediaProjectionManager);
mScreenGrabTask.execute("Value");
}
return true;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Log.v(TAG, "onTouch...");
int action = motionEvent.getAction();
if (action == MotionEvent.ACTION_DOWN) {
downRawX = motionEvent.getRawX();
downRawY = motionEvent.getRawY();
dX = layoutParams.x - downRawX;
dY = layoutParams.y - downRawY;
return true; // Consumed
} else if (action == MotionEvent.ACTION_MOVE) {
int viewWidth = 48;
int viewHeight = 48;
int parentWidth = Resources.getSystem().getDisplayMetrics().widthPixels;
int parentHeight = Resources.getSystem().getDisplayMetrics().heightPixels;
float newX = motionEvent.getRawX() + dX;
newX = Math.max(0, newX); // Don't allow the FAB past the left hand side of the parent
newX = Math.min(parentWidth - viewWidth, newX); // Don't allow the FAB past the right hand side of the parent
float newY = motionEvent.getRawY() + dY;
Log.i(TAG, "NewY = " + Float.toString(newY));
newY = Math.max(0, newY); // Don't allow the FAB past the top of the parent
newY = Math.min(parentHeight - viewHeight, newY); // Don't allow the FAB past the bottom of the parent
layoutParams.x = (int)newX;
layoutParams.y = (int)newY;
windowManager.updateViewLayout(floatyView, layoutParams);
/*
view.animate()
.x(newX)
.y(newY)
.setDuration(0)
.start();
*/
return true; // Consumed
} else if (action == MotionEvent.ACTION_UP) {
float upRawX = motionEvent.getRawX();
float upRawY = motionEvent.getRawY();
float upDX = upRawX - downRawX;
float upDY = upRawY - downRawY;
if (Math.abs(upDX) < CLICK_DRAG_TOLERANCE && Math.abs(upDY) < CLICK_DRAG_TOLERANCE) { // A click
return performClick();
} else { // A drag
return true; // Consumed
}
}
return false;
}
OcrTask mOcrTask = null;
public void onScreenGrab(Bitmap bitmap) {
Log.d(TAG, "Received bitmap");
mOcrTask = new OcrTask(this, this);
mOcrTask.execute(bitmap);
mScreenGrabTask = null;
}
/*
// Kill service
onDestroy();
*/
@Override
public void onTextRecognizerResponse(String response) {
overlayButton.setVisibility(View.VISIBLE);
sendMessage(response);
mOcrTask = null;
}
/**
* Handle broadcast from Notification and close the app.
*/
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain(null, MSG_CLOSE_APP, 0, 0);
msg.obj = "CLOSE_APP";
for (int i=mClients.size()-1; i>=0; i--) {
try {
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list;
// we are going through the list from back to front
// so this is safe to do inside the loop.
mClients.remove(i);
}
}
}
};
}
| 31.134715 | 115 | 0.667582 |
4212cf9ad98cf2bd6ffa5dacd1322563b92c1203 | 8,945 | /*
*
* Copyright (c) 2013-2021, Alibaba Group Holding Limited;
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.aliyun.polardbx.binlog.domain.po;
import lombok.Builder;
import javax.annotation.Generated;
import java.util.Date;
@Builder
public class BinlogPhyDdlHistory {
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.676+08:00",
comments = "Source field: binlog_phy_ddl_history.id")
private Integer id;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.gmt_created")
private Date gmtCreated;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.gmt_modified")
private Date gmtModified;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.tso")
private String tso;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.binlog_file")
private String binlogFile;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.pos")
private Integer pos;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.storage_inst_id")
private String storageInstId;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.db_name")
private String dbName;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.extra")
private String extra;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.ddl")
private String ddl;
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.676+08:00",
comments = "Source Table: binlog_phy_ddl_history")
public BinlogPhyDdlHistory(Integer id, Date gmtCreated, Date gmtModified, String tso, String binlogFile,
Integer pos, String storageInstId, String dbName, String extra, String ddl) {
this.id = id;
this.gmtCreated = gmtCreated;
this.gmtModified = gmtModified;
this.tso = tso;
this.binlogFile = binlogFile;
this.pos = pos;
this.storageInstId = storageInstId;
this.dbName = dbName;
this.extra = extra;
this.ddl = ddl;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.676+08:00",
comments = "Source Table: binlog_phy_ddl_history")
public BinlogPhyDdlHistory() {
super();
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.676+08:00",
comments = "Source field: binlog_phy_ddl_history.id")
public Integer getId() {
return id;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.676+08:00",
comments = "Source field: binlog_phy_ddl_history.id")
public void setId(Integer id) {
this.id = id;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.gmt_created")
public Date getGmtCreated() {
return gmtCreated;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.gmt_created")
public void setGmtCreated(Date gmtCreated) {
this.gmtCreated = gmtCreated;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.gmt_modified")
public Date getGmtModified() {
return gmtModified;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.gmt_modified")
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.tso")
public String getTso() {
return tso;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.tso")
public void setTso(String tso) {
this.tso = tso == null ? null : tso.trim();
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.binlog_file")
public String getBinlogFile() {
return binlogFile;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.binlog_file")
public void setBinlogFile(String binlogFile) {
this.binlogFile = binlogFile == null ? null : binlogFile.trim();
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.pos")
public Integer getPos() {
return pos;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.pos")
public void setPos(Integer pos) {
this.pos = pos;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.677+08:00",
comments = "Source field: binlog_phy_ddl_history.storage_inst_id")
public String getStorageInstId() {
return storageInstId;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.storage_inst_id")
public void setStorageInstId(String storageInstId) {
this.storageInstId = storageInstId == null ? null : storageInstId.trim();
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.db_name")
public String getDbName() {
return dbName;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.db_name")
public void setDbName(String dbName) {
this.dbName = dbName == null ? null : dbName.trim();
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.extra")
public String getExtra() {
return extra;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.extra")
public void setExtra(String extra) {
this.extra = extra == null ? null : extra.trim();
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.ddl")
public String getDdl() {
return ddl;
}
@Generated(value = "org.mybatis.generator.api.MyBatisGenerator", date = "2020-12-18T11:31:09.678+08:00",
comments = "Source field: binlog_phy_ddl_history.ddl")
public void setDdl(String ddl) {
this.ddl = ddl == null ? null : ddl.trim();
}
} | 43.004808 | 108 | 0.683622 |
fb6bea49a2879aa41b86b12c01b4c94b693df5f3 | 2,268 | /*
* Copyright 2020 Haulmont.
*
* 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.haulmont.cuba.web.gui.facets;
import com.haulmont.cuba.gui.components.MessageDialogFacet;
import com.haulmont.cuba.web.gui.components.WebMessageDialogFacet;
import io.jmix.ui.facet.MessageDialogFacetProvider;
import io.jmix.ui.xml.layout.ComponentLoader;
import org.dom4j.Element;
import org.springframework.stereotype.Component;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
@Component("cuba_MessageDialogFacetProvider")
public class CubaMessageDialogFacetProvider extends MessageDialogFacetProvider {
@Override
public Class getFacetClass() {
return MessageDialogFacet.class;
}
@Override
public MessageDialogFacet create() {
return new WebMessageDialogFacet();
}
@Override
public void loadFromXml(io.jmix.ui.component.MessageDialogFacet facet, Element element, ComponentLoader.ComponentContext context) {
super.loadFromXml(facet, element, context);
if (facet instanceof MessageDialogFacet) {
loadMaximized((MessageDialogFacet) facet, element);
}
}
protected void loadMaximized(MessageDialogFacet facet, Element element) {
String maximized = element.attributeValue("maximized");
if (isNotEmpty(maximized)) {
facet.setMaximized(Boolean.parseBoolean(maximized));
}
}
@Override
protected void loadStyleName(io.jmix.ui.component.MessageDialogFacet facet, Element element) {
String styleName = element.attributeValue("styleName");
if (isNotEmpty(styleName)) {
facet.setStyleName(styleName);
}
}
}
| 34.892308 | 136 | 0.711199 |
3d2d1a237bb916e3414033ef99bd62e9bce7f5bc | 1,315 | /*
* Copyright (c) 2020. Adam Arthur Faizal
*/
package Praktikum09Collections;
import java.util.HashMap;
import java.util.Map;
public class HashMap3 {
public static void main(String[] args) {
HashMap<Integer, String> hashMap2 = new HashMap<>();
hashMap2.put(100,"Adam");
hashMap2.put(101,"Arthur");
hashMap2.put(102,"Faizal");
System.out.println("Initial list of elements : ");
for (Map.Entry elemen : hashMap2.entrySet()) {
System.out.println(elemen.getKey() + " " + elemen.getValue());
}
System.out.println("Updated list of elements : ");
hashMap2.replace(102, "Putih");
for (Map.Entry elemen : hashMap2.entrySet()) {
System.out.println(elemen.getKey() + " " + elemen.getValue());
}
System.out.println("Updated list of elements : ");
hashMap2.replace(101, "Arthur", "Mbah");
for (Map.Entry elemen : hashMap2.entrySet()) {
System.out.println(elemen.getKey() + " " + elemen.getValue());
}
System.out.println("Updated list of elements : ");
hashMap2.replaceAll((a,b) -> "Mulyosugito");
for (Map.Entry elemen : hashMap2.entrySet()) {
System.out.println(elemen.getKey() + " " + elemen.getValue());
}
}
}
| 34.605263 | 74 | 0.587072 |
fec696235a7d0c5c5ea0cacc1034658ee14a84b8 | 859 | package com.example.fugle_realtime_java_sdk_core.dto.response.chart;
import java.util.List;
public class Chart {
private List<Double> o;
private List<Double> h;
private List<Double> l;
private List<Double> c;
private List<Double> v;
private List<Double> t;
public List<Double> getO() {
return o;
}
public void setO(List<Double> o) {
this.o = o;
}
public List<Double> getH() {
return h;
}
public void setH(List<Double> h) {
this.h = h;
}
public List<Double> getL() {
return l;
}
public void setL(List<Double> l) {
this.l = l;
}
public List<Double> getC() {
return c;
}
public void setC(List<Double> c) {
this.c = c;
}
public List<Double> getV() {
return v;
}
public void setV(List<Double> v) {
this.v = v;
}
public List<Double> getT() {
return t;
}
public void setT(List<Double> t) {
this.t = t;
}
}
| 16.843137 | 68 | 0.641444 |
2597d4205c5c7e7b074783af760db84f17c55570 | 661 | package com.example.pass.view.popWindows.fontstylePopWindows.bean;
import android.graphics.Typeface;
public class TextTypeface {
/**
* 本地ttf文件路径
*/
private String ttf_path;
/**
* 字体样式文字解释
*/
private String text;
public TextTypeface(String ttf_path, String text) {
this.ttf_path = ttf_path;
this.text = text;
}
public String getTtf_path() {
return ttf_path;
}
public void setTtf_path(String ttf_path) {
this.ttf_path = ttf_path;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
} | 17.394737 | 66 | 0.603631 |
fae5e77c18da8d9717460796f8c9d453e37cb209 | 1,423 | package game;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/** CODE WRITTEN BY: MARY GOONERATNE (@mmg53)
* YouWin() is a object definition to define a scene to be displayed at the victory of
* Breakout game
*
*/
public class YouWin{
public static final int SIZE = 400;
public static final String YOU_WIN_IMAGE = "youWin.gif";
private Scene scene;
private ImageView image;
/** Initializes the YouWin object by creating a scene with the correct image
*
* @param width width of scene
* @param height height of scene
*/
public YouWin(int width, int height) {
var root = new Group();
this.scene = new Scene(root, width, height);
this.setImage();
root.getChildren().add(this.getImage());
}
private void setImage(){
var getSplashScreenImage = new Image(this.getClass().getClassLoader().getResourceAsStream(YOU_WIN_IMAGE));
this.image = new ImageView(getSplashScreenImage);
this.image.setPreserveRatio(true);
this.image.setFitWidth(SIZE);
}
private ImageView getImage(){
return this.image;
}
/**Getter method to get scene to show on stage in SceneController
*
* @return Scene object YouWin class showing victory message
*/
public Scene getScene(){
return this.scene;
}
} | 28.46 | 114 | 0.668306 |
821e780aadc70b00b36abf96ee6cbee84d15172a | 29,275 | /*
* Copyright 2006-2014 smartics, Kronseder & Reiner GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.redhat.rcm.maven.plugin.buildmetadata;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.scm.ScmBranch;
import org.apache.maven.scm.manager.ScmManager;
import org.apache.maven.settings.Settings;
import org.codehaus.plexus.util.StringUtils;
import com.redhat.rcm.maven.plugin.buildmetadata.common.Constant;
import com.redhat.rcm.maven.plugin.buildmetadata.common.ScmControl;
import com.redhat.rcm.maven.plugin.buildmetadata.common.ScmCredentials;
import com.redhat.rcm.maven.plugin.buildmetadata.common.ScmInfo;
import com.redhat.rcm.maven.plugin.buildmetadata.data.HostMetaDataProvider;
import com.redhat.rcm.maven.plugin.buildmetadata.data.MavenMetaDataProvider;
import com.redhat.rcm.maven.plugin.buildmetadata.data.MavenMetaDataSelection;
import com.redhat.rcm.maven.plugin.buildmetadata.data.ScmMetaDataProvider;
import com.redhat.rcm.maven.plugin.buildmetadata.io.AdditionalLocationsSupport;
import com.redhat.rcm.maven.plugin.buildmetadata.io.BuildPropertiesFileHelper;
import com.redhat.rcm.maven.plugin.buildmetadata.io.BuildXmlFileHelper;
import com.redhat.rcm.maven.plugin.buildmetadata.scm.ScmNoRevisionException;
import com.redhat.rcm.maven.plugin.buildmetadata.util.FilePathNormalizer;
/**
* Provides the build properties. This information is also written to a
* <code>build.properties</code> file.
*
* @goal provide-buildmetadata
* @phase initialize
* @requiresProject
* @threadSafe
* @since 1.0
* @description Provides a build meta data to the build process.
*/
public final class BuildMetaDataMojo extends AbstractBuildMojo // NOPMD
{ // NOPMD
// ********************************* Fields *********************************
// --- constants ------------------------------------------------------------
// --- members --------------------------------------------------------------
// ... Mojo infrastructure ..................................................
/**
* The user's settings.
*
* @parameter expression="${settings}"
* @required
* @readonly
* @since 1.0
*/
private Settings settings;
/**
* If set to <code>true</code>, build properties will be generate even if they
* already exist in the target folder.
*
* @parameter default-value="false"
* @since 1.0
*/
private boolean forceNewProperties;
/**
* In offline mode the plugin will not generate revision information.
*
* @parameter default-value="${settings.offline}"
* @required
* @readonly
* @since 1.0
*/
private boolean offline;
/**
* Add SCM information if set to <code>true</code>, skip it, if set to
* <code>false</code>. If you are not interested in SCM information, set this
* to <code>false</code>.
* <p>
* For security reasons you may want to remove the properties file from the
* META-INF folder. Please refer to <code>propertiesOutputFile</code>
* property.
* </p>
*
* @parameter expression="${buildMetaData.addScmInfo}" default-value="true"
* @since 1.0
*/
private boolean addScmInfo;
/**
* Fail if revision is requested to be retrieved, access to SCM is provided,
* system is online, nothing should prevent the build from fetching the
* information.
* <p>
* If set to <code>true</code> the build will fail, if revision cannot be
* fetched under the conditions mentioned above. If set to <code>false</code>
* the build will continue silently so that the meta data do not contain the
* revision.
* </p>
*
* @parameter expression="${buildMetaData.failOnMissingRevision}"
* default-value="false"
* @since 1.0
*/
private boolean failOnMissingRevision;
/**
* Add host information if set to <code>true</code>, skip it, if set to
* <code>false</code>. If you are not interested in host information (e.g. for
* security reasons), set this to <code>false</code>.
* <p>
* For security reasons you may want to remove the properties file from the
* META-INF folder. Please refer to <code>propertiesOutputFile</code>
* property.
* </p>
*
* @parameter expression="${buildMetaData.addHostInfo}" default-value="true"
* @since 1.0
*/
private boolean addHostInfo;
/**
* Add user information if set to <code>true</code>, skip it, if set to
* <code>false</code>.
*
* @parameter expression="${buildMetaData.addUserInfo}" default-value="false"
* @since 1.0
*/
private boolean addUserInfo;
/**
* Add build date information if set to <code>true</code>, skip it, if set to
* <code>false</code>.
*
* @parameter expression="${buildMetaData.addBuildDateInfo}" default-value="true"
* @since 1.0
*/
private boolean addBuildDateInfo;
/**
* Add environment variables if set to <code>true</code>, skip it, if set to
* <code>false</code>. If you are not interested in the environment variables
* of the host (e.g. for security reasons), set this to <code>false</code>.
* <p>
* For security reasons you may want to remove the properties file from the
* META-INF folder. Please refer to <code>propertiesOutputFile</code>
* property.
* </p>
*
* @parameter expression="${buildMetaData.addEnvInfo}" default-value="false"
* @since 1.0
*/
private boolean addEnvInfo;
/**
* Add information about the Java runtime running the build if set to
* <code>true</code>, skip it, if set to <code>false</code>.
*
* @parameter expression="${buildMetaData.addJavaRuntimeInfo}"
* default-value="true"
* @since 1.0
*/
private boolean addJavaRuntimeInfo;
/**
* Add information about the operating system the build is run in if set to
* <code>true</code>, skip it, if set to <code>false</code>.
*
* @parameter expression="${buildMetaData.addOsInfo}" default-value="true"
* @since 1.0
*/
private boolean addOsInfo;
/**
* Add Maven execution information (all properties starting with
* <code>build.maven.execution</code>, like command line, goals, profiles,
* etc.) if set to <code>true</code>, skip it, if set to <code>false</code>.
* If you are not interested in execution information, set this to
* <code>false</code>.
* <p>
* For security reasons you may want to remove the properties file from the
* META-INF folder. Please refer to <code>propertiesOutputFile</code>
* property.
* </p>
*
* @parameter expression="${buildMetaData.addMavenExecutionInfo}"
* default-value="true"
* @since 1.0
*/
private boolean addMavenExecutionInfo;
/**
* Add project information (homepage URL, categories, tags, etc.) if set to
* <code>true</code>, skip it, if set to <code>false</code>. If you are not
* interested in execution information, set this to <code>false</code>.
*
* @parameter expression="${buildMetaData.addProjectInfo}"
* default-value="false"
* @since 1.1
*/
private boolean addProjectInfo;
/**
* While the command line may be useful to refer to for a couple of reasons,
* displaying it with the build properties is a security issue. Some plugins
* allow to read passwords as properties from the command line and this
* sensible data will be shown.
* <p>
* Therefore the command line is hidden by default (<code>true</code>). If you
* want to include this information, use a value of <code>false</code>.
* </p>
*
* @parameter expression="${buildMetaData.hideCommandLineInfo}"
* default-value="true"
* @since 1.0
*/
private boolean hideCommandLineInfo;
/**
* While the <code>MAVEN_OPTS</code> may be useful to refer to for a couple of
* reasons, displaying them with the build properties is a security issue.
* Some plugins allow to read passwords as properties from the command line
* and this sensible data will be shown.
* <p>
* Therefore the <code>MAVEN_OPTS</code> are hidden by default (
* <code>true</code>). If you want to include this information, use a value of
* <code>false</code>.
* </p>
* <p>
* This exclusion does not prevent the property from being written as part of
* <code>addEnvInfo</code>!
* </p>
*
* @parameter expression="${buildMetaData.hideMavenOptsInfo}"
* default-value="true"
* @since 1.0
*/
private boolean hideMavenOptsInfo;
/**
* While the <code>JAVA_OPTS</code> may be useful to refer to for a couple of
* reasons, displaying them with the build properties is a security issue.
* Some plugins allow to read passwords as properties from the command line
* and this sensible data will be shown.
* <p>
* Therefore the <code>JAVA_OPTS</code> are hidden by default (
* <code>true</code>). If you want to include this information, use a value of
* <code>false</code>.
* </p>
* <p>
* This exclusion does not prevent the property from being written as part of
* <code>addEnvInfo</code>!
* </p>
*
* @parameter expression="${buildMetaData.hideJavaOptsInfo}"
* default-value="true"
* @since 1.0
*/
private boolean hideJavaOptsInfo;
/**
* A simple flag to skip the generation of the build information. If set on
* the command line use <code>-DbuildMetaData.skip</code>.
*
* @parameter expression="${buildMetaData.skip}" default-value="false"
* @since 1.0
*/
private boolean skip;
/**
* If it should be checked if the local files are up-to-date with the remote
* files in the SCM repository. If the value is <code>true</code> the result
* of the check, including the list of changed files, is added to the build
* meta data.
*
* @parameter expression="${buildMetaData.validateCheckout}"
* default-value="true"
* @since 1.0
*/
private boolean validateCheckout;
/**
* Specifies the log level used for this plugin.
* <p>
* Allowed values are <code>SEVERE</code>, <code>WARNING</code>,
* <code>INFO</code> and <code>FINEST</code>.
* </p>
*
* @parameter expression="${buildMetaData.logLevel}"
* @since 1.0
*/
private String logLevel;
public String getLogLevel() {
return logLevel;
}
public void setLogLevel(String logLevel) {
this.logLevel = logLevel;
}
/**
* The manager instance to access the SCM system. Provides access to the
* repository and the provider information.
*
* @component
* @since 1.0
*/
private ScmManager scmManager;
/**
* Allows the user to choose which scm connection to use when connecting to
* the scm. Can either be "connection" or "developerConnection".
*
* @parameter default-value="connection"
* @required
* @since 1.0
*/
private String connectionType;
// ... core information .....................................................
/**
* The date pattern to use to format the build and revision dates. Please
* refer to the <a href =
* "http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html"
* >SimpleDateFormat</a> class for valid patterns.
*
* @parameter expression="${buildMetaData.buildDate.pattern}"
* default-value="dd.MM.yyyy"
* @since 1.0
*/
protected String buildDatePattern = Constant.DEFAULT_DATE_PATTERN; // NOPMD
/**
* The property to query for the build user.
*
* @parameter default-value="username"
* @since 1.0
*/
private String buildUserPropertyName;
// ... build information related ............................................
/**
* Flag to add the build date to the full version separated by a '-'. If
* <code>true</code> the build date is added, if <code>false</code> it is not.
*
* @parameter expression="${buildMetaData.addBuildDateToFullVersion}"
* default-value="true"
* @since 1.0
*/
private boolean addBuildDateToFullVersion;
// ... svn related ..........................................................
/**
* Used to specify the date format of the log entries that are retrieved from
* your SCM system.
*
* @parameter expression="${changelog.dateFormat}"
* default-value="yyyy-MM-dd HH:mm:ss"
* @required
* @since 1.0
*/
private String scmDateFormat;
/**
* Input dir. Directory where the files under SCM control are located.
*
* @parameter expression="${basedir}"
* @required
* @since 1.0
*/
private File basedir;
/**
* The user name (used by svn and starteam protocol).
*
* @parameter expression="${username}"
* @since 1.0
*/
private String userName;
/**
* The user password (used by svn and starteam protocol).
*
* @parameter expression="${password}"
* @since 1.0
*/
private String password;
/**
* The private key (used by java svn).
*
* @parameter expression="${privateKey}"
* @since 1.0
*/
private String privateKey;
/**
* The passphrase (used by java svn).
*
* @parameter expression="${passphrase}"
* @since 1.0
*/
private String passphrase;
/**
* The url of tags base directory (used by svn protocol).
*
* @parameter expression="${tagBase}"
* @since 1.0
*/
private String tagBase;
/**
* Flag to add the revision number to the full version separated by an 'r'. If
* <code>true</code> the revision number is added, if <code>false</code> it is
* not.
*
* @parameter expression="${buildMetaData.addReleaseNumberToFullVersion}"
* default-value="true"
* @since 1.0
*/
private boolean addReleaseNumberToFullVersion;
/**
* Flag to add the tag <code>-locally-modified</code> to the full version
* string to make visible that this artifact has been created with locally
* modified sources. This is often the case while the artifact is built while
* still working on an issue before it is committed to the SCM repository.
*
* @parameter expression="${buildMetaData.addLocallyModifiedTagToFullVersion}"
* default-value="true"
* @since 1.0
*/
private boolean addLocallyModifiedTagToFullVersion;
/**
* The range of the query in days to fetch change log entries from the SCM. If
* no change logs have been found, the range is incremented up to {@value
* com.redhat.rcm.maven.plugin.buildmetadata.scm.maven.ScmAccessInfo;#
* DEFAULT_RETRY_COUNT} (5) times. If no change log has been found after these
* {@value com.redhat.rcm.maven.plugin.buildmetadata.scm.maven.ScmAccessInfo;#
* DEFAULT_RETRY_COUNT} (5) additional queries, the revision number will not
* be set with a valid value.
*
* @parameter expression="${buildMetaData.queryRangeInDays}"
* default-value="30"
* @since 1.0
*/
private int queryRangeInDays;
/**
* Flag to fail if local modifications have been found. The value is
* <code>true</code> if the build should fail if there are modifications (any
* files not in-sync with the remote repository), <code>false</code> if the
* fact is only to be noted in the build properties.
*
* @parameter default-value="false"
* @since 1.0
*/
private boolean failOnLocalModifications;
/**
* The flag to ignore files and directories starting with a dot for checking
* modified files. This implicates that any files or directories, starting
* with a dot, are ignored when the check on changed files is run. If the
* value is <code>true</code>, dot files are ignored, if it is set to
* <code>false</code>, dot files are respected.
*
* @parameter default-value="true"
* @since 1.0
*/
private boolean ignoreDotFilesInBaseDir;
/**
* Flag to copy build report files to the <code>generated-sources</code>
* folder, if the Maven sources plugin is configured.
*
* @parameter default-value="true"
* @since 1.5.0
*/
private boolean addToGeneratedSources;
/**
* The list of locations the report files are to be copied to. If it is not
* absolute, the subfolder <code>META-INF</code> is appended.
*
* @parameter
* @since 1.5.0
*/
private List<String> addToLocations;
// ****************************** Initializer *******************************
// ****************************** Constructors ******************************
// ****************************** Inner Classes *****************************
// ********************************* Methods ********************************
// --- init -----------------------------------------------------------------
// --- get&set --------------------------------------------------------------
// --- business -------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
if (!skip)
{
super.execute();
final String baseDir = project.getBasedir().getAbsolutePath();
final FilePathNormalizer filePathNormalizer =
new FilePathNormalizer(baseDir);
final BuildPropertiesFileHelper helper =
new BuildPropertiesFileHelper(getLog(), propertiesOutputFile,
filePathNormalizer);
final Properties projectProperties = helper.getProjectProperties(project);
if (!isBuildPropertiesAlreadySet(projectProperties))
{
final Properties buildMetaDataProperties = new Properties();
if (isBuildPropertiesToBeRebuild())
{
createBuildProperties(helper, projectProperties,
buildMetaDataProperties);
}
else
{
getLog().info("Reusing previously built metadata file.");
helper.readBuildPropertiesFile(buildMetaDataProperties);
}
updateMavenEnvironment(buildMetaDataProperties, helper);
}
}
else
{
getLog().info("Skipping buildmetadata collection since skip=true.");
}
}
private void createBuildProperties(final BuildPropertiesFileHelper helper,
final Properties projectProperties,
final Properties buildMetaDataProperties) throws MojoExecutionException,
MojoFailureException
{
final Date buildDate = session.getStartTime();
provideBuildUser(projectProperties, buildMetaDataProperties);
provideMavenMetaData(buildMetaDataProperties);
provideHostMetaData(buildMetaDataProperties);
final ScmInfo scmInfo = provideScmMetaData(buildMetaDataProperties);
provideBuildDateMetaData(buildMetaDataProperties, buildDate);
provideBuildVersionMetaData(buildMetaDataProperties, buildDate);
// The custom providers are required to be run at the end.
// This allows these providers to access the information generated
// by the built-in providers.
provideBuildMetaData(buildMetaDataProperties, scmInfo, providers, false);
writeBuildMetaData(helper, buildMetaDataProperties);
}
private void writeBuildMetaData(final BuildPropertiesFileHelper helper,
final Properties buildMetaDataProperties) throws MojoExecutionException
{
final File propertiesFile =
helper.writePropertiesFile(buildMetaDataProperties);
final AdditionalLocationsSupport.Config config =
new AdditionalLocationsSupport.Config();
config.setAddToGeneratedSources(addToGeneratedSources).setAddToLocations(
addToLocations);
final AdditionalLocationsSupport additionalLocations =
new AdditionalLocationsSupport(project, config);
additionalLocations.handle(propertiesFile);
final boolean writable = !writeProtectFiles;
propertiesFile.setWritable(writable);
if (createXmlReport)
{
final String projectRootPath = project.getBasedir().getAbsolutePath();
final BuildXmlFileHelper xmlHelper =
new BuildXmlFileHelper(projectRootPath, getLog(), xmlOutputFile,
properties);
final File xmlFile = xmlHelper.writeXmlFile(buildMetaDataProperties);
additionalLocations.handle(xmlFile);
xmlFile.setWritable(writable);
}
}
private void provideMavenMetaData(final Properties buildMetaDataProperties)
{
final MavenMetaDataSelection selection = new MavenMetaDataSelection();
selection.setAddMavenExecutionInfo(addMavenExecutionInfo);
selection.setAddEnvInfo(addEnvInfo);
selection.setAddJavaRuntimeInfo(addJavaRuntimeInfo);
selection.setAddOsInfo(addOsInfo);
selection.setAddProjectInfo(addProjectInfo);
selection.setHideCommandLineInfo(hideCommandLineInfo);
selection.setHideJavaOptsInfo(hideJavaOptsInfo);
selection.setHideMavenOptsInfo(hideMavenOptsInfo);
selection.setSelectedSystemProperties(properties);
final MavenMetaDataProvider mavenMetaDataProvider =
new MavenMetaDataProvider(project, session, runtime, selection);
mavenMetaDataProvider.provideBuildMetaData(buildMetaDataProperties);
}
private ScmInfo provideScmMetaData(final Properties buildMetaDataProperties)
throws MojoFailureException
{
final ScmInfo scmInfo = createScmInfo();
try
{
final ScmMetaDataProvider scmMetaDataProvider =
new ScmMetaDataProvider(project, scmInfo);
scmMetaDataProvider.provideBuildMetaData(buildMetaDataProperties);
}
catch (final ScmNoRevisionException e)
{
if (failOnMissingRevision)
{
throw new MojoFailureException(e.getMessage()); // NOPMD
}
else
{
getLog().info( "Unable to determine SCM revision information "
+
(e.getCause() == null ? "" : e.getCause().getMessage()));
getLog().debug( "Unable to determine SCM revision information: ", e );
}
}
return scmInfo;
}
private void provideHostMetaData(final Properties buildMetaDataProperties)
throws MojoExecutionException
{
if (addHostInfo)
{
final HostMetaDataProvider hostMetaData = new HostMetaDataProvider();
hostMetaData.provideBuildMetaData(buildMetaDataProperties);
}
}
private void provideBuildDateMetaData(
final Properties buildMetaDataProperties, final Date buildDate)
{
if (addBuildDateInfo)
{
createBuildDate(buildMetaDataProperties, buildDate);
createYears(buildMetaDataProperties, buildDate);
}
}
private ScmInfo createScmInfo()
{
final ScmCredentials scmCredentials =
new ScmCredentials(settingsDecrypter, settings, userName, password,
privateKey, passphrase);
final ScmControl scmControl =
new ScmControl(failOnLocalModifications, ignoreDotFilesInBaseDir,
offline, addScmInfo, validateCheckout, failOnMissingRevision);
final ScmInfo scmInfo =
new ScmInfo(scmManager, connectionType, scmDateFormat, basedir,
scmCredentials, tagBase, queryRangeInDays, buildDatePattern,
scmControl, StringUtils.isNotBlank(remoteVersion) ? new ScmBranch(
remoteVersion) : null);
return scmInfo;
}
private boolean isBuildPropertiesToBeRebuild()
{
return forceNewProperties || !propertiesOutputFile.exists();
}
private boolean isBuildPropertiesAlreadySet(final Properties projectProperties)
{
return projectProperties.getProperty(Constant.PROP_NAME_FULL_VERSION) != null;
}
/**
* Provides the name of the user running the build. The value is either
* specified in the project properties or is taken from the Java system
* properties (<code>user.name</code>).
*
* @param projectProperties the project properties.
* @param buildMetaDataProperties the build meta data properties.
*/
private void provideBuildUser(final Properties projectProperties,
final Properties buildMetaDataProperties)
{
if (addUserInfo)
{
String userNameValue = System.getProperty("user.name");
if ((buildUserPropertyName != null))
{
final String value = projectProperties.getProperty(buildUserPropertyName);
if (!StringUtils.isBlank(value))
{
userNameValue = value;
}
}
if (userNameValue != null)
{
buildMetaDataProperties.setProperty(Constant.PROP_NAME_BUILD_USER, userNameValue);
}
}
}
/**
* Creates and adds the build date information.
*
* @param buildMetaDataProperties the build meta data properties.
* @param buildDate the date of the build.
* @return the formatted build date.
*/
private void createBuildDate(final Properties buildMetaDataProperties,
final Date buildDate)
{
final DateFormat format =
new SimpleDateFormat(buildDatePattern, Locale.ENGLISH);
final String buildDateString = format.format(buildDate);
final String timestamp = String.valueOf(buildDate.getTime());
buildMetaDataProperties.setProperty(Constant.PROP_NAME_BUILD_DATE,
buildDateString);
buildMetaDataProperties.setProperty(Constant.PROP_NAME_BUILD_DATE_PATTERN,
this.buildDatePattern);
buildMetaDataProperties.setProperty(Constant.PROP_NAME_BUILD_TIMESTAMP,
timestamp);
}
/**
* Adds the build and copyright year information.
*
* @param buildMetaDataProperties the build meta data properties.
* @param buildDate the build date to create the build year information.
*/
private void createYears(final Properties buildMetaDataProperties,
final Date buildDate)
{
final DateFormat yearFormat = new SimpleDateFormat("yyyy", Locale.ENGLISH);
final String buildYearString = yearFormat.format(buildDate);
buildMetaDataProperties.setProperty(Constant.PROP_NAME_BUILD_YEAR,
buildYearString);
final String inceptionYearString = project.getInceptionYear();
final String copyrightYearString =
(inceptionYearString == null ? buildYearString : (buildYearString
.equals(inceptionYearString) ? inceptionYearString
: inceptionYearString + '-' + buildYearString));
buildMetaDataProperties.setProperty(Constant.PROP_NAME_COPYRIGHT_YEAR,
copyrightYearString);
}
/**
* Adds the version information of the artifact.
* @param buildMetaDataProperties the build meta data properties.
* @param buildDate the date of the build.
*/
private void provideBuildVersionMetaData(final Properties buildMetaDataProperties, final Date buildDate)
{
final String version = project.getVersion();
buildMetaDataProperties.setProperty(Constant.PROP_NAME_VERSION, version);
buildMetaDataProperties.setProperty(Constant.PROP_NAME_GROUP_ID,
project.getGroupId());
buildMetaDataProperties.setProperty(Constant.PROP_NAME_ARTIFACT_ID,
project.getArtifactId());
final String fullVersion =
createFullVersion(buildMetaDataProperties, buildDate);
buildMetaDataProperties.setProperty(Constant.PROP_NAME_FULL_VERSION,
fullVersion);
}
/**
* Creates the full version string which may include the date, the build, and
* the revision.
*
* @param buildMetaDataProperties the generated build meta data properties.
* @param buildDate the date of the current build.
* @return the full version string.
*/
private String createFullVersion(final Properties buildMetaDataProperties,
final Date buildDate)
{
final String version = project.getVersion();
final DateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
final String datePart = format.format(buildDate);
final String revisionId =
buildMetaDataProperties.getProperty(Constant.PROP_NAME_SCM_REVISION_ID);
final String versionPrefix, versionSuffix;
if (version.endsWith("-SNAPSHOT"))
{
versionPrefix = version.substring(0, version.lastIndexOf('-'));
versionSuffix = "-SNAPSHOT";
}
else
{
versionPrefix = version;
versionSuffix = "";
}
final String modified;
if (addLocallyModifiedTagToFullVersion
&& "true".equals(buildMetaDataProperties
.getProperty(Constant.PROP_NAME_SCM_LOCALLY_MODIFIED)))
{
modified = "-locally-modified";
}
else
{
modified = "";
}
final String fullVersion =
versionPrefix
+ (addBuildDateToFullVersion ? '-' + datePart : "")
+ (addReleaseNumberToFullVersion
&& StringUtils.isNotBlank(revisionId) ? "r" + revisionId : "")
+ modified + versionSuffix;
return fullVersion;
}
// --- object basics --------------------------------------------------------
}
| 33.883102 | 106 | 0.672758 |
88c23edd9cdc997caf563d0aac4045750cb3b155 | 847 | package wybren_erik.hanzespel.dialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class ArrivedDialog extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("U bent gearriveerd!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
| 32.576923 | 80 | 0.661157 |
cc8b16d9eed119307be41e823f36ca31c77040c4 | 1,262 | package com.chizganov.puzzlers.leetcode.may;
import com.chizganov.puzzlers.util.TestSource;
import org.junit.jupiter.params.ParameterizedTest;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import static java.nio.file.Files.newBufferedReader;
import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
class FindAllAnagramsTest {
@ParameterizedTest
@TestSource(FindAllAnagrams.class)
void findAnagrams(FindAllAnagrams solution, Path input, Path output) throws IOException {
try (BufferedReader in = newBufferedReader(input);
BufferedReader out = newBufferedReader(output)) {
String string = in.readLine();
String anagram = in.readLine();
List<Integer> expectedResult = Arrays.stream(out.readLine().replaceAll("[\\[\\]]", "").split(", "))
.map(Integer::parseInt).collect(toList());
List<Integer> actualResult = solution.findAnagrams(string, anagram);
assertEquals(expectedResult, actualResult,
String.format("Input: string = '%s', anagram = '%s'", string, anagram));
}
}
} | 37.117647 | 111 | 0.692552 |
e226110d8391f589ba4ee7f94814ced13419ef93 | 11,917 | package ssangyong.dclass.seoulexploration.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import ssangyong.dclass.seoulexploration.R;
import ssangyong.dclass.seoulexploration.adapter.SearchListAdapter;
import ssangyong.dclass.seoulexploration.data.TourDAO;
import ssangyong.dclass.seoulexploration.data.TourDTO;
import ssangyong.dclass.seoulexploration.temp.Utils;
import ssangyong.dclass.seoulexploration.view.CategoryManager;
import static ssangyong.dclass.seoulexploration.activity.LoadActivity.sysLanguage;
/********************************************************************************
* * 작성자 : 박보현
* * 기 능 : 카테고리 검색 및 직접 검색어 입력하여 검색
* * 수정내용 :
* * 버 전 :
* *******************************************************************************/
public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
Spinner categorySpinner;
Spinner subCategorySpinner;
ArrayAdapter<String> categoryAdapter;
ArrayAdapter<String> subCategoryAdapter;
Button cateSearchBtn;
Button keywordSearchBtn;
SearchView searchView;
SearchListAdapter searchListAdapter;
ListView searchListView;
List<TourDTO> searchedList = new ArrayList<>();
InputMethodManager imm;
String selCateName;
String SELECTED_TYPE = "";
boolean isPageOpen = false;
Animation translateLeftAnim;
Animation translateRightAnim;
//슬라이딩으로 보여줄 페이지
LinearLayout slidingMenuPage;
Button backBtn;
@Override
public void onClick(View v) {
if (v == cateSearchBtn) {
hideKeyboard();
String selSubCateName = (String) subCategorySpinner.getSelectedItem();
searchedList = searchByCategory(selCateName, selSubCateName);
searchListAdapter = new SearchListAdapter(this, searchedList, SELECTED_TYPE);
searchListView.setAdapter(searchListAdapter);
searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
TourDTO tour = searchedList.get(position);
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("name", tour.getName());
startActivity(intent);
}
});
} else if (v == keywordSearchBtn) {
String query = searchView.getQuery().toString();
submitQuery(query);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar ab = getSupportActionBar();
ab.setTitle("카테고리로 선택");
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xFF293133));
setContentView(R.layout.activity_search);
//홈버튼 보여주기
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.menuicon);
//슬라이드메뉴 res 왼쪽 오른쪽 값 애니메이션 객체에 넣어주기
translateLeftAnim = AnimationUtils.loadAnimation(this, R.anim.menu_left);
translateRightAnim = AnimationUtils.loadAnimation(this, R.anim.menu_right);
//슬라이드메뉴페이지
slidingMenuPage = (LinearLayout) findViewById(R.id.slidingMenuPage);
backBtn = (Button) findViewById(R.id.backBtn);
imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
Locale systemLocale = getResources().getConfiguration().locale;
sysLanguage = systemLocale.getLanguage();
categorySpinner = (Spinner) findViewById(R.id.cate_spinner);
subCategorySpinner = (Spinner) findViewById(R.id.sub_cate_spinner);
cateSearchBtn = (Button) findViewById(R.id.cate_search_btn);
cateSearchBtn.setOnClickListener(this);
keywordSearchBtn = (Button) findViewById(R.id.keyword_search_btn);
keywordSearchBtn.setOnClickListener(this);
searchListView = (ListView) findViewById(R.id.search_list);
categoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, CategoryManager.getCategory(sysLanguage));
categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categorySpinner.setAdapter(categoryAdapter);
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String categoryName = (String) categorySpinner.getSelectedItem();
selCateName = categoryName;
makeSubCategory(categoryName);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
searchView = (SearchView) findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
submitQuery(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
private void submitQuery(String query) {
hideKeyboard();
searchedList = searchByKeyword(query);
if (searchedList.size() == 1) {
TourDTO tour = searchedList.get(0);
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("name", tour.getName());
startActivity(intent);
} else if (searchedList.size() > 1) {
searchListAdapter = new SearchListAdapter(getApplicationContext(), searchedList, SELECTED_TYPE);
searchListView.setAdapter(searchListAdapter);
searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
TourDTO tour = searchedList.get(position);
/*Utils.toast(getApplication(), "Show Detail : " + tour.getName());*/
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("name", tour.getName());
startActivity(intent);
}
});
} else if (searchedList.size() == 0) {
Utils.toast(getApplicationContext(), "검색 결과가 없습니다");
}
}
private void hideKeyboard() {
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
}
public void makeSubCategory(String categoryName) {
if (categoryName.equals("구역") || categoryName.equals("area")) {
subCategoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, CategoryManager.getAreaCategory(sysLanguage));
SELECTED_TYPE = "AREA";
} else if (categoryName.equals("테마") || categoryName.equals("theme")) {
SELECTED_TYPE = "THEME";
subCategoryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, CategoryManager.getThemeCategory(sysLanguage));
}
subCategoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
subCategorySpinner.setAdapter(subCategoryAdapter);
subCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// String categoryName = (String) subCategorySpinner.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public List<TourDTO> getTourList() {
TourDAO dao = new TourDAO(this,sysLanguage);
return dao.selectAll();
}
public List<TourDTO> searchByCategory(String cate, String subCate) {
List<TourDTO> result = new ArrayList<>();
List<TourDTO> tourList = getTourList();
// Utils.log("# SEARCH BY CATEGORY: "+cate+" > "+subCate+" in "+tourList.size());
for (TourDTO tour : tourList) {
if (cate.equals("구역") || cate.equals("area")) {
if (tour.getArea().replaceAll("\\s","").equalsIgnoreCase(subCate.trim().replaceAll("\\s", ""))) {
result.add(tour);
}
} else if (cate.equals("테마") || cate.equals("theme")) {
if (tour.getTheme().equalsIgnoreCase(subCate)) {
result.add(tour);
}
}
}
// Utils.log("# SEARCH RESULT " + result.size() + "개");
return result;
}
public List<TourDTO> searchByKeyword(String query) {
List<TourDTO> result = new ArrayList<>();
List<TourDTO> tourList = getTourList();
// Utils.log("# SEARCH BY KEYWORD: " + query + " in " + tourList.size());
for (TourDTO tour : tourList) {
String target = tour.getName().replaceAll("\\s", "");
query = query.replaceAll("\\s", "");
if (target.equalsIgnoreCase(query) || target.toLowerCase().contains(query.toLowerCase())) {
result.add(tour);
}
}
// Utils.log("# SEARCH RESULT " + result.size() + "개");
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//홈버튼을 선택하면
if(id == android.R.id.home){
if(isPageOpen){ //페이지가 열려있으면
isPageOpen = false;
slidingMenuPage.startAnimation(translateLeftAnim);
slidingMenuPage.setVisibility(View.INVISIBLE);
backBtn.setVisibility(View.INVISIBLE);
}
else{ //페이지가 닫혀있으면
isPageOpen = true;
slidingMenuPage.startAnimation(translateRightAnim);
slidingMenuPage.setVisibility(View.VISIBLE);
backBtn.setVisibility(View.VISIBLE);
}
}
return super.onOptionsItemSelected(item);
}
public void onClickTourInfoBtn(View v) { //관광 안내소 버튼
if(isPageOpen){ //페이지가 열려있으면
isPageOpen = false;
slidingMenuPage.setVisibility(View.INVISIBLE);
}
Intent intent = new Intent(getApplicationContext(),TourInfoActivity.class);
startActivity(intent);
}
public void onClickInfoBtn(View v) { //출처 안내 버튼
if(isPageOpen){ //페이지가 열려있으면
isPageOpen = false;
slidingMenuPage.setVisibility(View.INVISIBLE);
}
Intent intent = new Intent(getApplicationContext(),InfoActivity.class);
startActivity(intent);
}
public void onClickBack(View v){ //다른 곳 눌러도 닫히게
if(isPageOpen){ //페이지가 열려있으면
isPageOpen = false;
slidingMenuPage.startAnimation(translateLeftAnim);
slidingMenuPage.setVisibility(View.INVISIBLE);
backBtn.setVisibility(View.INVISIBLE);
}
}
}
| 36.003021 | 149 | 0.634472 |
48b50ff765e80b9d470acf3f4a25a85814eda0cf | 19,519 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.bluej.upgrade;
import java.io.*;
import java.util.*;
import org.openide.util.*;
import java.util.jar.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.openide.xml.XMLUtil;
import org.openide.filesystems.*;
import org.openide.filesystems.FileSystem;
/** Does copy of objects on filesystems.
*
* @author Jaroslav Tulach
*/
final class Copy extends Object {
/** Does a selective copy of one source tree to another.
* @param source file object to copy from
* @param target file object to copy to
* @param thoseToCopy set on which contains (relativeNameOfAFileToCopy)
* is being called to find out whether to copy or not
* @throws IOException if coping fails
*/
public static void copyDeep (FileObject source, FileObject target, Set thoseToCopy)
throws IOException {
copyDeep (source, target, thoseToCopy, null);
}
private static void copyDeep (
FileObject source, FileObject target, Set thoseToCopy, String prefix
) throws IOException {
FileObject src = prefix == null ? source : FileUtil.createFolder (source, prefix);
FileObject[] arr = src.getChildren();
for (int i = 0; i < arr.length; i++) {
String fullname;
if (prefix == null) {
fullname = arr[i].getNameExt ();
} else {
fullname = prefix + "/" + arr[i].getNameExt ();
}
if (arr[i].isData ()) {
if (!thoseToCopy.contains (fullname)) {
continue;
}
}
if (arr[i].isFolder()) {
copyDeep (source, target, thoseToCopy, fullname);
if (thoseToCopy.contains (fullname) && arr[i].getAttributes ().hasMoreElements ()) {
FileObject tg = FileUtil.createFolder (target, fullname);
FileUtil.copyAttributes (arr[i], tg);
}
} else {
FileObject folder = prefix == null ? target : FileUtil.createFolder (target, prefix);
FileObject tg = folder.getFileObject (arr[i].getNameExt ());
try {
if (tg == null) {
// copy the file otherwise keep old content
tg = FileUtil.copyFile (arr[i], folder, arr[i].getName(), arr[i].getExt ());
}
} catch (IOException ex) {
if (arr[i].getNameExt().endsWith("_hidden")) {
continue;
}
throw ex;
}
FileUtil.copyAttributes (arr[i], tg);
}
}
}
/** Updates the IDE.
* @param sourceDir original instalation of the IDE
* @param targetSystem target system to copy files to
* @param backupSystem filesystem to do backupSystemFo to (or null)
* @exception IOException if the copying fails
*
protected final void upgradeIde (String ver, File src, File trg) throws Exception {
int version = getIdeVersion (ver);
if (version < 0 || version >= versions.length) {
message (getString ("MSG_BAD_IDE"));
for (int i = 0 ; i < versions.length ; i++ ) {
message (versions[i]);
}
throw new Exception ("Invalid IDE version"); //NOI18N
}
message (getString ("MSG_UPDATE_FROM", versions[version]));
FileSystem srcFS = null;
FileSystem trgFS = null;
FileSystem tmpFS = null;
Object filter [] = null;
if (-1 != ver.indexOf (DIRTYPE_INST)) {
File srcFile = new File (src, "system"); //NOI18N
File trgFile = new File (trg, "system"); //NOI18N
srcFS = createFileSystem (srcFile);
trgFS = createFileSystem (trgFile);
if (srcFS == null) {
message (getString ("MSG_directory_not_exist", srcFile.getAbsolutePath ())); //NOI18N
throw new Exception ("Directory doesn't exist - " + srcFile.getAbsolutePath ()); //NOI18N
}
if (trgFS == null) {
message (getString ("MSG_directory_not_exist", trgFile.getAbsolutePath ()));
throw new Exception ("Directory doesn't exist - " + trgFile.getAbsolutePath ()); //NOI18N
}
File tmpRoot = new File (trg, "system_backup"); //NOI18N
if (!tmpRoot.exists ()) {
// message (getString ("MSG_BackupDir_exists", tmpRoot.getAbsolutePath ())); //NOI18N
// throw new Exception ("Backup directory already exists - " + tmpRoot.getAbsolutePath ()); //NOI18N
// } else {
tmpRoot.mkdirs ();
}
tmpFS = createFileSystem (tmpRoot);
filter = originalFiles (nonCpFiles[version]);
} else {
srcFS = createFileSystem (src); //NOI18N
trgFS = createFileSystem (trg); //NOI18N
if (srcFS == null) {
message (getString ("MSG_directory_not_exist", src.getAbsolutePath ())); //NOI18N
throw new Exception ("Directory doesn't exist - " + src.getAbsolutePath ()); //NOI18N
}
if (trgFS == null) {
message (getString ("MSG_directory_not_exist", trg.getAbsolutePath ())); //NOI18N
throw new Exception ("Directory doesn't exist - " + trg.getAbsolutePath ()); //NOI18N
}
File tmpRoot = new File (trg.getParentFile (), "userdir_backup"); //NOI18N
if (!tmpRoot.exists ()) {
// message (getString ("MSG_BackupDir_exists", tmpRoot.getAbsolutePath ())); //NOI18N
// throw new Exception ("Backup directory already exists - " + tmpRoot.getAbsolutePath ()); //NOI18N
// } else {
tmpRoot.mkdirs ();
}
tmpFS = createFileSystem (tmpRoot);
filter = originalFiles (userdirNonCpFiles);
}
if (tmpFS != null) {
// clean up temporary filesystem
FileObject ch [] = tmpFS.getRoot ().getChildren ();
for (int i = 0; i < ch.length; i++) {
deleteAll (ch[i]);
}
// make a backup copy
copyAttributes(trgFS.getRoot (), tmpFS.getRoot ());
recursiveCopy(trgFS.getRoot (), tmpFS.getRoot ());
}
try {
update (srcFS, trgFS, getLastModified (src), filter);
}
catch (Exception e) {
if (tmpFS != null) {
message (getString ("MSG_recovery_started")); //NOI18N
deleteAll (trgFS.getRoot ());
copyAttributes (tmpFS.getRoot (), trgFS.getRoot ());
recursiveCopy (tmpFS.getRoot (), trgFS.getRoot ());
message (getString ("MSG_recovery_finished")); //NOI18N
}
throw e;
}
}
private FileSystem createFileSystem (File root) {
LocalFileSystem lfs = null;
if (root.exists () && root.isDirectory ()) {
try {
lfs = new LocalFileSystem ();
lfs.setRootDirectory (root);
}
catch (Exception e) {
lfs = null;
}
}
return lfs == null ? null : new AttrslessLocalFileSystem (lfs);
}
private void update(
FileSystem src, FileSystem trg, long sourceBaseTime, Object[] filter
) throws IOException {
items = 0;
maxItems = 0;
copyAttributes (src.getRoot (),trg.getRoot ());
recursiveCopyWithFilter (
src.getRoot (),
trg.getRoot (),
filter,
sourceBaseTime
);
}
/** copies recursively directory, skips files existing in target location
* @param source source directory
* @param dest destination directory
*/
private void recursiveCopy (FileObject sourceFolder, FileObject destFolder) throws IOException {
FileObject childrens [] = sourceFolder.getChildren();
for (int i = 0 ; i < childrens.length ; i++ ) {
final FileObject subSourceFo = childrens[i];
FileObject subTargetFo = null;
if (subSourceFo.isFolder()) {
subTargetFo = destFolder.getFileObject(subSourceFo.getName());
if (subTargetFo == null) {
subTargetFo = destFolder.createFolder(subSourceFo.getName());
}
copyAttributes(subSourceFo,subTargetFo);
recursiveCopy(subSourceFo,subTargetFo);
} else {
subTargetFo = destFolder.getFileObject(subSourceFo.getNameExt());
if (subTargetFo == null) {
if ( Utilities.getOperatingSystem () == Utilities.OS_VMS
&& subSourceFo.getNameExt ().equalsIgnoreCase ( "_nbattrs.") )
subTargetFo = FileUtil.copyFile(subSourceFo, destFolder, subSourceFo.getNameExt(), subSourceFo.getExt());
else
subTargetFo = FileUtil.copyFile(subSourceFo, destFolder, subSourceFo.getName(), subSourceFo.getExt());
}
copyAttributes(subSourceFo,subTargetFo);
}
}
}
private void message (String s) {
}
private void progress (int x, int y) {
}
private int maxItems;
private int items;
private int timeDev;
/** Copies recursively dircectory. Files are copied when when basicTime + timeDev < time of file.
* @param source source directory
* @param #dest destination dirctory
*/
private void recursiveCopyWithFilter (
FileObject source, FileObject dest, Object[] filter, long basicTime
) throws IOException {
FileObject childrens [] = source.getChildren();
if (source.isFolder() == false ) {
message (getString("MSG_IS_NOT_FOLDER", source.getName()));
}
// adjust max number of items
maxItems += childrens.length;
for (int i = 0 ; i < childrens.length ; i++ ) {
FileObject subSourceFo = childrens[i];
// report progress
items++;
progress(items, maxItems);
if (!canCopy (subSourceFo, filter, basicTime))
continue;
FileObject subTargetFo = null;
if (subSourceFo.isFolder ()) {
subTargetFo = dest.getFileObject (subSourceFo.getNameExt ());
if (subTargetFo == null) {
subTargetFo = dest.createFolder (subSourceFo.getNameExt ());
}
copyAttributes (subSourceFo, subTargetFo);
recursiveCopyWithFilter (subSourceFo, subTargetFo, filter, basicTime);
} else {
subTargetFo = dest.getFileObject (subSourceFo.getName (), subSourceFo.getExt ());
if (subTargetFo != null) {
FileLock lock = subTargetFo.lock ();
subTargetFo.delete (lock);
lock.releaseLock ();
}
if ( Utilities.getOperatingSystem () == Utilities.OS_VMS
&& subSourceFo.getNameExt ().equalsIgnoreCase ( "_nbattrs.") )
subTargetFo = copyFile (subSourceFo, dest, subSourceFo.getNameExt ());
else
subTargetFo = copyFile (subSourceFo, dest, subSourceFo.getName ());
copyAttributes (subSourceFo, subTargetFo);
}
}
}
private FileObject copyFile (FileObject src, FileObject trg, String newName) throws IOException {
return FileUtil.copyFile (src, trg, newName);
}
private static void copyAttributes (FileObject source, FileObject dest) throws IOException {
Enumeration attrKeys = source.getAttributes();
while (attrKeys.hasMoreElements()) {
String key = (String) attrKeys.nextElement();
Object value = source.getAttribute(key);
if (value != null) {
dest.setAttribute(key, value);
}
}
}
/** test if file can be copied
*/
private boolean canCopy (FileObject fo, Object[] filter, long basicTime) throws IOException {
String nonCopiedFiles [] = (String []) filter [0];
String wildcards [] = (String []) filter [1];
String name = fo.getPath();
if (fo.isFolder ()) {
return Arrays.binarySearch (nonCopiedFiles, name + "/*") < 0; //NOI18N
}
for (int i = 0; i < wildcards.length; i++) {
if (name.endsWith (wildcards [i])) {
return false;
}
}
long time = fo.lastModified().getTime();
boolean canCopy = Arrays.binarySearch (nonCopiedFiles, name) < 0 &&
basicTime + timeDev <= time;
if (!canCopy) {
return false;
}
// #31623 - the fastjavac settings should not be imported.
// In NB3.5 the fastjavac was separated into its own module.
// Its old settings (bounded to java module) must not be imported.
// For fastjavac settings created by NB3.5 this will work, because they
// will be bound to new "org.netbeans.modules.java.fastjavac" module.
if (fo.getExt().equals("settings")) { //NOI18N
boolean tag1 = false;
boolean tag2 = false;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(fo.getInputStream()));
String line;
while (null != (line = reader.readLine())) {
if (line.indexOf("<module name=") != -1) { //NOI18N
if (line.indexOf("<module name=\"org.netbeans.modules.java/1\"") != -1) { //NOI18N
tag1 = true; // it is java module setting
} else {
break; // some other setting, ignore this file
}
}
if (line.indexOf("<serialdata class=") != -1) { //NOI18N
if (line.indexOf("<serialdata class=\"org.netbeans.modules.java.FastJavacCompilerType\">") != -1) { //NOI18N
tag2 = true; // it is fastjavac setting
if (tag1) {
break;
}
} else {
break; // some other setting, ignore this file
}
}
}
} catch (IOException ex) {
// ignore this problem.
// in worst case the fastjavac settings will be copied.
} finally {
if (reader != null) {
reader.close();
}
}
if (tag1 && tag2) {
return false; // ignore this file. it is fastjavac settings
}
}
return true;
}
// ************************* version retrieving code ********************
/** We support import just from release 3.6
* @param dir user dir to check for version
* @return either null or name of the version
*/
public static String getIdeVersion (File dir) {
String version = null;
String dirType = null;
String branding = null;
if (new File (dir, "system").exists ()) {
return "3.6";
}
return null;
}
// ************** strings from bundle ***************
protected static String getString (String key) {
return NbBundle.getMessage (Copy.class, key);
}
protected static String getString (String key,String param) {
return NbBundle.getMessage(Copy.class,key,param);
}
private static class AttrslessLocalFileSystem extends AbstractFileSystem implements AbstractFileSystem.Attr {
public AttrslessLocalFileSystem (LocalFileSystem fs) {
super ();
this.change = new LocalFileSystem.Impl (fs);
this.info = (AbstractFileSystem.Info) this.change;
this.list = (AbstractFileSystem.List) this.change;
this.attr = this;
}
public boolean isReadOnly () {
return false;
}
public String getDisplayName () {
return getClass ().toString (); // this will never be shown to user
}
// ***** no-op implementation of AbstractFileSystem.Attr *****
public void deleteAttributes (String name) {
}
public Enumeration attributes (String name) {
return org.openide.util.Enumerations.empty ();
}
public void renameAttributes (String oldName, String newName) {
}
public void writeAttribute (String name, String attrName, Object value) throws IOException {
}
public Object readAttribute (String name, String attrName) {
return null;
}
}
}
| 39.194779 | 132 | 0.554742 |
267ac2bb431cd65da07176d6a5c80904cdae1019 | 4,912 | package com.hbm.items.weapon;
import com.hbm.entity.particle.EntitySSmokeFX;
import com.hbm.entity.projectile.EntityBulletBase;
import com.hbm.handler.BulletConfigSyncingUtil;
import com.hbm.interfaces.IHoldableWeapon;
import com.hbm.items.ModItems;
import com.hbm.lib.HBMSoundHandler;
import com.hbm.lib.Library;
import com.hbm.render.misc.RenderScreenOverlay.Crosshair;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.world.World;
public class GunFolly extends Item implements IHoldableWeapon {
@Override
public Crosshair getCrosshair() {
return Crosshair.L_SPLIT;
}
public GunFolly(String s) {
this.setUnlocalizedName(s);
this.setRegistryName(s);
this.maxStackSize = 1;
ModItems.ALL_ITEMS.add(this);
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
ItemStack stack = player.getHeldItem(hand);
int state = getState(stack);
if(state == 0) {
world.playSound(null, player.posX, player.posY, player.posZ, HBMSoundHandler.follyOpen, SoundCategory.PLAYERS, 1.0F, 1.0F);
setState(stack, 1);
} else if(state == 1) {
if(Library.hasInventoryItem(player.inventory, ModItems.ammo_folly)) {
world.playSound(null, player.posX, player.posY, player.posZ, HBMSoundHandler.follyReload, SoundCategory.PLAYERS, 1.0F, 1.0F);
Library.consumeInventoryItem(player.inventory, ModItems.ammo_folly);
setState(stack, 2);
} else {
world.playSound(null, player.posX, player.posY, player.posZ, HBMSoundHandler.follyClose, SoundCategory.PLAYERS, 1.0F, 1.0F);
setState(stack, 0);
}
} else if(state == 2) {
world.playSound(null, player.posX, player.posY, player.posZ, HBMSoundHandler.follyClose, SoundCategory.PLAYERS, 1.0F, 1.0F);
setState(stack, 3);
setTimer(stack, 100);
} else if(state == 3) {
if(getTimer(stack) == 0) {
setState(stack, 0);
world.playSound(null, player.posX, player.posY, player.posZ, HBMSoundHandler.follyFire, SoundCategory.PLAYERS, 1.0F, 1.0F);
double mult = 1.75D;
player.motionX -= player.getLookVec().x * mult;
player.motionY -= player.getLookVec().y * mult;
player.motionZ -= player.getLookVec().z * mult;
if (!world.isRemote) {
EntityBulletBase bullet = new EntityBulletBase(world, BulletConfigSyncingUtil.TEST_CONFIG, player, player.getHeldItemMainhand() == stack ? EnumHand.MAIN_HAND : EnumHand.OFF_HAND);
world.spawnEntity(bullet);
for(int i = 0; i < 25; i++) {
EntitySSmokeFX flame = new EntitySSmokeFX(world);
flame.motionX = player.getLookVec().x;
flame.motionY = player.getLookVec().y;
flame.motionZ = player.getLookVec().z;
flame.posX = player.posX + flame.motionX + world.rand.nextGaussian() * 0.35;
flame.posY = player.posY + flame.motionY + world.rand.nextGaussian() * 0.35 + player.eyeHeight;
flame.posZ = player.posZ + flame.motionZ + world.rand.nextGaussian() * 0.35;
world.spawnEntity(flame);
}
}
}
}
return super.onItemRightClick(world, player, hand);
}
@Override
public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
return false;
}
@Override
public void onUpdate(ItemStack stack, World world, Entity entity, int itemSlot, boolean isSelected) {
if(getState(stack) == 3) {
if(isSelected) {
int timer = getTimer(stack);
if(timer > 0) {
timer--;
if(timer % 20 == 0 && timer != 0)
world.playSound(null, entity.posX, entity.posY, entity.posZ, HBMSoundHandler.follyBuzzer, SoundCategory.PLAYERS, 1.0F, 1.0F);
if(timer == 0)
world.playSound(null, entity.posX, entity.posY, entity.posZ, HBMSoundHandler.follyAquired, SoundCategory.PLAYERS, 1.0F, 1.0F);
setTimer(stack, timer);
}
} else {
setTimer(stack, 100);
}
}
}
public static void setState(ItemStack stack, int i) {
writeNBT(stack, "state", i);
}
public static int getState(ItemStack stack) {
return readNBT(stack, "state");
}
public static void setTimer(ItemStack stack, int i) {
writeNBT(stack, "timer", i);
}
public static int getTimer(ItemStack stack) {
return readNBT(stack, "timer");
}
private static void writeNBT(ItemStack stack, String key, int value) {
if(!stack.hasTagCompound())
stack.setTagCompound(new NBTTagCompound());
stack.getTagCompound().setInteger(key, value);
}
private static int readNBT(ItemStack stack, String key) {
if(!stack.hasTagCompound())
return 0;
return stack.getTagCompound().getInteger(key);
}
}
| 29.95122 | 184 | 0.701547 |
d3f3d714c2d8ab0fa231aa18d7b5059354339ff9 | 1,575 | /**
* Copyright (c) 2018, hiwepy (https://github.com/hiwepy).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.hiwepy.calibre.invoker.exception;
/**
* Signals an error during the construction of the command line used to invoke
* Maven.
*/
public class CommandLineConfigurationException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Creates a new exception using the specified detail message and cause.
*
* @param message
* The detail message for this exception, may be <code>null</code>.
* @param cause
* The nested exception, may be <code>null</code>.
*/
public CommandLineConfigurationException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a new exception using the specified detail message.
*
* @param message
* The detail message for this exception, may be <code>null</code>.
*/
public CommandLineConfigurationException(String message) {
super(message);
}
}
| 32.142857 | 81 | 0.692698 |
db4b31603920335910fb5fb0e0239f9d7949da0d | 1,328 | package com.builtbroken.icbm.content.launcher.launcher;
import com.builtbroken.icbm.ICBM;
import com.builtbroken.icbm.content.launcher.TileAbstractLauncher;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;
/**
* @see <a href="https://github.com/BuiltBrokenModding/VoltzEngine/blob/development/license.md">License</a> for what you can and can't do with the code.
* Created by Dark(DarkGuardsman, Robert) on 12/2/2015.
*/
public abstract class TileAbstractLauncherPad extends TileAbstractLauncher
{
public TileAbstractLauncherPad(String name)
{
this(name, 1);
}
public TileAbstractLauncherPad(String name, int slots)
{
super(name, Material.iron, slots);
this.isOpaque = false;
this.renderNormalBlock = true;
this.renderTileEntity = true;
this.itemBlock = ItemBlockLauncherPad.class;
}
@SideOnly(Side.CLIENT)
@Override
public IIcon getIcon(int side)
{
return ICBM.blockLauncherParts.getIcon(side, 0);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister)
{
//We have no icons to register
}
}
| 29.511111 | 152 | 0.71988 |
2db48d2ca1fcb57bba7cbe85eedd72545a3315b4 | 3,832 | package edu.cmu.cs.sb.drem;
import edu.cmu.cs.sb.core.*;
import edu.umd.cs.piccolo.nodes.PPath;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
import edu.umd.cs.piccolo.nodes.PImage;
import edu.umd.cs.piccolo.PCanvas;
/**
* Class for window to specify to save the current DREM main interface as an image
*/
public class DREMGui_SaveDREM extends JPanel
{
final static Color bgColor = Color.white;
final static Color fgColor = Color.black;
DREMGui theDREMGui;
HashSet validExt = new HashSet();
/**
* Class constructor builds the panel window
*/
public DREMGui_SaveDREM(DREMGui theDREMGui,final JFrame theFrame)
{
this.theDREMGui = theDREMGui;
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
setForeground(fgColor);
final JFileChooser theChooser = new JFileChooser();
String[] sznames = ImageIO.getWriterFormatNames();
DREMGui_ImageFilter filter = new DREMGui_ImageFilter();
StringBuffer szdescbuf = new StringBuffer();
StringBuffer szvalidbuf = new StringBuffer();
boolean bfirst = true;
for (int nindex = 0; nindex < sznames.length; nindex++)
{
String szlower = sznames[nindex].toLowerCase(Locale.ENGLISH);
if (!validExt.contains(szlower))
{
filter.addExtension(szlower);
validExt.add(szlower);
if (!bfirst)
{
szdescbuf.append(", ");
szvalidbuf.append(", ");
}
szdescbuf.append("*."+szlower);
szvalidbuf.append(szlower);
bfirst = false;
}
}
final String szvalidext = szvalidbuf.toString();
filter.setDescription("Image Files ("+szdescbuf.toString()+")");
theChooser.setFileFilter(filter);
add(theChooser);
theChooser.setAcceptAllFileFilterUsed(false);
theChooser.setDialogType(JFileChooser.SAVE_DIALOG);
final DREMGui ftheDREMGui = theDREMGui;
theChooser.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// set label's icon to the current image
String state = (String)e.getActionCommand();
if (state.equals(JFileChooser.CANCEL_SELECTION))
{
theFrame.setVisible(false);
theFrame.dispose();
}
else if (state.equals(JFileChooser.APPROVE_SELECTION))
{
boolean bok = false;
File f = theChooser.getSelectedFile();
try
{
PCanvas canvas = ftheDREMGui.getCanvas();
// TODO try making the images higher resolution
int width = (int) canvas.getCamera().getWidth() * 10;
int height= (int) canvas.getCamera().getHeight() * 10;
Image theImage =
canvas.getLayer().toImage(width,height,Color.white);
BufferedImage bi = PImage.toBufferedImage(theImage,true);
String szext = DREMGui_ImageFilter.getExtension(f);
if (validExt.contains(szext))
{
ImageIO.write(bi, szext, f);
bok = true;
}
else
{
final String fszext = szext;
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JOptionPane.showMessageDialog(null,
fszext +" is not a recognized image extension. "+
"Recognized extensions are "+szvalidext+".",
"Invalid Image Extension", JOptionPane.ERROR_MESSAGE);
}
});
}
}
catch (final IOException fex)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JOptionPane.showMessageDialog(null, fex.getMessage(),
"Exception thrown", JOptionPane.ERROR_MESSAGE);
}
});
fex.printStackTrace(System.out);
}
if (bok)
{
theFrame.setVisible(false);
theFrame.dispose();
}
}
}
});
}
} | 26.985915 | 82 | 0.659447 |
1080962750c7b2a52d63ec8c13f2c7ff4cbeb8bf | 3,706 | /*
* 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.aliyuncs.cloudesl.transform.v20190801;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.cloudesl.model.v20190801.DescribeUserLogResponse;
import com.aliyuncs.cloudesl.model.v20190801.DescribeUserLogResponse.UserLogInfo;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeUserLogResponseUnmarshaller {
public static DescribeUserLogResponse unmarshall(DescribeUserLogResponse describeUserLogResponse, UnmarshallerContext _ctx) {
describeUserLogResponse.setRequestId(_ctx.stringValue("DescribeUserLogResponse.RequestId"));
describeUserLogResponse.setErrorMessage(_ctx.stringValue("DescribeUserLogResponse.ErrorMessage"));
describeUserLogResponse.setPageNumber(_ctx.integerValue("DescribeUserLogResponse.PageNumber"));
describeUserLogResponse.setErrorCode(_ctx.stringValue("DescribeUserLogResponse.ErrorCode"));
describeUserLogResponse.setMessage(_ctx.stringValue("DescribeUserLogResponse.Message"));
describeUserLogResponse.setDynamicCode(_ctx.stringValue("DescribeUserLogResponse.DynamicCode"));
describeUserLogResponse.setPageSize(_ctx.integerValue("DescribeUserLogResponse.PageSize"));
describeUserLogResponse.setCode(_ctx.stringValue("DescribeUserLogResponse.Code"));
describeUserLogResponse.setDynamicMessage(_ctx.stringValue("DescribeUserLogResponse.DynamicMessage"));
describeUserLogResponse.setTotalCount(_ctx.integerValue("DescribeUserLogResponse.TotalCount"));
describeUserLogResponse.setSuccess(_ctx.booleanValue("DescribeUserLogResponse.Success"));
List<UserLogInfo> userLogs = new ArrayList<UserLogInfo>();
for (int i = 0; i < _ctx.lengthValue("DescribeUserLogResponse.UserLogs.Length"); i++) {
UserLogInfo userLogInfo = new UserLogInfo();
userLogInfo.setOperateType(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].OperateType"));
userLogInfo.setOperateUserId(_ctx.longValue("DescribeUserLogResponse.UserLogs["+ i +"].OperateUserId"));
userLogInfo.setMac(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].Mac"));
userLogInfo.setItemActionPrice(_ctx.integerValue("DescribeUserLogResponse.UserLogs["+ i +"].ItemActionPrice"));
userLogInfo.setStoreId(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].StoreId"));
userLogInfo.setEslBarCode(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].EslBarCode"));
userLogInfo.setOperateStatus(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].OperateStatus"));
userLogInfo.setItemBarCode(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].ItemBarCode"));
userLogInfo.setItemId(_ctx.longValue("DescribeUserLogResponse.UserLogs["+ i +"].ItemId"));
userLogInfo.setShelfCode(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].ShelfCode"));
userLogInfo.setOperateTime(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].OperateTime"));
userLogInfo.setItemTitle(_ctx.stringValue("DescribeUserLogResponse.UserLogs["+ i +"].ItemTitle"));
userLogs.add(userLogInfo);
}
describeUserLogResponse.setUserLogs(userLogs);
return describeUserLogResponse;
}
} | 58.825397 | 126 | 0.796816 |
453e7dbd10e1a5399070aacd73bdedc40bb00725 | 2,285 | package com.stardust.autojs.core.image.capture;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.stardust.app.OnActivityResultDelegate;
import com.stardust.util.IntentExtras;
/**
* Created by Stardust on 2017/5/22.
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ScreenCaptureRequestActivity extends Activity {
private OnActivityResultDelegate.Mediator mOnActivityResultDelegateMediator = new OnActivityResultDelegate.Mediator();
private ScreenCaptureRequester mScreenCaptureRequester;
private ScreenCaptureRequester.Callback mCallback;
public static void request(Context context, ScreenCaptureRequester.Callback callback) {
Intent intent = new Intent(context, ScreenCaptureRequestActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
IntentExtras.newExtras()
.put("callback", callback)
.putInIntent(intent);
context.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentExtras extras = IntentExtras.fromIntentAndRelease(getIntent());
if (extras == null) {
finish();
return;
}
mCallback = extras.get("callback");
if (mCallback == null) {
finish();
return;
}
mScreenCaptureRequester = new ScreenCaptureRequester.ActivityScreenCaptureRequester(mOnActivityResultDelegateMediator, this);
mScreenCaptureRequester.setOnActivityResultCallback(mCallback);
mScreenCaptureRequester.request();
}
@Override
protected void onDestroy() {
super.onDestroy();
mCallback = null;
if (mScreenCaptureRequester == null)
return;
mScreenCaptureRequester.cancel();
mScreenCaptureRequester = null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mOnActivityResultDelegateMediator.onActivityResult(requestCode, resultCode, data);
finish();
}
} | 33.602941 | 133 | 0.707221 |
d533b59f04f0a0cab2a334af9abdf89745bc58ba | 17,772 | package edu.pse.beast.saverloader;
import java.awt.Component;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import edu.pse.beast.datatypes.NameInterface;
import edu.pse.beast.stringresource.StringResourceLoader;
import edu.pse.beast.toolbox.SuperFolderFinder;
/**
* Class that allows saving and loading files.
* @author NikolaiLMS
*/
public class FileChooser {
private JFileChooser fileChooser;
private StringResourceLoader stringResourceLoader;
private Component component;
private SaverLoader saverLoader;
private File lastLoadedFile;
private boolean hasBeenSaved = false;
private Object[] options = {"OK"};
private String saveChanges;
private String save;
private String yesOption;
private String noOption;
private String cancelOption;
/**
* Constructor
* @param stringResourceLoader the stringResourceLoader providing the Strings needed for displaying save and open
* JFileChoosers
* @param saverLoader a class implementing the SaverLoader interface for creating Strings from objects
* and vice versa
* @param component the component the JFileChoosers should be displayed in, currently not in use since components
* might be too small for JFileChoosers and cause unaesthetic window placement
*/
public FileChooser(StringResourceLoader stringResourceLoader, SaverLoader saverLoader, Component component) {
this.fileChooser = new JFileChooser();
this.stringResourceLoader = stringResourceLoader;
this.component = component;
this.saverLoader = saverLoader;
updateStringRessourceLoader(stringResourceLoader);
}
/**
* Method that obtains a file location either by JFileChooser or previously save-location and then calls
* saveToFile to save the given object.
* Calls itself recursively if saveToFile returns false.
* @param object the object to be saved, has to correspond to the given SaverLoader class.
* @param forceDialog true if a save Dialog should be forced (SaveAs UserAction), false otherwise (SaveAction)
* @return true if saving was successful
*/
public boolean saveObject(Object object, boolean forceDialog) {
if (fileChooser.getSelectedFile() != null) {
fileChooser.setSelectedFile(new File(
fileChooser.getSelectedFile().getParent() + "/" + ((NameInterface) object).getName()
+ stringResourceLoader.getStringFromID(
"fileSuffix")));
} else {
fileChooser.setSelectedFile(new File(System.getProperty("user.home") + "/"
+ ((NameInterface) object).getName()));
}
fileChooser.setApproveButtonText(stringResourceLoader.getStringFromID("saveApproveButtonText"));
if (hasBeenSaved && !forceDialog) {
return saveToFile(object, lastLoadedFile);
} else {
if (fileChooser.showDialog(component, stringResourceLoader.getStringFromID("saveDialogTitleText"))
== JFileChooser.APPROVE_OPTION) {
if (!saveToFile(object, fileChooser.getSelectedFile())) {
return saveObject(object, forceDialog);
} else {
lastLoadedFile = fileChooser.getSelectedFile();
hasBeenSaved = true;
return true;
}
} else {
return false;
}
}
}
/**
* Opens the JFileChooser and when a valid input based on this class' SaverLoader objects is selected, creates
* an object with it and returns it.
* @return the loaded object upon success, null otherwise
*/
public Object loadObject() {
fileChooser.setApproveButtonText(stringResourceLoader.getStringFromID("openApproveButtonText"));
if (fileChooser.showDialog(component, stringResourceLoader.getStringFromID("openDialogTitleText"))
== JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String content = "";
BufferedReader inputReader = null;
boolean caught = false;
try {
inputReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(selectedFile), "UTF8"));
} catch (UnsupportedEncodingException e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID(
"wrongEncodingError"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
caught = true;
} catch (FileNotFoundException e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID("inputOutputErrorOpen"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
caught = true;
}
if (caught) {
if (inputReader != null) {
try {
inputReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return (loadObject());
}
String sCurrentLine;
try {
while ((sCurrentLine = inputReader.readLine()) != null) {
content += (sCurrentLine + "\n");
}
} catch (IOException e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID("inputOutputErrorOpen"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
return (loadObject());
}
Object outputObject = null;
boolean closed = false;
try {
outputObject = saverLoader.createFromSaveString(content);
lastLoadedFile = selectedFile;
hasBeenSaved = true;
} catch (Exception e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID(
"invalidFileFormatErrorMessage"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
return (loadObject());
} finally {
try {
inputReader.close();
closed = true;
} catch (IOException ex) {
ex.printStackTrace();
closed = false;
}
}
if (closed) {
return outputObject;
} else {
return loadObject();
}
} else {
return null;
}
}
/**
* Method that saves the given
* @param object to the given
* @param file location.
* @return true if saving was successful, false if not
*/
private boolean saveToFile(Object object, File file) {
File localfile = file;
if (!localfile.getName().matches("[_a-zA-Z0-9\\-\\.\\s]+")) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID("wrongFileNameError"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
return false;
} else if (!fileChooser.getSelectedFile().getName().endsWith(stringResourceLoader.getStringFromID(
"fileSuffix"))) {
localfile = new File(localfile.getAbsolutePath() + stringResourceLoader.getStringFromID("fileSuffix"));
}
fileChooser.setSelectedFile(localfile);
String saveString;
((NameInterface) object).setNewName(localfile.getName().split(stringResourceLoader.getStringFromID(
"fileSuffix"))[0]);
saveString = saverLoader.createSaveString(object);
Writer out = null;
boolean closed = false;
boolean success = true;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(localfile), "UTF-8"));
} catch (UnsupportedEncodingException e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID(
"wrongEncodingError"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
success = false;
return false;
} catch (FileNotFoundException e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID("inputOutputErrorSave"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
success = false;
return false;
} finally {
try {
if (!success) {
out.close();
closed = true;
}
} catch (IOException e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID(
"objectCouldNotBeSavedError"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
closed = false;
}
}
closed = false;
try {
try {
out.write(saveString);
} catch (IOException e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID(
"objectCouldNotBeSavedError"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
return false;
}
} finally {
try {
out.close();
closed = true;
} catch (IOException e) {
JOptionPane.showOptionDialog(null,
stringResourceLoader.getStringFromID(
"objectCouldNotBeSavedError"), "",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[0]);
closed = false;
}
}
if (closed) {
lastLoadedFile = localfile;
return true;
} else {
return false;
}
}
/**
* Method that calls showSaveOptionPane and based on its return saves the
* given object, called when a new Object is loaded into one of the GUIs.
*
* @param object the object containing changes that might be saved, needs to
* implement NameInterface
* @return false if the user pressed "Cancel" on the dialog, thus cancelling
* any previous load action true otherwise
*
*/
public boolean openSaveChangesDialog(Object object) {
int option = showSaveOptionPane(((NameInterface) object).getName());
if (option == JOptionPane.YES_OPTION) {
return saveObject(object, false);
} else {
return (!(option == JOptionPane.CANCEL_OPTION));
}
}
/**
* Method that opens pane that asks the user whether he wants to save his
* changes or not.
*
* @return the option clicked by the user
*/
private int showSaveOptionPane(String propertyName) {
Object[] options = {yesOption,
noOption,
cancelOption};
return JOptionPane.showOptionDialog(null,
saveChanges + propertyName + save,
"",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
}
/**
* Updates the StringResourceLoader and the language dependent fields of the JFileChooser.
* @param stringResourceLoader the new StringResourceLoader object
*/
public void updateStringRessourceLoader(StringResourceLoader stringResourceLoader) {
this.stringResourceLoader = stringResourceLoader;
fileChooser = new JFileChooser();
//sets the text and language of all the components in JFileChooser
UIManager.put("FileChooser.openDialogTitleText",
stringResourceLoader.getStringFromID("openDialogTitleText"));
UIManager.put("FileChooser.lookInLabelText", stringResourceLoader.getStringFromID("lookInLabelText"));
UIManager.put("FileChooser.openButtonText", stringResourceLoader.getStringFromID("openButtonText"));
UIManager.put("FileChooser.cancelButtonText", stringResourceLoader.getStringFromID("cancelButtonText"));
UIManager.put("FileChooser.fileNameLabelText", stringResourceLoader.getStringFromID("fileNameLabelText"));
UIManager.put("FileChooser.filesOfTypeLabelText",
stringResourceLoader.getStringFromID("filesOfTypeLabelText"));
UIManager.put("FileChooser.approveButtonToolTipText", "");
UIManager.put("FileChooser.cancelButtonToolTipText", "");
UIManager.put("FileChooser.openButtonToolTipText",
stringResourceLoader.getStringFromID("openApproveButtonToolTipText"));
UIManager.put("FileChooser.fileNameHeaderText",
stringResourceLoader.getStringFromID("fileNameHeaderText"));
UIManager.put("FileChooser.upFolderToolTipText",
stringResourceLoader.getStringFromID("upFolderToolTipText"));
UIManager.put("FileChooser.homeFolderToolTipText",
stringResourceLoader.getStringFromID("homeFolderToolTipText"));
UIManager.put("FileChooser.newFolderToolTipText",
stringResourceLoader.getStringFromID("newFolderToolTipText"));
UIManager.put("FileChooser.listViewButtonToolTipText",
stringResourceLoader.getStringFromID("listViewButtonToolTipText"));
UIManager.put("FileChooser.newFolderButtonText",
stringResourceLoader.getStringFromID("newFolderButtonText"));
UIManager.put("FileChooser.renameFileButtonText",
stringResourceLoader.getStringFromID("renameFileButtonText"));
UIManager.put("FileChooser.deleteFileButtonText",
stringResourceLoader.getStringFromID("deleteFileButtonText"));
UIManager.put("FileChooser.filterLabelText", stringResourceLoader.getStringFromID("filterLabelText"));
UIManager.put("FileChooser.detailsViewButtonToolTipText",
stringResourceLoader.getStringFromID("detailsViewButtonToolTipText"));
UIManager.put("FileChooser.fileSizeHeaderText",
stringResourceLoader.getStringFromID("fileSizeHeaderText"));
UIManager.put("FileChooser.fileDateHeaderText",
stringResourceLoader.getStringFromID("fileDateHeaderText"));
saveChanges = stringResourceLoader.getStringFromID("saveChanges");
save = stringResourceLoader.getStringFromID("saveChangesSuffix");
cancelOption = stringResourceLoader.getStringFromID("cancelOption");
noOption = stringResourceLoader.getStringFromID("noOption");
yesOption = stringResourceLoader.getStringFromID("yesOption");
fileChooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return (file.getName().matches(stringResourceLoader.getStringFromID("fileApproveRegex"))
|| file.isDirectory());
}
@Override
public String getDescription() {
return stringResourceLoader.getStringFromID("fileDescription");
}
});
fileChooser.setSelectedFile(new File(SuperFolderFinder.getSuperFolder() + "/projectFiles/ "));
fileChooser.setAcceptAllFileFilterUsed(false);
}
/**
* Setter for the hasBeenSaved boolean.
* @param bool the new value
*/
public void setHasBeenSaved(boolean bool) {
this.hasBeenSaved = bool;
}
}
| 42.113744 | 117 | 0.579957 |
a45ca01c5a07ec5ab579f25571c7b7081019659d | 3,034 | /*
* Copyright (c) 2021 Aaron Coburn and individual contributors
*
* 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.trellisldp.ext.cassandra.query.binary;
import static org.slf4j.LoggerFactory.getLogger;
import com.datastax.oss.driver.api.core.ConsistencyLevel;
import com.datastax.oss.driver.api.core.CqlSession;
import java.io.InputStream;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.apache.commons.rdf.api.IRI;
import org.slf4j.Logger;
import org.trellisldp.ext.cassandra.BinaryWriteConsistency;
/**
* Insert binary data into a table.
*/
@ApplicationScoped
public class Insert extends BinaryQuery implements Executor {
private static final Logger LOGGER = getLogger(Insert.class);
/**
* For use with RESTeasy and CDI proxies.
*
* @apiNote This construtor is used by CDI runtimes that require a public, no-argument constructor.
* It should not be invoked directly in user code.
*/
public Insert() {
super();
}
/**
* @param session the cassandra session
* @param consistency the consistency level
*/
@Inject
public Insert(final CqlSession session, @BinaryWriteConsistency final ConsistencyLevel consistency) {
super(session, "INSERT INTO " + BINARY_TABLENAME + " (identifier, chunkSize, chunkIndex, chunk) VALUES "
+ "(:identifier, :chunkSize, :chunkIndex, :chunk)", consistency);
}
/**
* @param id the {@link IRI} of this binary
* @param chunkSize size of chunk to use for this binary
* @param chunkIndex which chunk this is
* @param chunk the bytes of this chunk
* @return whether and when it has been inserted
*/
public CompletionStage<Void> execute(final IRI id, final int chunkSize, final int chunkIndex,
final InputStream chunk) {
return preparedStatementAsync().thenApply(stmt -> stmt.bind().set("identifier", id, IRI.class)
.setInt("chunkSize", chunkSize).setInt("chunkIndex", chunkIndex)
.set("chunk", chunk, InputStream.class)
.setConsistencyLevel(consistency))
.thenCompose(session::executeAsync)
.thenAccept(r -> LOGGER.debug("Executed query: {}", queryString));
}
@Override
public void execute(final Runnable command) {
writeWorkers.execute(command);
}
}
| 36.119048 | 112 | 0.691496 |
4f97c564269bc71407a2b1192a99b3566dbf14c0 | 2,284 | package com.basho.riak.client.core;
import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.RiakCommand;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
/**
*
* @author Alex Moore <amoore at basho dot com>
*/
public class RiakClientTest
{
private static RiakClient client = new RiakClient(mock(RiakCluster.class));
@Test
public void clientExecutesCommand() throws UnknownHostException, ExecutionException, InterruptedException
{
final CommandFake command = new CommandFake();
client.execute(command);
assertTrue(command.executeAsyncCalled);
}
@Test
public void clientExecutesTimeoutCommand()
throws UnknownHostException, ExecutionException, InterruptedException, TimeoutException
{
final CommandFake command = new CommandFake();
client.execute(command, 1, TimeUnit.SECONDS);
assertTrue(command.executeAsyncCalled);
verify(command.getMockFuture()).get(1, TimeUnit.SECONDS);
}
public class CommandFake extends RiakCommand<String, String>
{
private boolean executeAsyncCalled = false;
@SuppressWarnings("unchecked")
private RiakFuture<String, String> mockFuture = (RiakFuture<String, String>) mock(RiakFuture.class);
@Override
protected RiakFuture<String, String> executeAsync(RiakCluster cluster)
{
executeAsyncCalled = true;
return mockFuture;
}
public boolean wasExecuteAsyncCalled()
{
return executeAsyncCalled;
}
public RiakFuture<String, String> getMockFuture()
{
return mockFuture;
}
}
}
| 30.453333 | 109 | 0.720665 |
89952eb814aff2be1c0586df197eead15b0da866 | 6,293 | /*
* Copyright 2021 EPAM Systems
*
* 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.epam.ta.reportportal.core.integration.util;
import com.epam.reportportal.extension.bugtracking.BtsExtension;
import com.epam.ta.reportportal.commons.validation.Suppliers;
import com.epam.ta.reportportal.core.integration.util.property.BtsProperties;
import com.epam.ta.reportportal.core.plugin.PluginBox;
import com.epam.ta.reportportal.dao.IntegrationRepository;
import com.epam.ta.reportportal.entity.enums.AuthType;
import com.epam.ta.reportportal.entity.integration.Integration;
import com.epam.ta.reportportal.exception.ReportPortalException;
import com.epam.ta.reportportal.ws.model.ErrorType;
import com.google.common.collect.Maps;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Optional;
import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect;
import static com.epam.ta.reportportal.ws.model.ErrorType.UNABLE_INTERACT_WITH_INTEGRATION;
/**
* @author <a href="mailto:[email protected]">Pavel Bortnik</a>
*/
@Service
public class BtsIntegrationService extends BasicIntegrationServiceImpl {
private final BasicTextEncryptor basicTextEncryptor;
@Autowired
public BtsIntegrationService(IntegrationRepository integrationRepository, PluginBox pluginBox, BasicTextEncryptor basicTextEncryptor) {
super(integrationRepository, pluginBox);
this.basicTextEncryptor = basicTextEncryptor;
}
@Override
public Map<String, Object> retrieveCreateParams(String integrationType, Map<String, Object> integrationParams) {
expect(integrationParams, MapUtils::isNotEmpty).verify(ErrorType.BAD_REQUEST_ERROR, "No integration params provided");
Map<String, Object> resultParams = Maps.newHashMapWithExpectedSize(BtsProperties.values().length);
resultParams.put(BtsProperties.PROJECT.getName(),
BtsProperties.PROJECT.getParam(integrationParams)
.orElseThrow(() -> new ReportPortalException(UNABLE_INTERACT_WITH_INTEGRATION, "BTS project is not specified."))
);
resultParams.put(BtsProperties.URL.getName(),
BtsProperties.URL.getParam(integrationParams)
.orElseThrow(() -> new ReportPortalException(UNABLE_INTERACT_WITH_INTEGRATION, "BTS url is not specified."))
);
final String authName = BtsProperties.AUTH_TYPE.getParam(integrationParams)
.orElseThrow(() -> new ReportPortalException(UNABLE_INTERACT_WITH_INTEGRATION, "Auth type is not specified."));
retrieveAuthParams(integrationParams, resultParams, authName);
resultParams.put(BtsProperties.AUTH_TYPE.getName(), authName);
return resultParams;
}
@Override
public Map<String, Object> retrieveUpdatedParams(String integrationType, Map<String, Object> integrationParams) {
Map<String, Object> resultParams = Maps.newHashMapWithExpectedSize(integrationParams.size());
BtsProperties.URL.getParam(integrationParams)
.ifPresent(url -> resultParams.put(BtsProperties.URL.getName(), url));
BtsProperties.PROJECT.getParam(integrationParams)
.ifPresent(url -> resultParams.put(BtsProperties.PROJECT.getName(), url));
BtsProperties.AUTH_TYPE.getParam(integrationParams).ifPresent(authName -> {
retrieveAuthParams(integrationParams, resultParams, authName);
resultParams.put(BtsProperties.AUTH_TYPE.getName(), authName);
});
Optional.ofNullable(integrationParams.get("defectFormFields"))
.ifPresent(defectFormFields -> resultParams.put("defectFormFields", defectFormFields));
return resultParams;
}
@Override
public boolean checkConnection(Integration integration) {
BtsExtension extension = pluginBox.getInstance(integration.getType().getName(), BtsExtension.class)
.orElseThrow(() -> new ReportPortalException(ErrorType.UNABLE_INTERACT_WITH_INTEGRATION,
Suppliers.formattedSupplier("Could not find plugin with name '{}'.", integration.getType().getName()).get()
));
expect(extension.testConnection(integration), BooleanUtils::isTrue).verify(ErrorType.UNABLE_INTERACT_WITH_INTEGRATION,
"Connection refused."
);
return true;
}
/**
* Retrieves auth params based on auth type
*/
private Map<String, Object> retrieveAuthParams(Map<String, Object> integrationParams, Map<String, Object> resultParams,
String authName) {
AuthType authType = AuthType.findByName(authName)
.orElseThrow(() -> new ReportPortalException(ErrorType.INCORRECT_AUTHENTICATION_TYPE, authName));
if (AuthType.BASIC.equals(authType)) {
resultParams.put(BtsProperties.USER_NAME.getName(),
BtsProperties.USER_NAME.getParam(integrationParams)
.orElseThrow(() -> new ReportPortalException(UNABLE_INTERACT_WITH_INTEGRATION,
"Username value is not specified"
))
);
String encryptedPassword = basicTextEncryptor.encrypt(BtsProperties.PASSWORD.getParam(integrationParams)
.orElseThrow(() -> new ReportPortalException(UNABLE_INTERACT_WITH_INTEGRATION, "Password value is not specified")));
resultParams.put(BtsProperties.PASSWORD.getName(), encryptedPassword);
} else if (AuthType.OAUTH.equals(authType)) {
final String encryptedAccessKey = basicTextEncryptor.encrypt(BtsProperties.OAUTH_ACCESS_KEY.getParam(integrationParams)
.orElseThrow(() -> new ReportPortalException(UNABLE_INTERACT_WITH_INTEGRATION, "AccessKey value is not specified")));
resultParams.put(BtsProperties.OAUTH_ACCESS_KEY.getName(), encryptedAccessKey);
} else {
throw new ReportPortalException(ErrorType.UNABLE_INTERACT_WITH_INTEGRATION,
"Unsupported auth type for integration - " + authType.name()
);
}
return resultParams;
}
}
| 44.631206 | 136 | 0.791355 |
2f8178c6235824bbfddeabe2d8aa2cec1fc2192d | 8,167 | package com.salesmanager.core.business.modules.cms.product.local;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.salesmanager.core.business.constants.Constants;
import com.salesmanager.core.business.exception.ServiceException;
import com.salesmanager.core.business.modules.cms.impl.CMSManager;
import com.salesmanager.core.business.modules.cms.impl.LocalCacheManagerImpl;
import com.salesmanager.core.business.modules.cms.product.ProductAssetsManager;
import com.salesmanager.core.model.catalog.product.Product;
import com.salesmanager.core.model.catalog.product.file.ProductImageSize;
import com.salesmanager.core.model.catalog.product.image.ProductImage;
import com.salesmanager.core.model.content.FileContentType;
import com.salesmanager.core.model.content.ImageContentFile;
import com.salesmanager.core.model.content.OutputContentFile;
import com.salesmanager.core.model.merchant.MerchantStore;
/**
* Manager for storing and deleting image files from the CMS which is a web server
*
* Manages - Product images
*
* @author Carl Samson
*/
public class CmsImageFileManagerImpl
// implements ProductImagePut, ProductImageGet, ProductImageRemove
implements ProductAssetsManager {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(CmsImageFileManagerImpl.class);
private static CmsImageFileManagerImpl fileManager = null;
private final static String ROOT_NAME = "";
private final static String SMALL = "SMALL";
private final static String LARGE = "LARGE";
private static final String ROOT_CONTAINER = "products";
private String rootName = ROOT_NAME;
private LocalCacheManagerImpl cacheManager;
@PostConstruct
void init() {
this.rootName = ((CMSManager) cacheManager).getRootName();
LOGGER.info("init " + getClass().getName() + " setting root" + this.rootName);
}
public static CmsImageFileManagerImpl getInstance() {
if (fileManager == null) {
fileManager = new CmsImageFileManagerImpl();
}
return fileManager;
}
private CmsImageFileManagerImpl() {
}
/**
* root/products/<merchant id>/<product id>/1.jpg
*/
@Override
public void addProductImage(ProductImage productImage, ImageContentFile contentImage)
throws ServiceException {
try {
// base path
String rootPath = this.buildRootPath();
Path confDir = Paths.get(rootPath);
this.createDirectoryIfNorExist(confDir);
// node path
StringBuilder nodePath = new StringBuilder();
nodePath.append(rootPath).append(productImage.getProduct().getMerchantStore().getCode());
Path merchantPath = Paths.get(nodePath.toString());
this.createDirectoryIfNorExist(merchantPath);
// product path
nodePath.append(Constants.SLASH).append(productImage.getProduct().getSku())
.append(Constants.SLASH);
Path dirPath = Paths.get(nodePath.toString());
this.createDirectoryIfNorExist(dirPath);
// small large
if (contentImage.getFileContentType().name().equals(FileContentType.PRODUCT.name())) {
nodePath.append(SMALL);
} else if (contentImage.getFileContentType().name()
.equals(FileContentType.PRODUCTLG.name())) {
nodePath.append(LARGE);
}
Path sizePath = Paths.get(nodePath.toString());
this.createDirectoryIfNorExist(sizePath);
// file creation
nodePath.append(Constants.SLASH).append(contentImage.getFileName());
Path path = Paths.get(nodePath.toString());
InputStream isFile = contentImage.getFile();
Files.copy(isFile, path, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
throw new ServiceException(e);
}
}
@Override
public OutputContentFile getProductImage(ProductImage productImage) throws ServiceException {
// the web server takes care of the images
return null;
}
public List<OutputContentFile> getImages(MerchantStore store, FileContentType imageContentType)
throws ServiceException {
// the web server takes care of the images
return null;
}
@Override
public List<OutputContentFile> getImages(Product product) throws ServiceException {
// the web server takes care of the images
return null;
}
@Override
public void removeImages(final String merchantStoreCode) throws ServiceException {
try {
StringBuilder merchantPath = new StringBuilder();
merchantPath.append(buildRootPath()).append(Constants.SLASH).append(merchantStoreCode);
Path path = Paths.get(merchantPath.toString());
Files.deleteIfExists(path);
} catch (Exception e) {
throw new ServiceException(e);
}
}
@Override
public void removeProductImage(ProductImage productImage) throws ServiceException {
try {
StringBuilder nodePath = new StringBuilder();
nodePath.append(buildRootPath()).append(Constants.SLASH)
.append(productImage.getProduct().getMerchantStore().getCode()).append(Constants.SLASH)
.append(productImage.getProduct().getSku());
// delete small
StringBuilder smallPath = new StringBuilder(nodePath);
smallPath.append(Constants.SLASH).append(SMALL).append(Constants.SLASH)
.append(productImage.getProductImage());
Path path = Paths.get(smallPath.toString());
Files.deleteIfExists(path);
// delete large
StringBuilder largePath = new StringBuilder(nodePath);
largePath.append(Constants.SLASH).append(LARGE).append(Constants.SLASH)
.append(productImage.getProductImage());
path = Paths.get(largePath.toString());
Files.deleteIfExists(path);
} catch (Exception e) {
throw new ServiceException(e);
}
}
@Override
public void removeProductImages(Product product) throws ServiceException {
try {
StringBuilder nodePath = new StringBuilder();
nodePath.append(buildRootPath()).append(Constants.SLASH)
.append(product.getMerchantStore().getCode()).append(Constants.SLASH)
.append(product.getSku());
Path path = Paths.get(nodePath.toString());
Files.deleteIfExists(path);
} catch (Exception e) {
throw new ServiceException(e);
}
}
@Override
public List<OutputContentFile> getImages(final String merchantStoreCode,
FileContentType imageContentType) throws ServiceException {
// the web server taks care of the images
return null;
}
@Override
public OutputContentFile getProductImage(String merchantStoreCode, String productCode,
String imageName) throws ServiceException {
return getProductImage(merchantStoreCode, productCode, imageName,
ProductImageSize.SMALL.name());
}
@Override
public OutputContentFile getProductImage(String merchantStoreCode, String productCode,
String imageName, ProductImageSize size) throws ServiceException {
return getProductImage(merchantStoreCode, productCode, imageName, size.name());
}
private OutputContentFile getProductImage(String merchantStoreCode, String productCode,
String imageName, String size) throws ServiceException {
return null;
}
private String buildRootPath() {
return new StringBuilder().append(getRootName()).append(Constants.SLASH).append(ROOT_CONTAINER)
.append(Constants.SLASH).toString();
}
private void createDirectoryIfNorExist(Path path) throws IOException {
if (Files.notExists(path)) {
Files.createDirectory(path);
}
}
public void setRootName(String rootName) {
this.rootName = rootName;
}
public String getRootName() {
return rootName;
}
public LocalCacheManagerImpl getCacheManager() {
return cacheManager;
}
public void setCacheManager(LocalCacheManagerImpl cacheManager) {
this.cacheManager = cacheManager;
}
}
| 26.26045 | 99 | 0.724501 |
44e073d9cc3a07bf50be3aaa3619d0c93e1b02b0 | 536 | package org.forestguardian.DataAccess.Local;
import com.google.gson.annotations.Expose;
import io.realm.RealmObject;
/**
* Created by emma on 27/07/17.
*/
public class DeviceInfo extends RealmObject{
@Expose
private String firebase_registration_token;
public String getFirebaseRegistrationToken() {
return firebase_registration_token;
}
public void setFirebaseRegistrationToken(final String pFirebase_registration_token) {
firebase_registration_token = pFirebase_registration_token;
}
}
| 22.333333 | 89 | 0.764925 |
956ad2285f8c8df1a324c3b0dc56fbee9aae340d | 3,418 | package com.example.rachs.tutorapp_mobapde;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class EditCodeClass extends AppCompatActivity {
private EditText titleText, typeText, contentText;
private FirebaseDatabase database;
private FirebaseInterface fbInterface;
private DatabaseReference codeRef;
private String id;
private ArrayList<CodeSample> sample;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_code_sample);
TextView addView = findViewById(R.id.addView);
titleText = findViewById(R.id.titleText);
typeText = findViewById(R.id.typeText);
contentText = findViewById(R.id.contentText);
Button btnAdd = findViewById(R.id.btnAdd);
addView.setText("Edit Code Sample");
btnAdd.setText("Edit");
Intent intent = getIntent();
id = intent.getStringExtra("CODE_SAMPLE_ID");
sample = new ArrayList<>();
database = FirebaseDatabase.getInstance();
fbInterface = new FirebaseInterface();
codeRef = database.getReference("codesamples");
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// use fbInterface to get the CodeSample object through ID in the extras of intent then store it as attribute then use that for updating
fbInterface.updateCodeTitle(sample.get(0), titleText.getText().toString(), codeRef);
fbInterface.updateCodeType(sample.get(0), typeText.getText().toString(), codeRef);
fbInterface.updateCodeSample(sample.get(0), contentText.getText().toString(), codeRef);
finish();
startActivity(new Intent(EditCodeClass.this, ProfileClass.class).putExtra("USER_ID", getIntent().getStringExtra("USER_ID")));
}
});
}
@Override
protected void onStart() {
super.onStart();
codeRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Intent intent = getIntent();
String userID = intent.getStringExtra("USER_ID");
String postID = intent.getStringExtra("CODE_SAMPLE_ID");
fbInterface.getSpecificSampleData(userID, postID, dataSnapshot);
sample = fbInterface.getCodes();
titleText.setText(sample.get(0).getTitle());
typeText.setText(sample.get(0).getType());
contentText.setText(sample.get(0).getCodeSample());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
| 37.977778 | 152 | 0.677297 |
8672a2548e162a022b1d222a0bf696464a7e5af2 | 753 | package com.yikuan.androidcommon;
import android.app.Application;
import android.content.Context;
/**
* @author yikuan
* @date 2019/09/08
*/
public class AndroidCommon {
private static Application sApplication;
private AndroidCommon() {
throw new UnsupportedOperationException("cannot be instantiated");
}
public static void init(Context context) {
if (context == null) {
throw new NullPointerException("context is null");
}
sApplication = (Application) context.getApplicationContext();
}
public static Application getApp() {
if (sApplication == null) {
throw new NullPointerException("u need to init first");
}
return sApplication;
}
}
| 24.290323 | 74 | 0.653386 |
3bba1cb997b3462ff7ed6f824fe597c3ab26fb9e | 741 | package org.femtoframework.coin.exception;
/**
* Bean doesn't have expected kind
*
* @author fengyun
* @version 1.00 2009-2-3 14:28:22
*/
public class BeanNotExpectedException extends BeanCreationException
{
public BeanNotExpectedException(String objectName, Class objectType, Class expectedType)
{
super(objectName, "The bean kind is " + objectType.getName()
+ " but expected kind is " + expectedType.getName());
}
public BeanNotExpectedException(String expectedName, String declaredName)
{
super("The expected name is " + expectedName + ", but declared name is " + declaredName);
}
public BeanNotExpectedException(String msg)
{
super(msg);
}
}
| 26.464286 | 97 | 0.669366 |
dc0a333a06fb36cebbc1a6f71fb81d0c14f5362d | 12,549 | /*
* 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.netbeans.modules.glassfish.tooling.admin;
import java.io.*;
import java.net.HttpURLConnection;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.netbeans.modules.glassfish.tooling.data.GlassFishServer;
import org.netbeans.modules.glassfish.tooling.logging.Logger;
import org.netbeans.modules.glassfish.tooling.utils.Utils;
/**
* GlassFish Server <code>deploy</code> Administration Command Execution
* using HTTP interface.
* <p/>
* Class implements GlassFish server administration functionality trough HTTP
* interface.
* <p/>
* @author Tomas Kraus, Peter Benedikovic
*/
public class RunnerHttpDeploy extends RunnerHttp {
////////////////////////////////////////////////////////////////////////////
// Class attributes //
////////////////////////////////////////////////////////////////////////////
/** Logger instance for this class. */
private static final Logger LOGGER = new Logger(RunnerHttpDeploy.class);
/** Deploy command <code>DEFAULT</code> parameter name. */
private static final String DEFAULT_PARAM = "DEFAULT";
/** Deploy command <code>target</code> parameter name. */
private static final String TARGET_PARAM = "target";
/** Deploy command <code>name</code> parameter name. */
private static final String NAME_PARAM = "name";
/** Deploy command <code>contextroot</code> parameter name. */
private static final String CTXROOT_PARAM = "contextroot";
/** Deploy command <code>force</code> parameter name. */
private static final String FORCE_PARAM = "force";
/** Deploy command <code>properties</code> parameter name. */
private static final String PROPERTIES_PARAM = "properties";
/** Deploy command <code>libraries</code> parameter name. */
private static final String LIBRARIES_PARAM = "libraries";
/** Deploy command <code>force</code> parameter value. */
private static final boolean FORCE_VALUE = true;
////////////////////////////////////////////////////////////////////////////
// Static methods //
////////////////////////////////////////////////////////////////////////////
/**
* Builds deploy query string for given command.
* <p/>
* <code>QUERY :: "DEFAULT" '=' <path> <br/>
* '&' "force" '=' true | false <br/>
* ['&' "name" '=' <name> ] <br/>
* ['&' "target" '=' <target> ] <br/>
* ['&' "contextroot" '=' <contextRoot> ] <br/>
* ['&' "properties" '=' <pname> '=' <pvalue>
* { ':' <pname> '=' <pvalue>} ]</code>
* ['&' "libraries" '=' <lname> '=' <lvalue>
* { ':' <lname> '=' <lvalue>} ]</code>
* <p/>
* @param command GlassFish server administration deploy command entity.
* @return Deploy query string for given command.
*/
private static String query(final Command command) {
// Prepare values
String name;
String path;
String target;
String ctxRoot;
String force = Boolean.toString(FORCE_VALUE);
if (command instanceof CommandDeploy) {
if (((CommandDeploy)command).path == null) {
throw new CommandException(CommandException.ILLEGAL_NULL_VALUE);
}
name = Utils.sanitizeName(((CommandDeploy)command).name);
path = ((CommandDeploy)command).path.getAbsolutePath();
target =((CommandDeploy)command).target;
ctxRoot = ((CommandDeploy)command).contextRoot;
}
else {
throw new CommandException(
CommandException.ILLEGAL_COMAND_INSTANCE);
}
// Calculate StringBuilder initial length to avoid resizing
StringBuilder sb = new StringBuilder(
DEFAULT_PARAM.length() + 1 + path.length() +
1 + FORCE_PARAM.length() + 1 + force.length()
+ queryPropertiesLength(
((CommandDeploy)command).properties, PROPERTIES_PARAM)
+ queryLibrariesLength(
((CommandDeploy)command).libraries, LIBRARIES_PARAM)
+ ( name != null && name.length() > 0
? 1 + NAME_PARAM.length() + 1 + name.length()
: 0
) + ( target != null
? 1 + TARGET_PARAM.length() + 1 + target.length()
: 0
) + ( ctxRoot != null && ctxRoot.length() > 0
? 1 + CTXROOT_PARAM.length() + 1 + ctxRoot.length()
: 0
));
// Build query string
sb.append(DEFAULT_PARAM).append(PARAM_ASSIGN_VALUE).append(path);
sb.append(PARAM_SEPARATOR);
sb.append(FORCE_PARAM).append(PARAM_ASSIGN_VALUE).append(force);
if (name != null && name.length() > 0) {
sb.append(PARAM_SEPARATOR);
sb.append(NAME_PARAM).append(PARAM_ASSIGN_VALUE).append(name);
}
if (target != null) {
sb.append(PARAM_SEPARATOR);
sb.append(TARGET_PARAM).append(PARAM_ASSIGN_VALUE).append(target);
}
if (ctxRoot != null && ctxRoot.length() > 0) {
sb.append(PARAM_SEPARATOR);
sb.append(CTXROOT_PARAM).append(PARAM_ASSIGN_VALUE).append(ctxRoot);
}
// Add properties into query string.
queryPropertiesAppend(sb, ((CommandDeploy)command).properties,
PROPERTIES_PARAM, true);
queryLibrariesAppend(sb, ((CommandDeploy)command).libraries,
LIBRARIES_PARAM, true);
return sb.toString();
}
////////////////////////////////////////////////////////////////////////////
// Instance attributes //
////////////////////////////////////////////////////////////////////////////
/** Holding data for command execution. */
@SuppressWarnings("FieldNameHidesFieldInSuperclass")
final CommandDeploy command;
////////////////////////////////////////////////////////////////////////////
// Constructors //
////////////////////////////////////////////////////////////////////////////
/**
* Constructs an instance of administration command executor using
* HTTP interface.
* <p>
* @param server GlassFish server entity object.
* @param command GlassFish server administration command entity.
*/
public RunnerHttpDeploy(final GlassFishServer server,
final Command command) {
super(server, command, query(command));
this.command = (CommandDeploy)command;
}
////////////////////////////////////////////////////////////////////////////
// Implemented Abstract Methods //
////////////////////////////////////////////////////////////////////////////
/**
* Send deployed file to the server via HTTP POST when it's not
* a directory deployment.
* <p/>
* @return <code>true</code> if using HTTP POST to send to server
* or <code>false</code> otherwise
*/
@Override
public boolean getDoOutput() {
return !command.dirDeploy;
}
/**
* HTTP request method used for this command is <code>POST</code> for
* file deployment and <code>GET</code> for directory deployment.
*
* @return HTTP request method used for this command.
*/
@Override
public String getRequestMethod() {
return command.dirDeploy ? super.getRequestMethod() : "POST";
}
/**
* Handle sending data to server using HTTP command interface.
* <p/>
* This is based on reading the code of <code>CLIRemoteCommand.java</code>
* from the server's code repository. Since some asadmin commands
* need to send multiple files, the server assumes the input is a ZIP
* stream.
*/
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
final String METHOD = "handleSend";
InputStream istream = getInputStream();
if(istream != null) {
ZipOutputStream ostream = null;
try {
ostream = new ZipOutputStream(new BufferedOutputStream(
hconn.getOutputStream(), 1024*1024));
ZipEntry e = new ZipEntry(command.path.getName());
e.setExtra(getExtraProperties());
ostream.putNextEntry(e);
byte buffer[] = new byte[1024*1024];
while (true) {
int n = istream.read(buffer);
if (n < 0) {
break;
}
ostream.write(buffer, 0, n);
}
ostream.closeEntry();
ostream.flush();
} finally {
try {
istream.close();
} catch(IOException ex) {
LOGGER.log(Level.INFO, METHOD, "ioException", ex);
}
if(ostream != null) {
try {
ostream.close();
} catch(IOException ex) {
LOGGER.log(Level.INFO, METHOD, "ioException", ex);
}
}
}
} else if("POST".equalsIgnoreCase(getRequestMethod())) {
LOGGER.log(Level.INFO, METHOD, "noData");
}
}
////////////////////////////////////////////////////////////////////////////
// Fake Getters //
////////////////////////////////////////////////////////////////////////////
/**
* Set the content-type of information sent to the server.
* Returns <code>application/zip</code> for file deployment
* and <code>null</code> (not set) for directory deployment.
*
* @return content-type of data sent to server via HTTP POST
*/
@Override
public String getContentType() {
return command.dirDeploy ? null : "application/zip";
}
/**
* Provide the lastModified date for data source whose
* <code>InputStream</code> is returned by getInputStream.
* <p/>
* @return String format of long integer from lastModified date of source.
*/
@Override
public String getLastModified() {
return Long.toString(command.path.lastModified());
}
/**
* Get <code>InputStream</code> object for deployed file.
* <p/>
* @return <code>InputStream</code> object for deployed file
* or <code>null</code> for directory deployment.
*/
public InputStream getInputStream() {
final String METHOD = "getInputStream";
if (command.dirDeploy) {
return null;
} else {
try {
return new FileInputStream(command.path);
} catch (FileNotFoundException fnfe) {
LOGGER.log(Level.INFO, METHOD, "fileNotFound", fnfe);
return null;
}
}
}
}
| 41.144262 | 110 | 0.52817 |
f899b71162dbb2cc76da3b77589d4db4d37583d4 | 2,276 | package com.workhub.z.servicechat.entity;
import java.util.Date;
import java.io.Serializable;
/**
* 字典词汇表(ZzDictionaryWords)实体类
*
* @author makejava
* @since 2019-05-17 14:56:57
*/
public class ZzDictionaryWords implements Serializable {
private static final long serialVersionUID = -16442401804845507L;
//主键
private String id;
//词汇类型(1-涉密,2-敏感)
private String wordType;
//词汇编码
private String wordCode;
//词汇名称
private String wordName;
//替换词汇
private String replaceWord;
//创建时间
private Date createTime;
//创建人
private String createUser;
//修改时间
private Date updateTime;
//修改人
private String updateUser;
//是否启用(0-否,1-是)
private Object isUse;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getWordType() {
return wordType;
}
public void setWordType(String wordType) {
this.wordType = wordType;
}
public String getWordCode() {
return wordCode;
}
public void setWordCode(String wordCode) {
this.wordCode = wordCode;
}
public String getWordName() {
return wordName;
}
public void setWordName(String wordName) {
this.wordName = wordName;
}
public String getReplaceWord() {
return replaceWord;
}
public void setReplaceWord(String replaceWord) {
this.replaceWord = replaceWord;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public Object getIsUse() {
return isUse;
}
public void setIsUse(Object isUse) {
this.isUse = isUse;
}
} | 19.62069 | 69 | 0.623462 |
ad7303e26b6737eb8c8fe3587f46d39f49cf542d | 3,076 | package net.powermatcher.examples;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.powermatcher.api.monitoring.AgentObserver;
import net.powermatcher.api.monitoring.ObservableAgent;
import net.powermatcher.api.monitoring.events.AgentEvent;
/**
* {@link ConsoleObserver} is an example implementation of the {@link BaseObserver} interface. You can add
* {@link ObservableAgent}s and it can receive {@link AgentEvent}s from them.
*
* @author FAN
* @version 2.1
*/
@Component(immediate = true)
@Designate(ocd = ConsoleObserver.Config.class)
public class ConsoleObserver
implements AgentObserver {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleObserver.class);
/**
* This interface describes the configuration of this {@link ConsoleObserver}. It defines the filter for the
* {@link ObservableAgent}s that are needed.
*/
@ObjectClassDefinition
public @interface Config {
@AttributeDefinition(required = false,
description = "The LDAP filter for the ObservableAgents that we want to monitor. "
+ "E.g. '(agentId=auctioneer)'")
String observableAgent_filter() default "";
}
/**
* Adds an {@link ObservableAgent} to this {@link ConsoleObserver}. This will register itself with the object.
* Normally this should be called by the OSGi platform using DS. This method has no effect if this was already
* registered.
*
* @param observable
* The {@link ObservableAgent} that it should be registered on.
*/
@Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE)
public void addObservableAgent(ObservableAgent observable) {
observable.addObserver(this);
}
/**
* Removes an {@link ObservableAgent} from this {@link ConsoleObserver}. This will unregister itself with the
* object. Normally this should be called by the OSGi platform using DS. This method has no effect if this wasn't
* already registered.
*
* @param observable
* The {@link ObservableAgent} that it should unregister from.
*/
public void removeObservableAgent(ObservableAgent observable) {
observable.removeObserver(this);
}
/**
* Prints the {@link AgentEvent} to the logging using its toString() method.
*
* @param event
* The {@link AgentEvent} that is to be printed.
*/
@Override
public void handleAgentEvent(AgentEvent event) {
LOGGER.info("Received event: {}", event);
}
}
| 38.936709 | 117 | 0.705462 |
3cbcdf735df4e8b916491b04d9f9cb0e57d289ce | 4,694 | /*
* 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.tuscany.sca.binding.jsonrpc.provider;
import java.lang.reflect.Method;
import java.util.Collection;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Utility class to create a Simple Method Description (SMD) descriptor
* from a Java class. See http://dojo.jot.com/SMD.
*
* TODO: Change to work from the Tuscany Interface instead of a Java class
*
* @version $Rev$ $Date$
*/
public class JavaToSmd {
public static String interfaceToSmd(Class<?> klazz, String serviceUrl) {
try {
String name = klazz.getSimpleName();
Method[] methods = klazz.getMethods();
JSONObject smd = new JSONObject();
smd.put("SMDVersion", ".1");
smd.put("objectName", name);
smd.put("serviceType", "JSON-RPC");
smd.put("serviceURL", serviceUrl);
JSONArray services = new JSONArray();
for (int i = 0; i < methods.length; i++) {
JSONObject service = new JSONObject();
Class<?>[] params = methods[i].getParameterTypes();
JSONArray paramArray = new JSONArray();
for (int j = 0; j < params.length; j++) {
JSONObject param = new JSONObject();
param.put("name", "param" + j);
param.put("type", getJSONType(params[j]));
paramArray.put(param);
}
service.put("name", methods[i].getName());
service.put("parameters", paramArray);
services.put(service);
}
smd.put("methods", services);
return smd.toString(2);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static String interfaceToSmd20(Class<?> klazz, String serviceUrl) {
try {
String name = klazz.getSimpleName();
Method[] methods = klazz.getMethods();
JSONObject smd = new JSONObject();
smd.put("SMDVersion", "2.0");
smd.put("transport", "POST");
smd.put("envelope", "JSON-RPC-1.0");
smd.put("target", serviceUrl);
smd.put("id", klazz.getName());
smd.put("description", "JSON-RPC service provided by Tuscany: " + name);
JSONObject services = new JSONObject();
for (int i = 0; i < methods.length; i++) {
JSONObject service = new JSONObject();
Class<?>[] params = methods[i].getParameterTypes();
JSONArray paramArray = new JSONArray();
for (int j = 0; j < params.length; j++) {
JSONObject param = new JSONObject();
param.put("name", "param" + j);
param.put("type", getJSONType(params[j]));
paramArray.put(param);
}
service.put("parameters", paramArray);
services.put(methods[i].getName(), service);
}
smd.put("services", services);
return smd.toString(2);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private static String getJSONType(Class<?> type) {
if (type == boolean.class || type == Boolean.class) {
return "boolean";
}
if (type == String.class) {
return "string";
}
if (byte.class == type || short.class == type
|| int.class == type
|| long.class == type
|| float.class == type
|| double.class == type
|| Number.class.isAssignableFrom(type)) {
return "number";
}
if (type.isArray() || Collection.class.isAssignableFrom(type)) {
return "array";
}
return "object";
}
}
| 35.560606 | 84 | 0.558585 |
53e2f99f69d9e0986cc87faa7f5994c77b211ee7 | 1,486 | /*
* 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.exadel.aem.toolkit.test.widget;
import com.exadel.aem.toolkit.api.annotations.main.Dialog;
import com.exadel.aem.toolkit.api.annotations.main.DialogLayout;
import com.exadel.aem.toolkit.api.annotations.widgets.Checkbox;
@Dialog(
name = "test-component",
title = "test-component-dialog",
layout = DialogLayout.FIXED_COLUMNS
)
@SuppressWarnings("unused")
public class NestedCheckboxListWidget {
@Checkbox(text = "Level 1 Checkbox", sublist = Sublist.class)
boolean option1L1;
static class Sublist {
@Checkbox(text = "Level 2 Checkbox 1")
boolean option2L1;
@Checkbox(text = "Level 2 Checkbox 2", sublist = Sublist2.class)
boolean option2L2;
}
private static class Sublist2 {
@Checkbox(text = "Level 3 Checkbox 1")
boolean option3L1;
@Checkbox(text = "Level 3 Checkbox 2")
boolean option3L2;
}
}
| 31.617021 | 75 | 0.701211 |
3637bb2da93f0e515ade8d2746851d85afd076a4 | 4,101 | /*
* 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.lucene.queries.function.docvalues;
import java.io.IOException;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.ValueSourceScorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueLong;
/**
* Abstract {@link FunctionValues} implementation which supports retrieving long values.
* Implementations can control how the long values are loaded through {@link #longVal(int)}}
*/
public abstract class LongDocValues extends FunctionValues {
protected final ValueSource vs;
public LongDocValues(ValueSource vs) {
this.vs = vs;
}
@Override
public byte byteVal(int doc) throws IOException {
return (byte)longVal(doc);
}
@Override
public short shortVal(int doc) throws IOException {
return (short)longVal(doc);
}
@Override
public float floatVal(int doc) throws IOException {
return (float)longVal(doc);
}
@Override
public int intVal(int doc) throws IOException {
return (int)longVal(doc);
}
@Override
public abstract long longVal(int doc) throws IOException;
@Override
public double doubleVal(int doc) throws IOException {
return (double)longVal(doc);
}
@Override
public boolean boolVal(int doc) throws IOException {
return longVal(doc) != 0;
}
@Override
public String strVal(int doc) throws IOException {
return Long.toString(longVal(doc));
}
@Override
public Object objectVal(int doc) throws IOException {
return exists(doc) ? longVal(doc) : null;
}
@Override
public String toString(int doc) throws IOException {
return vs.description() + '=' + strVal(doc);
}
protected long externalToLong(String extVal) {
return Long.parseLong(extVal);
}
@Override
public ValueSourceScorer getRangeScorer(Weight weight, LeafReaderContext readerContext, String lowerVal, String upperVal, boolean includeLower, boolean includeUpper) {
long lower,upper;
// instead of using separate comparison functions, adjust the endpoints.
if (lowerVal==null) {
lower = Long.MIN_VALUE;
} else {
lower = externalToLong(lowerVal);
if (!includeLower && lower < Long.MAX_VALUE) lower++;
}
if (upperVal==null) {
upper = Long.MAX_VALUE;
} else {
upper = externalToLong(upperVal);
if (!includeUpper && upper > Long.MIN_VALUE) upper--;
}
final long ll = lower;
final long uu = upper;
return new ValueSourceScorer(weight, readerContext, this) {
@Override
public boolean matches(int doc) throws IOException {
if (!exists(doc)) return false;
long val = longVal(doc);
return val >= ll && val <= uu;
}
};
}
@Override
public ValueFiller getValueFiller() {
return new ValueFiller() {
private final MutableValueLong mval = new MutableValueLong();
@Override
public MutableValue getValue() {
return mval;
}
@Override
public void fillValue(int doc) throws IOException {
mval.value = longVal(doc);
mval.exists = exists(doc);
}
};
}
}
| 28.678322 | 170 | 0.703975 |
1b81cf093c0bd2713e278a9260ef290e85a41411 | 6,227 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.security.propertyeditor;
import java.beans.PropertyEditorSupport;
import java.security.KeyStore;
import java.security.Principal;
import java.util.Set;
import javax.naming.InitialContext;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.Subject;
import org.jboss.security.SecurityDomain;
import org.jboss.logging.Logger;
/** A property editor for org.jboss.security.SecurityDomain types. This editor
* transforms a jndi name string to a SecurityDomain by looking up the binding.
* The only unusual aspect of this editor is that the jndi name is usually of
* the form java:/jaas/xxx and the java:/jaas context is a dynamic ObjectFactory
* that will create a binding for any xxx. If there is an attempt to lookup a
* binding before it has been created by the underlying service that provides
* the SecurityDomain, the lookup will return the default security service
* which typically does not implement SecurityDomain. In this case, the editor
* will create a proxy that delays the lookup of the SecurityDomain until the
* first method invocation against the proxy.
*
* @author [email protected]
* @version $Revision: 57203 $
*/
public class SecurityDomainEditor
extends PropertyEditorSupport
{
private static Logger log = Logger.getLogger(SecurityDomainEditor.class);
private String domainName;
/** Get the SecurityDomain from the text which is the jndi name of the
* SecurityDomain binding. This may have to create a proxy if the current
* value of the binding is not a SecurityDomain.
* @param text - the name of the Principal
*/
public void setAsText(final String text)
{
this.domainName = text;
try
{
InitialContext ctx = new InitialContext();
Object ref = ctx.lookup(text);
SecurityDomain domain = null;
if( ref instanceof SecurityDomain )
{
domain = (SecurityDomain) ref;
}
else
{
// Create a proxy to delay the lookup until needed
domain = new SecurityDomainProxy(domainName);
}
setValue(domain);
}
catch(Exception e)
{
log.error("Failed to lookup SecurityDomain, "+domainName, e);
}
}
/** Return the original security domain jndi name since we cannot get
* this back from the SecurityDomain itself.
* @return
*/
public String getAsText()
{
return domainName;
}
/** A proxy that delays the lookup of the SecurityDomain until there
* is a SecurityDomain method invocation. This gets around the problem
* of a service not exposing its SecurityDomain binding until its started.
*/
static class SecurityDomainProxy implements SecurityDomain
{
SecurityDomain delegate;
private String jndiName;
SecurityDomainProxy(String jndiName)
{
this.jndiName = jndiName;
}
private synchronized void initDelegate()
{
if( delegate == null )
{
try
{
InitialContext ctx = new InitialContext();
delegate = (SecurityDomain) ctx.lookup(jndiName);
}
catch(Exception e)
{
SecurityException se = new SecurityException("Failed to lookup SecurityDomain, "+jndiName);
se.initCause(e);
throw se;
}
}
}
public KeyStore getKeyStore() throws SecurityException
{
initDelegate();
return delegate.getKeyStore();
}
public KeyManagerFactory getKeyManagerFactory() throws SecurityException
{
initDelegate();
return delegate.getKeyManagerFactory();
}
public KeyStore getTrustStore() throws SecurityException
{
initDelegate();
return delegate.getTrustStore();
}
public TrustManagerFactory getTrustManagerFactory() throws SecurityException
{
initDelegate();
return delegate.getTrustManagerFactory();
}
public String getSecurityDomain()
{
initDelegate();
return delegate.getSecurityDomain();
}
public boolean isValid(Principal principal, Object credential)
{
return this.isValid(principal, credential, null);
}
public boolean isValid(Principal principal, Object credential,
Subject activeSubject)
{
initDelegate();
return delegate.isValid(principal, credential, activeSubject);
}
public Subject getActiveSubject()
{
initDelegate();
return delegate.getActiveSubject();
}
public Principal getPrincipal(Principal principal)
{
initDelegate();
return delegate.getPrincipal(principal);
}
public boolean doesUserHaveRole(Principal principal, Set roles)
{
initDelegate();
return delegate.doesUserHaveRole(principal, roles);
}
public Set getUserRoles(Principal principal)
{
initDelegate();
return delegate.getUserRoles(principal);
}
}
}
| 31.933333 | 106 | 0.669825 |
c2f02e5562448c2a58c8ec80cb01ef7b10b08945 | 1,843 | ////////////////////////////////////////////////////////////////////////////////
//
// Created by NUebele on 10.08.2018.
//
// Copyright (c) 2006 - 2018 FORCAM GmbH. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
package com.forcam.na.ffwebservices.model.workplace;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.forcam.na.ffwebservices.model.TimePeriodWSModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
* Workplace scheduled maintenance times properties model.
*/
@JsonPropertyOrder({ "elements" })
public class WorkplaceScheduledMaintenanceTimesPropertiesWSModel {
// ------------------------------------------------------------------------
// members
// ------------------------------------------------------------------------
/** Workplace scheduled maintenance times elements. */
private List<TimePeriodWSModel> mElements;
// ------------------------------------------------------------------------
// getters/setters
// ------------------------------------------------------------------------
/**
* Setter for {@link WorkplaceScheduledMaintenanceTimesPropertiesWSModel#mElements}.
*
* @param elements Workplace scheduled maintenance times elements.
*/
@ApiModelProperty(value = "Array of time periods, i.e. the periods from the start date to th end date of a scheduled maintenance", position = 0)
public void setElements(List<TimePeriodWSModel> elements) {
mElements = elements;
}
/**
* Getter for {@link WorkplaceScheduledMaintenanceTimesPropertiesWSModel#mElements}.
*
* @return Workplace scheduled maintenance times elements.
*/
public List<TimePeriodWSModel> getElements() {
return mElements;
}
} | 36.86 | 148 | 0.539881 |
9813c865b6fc66ecab82000e48b4bba24e1ec277 | 539 | package org.jboss.resteasy.test.microprofile.restclient.resource;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("/thePatron")
@ApplicationScoped
public class FollowRedirectsResource {
@Path("redirected")
@GET
public Response redirected(){
return Response.ok("OK").build();
}
@GET
@Path("redirectedDirectResponse")
public String redirectedDirectResponse() {
return "ok - direct response";
}
}
| 21.56 | 65 | 0.710575 |
ec0ed07c1765a07773af9b60daa3cfb75a893397 | 66,444 | /*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* 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.slc.sli.api.service;
import junit.framework.Assert;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.slc.sli.api.config.BasicDefinitionStore;
import org.slc.sli.api.config.DefinitionFactory;
import org.slc.sli.api.config.EntityDefinition;
import org.slc.sli.api.representation.EntityBody;
import org.slc.sli.api.resources.SecurityContextInjector;
import org.slc.sli.api.security.SLIPrincipal;
import org.slc.sli.api.security.context.APIAccessDeniedException;
import org.slc.sli.api.security.context.ContextValidator;
import org.slc.sli.api.security.roles.EntityRightsFilter;
import org.slc.sli.api.security.roles.RightAccessValidator;
import org.slc.sli.api.service.query.ApiQuery;
import org.slc.sli.api.test.WebContextTestExecutionListener;
import org.slc.sli.api.util.RequestUtil;
import org.slc.sli.api.util.SecurityUtil;
import org.slc.sli.common.constants.EntityNames;
import org.slc.sli.common.constants.ParameterConstants;
import org.slc.sli.domain.*;
import org.slc.sli.domain.enums.Right;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
*
* Unit Tests
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext-test.xml" })
@TestExecutionListeners({ WebContextTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
public class BasicServiceTest {
private static final Logger LOG = LoggerFactory.getLogger(BasicServiceTest.class);
private BasicService service = null; //class under test
@Autowired
private ApplicationContext context;
@Autowired
private SecurityContextInjector securityContextInjector;
@Autowired
private BasicDefinitionStore definitionStore;
@Autowired
DefinitionFactory factory;
@Autowired
@Qualifier("validationRepo")
private Repository<Entity> securityRepo;
private Repository<Entity> mockRepo;
private EntityRightsFilter mockRightsFilter;
private List<Treatment> mockTreatments = new ArrayList<Treatment>();
// For later cleanup.
private static SecurityUtil.UserContext prevUserContext = SecurityUtil.getUserContext();
private static SecurityContext prevSecurityContext = SecurityContextHolder.getContext();
private static final int MAX_RESULT_SIZE = 0;
class MatchesNotAccessible extends ArgumentMatcher<Entity> {
Set<String> studentIds = new HashSet<String>(Arrays.asList("student1", "student2", "student4", "student5", "student6",
"student13", "student14", "student16", "student17", "student18", "student20", "student22", "student23", "student24"));
@Override
public boolean matches(Object arg) {
return !studentIds.contains(((Entity) arg).getEntityId());
}
}
class MatchesNotFieldAccessible extends ArgumentMatcher<Entity> {
Set<String> studentIds = new HashSet<String>(Arrays.asList("student2", "student3", "student4", "student5", "student6", "student7", "student8",
"student11", "student12", "student13", "student15", "student16", "student17", "student18", "student21", "student22", "student23"));
@Override
public boolean matches(Object arg) {
return !studentIds.contains(((Entity) arg).getEntityId());
}
}
@SuppressWarnings("unchecked")
@Before
public void setup() throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
service = (BasicService) context.getBean("basicService", "student", null, securityRepo);
EntityDefinition student = factory.makeEntity("student")
.exposeAs("students").build();
service.setDefn(student);
mockRepo = Mockito.mock(Repository.class);
Field repo = BasicService.class.getDeclaredField("repo");
repo.setAccessible(true);
repo.set(service, mockRepo);
mockRightsFilter = Mockito.mock(EntityRightsFilter.class);
Field entityRightsFilter = BasicService.class.getDeclaredField("entityRightsFilter");
entityRightsFilter.setAccessible(true);
entityRightsFilter.set(service, mockRightsFilter);
Field treatments = BasicService.class.getDeclaredField("treatments");
treatments.setAccessible(true);
treatments.set(service, mockTreatments);
}
@Test
public void testCheckFieldAccessAdmin() {
// inject administrator security context for unit testing
securityContextInjector.setAdminContextWithElevatedRights();
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("economicDisadvantaged", "=", "true"));
NeutralQuery query1 = new NeutralQuery(query);
service.checkFieldAccess(query, false);
assertTrue("Should match", query1.equals(query));
}
@Test (expected = QueryParseException.class)
public void testCheckFieldAccessEducator() {
// inject administrator security context for unit testing
securityContextInjector.setEducatorContext();
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("economicDisadvantaged", "=", "true"));
service.checkFieldAccess(query, false);
}
@Test
public void testWriteSelf() {
BasicService basicService = (BasicService) context.getBean("basicService", "teacher", new ArrayList<Treatment>(), securityRepo);
basicService.setDefn(definitionStore.lookupByEntityType("teacher"));
securityContextInjector.setEducatorContext("my-id");
Map<String, Object> body = new HashMap<String, Object>();
Entity entity = securityRepo.create("teacher", body);
EntityBody updated = new EntityBody();
basicService.update(entity.getEntityId(), updated, false);
}
@Test
public void testIsSelf() {
BasicService basicService = (BasicService) context.getBean("basicService", "teacher", new ArrayList<Treatment>(), securityRepo);
basicService.setDefn(definitionStore.lookupByEntityType("teacher"));
securityContextInjector.setEducatorContext("my-id");
assertTrue(basicService.isSelf(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.OPERATOR_EQUAL, "my-id"))));
NeutralQuery query = new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList("my-id")));
assertTrue(basicService.isSelf(query));
query.addCriteria(new NeutralCriteria("someOtherProperty", NeutralCriteria.OPERATOR_EQUAL, "somethingElse"));
assertTrue(basicService.isSelf(query));
query.addOrQuery(new NeutralQuery(new NeutralCriteria("refProperty", NeutralCriteria.OPERATOR_EQUAL, "my-id")));
assertTrue(basicService.isSelf(query));
query.addOrQuery(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.OPERATOR_EQUAL, "someoneElse")));
assertFalse(basicService.isSelf(query));
assertFalse(basicService.isSelf(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList("my-id", "someoneElse")))));
}
@SuppressWarnings("unchecked")
@Test
public void testList() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setEducatorContext();
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
EntityBody entityBody1 = new EntityBody();
entityBody1.put("studentUniqueStateId", "student1");
EntityBody entityBody2 = new EntityBody();
entityBody2.put("studentUniqueStateId", "student2");
Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>());
Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>());
Iterable<Entity> entities = Arrays.asList(entity1, entity2);
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities);
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(2L);
Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity1), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.any(Collection.class), Mockito.any(Collection.class))).thenReturn(entityBody1);
Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity2), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.any(Collection.class), Mockito.any(Collection.class))).thenReturn(entityBody2);
RequestUtil.setCurrentRequestId();
Iterable<EntityBody> listResult = service.list(new NeutralQuery());
List<EntityBody> bodies= new ArrayList<EntityBody>();
for (EntityBody body : listResult) {
bodies.add(body);
}
Assert.assertEquals("EntityBody mismatch", entityBody1, bodies.toArray()[0]);
Assert.assertEquals("EntityBody mismatch", entityBody2, bodies.toArray()[1]);
long count = service.count(new NeutralQuery());
Assert.assertEquals(2, count);
}
@SuppressWarnings("unchecked")
@Test
public void testListBasedOnContextualRoles() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setEducatorContext();
SecurityUtil.setUserContext(SecurityUtil.UserContext.TEACHER_CONTEXT);
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
Collection<GrantedAuthority> teacherContextRights = new HashSet<GrantedAuthority>(Arrays.asList(Right.TEACHER_CONTEXT, Right.READ_PUBLIC, Right.WRITE_PUBLIC));
EntityBody entityBody1 = new EntityBody();
entityBody1.put("studentUniqueStateId", "student1");
EntityBody entityBody2 = new EntityBody();
entityBody2.put("studentUniqueStateId", "student2");
Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>());
Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>());
Iterable<Entity> entities = Arrays.asList(entity1, entity2);
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities);
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(2L);
Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity1), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.anyBoolean(), Mockito.any(Collection.class), Mockito.any(SecurityUtil.UserContext.class))).thenReturn(entityBody1);
Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity2), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.anyBoolean(), Mockito.any(Collection.class), Mockito.any(SecurityUtil.UserContext.class))).thenReturn(entityBody2);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(false), Matchers.eq(entity1), Matchers.eq(SecurityUtil.UserContext.TEACHER_CONTEXT), Matchers.eq(true))).thenReturn(teacherContextRights);
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
studentContext.put(entity1.getEntityId(), SecurityUtil.UserContext.TEACHER_CONTEXT);
studentContext.put(entity2.getEntityId(), SecurityUtil.UserContext.TEACHER_CONTEXT);
Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext);
NeutralQuery query = new NeutralQuery();
query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT);
RequestUtil.setCurrentRequestId();
Iterable<EntityBody> listResult = service.listBasedOnContextualRoles(query);
List<EntityBody> bodies= new ArrayList<EntityBody>();
for (EntityBody body : listResult) {
bodies.add(body);
}
Assert.assertEquals("EntityBody mismatch", entityBody1, bodies.toArray()[0]);
Assert.assertEquals("EntityBody mismatch", entityBody2, bodies.toArray()[1]);
long count = service.countBasedOnContextualRoles(new NeutralQuery());
Assert.assertEquals(2, count);
}
@SuppressWarnings("unchecked")
@Test
public void testListBasedOnContextualRolesDualContext() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setDualContext();
SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT);
Collection<GrantedAuthority> teacherContextRights = new HashSet<GrantedAuthority>(Arrays.asList(Right.TEACHER_CONTEXT, Right.READ_PUBLIC, Right.WRITE_PUBLIC));
Collection<GrantedAuthority> staffContextRights = new HashSet<GrantedAuthority>(Arrays.asList(Right.STAFF_CONTEXT, Right.READ_GENERAL, Right.WRITE_GENERAL));
Collection<GrantedAuthority> dualContextRights = new HashSet<GrantedAuthority>(teacherContextRights);
dualContextRights.addAll(staffContextRights);
Collection<GrantedAuthority> noContextRights = new HashSet<GrantedAuthority>();
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
List<Entity> entities = new ArrayList<Entity>();
Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
for (int i=0; i<30; i++) {
String id = "student" + i;
Entity entity = new MongoEntity("student", id, new HashMap<String,Object>(), new HashMap<String,Object>());
entity.getBody().put("key","value");
entities.add(entity);
EntityBody entityBody = new EntityBody();
entityBody.put("studentUniqueStateId", id);
Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.anyBoolean(),
Mockito.any(Collection.class), Mockito.any(SecurityUtil.UserContext.class))).thenReturn(entityBody);
if ((i % 12) == 0) {
studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(false), Matchers.eq(entity), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.eq(true))).thenReturn(dualContextRights);
} else if ((i % 3) == 0) {
studentContext.put(id, SecurityUtil.UserContext.STAFF_CONTEXT);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(false), Matchers.eq(entity), Matchers.eq(SecurityUtil.UserContext.STAFF_CONTEXT), Matchers.eq(true))).thenReturn(staffContextRights);
} else if ((i % 4) == 0) {
studentContext.put(id, SecurityUtil.UserContext.TEACHER_CONTEXT);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(false), Matchers.eq(entity), Matchers.eq(SecurityUtil.UserContext.TEACHER_CONTEXT), Matchers.eq(true))).thenReturn(teacherContextRights);
} else {
studentContext.put(id, SecurityUtil.UserContext.NO_CONTEXT);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(false), Matchers.eq(entity), Matchers.eq(SecurityUtil.UserContext.NO_CONTEXT), Matchers.eq(true))).thenReturn(noContextRights);
}
}
NeutralQuery query = new NeutralQuery();
query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT);
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities);
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.eq(query))).thenReturn(50L);
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(), Mockito.eq(staffContextRights));
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()), Mockito.anyString(), Mockito.eq(teacherContextRights));
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.any(Entity.class), Mockito.anyString(), Mockito.eq(noContextRights));
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext);
RequestUtil.setCurrentRequestId();
Iterable<EntityBody> listResult = service.listBasedOnContextualRoles(query);
Iterable<String> expectedResult1 = Arrays.asList("student0", "student4", "student6", "student8", "student12", "student16", "student18", "student24");
assertEntityBodyIdsEqual(expectedResult1.iterator(), listResult.iterator());
long count = service.countBasedOnContextualRoles(query);
Assert.assertEquals(8, count);
// Assure same order and count.
RequestUtil.setCurrentRequestId();
listResult = service.listBasedOnContextualRoles(query);
Iterable<String> expectedResult2 = Arrays.asList("student0", "student4", "student6", "student8", "student12", "student16", "student18", "student24");
assertEntityBodyIdsEqual(expectedResult2.iterator(), listResult.iterator());
count = service.countBasedOnContextualRoles(query);
Assert.assertEquals(8, count);
}
@SuppressWarnings("unchecked")
@Test
public void testCreate() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setEducatorContext();
//adding this to research "Heisenbug" that may be related to timing of resource initialization, which causes nonrepeatable test failures.
try {
Thread.currentThread().sleep(5L); //sleep for 5 ms
} catch (InterruptedException is) {
//squish
}
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
//adding this to research "Heisenbug" that may be related to timing of resource initialization, which causes nonrepeatable test failures.
try {
Thread.currentThread().sleep(5L); //sleep for 5 ms
} catch (InterruptedException is) {
//squish
}
EntityBody entityBody1 = new EntityBody();
entityBody1.put("studentUniqueStateId", "student1");
EntityBody entityBody2 = new EntityBody();
entityBody2.put("studentUniqueStateId", "student2");
List<EntityBody> entityBodies = Arrays.asList(entityBody1, entityBody2);
Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>());
Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>());
Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody1), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity1);
Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody2), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity2);
LOG.debug(ToStringBuilder.reflectionToString(entityBodies, ToStringStyle.MULTI_LINE_STYLE));
//adding this to research "Heisenbug" that may be related to timing of resource initialization, which causes nonrepeatable test failures.
try {
Thread.currentThread().sleep(5L); //sleep for 5 ms
} catch (InterruptedException is) {
//squish
}
List<String> listResult = service.create(entityBodies);
Assert.assertEquals("EntityBody mismatch", entity1.getEntityId(), listResult.toArray()[0]);
Assert.assertEquals("EntityBody mismatch", entity2.getEntityId(), listResult.toArray()[1]);
}
@SuppressWarnings("unchecked")
@Test
public void testCreateBasedOnContextualRoles() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setEducatorContext();
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
EntityBody entityBody1 = new EntityBody();
entityBody1.put("studentUniqueStateId", "student1");
EntityBody entityBody2 = new EntityBody();
entityBody2.put("studentUniqueStateId", "student2");
List<EntityBody> entityBodies = Arrays.asList(entityBody1, entityBody2);
Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>());
Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>());
Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody1), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity1);
Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody2), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity2);
List<String> listResult = service.createBasedOnContextualRoles(entityBodies);
Assert.assertEquals("EntityBody mismatch", entity1.getEntityId(), listResult.toArray()[0]);
Assert.assertEquals("EntityBody mismatch", entity2.getEntityId(), listResult.toArray()[1]);
}
@Test
public void testUpdateBasedOnContextualRoles() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setStaffContext();
service = (BasicService) context.getBean("basicService", "student", new ArrayList<Treatment>(), securityRepo);
EntityDefinition studentDef = factory.makeEntity("student").exposeAs("students").build();
service.setDefn(studentDef);
EntityBody entityBody1 = new EntityBody();
entityBody1.put("studentUniqueStateId", "student1");
Entity student = securityRepo.create(EntityNames.STUDENT, entityBody1);
EntityBody entityBody2 = new EntityBody();
entityBody2.put(ParameterConstants.STUDENT_ID, student.getEntityId());
entityBody2.put(ParameterConstants.SCHOOL_ID, SecurityContextInjector.ED_ORG_ID);
securityRepo.create(EntityNames.STUDENT_SCHOOL_ASSOCIATION, entityBody2);
securityRepo.createWithRetries(EntityNames.EDUCATION_ORGANIZATION,SecurityContextInjector.ED_ORG_ID, new HashMap<String, Object>(), new HashMap<String, Object>(), EntityNames.EDUCATION_ORGANIZATION, 1);
EntityBody putEntity = new EntityBody();
putEntity.put("studentUniqueStateId", "student1");
putEntity.put("loginId", "student1");
boolean result = service.update(student.getEntityId(), putEntity, true);
Assert.assertTrue(result);
Entity studentResult = securityRepo.findById(EntityNames.STUDENT, student.getEntityId());
Assert.assertNotNull(studentResult.getBody());
Assert.assertNotNull(studentResult.getBody().get("studentUniqueStateId"));
Assert.assertEquals("student1", studentResult.getBody().get("studentUniqueStateId"));
Assert.assertNotNull(studentResult.getBody().get("loginId"));
Assert.assertEquals("student1",studentResult.getBody().get("loginId"));
}
@Test(expected = AccessDeniedException.class)
public void testUpdateBasedOnContextualRolesAccessDenied() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setEducatorContext();
service = (BasicService) context.getBean("basicService", "student", new ArrayList<Treatment>(), securityRepo);
EntityDefinition studentDef = factory.makeEntity("student").exposeAs("students").build();
service.setDefn(studentDef);
EntityBody entityBody1 = new EntityBody();
entityBody1.put("studentUniqueStateId", "student1");
Entity student = securityRepo.create(EntityNames.STUDENT, entityBody1);
EntityBody entityBody2 = new EntityBody();
entityBody2.put(ParameterConstants.STUDENT_ID, student.getEntityId());
entityBody2.put(ParameterConstants.SCHOOL_ID, SecurityContextInjector.ED_ORG_ID);
securityRepo.create(EntityNames.STUDENT_SCHOOL_ASSOCIATION, entityBody2);
securityRepo.createWithRetries(EntityNames.EDUCATION_ORGANIZATION,SecurityContextInjector.ED_ORG_ID, new HashMap<String, Object>(), new HashMap<String, Object>(), EntityNames.EDUCATION_ORGANIZATION, 1);
EntityBody putEntity = new EntityBody();
putEntity.put("studentUniqueStateId", "student1");
putEntity.put("loginId", "student1");
boolean result = service.update(student.getEntityId(), putEntity, true);
Assert.assertFalse(result);
}
@Test
public void testPatchBasedOnContextualRoles() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setStaffContext();
service = (BasicService) context.getBean("basicService", "student", new ArrayList<Treatment>(), securityRepo);
EntityDefinition studentDef = factory.makeEntity("student").exposeAs("students").build();
service.setDefn(studentDef);
EntityBody studentBody = new EntityBody();
studentBody.put("studentUniqueStateId", "123");
Entity student = securityRepo.create(EntityNames.STUDENT, studentBody);
EntityBody ssaBody = new EntityBody();
ssaBody.put(ParameterConstants.STUDENT_ID, student.getEntityId());
ssaBody.put(ParameterConstants.SCHOOL_ID, SecurityContextInjector.ED_ORG_ID);
securityRepo.create(EntityNames.STUDENT_SCHOOL_ASSOCIATION, ssaBody);
securityRepo.createWithRetries(EntityNames.EDUCATION_ORGANIZATION,SecurityContextInjector.ED_ORG_ID, new HashMap<String, Object>(), new HashMap<String, Object>(), EntityNames.EDUCATION_ORGANIZATION, 1);
EntityBody putEntity = new EntityBody();
putEntity.put("studentUniqueStateId", "456");
putEntity.put("schoolFoodServicesEligibility", "Yes");
boolean result = service.patch(student.getEntityId(), putEntity, true);
Assert.assertTrue(result);
Entity studentResult = securityRepo.findById(EntityNames.STUDENT, student.getEntityId());
Assert.assertNotNull(studentResult.getBody());
Assert.assertNotNull(studentResult.getBody().get("studentUniqueStateId"));
Assert.assertEquals("456", studentResult.getBody().get("studentUniqueStateId"));
Assert.assertNotNull(studentResult.getBody().get("schoolFoodServicesEligibility"));
Assert.assertEquals("Yes",studentResult.getBody().get("schoolFoodServicesEligibility"));
}
@Test
public void testPatchBasedOnContextualRolesWithEmptyPatchBody() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setStaffContext();
service = (BasicService) context.getBean("basicService", "student", new ArrayList<Treatment>(), securityRepo);
EntityDefinition studentDef = factory.makeEntity("student").exposeAs("students").build();
service.setDefn(studentDef);
EntityBody studentBody = new EntityBody();
studentBody.put("studentUniqueStateId", "123");
Entity student = securityRepo.create(EntityNames.STUDENT, studentBody);
EntityBody ssaBody = new EntityBody();
ssaBody.put(ParameterConstants.STUDENT_ID, student.getEntityId());
ssaBody.put(ParameterConstants.SCHOOL_ID, SecurityContextInjector.ED_ORG_ID);
securityRepo.create(EntityNames.STUDENT_SCHOOL_ASSOCIATION, ssaBody);
securityRepo.createWithRetries(EntityNames.EDUCATION_ORGANIZATION,SecurityContextInjector.ED_ORG_ID, new HashMap<String, Object>(), new HashMap<String, Object>(), EntityNames.EDUCATION_ORGANIZATION, 1);
EntityBody putEntity = new EntityBody();
boolean result = service.patch(student.getEntityId(), putEntity, true);
Assert.assertFalse(result);
Entity studentResult = securityRepo.findById(EntityNames.STUDENT, student.getEntityId());
Assert.assertNotNull(studentResult.getBody());
Assert.assertNotNull(studentResult.getBody().get("studentUniqueStateId"));
Assert.assertEquals("123", studentResult.getBody().get("studentUniqueStateId"));
Assert.assertNull(studentResult.getBody().get("schoolFoodServicesEligibility"));
}
@Test(expected = AccessDeniedException.class)
public void testPatchBasedOnContextualRolesAccessDenied() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
securityContextInjector.setEducatorContext();
service = (BasicService) context.getBean("basicService", "student", new ArrayList<Treatment>(), securityRepo);
EntityDefinition studentDef = factory.makeEntity("student").exposeAs("students").build();
service.setDefn(studentDef);
EntityBody studentBody = new EntityBody();
studentBody.put("studentUniqueStateId", "123");
Entity student = securityRepo.create(EntityNames.STUDENT, studentBody);
EntityBody ssaBody = new EntityBody();
ssaBody.put(ParameterConstants.STUDENT_ID, student.getEntityId());
ssaBody.put(ParameterConstants.SCHOOL_ID, SecurityContextInjector.ED_ORG_ID);
securityRepo.create(EntityNames.STUDENT_SCHOOL_ASSOCIATION, ssaBody);
securityRepo.createWithRetries(EntityNames.EDUCATION_ORGANIZATION,SecurityContextInjector.ED_ORG_ID, new HashMap<String, Object>(), new HashMap<String, Object>(), EntityNames.EDUCATION_ORGANIZATION, 1);
EntityBody putEntity = new EntityBody();
putEntity.put("studentUniqueStateId", "456");
putEntity.put("schoolFoodServicesEligibility", "Yes");
boolean result = service.patch(student.getEntityId(), putEntity, true);
Assert.assertFalse(result);
}
@Test
public void testgetEntityContextAuthorities() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException {
securityContextInjector.setDualContext();
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
boolean isSelf = true;
boolean isRead = true;
EntityBody entityBody1 = new EntityBody();
entityBody1.put("studentUniqueStateId", "student1");
Entity student = securityRepo.create(EntityNames.STUDENT, entityBody1);
Collection<GrantedAuthority> staffContextRights = SecurityUtil.getSLIPrincipal().getEdOrgContextRights().get(SecurityContextInjector.ED_ORG_ID).get(SecurityUtil.UserContext.STAFF_CONTEXT);
Collection<GrantedAuthority> teacherContextRights = SecurityUtil.getSLIPrincipal().getEdOrgContextRights().get(SecurityContextInjector.ED_ORG_ID).get(SecurityUtil.UserContext.TEACHER_CONTEXT);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(isSelf), Matchers.eq(student), Matchers.eq(SecurityUtil.UserContext.STAFF_CONTEXT), Matchers.eq(isRead))).thenReturn(staffContextRights);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(isSelf), Matchers.eq(student), Matchers.eq(SecurityUtil.UserContext.TEACHER_CONTEXT), Matchers.eq(isRead))).thenReturn(teacherContextRights);
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
studentContext.put(student.getEntityId(), SecurityUtil.UserContext.STAFF_CONTEXT);
Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext);
Collection<GrantedAuthority> rights = service.getEntityContextAuthorities(student, isSelf, isRead);
Assert.assertEquals(staffContextRights, rights);
securityContextInjector.setEducatorContext();
rights = service.getEntityContextAuthorities(student, isSelf, isRead);
Assert.assertEquals(teacherContextRights, rights);
}
@Test
public void testUserHasMultipleContextsOrDifferingRightsDualContext() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
securityContextInjector.setDualContext();
Method method = BasicService.class.getDeclaredMethod("userHasMultipleContextsOrDifferingRights");
method.setAccessible(true);
boolean testCondition = (Boolean) method.invoke(service);
Assert.assertTrue(testCondition);
}
@Test
public void testUserHasMultipleContextsOrDifferingRightsDifferentRights() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
securityContextInjector.setEducatorContext();
Set<GrantedAuthority> rights1 = new HashSet<GrantedAuthority>(Arrays.asList(Right.TEACHER_CONTEXT, Right.READ_PUBLIC, Right.WRITE_PUBLIC));
Set<GrantedAuthority> rights2 = new HashSet<GrantedAuthority>(Arrays.asList(Right.TEACHER_CONTEXT, Right.READ_PUBLIC, Right.READ_GENERAL, Right.WRITE_PUBLIC));
Map<String, Collection<GrantedAuthority>> edOrgRights = new HashMap<String, Collection<GrantedAuthority>>();
edOrgRights.put("edOrg1", rights1);
edOrgRights.put("edOrg2", rights2);
SLIPrincipal principal = Mockito.mock(SLIPrincipal.class);
Mockito.when(principal.getEdOrgRights()).thenReturn(edOrgRights);
setPrincipalInContext(principal);
Method method = BasicService.class.getDeclaredMethod("userHasMultipleContextsOrDifferingRights");
method.setAccessible(true);
boolean testCondition = (Boolean) method.invoke(service);
Assert.assertTrue(testCondition);
}
@Test
public void testUserHasMultipleContextsOrDifferingRightsSingleEdOrg() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
securityContextInjector.setEducatorContext();
Set<GrantedAuthority> rights1 = new HashSet<GrantedAuthority>(Arrays.asList(Right.TEACHER_CONTEXT, Right.READ_PUBLIC, Right.WRITE_PUBLIC));
Map<String, Collection<GrantedAuthority>> edOrgRights = new HashMap<String, Collection<GrantedAuthority>>();
edOrgRights.put("edOrg1", rights1);
SLIPrincipal principal = Mockito.mock(SLIPrincipal.class);
Mockito.when(principal.getEdOrgRights()).thenReturn(edOrgRights);
setPrincipalInContext(principal);
Method method = BasicService.class.getDeclaredMethod("userHasMultipleContextsOrDifferingRights");
method.setAccessible(true);
boolean testCondition = (Boolean) method.invoke(service);
Assert.assertFalse(testCondition);
}
@Test
public void testUserHasMultipleContextsOrDifferingRightsSameRights() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
securityContextInjector.setEducatorContext();
Set<GrantedAuthority> rights1 = new HashSet<GrantedAuthority>(Arrays.asList(Right.TEACHER_CONTEXT, Right.READ_PUBLIC, Right.WRITE_PUBLIC));
Map<String, Collection<GrantedAuthority>> edOrgRights = new HashMap<String, Collection<GrantedAuthority>>();
edOrgRights.put("edOrg1", rights1);
edOrgRights.put("edOrg2", rights1);
SLIPrincipal principal = Mockito.mock(SLIPrincipal.class);
Mockito.when(principal.getEdOrgRights()).thenReturn(edOrgRights);
setPrincipalInContext(principal);
Method method = BasicService.class.getDeclaredMethod("userHasMultipleContextsOrDifferingRights");
method.setAccessible(true);
boolean testCondition = (Boolean) method.invoke(service);
Assert.assertFalse(testCondition);
}
@SuppressWarnings("unchecked")
@Test
public void testGetResponseEntities() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
securityContextInjector.setDualContext();
SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT);
List<Entity> entities = new ArrayList<Entity>();
Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
for (int i=0; i<30; i++) {
String id = "student" + i;
entities.add(new MongoEntity("student", id, new HashMap<String,Object>(), new HashMap<String,Object>()));
studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT);
}
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities);
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L);
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext);
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean())).thenReturn(new HashSet<GrantedAuthority>());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(), Mockito.anyCollection());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()), Mockito.anyString(), Mockito.anyCollection());
NeutralQuery query = new NeutralQuery();
query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT);
Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class);
method.setAccessible(true);
RequestUtil.setCurrentRequestId();
Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult1 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23");
assertEntityIdsEqual(expectedResult1.iterator(), accessibleEntities.iterator());
long count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
// Assure same order and count.
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult2 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23");
assertEntityIdsEqual(expectedResult2.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
query.setOffset(7);
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult3 = Arrays.asList("student18", "student22", "student23");
assertEntityIdsEqual(expectedResult3.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
// Assure same order and count.
query.setOffset(7);
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult4 = Arrays.asList("student18", "student22", "student23");
assertEntityIdsEqual(expectedResult4.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
}
@SuppressWarnings("unchecked")
@Test
public void testGetResponseEntitiesPageLimit() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
securityContextInjector.setDualContext();
SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT);
List<Entity> entities = new ArrayList<Entity>();
Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
for (int i=0; i<30; i++) {
String id = "student" + i;
entities.add(new MongoEntity("student", id, new HashMap<String,Object>(), new HashMap<String,Object>()));
studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT);
}
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities);
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L);
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext);
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean())).thenReturn(new HashSet<GrantedAuthority>());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(), Mockito.anyCollection());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()), Mockito.anyString(), Mockito.anyCollection());
NeutralQuery query = new NeutralQuery();
query.setLimit(5);
Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class);
method.setAccessible(true);
RequestUtil.setCurrentRequestId();
Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult1 = Arrays.asList("student2", "student4", "student5", "student6", "student13");
assertEntityIdsEqual(expectedResult1.iterator(), accessibleEntities.iterator());
long count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
// Assure same order and count.
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult2 = Arrays.asList("student2", "student4", "student5", "student6", "student13");
assertEntityIdsEqual(expectedResult2.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
query.setOffset(4);
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult3 = Arrays.asList("student13", "student16", "student17", "student18", "student22");
assertEntityIdsEqual(expectedResult3.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
// Assure same order and count.
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult4 = Arrays.asList("student13", "student16", "student17", "student18", "student22");
assertEntityIdsEqual(expectedResult4.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
query.setOffset(7);
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult5 = Arrays.asList("student18", "student22", "student23");
assertEntityIdsEqual(expectedResult5.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
// Assure same order and count.
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult6 = Arrays.asList("student18", "student22", "student23");
assertEntityIdsEqual(expectedResult6.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
query.setOffset(10);
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Assert.assertEquals(0, accessibleEntities.size());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
}
@SuppressWarnings("unchecked")
@Test
public void testGetAccessibleEntitiesCountLimit() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
securityContextInjector.setDualContext();
SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT);
List<Entity> entities = new ArrayList<Entity>();
Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
for (int i=0; i<30; i++) {
String id = "student" + i;
entities.add(new MongoEntity("student", id, new HashMap<String,Object>(), new HashMap<String,Object>()));
studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT);
}
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities);
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L);
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext);
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean())).thenReturn(new HashSet<GrantedAuthority>());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(), Mockito.anyCollection());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()), Mockito.anyString(), Mockito.anyCollection());
NeutralQuery query = new NeutralQuery();
query.setLimit(MAX_RESULT_SIZE);
final long mockCountLimit = 5;
Field countLimit = BasicService.class.getDeclaredField("countLimit");
countLimit.setAccessible(true);
final long prevCountLimit = countLimit.getLong(service);
countLimit.set(service, mockCountLimit);
Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class);
method.setAccessible(true);
RequestUtil.setCurrentRequestId();
Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult1 = Arrays.asList("student2", "student4", "student5", "student6", "student13");
assertEntityIdsEqual(expectedResult1.iterator(), accessibleEntities.iterator());
long count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(5, count);
// Assure same order and count.
RequestUtil.setCurrentRequestId();
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult2 = Arrays.asList("student2", "student4", "student5", "student6", "student13");
assertEntityIdsEqual(expectedResult2.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(5, count);
countLimit.set(service, prevCountLimit);
}
@SuppressWarnings("unchecked")
@Test
public void testGetResponseEntitiesBatchLimit() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
securityContextInjector.setDualContext();
SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT);
List<Entity> entities = new ArrayList<Entity>();
Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
for (int i=0; i<30; i++) {
String id = "student" + i;
entities.add(new MongoEntity("student", id, new HashMap<String,Object>(), new HashMap<String,Object>()));
studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT);
}
final int mockBatchSize = 10;
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities.subList(0, mockBatchSize)).thenReturn(entities.subList(mockBatchSize, mockBatchSize * 2))
.thenReturn(entities.subList(mockBatchSize * 2, mockBatchSize * 3)).thenReturn(new ArrayList<Entity>());
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L);
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext);
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean())).thenReturn(new HashSet<GrantedAuthority>());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(), Mockito.anyCollection());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()), Mockito.anyString(), Mockito.anyCollection());
NeutralQuery query = new NeutralQuery();
query.setLimit(MAX_RESULT_SIZE);
Field batchSize = BasicService.class.getDeclaredField("batchSize");
batchSize.setAccessible(true);
int prevBatchSize = batchSize.getInt(service);
batchSize.set(service, mockBatchSize);
Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class);
method.setAccessible(true);
RequestUtil.setCurrentRequestId();
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities.subList(0, mockBatchSize)).thenReturn(entities.subList(mockBatchSize, mockBatchSize * 2))
.thenReturn(entities.subList(mockBatchSize * 2, mockBatchSize * 3)).thenReturn(new ArrayList<Entity>());
Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult1 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23");
assertEntityIdsEqual(expectedResult1.iterator(), accessibleEntities.iterator());
long count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
// Assure same order and count.
RequestUtil.setCurrentRequestId();
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities.subList(0, mockBatchSize)).thenReturn(entities.subList(mockBatchSize, mockBatchSize * 2))
.thenReturn(entities.subList(mockBatchSize * 2, mockBatchSize * 3)).thenReturn(new ArrayList<Entity>());
accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Iterable<String> expectedResult2 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23");
assertEntityIdsEqual(expectedResult2.iterator(), accessibleEntities.iterator());
count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(10, count);
batchSize.set(service, prevBatchSize);
}
@SuppressWarnings("unchecked")
@Test
public void testGetResponseEntitiesEmpty() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
securityContextInjector.setDualContext();
SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT);
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(new ArrayList<Entity>());
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(0L);
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
NeutralQuery query = new NeutralQuery();
query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT);
Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class);
method.setAccessible(true);
RequestUtil.setCurrentRequestId();
Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
Assert.assertTrue(accessibleEntities.isEmpty());
long count = service.getAccessibleEntitiesCount("student");
Assert.assertEquals(0, count);
}
@SuppressWarnings({ "unchecked", "unused" })
@Test
public void testGetResponseEntitiesNoAccess() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
securityContextInjector.setDualContext();
SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT);
List<Entity> entities = new ArrayList<Entity>();
Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
for (int i=0; i<30; i++) {
String id = "student" + i;
entities.add(new MongoEntity("student", id, new HashMap<String,Object>(), new HashMap<String,Object>()));
studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT);
}
Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities);
Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L);
ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
contextValidator.setAccessible(true);
contextValidator.set(service, mockContextValidator);
Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext);
RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
rightAccessValidator.setAccessible(true);
rightAccessValidator.set(service, mockAccessValidator);
Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean())).thenReturn(new HashSet<GrantedAuthority>());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.any(Entity.class), Mockito.anyString(), Mockito.anyCollection());
Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(Mockito.any(NeutralQuery.class), Mockito.any(Entity.class), Mockito.anyString(), Mockito.anyCollection());
NeutralQuery query = new NeutralQuery();
query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT);
Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class);
method.setAccessible(true);
try {
RequestUtil.setCurrentRequestId();
Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);
} catch (InvocationTargetException itex) {
Assert.assertEquals(APIAccessDeniedException.class, itex.getCause().getClass());
Assert.assertEquals("Access to resource denied.", itex.getCause().getMessage());
}
}
private void setPrincipalInContext(SLIPrincipal principal) {
Authentication authentication = Mockito.mock(Authentication.class);
Mockito.when(authentication.getPrincipal()).thenReturn(principal);
SecurityContext context = Mockito.mock(SecurityContext.class);
Mockito.when(context.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(context);
}
private void assertEntityBodyIdsEqual(Iterator<String> expected, Iterator<EntityBody> actual) {
while (expected.hasNext()) {
Assert.assertEquals(expected.next(), actual.next().get("studentUniqueStateId"));
}
Assert.assertFalse(actual.hasNext());
}
private void assertEntityIdsEqual(Iterator<String> expected, Iterator<Entity> actual) {
while (expected.hasNext()) {
Assert.assertEquals(expected.next(), actual.next().getEntityId());
}
Assert.assertFalse(actual.hasNext());
}
@AfterClass
public static void reset() {
// Let's be good citizens and clean up after ourselves for the subsequent tests!
SecurityUtil.setUserContext(prevUserContext);
SecurityContextHolder.setContext(prevSecurityContext);
}
}
| 56.644501 | 259 | 0.738426 |
f30aa28558b8d81f46da51816f0dec72e0a1321a | 4,338 | package simpledb.execution;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import simpledb.common.Type;
import simpledb.storage.Field;
import simpledb.storage.IntField;
import simpledb.storage.Tuple;
import simpledb.storage.TupleDesc;
import simpledb.storage.TupleIterator;
/**
* Knows how to compute some aggregate over a set of StringFields.
*/
public class StringAggregator implements Aggregator {
private static final long serialVersionUID = 1L;
private int gbField;
private Type gbFieldType;
private int aggField;
private Op aggOp;
private HashMap<Field, Integer> groupCounts;
/**
* Aggregate constructor
* @param gbfield the 0-based index of the group-by field in the tuple, or NO_GROUPING if there is no grouping
* @param gbfieldtype the type of the group by field (e.g., Type.INT_TYPE), or null if there is no grouping
* @param afield the 0-based index of the aggregate field in the tuple
* @param what aggregation operator to use -- only supports COUNT
* @throws IllegalArgumentException if what != COUNT
*/
public StringAggregator(int gbfield, Type gbfieldtype, int afield, Op what) {
if (what != Op.COUNT) throw new IllegalArgumentException();
this.gbField = gbfield;
this.gbFieldType = gbfieldtype;
this.aggField = afield;
this.aggOp = what;
this.groupCounts = new HashMap<>();
}
/**
* Merge a new tuple into the aggregate, grouping as indicated in the constructor
* @param tup the Tuple containing an aggregate field and a group-by field
*/
public void mergeTupleIntoGroup(Tuple tup) {
Field groupByField = this.getGroupByField(tup);
int updatedCount = this.getUpdatedCount(tup);
this.groupCounts.put(groupByField, updatedCount);
}
/**
* Create a OpIterator over group aggregate results.
*
* @return a OpIterator whose tuples are the pair (groupVal,
* aggregateVal) if using group, or a single (aggregateVal) if no
* grouping. The aggregateVal is determined by the type of
* aggregate specified in the constructor.
*/
public OpIterator iterator() {
TupleDesc groupAggregateTd;
ArrayList<Tuple> tuples = new ArrayList<>();
boolean hasGrouping = (this.gbField != Aggregator.NO_GROUPING);
if (hasGrouping) {
groupAggregateTd = new TupleDesc(new Type[]{this.gbFieldType, Type.INT_TYPE});
} else {
groupAggregateTd = new TupleDesc(new Type[]{Type.INT_TYPE});
}
for (Map.Entry<Field, Integer> groupAggregateEntry: this.groupCounts.entrySet()) {
Tuple groupCountsTuple = new Tuple(groupAggregateTd);
// If there is a grouping, we return a tuple in the form {groupByField, aggregateVal}
// If there is no grouping, we return a tuple in the form {aggregateVal}
if (hasGrouping) {
groupCountsTuple.setField(0, groupAggregateEntry.getKey());
groupCountsTuple.setField(1, new IntField(groupAggregateEntry.getValue()));
} else {
groupCountsTuple.setField(0, new IntField(groupAggregateEntry.getValue()));
}
tuples.add(groupCountsTuple);
}
return new TupleIterator(groupAggregateTd, tuples);
}
/**
* Returns the updated count aggregate (+1 for each tuple we've seen in a particular group)
* @param tup The tuple used to update the current count
* @return the updated count
*/
private int getUpdatedCount(Tuple tup) {
Field groupByField = getGroupByField(tup);
int currentCount = this.groupCounts.getOrDefault(groupByField, 0);
return ++currentCount;
}
/**
* Returns the groupby Field of the current tuple, or null if there is no grouping
* @param tup The tuple whose groupby Field we wish to return
* @return the Field used in the group by clause, or null if there is no grouping
*/
private Field getGroupByField(Tuple tup) {
Field groupByField;
if (this.gbField == Aggregator.NO_GROUPING) {
groupByField = null;
} else {
groupByField = tup.getField(this.gbField);
}
return groupByField;
}
}
| 37.721739 | 114 | 0.665053 |
0e42b3d3e4520ea8c020c075f9d7d1865c8785bb | 1,770 | package org.sandcast.canopy.config;
import java.util.ArrayList;
import java.util.List;
public class Recipe {
private List<List<String>> layout = new ArrayList<>();
private List<String> biomes;
private Builder builder;
private Boolean randomRotation = true;
private String name;
public Boolean getRandomRotation() {
return randomRotation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setRandomRotation(Boolean randomRotation) {
this.randomRotation = randomRotation;
}
public List<List<String>> getLayout() {
return layout;
}
public void setLayout(List<List<String>> layout) {
this.layout = layout;
}
public List<String> getBiomes() {
return biomes;
}
public void setBiomes(List<String> biomes) {
this.biomes = biomes;
}
public Builder getBuilder() {
return builder;
}
public void setBuilder(Builder builder) {
this.builder = builder;
}
public static class Builder {
public enum Strategy {SCHEMATIC, PROCEDURAL, DEFAULT}
private Strategy strategy = Strategy.SCHEMATIC;
private List<String> arguments = new ArrayList<>();
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public List<String> getArguments() {
return arguments;
}
public void setArguments(List<String> arguments) {
this.arguments = arguments;
}
}
}
| 22.987013 | 62 | 0.586441 |
300258bebb8c38ad4301d6bbb3cc6ad352cfff93 | 17,701 | package fi.aalto.dmg.frame;
import api.datastream.NoWindowJoinedStreams;
import fi.aalto.dmg.exceptions.UnsupportOperatorException;
import fi.aalto.dmg.exceptions.WorkloadException;
import fi.aalto.dmg.frame.functions.*;
import fi.aalto.dmg.frame.functions.FilterFunction;
import fi.aalto.dmg.frame.functions.FlatMapFunction;
import fi.aalto.dmg.frame.functions.MapFunction;
import fi.aalto.dmg.frame.functions.ReduceFunction;
import fi.aalto.dmg.statistics.LatencyLog;
import fi.aalto.dmg.util.TimeDurations;
import fi.aalto.dmg.util.WithTime;
import org.apache.flink.api.common.functions.*;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.TimestampExtractor;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.operators.StreamMap;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import scala.Tuple2;
import java.util.concurrent.TimeUnit;
/**
* Created by yangjun.wang on 24/10/15.
*/
public class FlinkPairWorkloadOperator<K, V> extends PairWorkloadOperator<K, V> {
private static final long serialVersionUID = 6796359288214662089L;
private DataStream<Tuple2<K, V>> dataStream;
public FlinkPairWorkloadOperator(DataStream<Tuple2<K, V>> dataStream1, int parallelism) {
super(parallelism);
this.dataStream = dataStream1;
}
public FlinkGroupedWorkloadOperator<K, V> groupByKey() {
KeyedStream<Tuple2<K, V>, Object> keyedStream = this.dataStream.keyBy(new KeySelector<Tuple2<K, V>, Object>() {
@Override
public K getKey(Tuple2<K, V> value) throws Exception {
return value._1();
}
});
return new FlinkGroupedWorkloadOperator<>(keyedStream, parallelism);
}
// TODO: reduceByKey - reduce first then groupByKey, at last reduce again
@Override
public PairWorkloadOperator<K, V> reduceByKey(final ReduceFunction<V> fun, String componentId) {
DataStream<Tuple2<K, V>> newDataStream = this.dataStream.keyBy(new KeySelector<Tuple2<K, V>, Object>() {
@Override
public Object getKey(Tuple2<K, V> value) throws Exception {
return value._1();
}
}).reduce(new org.apache.flink.api.common.functions.ReduceFunction<Tuple2<K, V>>() {
@Override
public Tuple2<K, V> reduce(Tuple2<K, V> t1, Tuple2<K, V> t2) throws Exception {
return new Tuple2<>(t1._1(), fun.reduce(t1._2(), t2._2()));
}
});
return new FlinkPairWorkloadOperator<>(newDataStream, parallelism);
}
@Override
public <R> PairWorkloadOperator<K, R> mapValue(final MapFunction<V, R> fun, String componentId) {
DataStream<Tuple2<K, R>> newDataStream = dataStream.map(new org.apache.flink.api.common.functions.MapFunction<Tuple2<K, V>, Tuple2<K, R>>() {
@Override
public Tuple2<K, R> map(Tuple2<K, V> tuple2) throws Exception {
return new Tuple2<>(tuple2._1(), fun.map(tuple2._2()));
}
});
return new FlinkPairWorkloadOperator<>(newDataStream, parallelism);
}
@Override
public <R> WorkloadOperator<R> map(final MapFunction<Tuple2<K, V>, R> fun, final String componentId) {
DataStream<R> newDataStream = dataStream.map(new org.apache.flink.api.common.functions.MapFunction<Tuple2<K, V>, R>() {
@Override
public R map(Tuple2<K, V> value) throws Exception {
return fun.map(value);
}
});
return new FlinkWorkloadOperator<>(newDataStream, parallelism);
}
@Override
public <R> WorkloadOperator<R> map(final MapFunction<Tuple2<K, V>, R> fun, final String componentId, Class<R> outputClass) {
org.apache.flink.api.common.functions.MapFunction<Tuple2<K, V>, R> mapper
= new org.apache.flink.api.common.functions.MapFunction<Tuple2<K, V>, R>() {
@Override
public R map(Tuple2<K, V> value) throws Exception {
return fun.map(value);
}
};
TypeInformation<R> outType = TypeExtractor.getForClass(outputClass);
DataStream<R> newDataStream = dataStream.transform("Map", outType,
new StreamMap<>(dataStream.getExecutionEnvironment().clean(mapper)));
return new FlinkWorkloadOperator<>(newDataStream, parallelism);
}
@Override
public <R> PairWorkloadOperator<K, R> flatMapValue(final FlatMapFunction<V, R> fun, String componentId) {
DataStream<Tuple2<K, R>> newDataStream = dataStream.flatMap(new org.apache.flink.api.common.functions.FlatMapFunction<Tuple2<K, V>, Tuple2<K, R>>() {
@Override
public void flatMap(Tuple2<K, V> tuple2, Collector<Tuple2<K, R>> collector) throws Exception {
Iterable<R> rIterable = fun.flatMap(tuple2._2());
for (R r : rIterable)
collector.collect(new Tuple2<>(tuple2._1(), r));
}
});
return new FlinkPairWorkloadOperator<>(newDataStream, parallelism);
}
@Override
public PairWorkloadOperator<K, V> filter(final FilterFunction<scala.Tuple2<K, V>> fun, String componentId) {
DataStream<Tuple2<K, V>> newDataStream = dataStream.filter(new org.apache.flink.api.common.functions.FilterFunction<Tuple2<K, V>>() {
@Override
public boolean filter(Tuple2<K, V> kvTuple2) throws Exception {
return fun.filter(kvTuple2);
}
});
return new FlinkPairWorkloadOperator<>(newDataStream, parallelism);
}
/**
* Whether is windowed stream?
*
* @param fun reduce function
* @param componentId current component id
* @return PairWorkloadOperator
*/
public PairWorkloadOperator<K, V> updateStateByKey(ReduceFunction<V> fun, String componentId) {
return this;
}
@Override
public PairWorkloadOperator<K, V> reduceByKeyAndWindow(ReduceFunction<V> fun, String componentId, TimeDurations windowDuration) {
return reduceByKeyAndWindow(fun, componentId, windowDuration);
}
// TODO: implement pre-aggregation
/**
* Pre-aggregation -> key group -> reduce
*
* @param fun reduce function
* @param componentId
* @param windowDuration
* @param slideDuration
* @return
*/
@Override
public PairWorkloadOperator<K, V> reduceByKeyAndWindow(final ReduceFunction<V> fun, String componentId, TimeDurations windowDuration, TimeDurations slideDuration) {
org.apache.flink.api.common.functions.ReduceFunction<Tuple2<K, V>> reduceFunction =
new org.apache.flink.api.common.functions.ReduceFunction<Tuple2<K, V>>() {
@Override
public Tuple2<K, V> reduce(Tuple2<K, V> t1, Tuple2<K, V> t2) throws Exception {
V result = fun.reduce(t1._2(), t2._2());
return new Tuple2<K, V>(t1._1(), result);
}
};
DataStream<Tuple2<K, V>> newDataStream = dataStream
.keyBy(new KeySelector<Tuple2<K, V>, Object>() {
@Override
public K getKey(Tuple2<K, V> value) throws Exception {
return value._1();
}
})
.timeWindow(Time.of(windowDuration.getLength(),
windowDuration.getUnit()),
Time.of(slideDuration.getLength(),
slideDuration.getUnit()))
.reduce(reduceFunction);
return new FlinkPairWorkloadOperator<>(newDataStream, parallelism);
}
@Override
public WindowedPairWorkloadOperator<K, V> window(TimeDurations windowDuration) {
return window(windowDuration, windowDuration);
}
/**
* Keyed stream window1
*
* @param windowDuration window1 size
* @param slideDuration slide size
* @return WindowedPairWorkloadOperator
*/
@Override
public WindowedPairWorkloadOperator<K, V> window(TimeDurations windowDuration, TimeDurations slideDuration) {
WindowedStream<Tuple2<K, V>, K, TimeWindow> windowedDataStream = dataStream.keyBy(new KeySelector<Tuple2<K, V>, K>() {
@Override
public K getKey(Tuple2<K, V> tuple2) throws Exception {
return tuple2._1();
}
}).timeWindow(Time.of(windowDuration.getLength(), windowDuration.getUnit()),
Time.of(slideDuration.getLength(), slideDuration.getUnit()));
return new FlinkWindowedPairWorkloadOperator<>(windowedDataStream, parallelism);
}
/**
* @param joinStream the other stream<K,R>
* @param windowDuration window1 length of this stream
* @param joinWindowDuration window1 length of joinStream
* @param <R> Value type of the other stream
* @return PairWorkloadOperator after join
*/
@Override
public <R> PairWorkloadOperator<K, scala.Tuple2<V, R>> join(String componentId,
PairWorkloadOperator<K, R> joinStream,
TimeDurations windowDuration,
TimeDurations joinWindowDuration) throws WorkloadException {
return join(componentId, joinStream, windowDuration, joinWindowDuration, null, null);
}
/**
* Event time join
*
* @param componentId current compute component id
* @param joinStream the other stream<K,R>
* @param windowDuration window1 length of this stream
* @param joinWindowDuration window1 length of joinStream
* @param eventTimeAssigner1 event time assignment for this stream
* @param eventTimeAssigner2 event time assignment for joinStream
* @param <R> Value type of the other stream
* @return PairWorkloadOperator
* @throws WorkloadException
*/
@Override
public <R> PairWorkloadOperator<K, Tuple2<V, R>> join(String componentId,
PairWorkloadOperator<K, R> joinStream,
TimeDurations windowDuration,
TimeDurations joinWindowDuration,
final AssignTimeFunction<V> eventTimeAssigner1,
final AssignTimeFunction<R> eventTimeAssigner2) throws WorkloadException {
StreamExecutionEnvironment env = this.dataStream.getExecutionEnvironment();
if (null != eventTimeAssigner1 && null != eventTimeAssigner2)
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
else
env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);
if (joinStream instanceof FlinkPairWorkloadOperator) {
FlinkPairWorkloadOperator<K, R> joinFlinkStream = ((FlinkPairWorkloadOperator<K, R>) joinStream);
final KeySelector<Tuple2<K, V>, K> keySelector1 = new KeySelector<Tuple2<K, V>, K>() {
@Override
public K getKey(Tuple2<K, V> kvTuple2) throws Exception {
return kvTuple2._1();
}
};
final KeySelector<Tuple2<K, R>, K> keySelector2 = new KeySelector<Tuple2<K, R>, K>() {
@Override
public K getKey(Tuple2<K, R> krTuple2) throws Exception {
return krTuple2._1();
}
};
// tmpKeySelector for get keyTypeInfo InvalidTypesException
// TODO: find a better solution to solve
KeySelector<K, K> tmpKeySelector = new KeySelector<K, K>() {
@Override
public K getKey(K value) throws Exception {
return value;
}
};
TypeInformation<K> keyTypeInfo = TypeExtractor.getUnaryOperatorReturnType(tmpKeySelector, KeySelector.class, false, false, dataStream.getType(), null, false);
DataStream<Tuple2<K, V>> dataStream1 = new KeyedStream<>(dataStream, keySelector1, keyTypeInfo);
if (null != eventTimeAssigner1) {
// final AscendingTimestampExtractor<Tuple2<K, V>> timestampExtractor1 = new AscendingTimestampExtractor<Tuple2<K, V>>() {
// @Override
// public long extractAscendingTimestamp(Tuple2<K, V> element, long currentTimestamp) {
// return eventTimeAssigner1.assign(element._2());
// }
// };
TimestampExtractor<Tuple2<K, V>> timestampExtractor1 = new TimestampExtractor<Tuple2<K, V>>() {
long currentTimestamp = 0L;
@Override
public long extractTimestamp(Tuple2<K, V> kvTuple2, long l) {
long timestamp = eventTimeAssigner1.assign(kvTuple2._2());
if (timestamp > this.currentTimestamp) {
this.currentTimestamp = timestamp;
}
return timestamp;
}
@Override
public long extractWatermark(Tuple2<K, V> kvTuple2, long l) {
return -9223372036854775808L;
}
@Override
public long getCurrentWatermark() {
return currentTimestamp - 500;
}
};
dataStream1 = dataStream1.assignTimestamps(timestampExtractor1);
}
DataStream<Tuple2<K, R>> dataStream2 = new KeyedStream<>(joinFlinkStream.dataStream, keySelector2, keyTypeInfo);
if (null != eventTimeAssigner2) {
// final AscendingTimestampExtractor<Tuple2<K, R>> timestampExtractor2 = new AscendingTimestampExtractor<Tuple2<K, R>>() {
// @Override
// public long extractAscendingTimestamp(Tuple2<K, R> element, long currentTimestamp) {
// return eventTimeAssigner2.assign(element._2());
// }
// };
TimestampExtractor<Tuple2<K, R>> timestampExtractor2 = new TimestampExtractor<Tuple2<K, R>>() {
long currentTimestamp = 0L;
@Override
public long extractTimestamp(Tuple2<K, R> kvTuple2, long l) {
long timestamp = eventTimeAssigner2.assign(kvTuple2._2());
if (timestamp > this.currentTimestamp) {
this.currentTimestamp = timestamp;
}
return timestamp;
}
@Override
public long extractWatermark(Tuple2<K, R> kvTuple2, long l) {
return -9223372036854775808L;
}
@Override
public long getCurrentWatermark() {
return currentTimestamp - 500;
}
};
dataStream2 = dataStream2.assignTimestamps(timestampExtractor2);
}
DataStream<Tuple2<K, Tuple2<V, R>>> joineStream =
new NoWindowJoinedStreams<>(dataStream1, dataStream2)
.where(keySelector1, keyTypeInfo)
.buffer(Time.of(windowDuration.toMilliSeconds(), TimeUnit.MILLISECONDS))
.equalTo(keySelector2, keyTypeInfo)
.buffer(Time.of(joinWindowDuration.toMilliSeconds(), TimeUnit.MILLISECONDS))
.apply(new JoinFunction<Tuple2<K, V>, Tuple2<K, R>, Tuple2<K, Tuple2<V, R>>>() {
@Override
public Tuple2<K, Tuple2<V, R>> join(Tuple2<K, V> first, Tuple2<K, R> second) throws Exception {
return new Tuple2<>(first._1(), new Tuple2<>(first._2(), second._2()));
}
});
return new FlinkPairWorkloadOperator<>(joineStream, parallelism);
} else {
throw new WorkloadException("Cast joinStrem to FlinkPairWorkloadOperator failed");
}
}
@Override
public void closeWith(OperatorBase stream, boolean broadcast) throws UnsupportOperatorException {
}
@Override
public void print() {
this.dataStream.print();
}
@Override
public void sink() {
// this.dataStream.print();
this.dataStream.addSink(new SinkFunction<Tuple2<K, V>>() {
LatencyLog latency = new LatencyLog("sink");
@Override
public void invoke(Tuple2<K, V> value) throws Exception {
latency.execute((WithTime<? extends Object>) value._2());
}
});
}
}
| 45.857513 | 170 | 0.592791 |
0a241e8f12bb31bfc51a7afe31bcdf7e3b343e00 | 3,566 | /*
* 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.catalina.util;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.tomcat.util.descriptor.web.ErrorPage;
/**
* Provides support for tracking per exception type and per HTTP status code
* error pages.
*/
public class ErrorPageSupport {
// Fully qualified class name to error page
private ConcurrentMap<String, ErrorPage> exceptionPages = new ConcurrentHashMap<>();
// HTTP status code to error page
private ConcurrentMap<Integer, ErrorPage> statusPages = new ConcurrentHashMap<>();
public void add(ErrorPage errorPage) {
String exceptionType = errorPage.getExceptionType();
if (exceptionType == null) {
statusPages.put(Integer.valueOf(errorPage.getErrorCode()), errorPage);
} else {
exceptionPages.put(exceptionType, errorPage);
}
}
public void remove(ErrorPage errorPage) {
String exceptionType = errorPage.getExceptionType();
if (exceptionType == null) {
statusPages.remove(Integer.valueOf(errorPage.getErrorCode()), errorPage);
} else {
exceptionPages.remove(exceptionType, errorPage);
}
}
public ErrorPage find(int statusCode) {
return statusPages.get(Integer.valueOf(statusCode));
}
/**
* Find the ErrorPage, if any, for the named exception type.
*
* @param exceptionType The fully qualified class name of the exception type
*
* @return The ErrorPage for the named exception type, or {@code null} if
* none is configured
*
* @deprecated Unused. Will be removed in Tomcat 10.
* Use {@link #find(Throwable)} instead.
*/
@Deprecated
public ErrorPage find(String exceptionType) {
return exceptionPages.get(exceptionType);
}
public ErrorPage find(Throwable exceptionType) {
if (exceptionType == null) {
return null;
}
Class<?> clazz = exceptionType.getClass();
String name = clazz.getName();
while (!Object.class.equals(clazz)) {
ErrorPage errorPage = exceptionPages.get(name);
if (errorPage != null) {
return errorPage;
}
clazz = clazz.getSuperclass();
if (clazz == null) {
break;
}
name = clazz.getName();
}
return null;
}
public ErrorPage[] findAll() {
Set<ErrorPage> errorPages = new HashSet<>();
errorPages.addAll(exceptionPages.values());
errorPages.addAll(statusPages.values());
return errorPages.toArray(new ErrorPage[0]);
}
}
| 32.715596 | 88 | 0.655356 |
7b54742f4abac1a234c0292b4a7ca16dd9f1198a | 3,996 | package Fonts;
import java.awt.Font;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class FontRender {
public static Font getProgressStyle() {
try {
InputStream myStream = new BufferedInputStream(
new FileInputStream("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/Progress.ttf"));
Font fontHelsky = Font.createFont(Font.TRUETYPE_FONT, myStream);
return fontHelsky.deriveFont(Font.PLAIN, 80);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 50);
}
}
public static Font getNewsPaperStyle() {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT,
new File("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/NewsPaper.ttf"));
return font.deriveFont(Font.PLAIN, 80);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 20);
}
}
public static Font getNewsPaperStyle3() {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT,
new File("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/NewsPaper.ttf"));
return font.deriveFont(Font.PLAIN, 20);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 20);
}
}
public static Font getNewsPaperStyle2() {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT,
new File("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/NewsPaper.ttf"));
return font.deriveFont(Font.PLAIN, 30);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 20);
}
}
public static Font getRemachineStyle() {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT,
new File("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/Remachine.ttf"));
return font.deriveFont(Font.PLAIN, 30);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 20);
}
}
public static Font getHelskyStyle() {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT,
new File("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/Helsky.ttf"));
return font.deriveFont(Font.PLAIN, 80);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 20);
}
}
public static Font getHelskyStyle2() {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT,
new File("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/Helsky.ttf"));
return font.deriveFont(Font.PLAIN, 45);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 20);
}
}
public static Font getDancingScript() {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT,
new File("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/DancingScript.ttf"));
return font.deriveFont(Font.PLAIN, 45);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 20);
}
}
public static Font getNiconne() {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT,
new File("/home/prathviraj/Documents/procode/TICTACTOE/src/Fonts/niconne.ttf"));
return font.deriveFont(Font.PLAIN, 35);
} catch (Exception e) {
System.err.println(e);
return new Font(Font.DIALOG, Font.BOLD, 20);
}
}
}
| 36 | 112 | 0.584334 |
6330e0732452d44b7639c3ab9d6a4c4114de2493 | 1,061 | package postprocessor;
enum ErrorType {
SYNTAX("syntax", 10.0),
SEMANTIC("semantic", 1.0),
STYLE("style", 0.1);
private final String type;
private final double deductedMarks;
ErrorType(String type, double deductedMarks) {
this.type = type;
this.deductedMarks = deductedMarks;
}
public double getDeductedMarks() {
return deductedMarks;
}
public String toString() {
return type;
}
/**
* Takes string indicating error type (e.g. as retrieved from JSON files)
* and returns corresponding ErrorType.
* @param jsonErrorType
* @return Returns an instance of an ErrorType
*/
public static ErrorType convertStringToErrorType(String jsonErrorType) {
switch(jsonErrorType) {
case "syntax":
return ErrorType.SYNTAX;
case "semantic":
return ErrorType.SEMANTIC;
case "style":
return ErrorType.STYLE;
default:
return null;
}
}
}
| 24.674419 | 77 | 0.589067 |
878c3fe011cd35e5291294385d4210db887223a3 | 1,531 | package com.scaleunlimited.flinkcrawler.functions;
import java.util.Collections;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.scaleunlimited.flinkcrawler.pojos.RawUrl;
import com.scaleunlimited.flinkcrawler.urls.BaseUrlLengthener;
@SuppressWarnings({
"serial"
})
public class LengthenUrlsFunction extends BaseAsyncFunction<RawUrl, RawUrl> {
static final Logger LOGGER = LoggerFactory.getLogger(LengthenUrlsFunction.class);
// FUTURE make this settable from command line
// See https://github.com/ScaleUnlimited/flink-crawler/issues/50
private static final int THREAD_COUNT = 100;
private BaseUrlLengthener _lengthener;
public LengthenUrlsFunction(BaseUrlLengthener lengthener) {
super(THREAD_COUNT, lengthener.getTimeoutInSeconds());
_lengthener = lengthener;
}
@Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
_lengthener.open();
}
@Override
public void asyncInvoke(final RawUrl url, ResultFuture<RawUrl> future) throws Exception {
record(this.getClass(), url);
_executor.execute(new Runnable() {
@Override
public void run() {
RawUrl lengthenedUrl = _lengthener.lengthen(url);
future.complete(Collections.singleton(lengthenedUrl));
}
});
}
}
| 29.442308 | 93 | 0.714566 |
4da008994b3e9729ac859c647cac28b0dae0b86c | 364 | package cn.laoshini.dk.domain.common;
import java.io.Serializable;
import java.util.List;
import lombok.Data;
/**
* @author fagarine
*/
@Data
public class MethodDescriptor implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String comment;
private List<Tuple<String, String>> params;
}
| 15.826087 | 55 | 0.733516 |
bcd66ce94acfb643a3ac82d5e60ea5161353df8b | 9,116 | package fi.vtt.moodtracker;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import fi.vtt.climblib.Choice;
import fi.vtt.climblib.Path;
import fi.vtt.climblib.Questionnaire;
public class MoodButtons extends WearableActivity implements View.OnClickListener,
SensorEventListener {
private RelativeLayout rl;
private TextView questionTV;
private Questionnaire questionnaire;
private ArrayList<Choice> choices;
private int qListPosition = 0;
private boolean qListLastElem = false;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private SensorManager mSensorManager;
private int heartBeat;
public static final String QUESTIONNAIRE_ID = "questionnaireId";
public static final String QUESTION = "question";
public static final String CHOICE_TITLE = "choiceTitle";
public static final String CHOICE_VALUE = "choiceValue";
public static final String HEARTBEAT = "heartbeat";
public static final String QL_LAST_ELEMENT = "lastElement";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
setContentView(R.layout.activity_mood_buttons); //Not in use
setAmbientEnabled();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
mSensorManager.registerListener(this, mHeartRateSensor, SensorManager.SENSOR_DELAY_FASTEST);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String json = sharedPref.getString(Path.JSON, "");
Gson gson = new GsonBuilder().serializeNulls().create();
questionnaire = gson.fromJson(json, Questionnaire.class);
Log.d("QUEST", questionnaire.getQuestions().get(0).getType());
nextQuestion();
}
@Override
public void onSensorChanged(SensorEvent event) {
heartBeat = Math.round(event.values[0]);
// Log.d("HEARTBEAT", Integer.toString(heartBeat));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void vibrate() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
long[] vibrationPattern = {0, 600};
final int indexInPatternToRepeat = -1; //-1 - don't repeat
vibrator.vibrate(vibrationPattern, indexInPatternToRepeat);
}
public void nextQuestion() {
if(qListPosition < questionnaire.getQuestions().size()) {
if (qListPosition == 0)
vibrate();
qListLastElem = false;
choices = new ArrayList<Choice>(questionnaire.getQuestions().get(qListPosition).getChoices());
//ButtonUI starts ******** Thanks for the algorithm Konstantino Sparakis:
//http://stackoverflow.com/questions/22700007/a-circle-of-textviews-in-android?lq=1
rl = new RelativeLayout(this);
setContentView(rl);
// Change the radius to change size of cirlce
double radius = 140;
// Change these to control the x and y position of the center of the circle
// For more screen friendly code changing this to margins might be more efficient
double cx = 150, cy = 10;
double angleStart = 0;
double angleMax = 0;
double angleIncr = 45;
if (questionnaire.getQuestions().get(qListPosition).getType().equals("choice_1_5")) {
angleStart = -180;
angleMax = -405;
} else if (questionnaire.getQuestions().get(qListPosition).getType().equals("choice_1_7")) {
angleStart = -135;
angleMax = -450;
}
int cListPosition = 0;
for (double angle = angleStart; angle > angleMax; angle -= angleIncr) {
double radAngle = Math.toRadians(angle);
double x = (Math.cos(radAngle)) * radius + cx;
double y = (1 - Math.sin(radAngle)) * radius + cy;
TextView textView = new TextView(this);
if (choices.get(cListPosition).getEmoji() == null |
choices.get(cListPosition).getEmoji().equals(""))
textView.setText(choices.get(cListPosition).getTitle());
else
textView.setText(choices.get(cListPosition).getEmoji());
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
// textView.setText(Double.toString(angle));
textView.setTag(cListPosition);
textView.setOnClickListener(this);
//the 150 is the width of the actual text view and the 50 is the height
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(120, 120);
//the margins control where each of textview is placed
lp.leftMargin = (int) x;
lp.topMargin = (int) y;
rl.addView(textView, lp);
cListPosition++;
}
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
// lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.CENTER_VERTICAL);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
questionTV = new TextView(this);
questionTV.setText(questionnaire.getQuestions().get(qListPosition).getQuestion());
questionTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
questionTV.setPadding(10, 10, 10, 10);
questionTV.setWidth(200);
rl.addView(questionTV, lp);
//ButtonUI ends ****************************************************
qListPosition++;
if(qListPosition >= questionnaire.getQuestions().size()) {
qListLastElem = true;
}
}
else {
qListPosition = 0;
final long millis = questionnaire.getInterval() * 60 * 1000;
long msAlarm = SystemClock.elapsedRealtime() + millis;
Intent myIntent = new Intent(MoodButtons.this, MoodAlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(MoodButtons.this, 0, myIntent, 0);
alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, msAlarm, alarmIntent);
finish();
}
}
@Override
public void onClick(View view) {
Intent intent = new Intent(this, ClimbConfirmation.class);
intent.putExtra(QUESTIONNAIRE_ID, questionnaire.getId());
intent.putExtra(QUESTION, questionTV.getText());
intent.putExtra(CHOICE_TITLE, choices.get((int) view.getTag()).getTitle());
intent.putExtra(CHOICE_VALUE, choices.get((int) view.getTag()).getValue());
intent.putExtra(HEARTBEAT, heartBeat);
intent.putExtra(QL_LAST_ELEMENT, qListLastElem);
// startActivity(intent);
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
nextQuestion();
}
/* if (resultCode == Activity.RESULT_CANCELED) {
setVibrateTimer();
}*/
}
}//onActivityResult
@Override
public void onEnterAmbient(Bundle ambientDetails) {
super.onEnterAmbient(ambientDetails);
updateDisplay();
}
@Override
public void onUpdateAmbient() {
super.onUpdateAmbient();
vibrate();
updateDisplay();
}
@Override
public void onExitAmbient() {
updateDisplay();
super.onExitAmbient();
}
private void updateDisplay() {
if (isAmbient()) {
rl.setBackgroundColor(Color.BLACK);
questionTV.setTextColor(Color.WHITE);
} else {
rl.setBackground(null);
questionTV.setTextColor(Color.BLACK);
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| 38.464135 | 106 | 0.646994 |
01538147c7c89a4071dc4e0de9a838b8820cf083 | 5,301 |
/*
* This file is public domain.
*
* SWIRLDS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SWIRLDS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
import com.swirlds.platform.Browser;
import com.swirlds.platform.Console;
import com.swirlds.platform.Platform;
import com.swirlds.platform.PlatformStatus;
import com.swirlds.platform.SwirldMain;
import com.swirlds.platform.SwirldState;
import com.swirlds.platform.Transaction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Random;
/**
* This HelloSwirld creates a single transaction, consisting of the string "Hello Swirld", and then goes
* into a busy loop (checking once a second) to see when the state gets the transaction. When it does, it
* prints it, too.
*/
public class GameOfThronesDemoMain implements SwirldMain {
/** the platform running this app */
public Platform platform;
/** ID number for this member */
public long selfId;
/** a console window for text output */
public Console console;
/** sleep this many milliseconds after each sync */
public final int sleepPeriod = 100;
/**
* This is just for debugging: it allows the app to run in Eclipse. If the config.txt exists and lists a
* particular SwirldMain class as the one to run, then it can run in Eclipse (with the green triangle
* icon).
*
* @param args
* these are not used
*/
public static void main(String[] args) {
Browser.main(args);
}
// ///////////////////////////////////////////////////////////////////
@Override
public void preEvent() {
}
@Override
public void init(Platform platform, long id) {
this.platform = platform;
this.selfId = id;
this.console = platform.createConsole(true); // create the window, make it visible
platform.setAbout("Game of Thrones v. 1.0\n"); // set the browser's "about" box
platform.setSleepAfterSync(sleepPeriod);
}
@Override
public void run() {
String myName;
try {
myName = platform.getState().getAddressBookCopy()
.getAddress(selfId).getSelfName();
} finally {
platform.releaseState();
}
console.out.println("Winter is coming, " + myName + "!");
// create a transaction. For this example app,
// we will define each transactions to simply
// be a string in UTF-8 encoding.
String[] alliances;
String[] families;
String[] connections_families_to_alliance;
try {
GameOfThronesDemoState state = (GameOfThronesDemoState) platform.getState();
alliances = state.getAlliances();
families = state.getFamilies();
connections_families_to_alliance = state.getConnect_families_to_alliance();
} finally {
platform.releaseState();
}
console.out.println("Alliances: " + String.join(", ", alliances));
console.out.println("Families: " + String.join(", ", families));
console.out.println("Connections Families to Alliance: " + String.join(", ", connections_families_to_alliance));
Random rand = new Random();
int family_index = rand.nextInt(families.length);
byte[] transaction = families[family_index].getBytes(StandardCharsets.UTF_8);
console.out.println("family in txn: " + families[family_index]);
console.out.println(("transaction: " + transaction));
// Send the transaction to the Platform, which will then
// forward it to the State object.
// The Platform will also send the transaction to
// all the other members of the community during syncs with them.
// The community as a whole will decide the order of the transactions
platform.createTransaction(new Transaction(transaction));
//String lastReceived = "";
String[] lastReceivedConnections_families_to_alliance = new String[]{};
while (true) {
String[] receivedConnections_families_to_alliance;
try {
GameOfThronesDemoState state = (GameOfThronesDemoState) platform.getState();
//received = state.getReceived();
receivedConnections_families_to_alliance = state.getConnect_families_to_alliance();
} finally {
platform.releaseState();
}
if (!Arrays.deepEquals(lastReceivedConnections_families_to_alliance, receivedConnections_families_to_alliance)) {
//lastReceivedConnections_families_to_alliance = receivedConnections_families_to_alliance;
lastReceivedConnections_families_to_alliance = Arrays.copyOf(receivedConnections_families_to_alliance, receivedConnections_families_to_alliance.length);
//console.out.println("Received Connections Families to Alliance: " + String.join(", ", receivedConnections_families_to_alliance)); // print all received transactions
console.out.println("Received Connections Families to Alliance: ");
for(int i = 0; i < receivedConnections_families_to_alliance.length; i++) {
console.out.println(receivedConnections_families_to_alliance[i]);
}
console.out.println("");
}
try {
Thread.sleep(sleepPeriod);
} catch (Exception e) {
}
}
}
@Override
public SwirldState newState() {
return new GameOfThronesDemoState();
}
@Override
public void platformStatusChange(PlatformStatus newStatus) {
}
} | 35.34 | 170 | 0.732692 |
cbfdb35e5be822391c9af6f7dc353fd0a9b8ad89 | 472 | package com.supervisor.sdk.pgsql.statement;
import com.supervisor.sdk.datasource.Base;
import java.util.Arrays;
public final class PgDeleteSingleStatement extends PgStatementUpdatable {
public PgDeleteSingleStatement(final Base base, final String tableName, final Long id) {
super(base, statement(tableName), Arrays.asList(id));
}
private static String statement(final String tableName) {
return String.format("DELETE FROM %s WHERE id=?", tableName);
}
}
| 26.222222 | 89 | 0.775424 |
aba08fd155ebfd8cbb558db1cd4ad5e8b63bb39e | 1,462 | /*******************************************************************************
* Copyright (c) 2004, 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.impl.util;
/**
* A directed graph edge
*/
public class DirectedGraphEdge
{
private GraphNode from;
private GraphNode to;
public DirectedGraphEdge( GraphNode from, GraphNode to )
{
if ( from == null || to == null )
{
throw new IllegalArgumentException( "from node or to node is null" );
}
this.from = from;
this.to = to;
}
@Override
public int hashCode( )
{
final int prime = 31;
return prime * from.hashCode( ) + to.hashCode( );
}
@Override
public boolean equals( Object obj )
{
if ( this == obj )
return true;
if ( obj == null )
return false;
if ( getClass( ) != obj.getClass( ) )
return false;
DirectedGraphEdge other = (DirectedGraphEdge) obj;
return from.equals( other.getFrom( ) ) && to.equals( other.getTo( ) );
}
protected GraphNode getFrom( )
{
return from;
}
protected GraphNode getTo( )
{
return to;
}
}
| 21.820896 | 81 | 0.601231 |
c579eb0961f6e774c4fa0cd740338783a7341ed8 | 1,490 | /**
* Copyright Dingxuan. All Rights Reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.bcia.julongchain.events.producer;
import org.bcia.julongchain.protos.node.EventsPackage;
/**
* 类描述
*
* @author sunianle
* @date 2018/04/25
* @company Dingxuan
*/
public class BlockEvents {
/**
*
*/
private EventsPackage.Event blockEvent;
/**
*
*/
private EventsPackage.Event filteredBlockEvent;
private String groupId;
public BlockEvents(EventsPackage.Event blockEvent, EventsPackage.Event filteredBlockEvent, String groupId) {
this.blockEvent = blockEvent;
this.filteredBlockEvent = filteredBlockEvent;
this.groupId = groupId;
}
public EventsPackage.Event getBlockEvent() {
return blockEvent;
}
public EventsPackage.Event getFilteredBlockEvent() {
return filteredBlockEvent;
}
public String getGroupId() {
return groupId;
}
}
| 26.140351 | 112 | 0.695302 |
056790d6ddbea2f19e3ddbdbc0c972691c8eae4a | 380 | package com.cloud.legacymodel.acl;
import com.cloud.legacymodel.domain.PartOf;
import com.cloud.legacymodel.user.OwnedBy;
/**
* ControlledEntity defines an object for which the access from an
* access must inherit this interface.
*/
public interface ControlledEntity extends OwnedBy, PartOf {
Class<?> getEntityType();
enum ACLType {
Account, Domain
}
}
| 22.352941 | 66 | 0.734211 |
667b91afa0b79635aa076d353a3a78bfcbe90b0f | 1,549 | /**
* Copyright (C) 2014-2018 LinkedIn Corp. ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.thirdeye.datalayer.entity;
public class AnomalyFunctionIndex extends AbstractIndexEntity {
String functionName;
boolean active;
long metricId;
String collection;
String metric;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getCollection() {
return collection;
}
public void setCollection(String collection) {
this.collection = collection;
}
public String getMetric() {
return metric;
}
public void setMetric(String metric) {
this.metric = metric;
}
public long getMetricId() {
return metricId;
}
public void setMetricId(long metricId) {
this.metricId = metricId;
}
public String getFunctionName() {
return functionName;
}
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
}
| 23.469697 | 75 | 0.712718 |
a7bd77767bcf6031f599077776eb95ea2eaa819b | 376 | package com.github.mustfun.mybatis.plugin.inspection;
import com.intellij.codeInspection.LocalQuickFix;
import org.jetbrains.annotations.NotNull;
/**
* @author yanglin
* @updater itar
* @function 通用快速修复
*/
public abstract class GenericQuickFix implements LocalQuickFix {
@NotNull
@Override
public String getFamilyName() {
return getName();
}
}
| 18.8 | 64 | 0.728723 |
94ead80a79b91a157d182a0e7bcf4f360748bca0 | 2,299 | package com.example.curious.model;
public class CommentData {
private String author;
private String body;
private String score;
private String id;
private String permalink;
private String created_utc;
private String retrieved_on;
private String subreddit;
private String subreddit_id;
private String link_id;
private String parent_id;
private String author_fullname;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPermalink() {
return permalink;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public String getCreated_utc() {
return created_utc;
}
public void setCreated_utc(String created_utc) {
this.created_utc = created_utc;
}
public String getRetrieved_on() {
return retrieved_on;
}
public void setRetrieved_on(String retrieved_on) {
this.retrieved_on = retrieved_on;
}
public String getSubreddit() {
return subreddit;
}
public void setSubreddit(String subreddit) {
this.subreddit = subreddit;
}
public String getSubreddit_id() {
return subreddit_id;
}
public void setSubreddit_id(String subreddit_id) {
this.subreddit_id = subreddit_id;
}
public String getLink_id() {
return link_id;
}
public void setLink_id(String link_id) {
this.link_id = link_id;
}
public String getParent_id() {
return parent_id;
}
public void setParent_id(String parent_id) {
this.parent_id = parent_id;
}
public String getAuthor_fullname() {
return author_fullname;
}
public void setAuthor_fullname(String author_fullname) {
this.author_fullname = author_fullname;
}
}
| 19.818966 | 60 | 0.627229 |
7f5531d8904a8a9dd2770879e740d214bfc63561 | 2,452 | package oop_project;
import java.awt.image.BufferedImage;
public abstract class IntegratedCircuit extends Sprite{
private final Node[] pins;
public Node vcc;
public Node grnd;
public IntegratedCircuit(BufferedImage[] images, int pins) {
super(images);
this.pins = new Node[pins];
if(TrainerBoard.zoomedIn)
setImage(getImage(1));
}
public void loadPins(Node node) throws Exception{
NodeGroup nodeGroup = (NodeGroup)node.getParent();
NodalGroup nodalGroup = (NodalGroup)nodeGroup.getParent();
TrainerBoard trainerBoard = (TrainerBoard)nodalGroup.getParent();
int nodalGroupIndex = 0, nodeGroupIndex = 0;
for(int i = 0; i < trainerBoard.nodalGroups.length; i++)
if(trainerBoard.nodalGroups[i] == nodalGroup)
nodalGroupIndex = i;
for(int i = 0; i < nodalGroup.nodeGroups.length; i++)
if(nodalGroup.nodeGroups[i] == nodeGroup)
nodeGroupIndex = i;
if(node != trainerBoard.nodalGroups[nodalGroupIndex].nodeGroups[nodeGroupIndex].nodes[4])
throw new Exception("Invalid Node");
int i = 0;
while(i < 2){
int j = 0;
while(j < pins.length/2){
this.pins[(pins.length/2 * i) + j] = trainerBoard.nodalGroups[nodalGroupIndex + i].nodeGroups[nodeGroupIndex + j].nodes[4];
j++;
}
i++;
}
vcc = pins[0];
grnd = pins[pins.length - 1];
}
@Override
public void tick(){
if (vcc != null && vcc.getValue() == 2 && grnd.getValue() == 1)
evaluate();
}
public Node getPin(int i){
return pins[i];
}
public void setPin(Node n, int i){
pins[i] = n;
}
public void stateChange(){
BufferedImage image = getImage();
BufferedImage normal = getImage(0);
BufferedImage zoom = getImage(1);
if(image == normal)
setImage(zoom);
else if(image == zoom){
setImage(normal);
x = pins[0].tx;
y = pins[0].ty;
}
}
public void movex(){
x += TrainerBoard.dx;
}
public void movey(){
y += TrainerBoard.dy;
}
public abstract void evaluate();
public abstract int function(Node[] input);
}
| 27.550562 | 139 | 0.541599 |
7024180cffafe35fb777f443145cea07a2778c1c | 7,632 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.springframework.geode.cache.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.util.function.Function;
import java.util.function.Supplier;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.apache.geode.cache.CacheRuntimeException;
import org.apache.geode.cache.LoaderHelper;
import org.springframework.core.env.Environment;
import org.springframework.data.repository.CrudRepository;
/**
* Unit Tests for {@link RepositoryCacheLoaderWriterSupport}.
*
* @author John Blum
* @see java.util.function.Function
* @see org.junit.Test
* @see org.mockito.Mockito
* @see org.mockito.junit.MockitoJUnitRunner
* @see org.springframework.core.env.Environment
* @see org.springframework.data.repository.CrudRepository
* @see org.springframework.geode.cache.support.RepositoryCacheLoaderWriterSupport
* @since 1.1.0
*/
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings({ "rawtypes", "unchecked" })
public class RepositoryCacheLoaderWriterSupportUnitTests {
@Mock
private CrudRepository<?, ?> mockCrudRepository;
@After
public void tearDown() {
System.clearProperty(RepositoryCacheLoaderWriterSupport.NUKE_AND_PAVE_PROPERTY);
}
@Test
public void constructsRepositoryCacheLoaderWriterSupportSuccessfully() {
RepositoryCacheLoaderWriterSupport<Object, Object> cacheLoaderWriter =
new TestRepositoryCacheLoaderWriterSupport(this.mockCrudRepository);
assertThat(cacheLoaderWriter).isNotNull();
assertThat(cacheLoaderWriter.getEnvironment().orElse(null)).isNull();
assertThat(cacheLoaderWriter.getRepository()).isEqualTo(mockCrudRepository);
}
@Test(expected = IllegalArgumentException.class)
public void constructsRepositoryCacheLoaderWriterSupportWithNull() {
try {
new TestRepositoryCacheLoaderWriterSupport<>(null);
}
catch (IllegalArgumentException expected) {
assertThat(expected).hasMessage("Repository is required");
assertThat(expected).hasNoCause();
throw expected;
}
}
@Test
public void setAndGetEnvironment() {
Environment mockEnvironment = mock(Environment.class);
RepositoryCacheLoaderWriterSupport<Object, Object> cacheLoaderWriter =
new TestRepositoryCacheLoaderWriterSupport(this.mockCrudRepository);
cacheLoaderWriter.setEnvironment(mockEnvironment);
assertThat(cacheLoaderWriter.getEnvironment().orElse(null)).isEqualTo(mockEnvironment);
cacheLoaderWriter.setEnvironment(null);
assertThat(cacheLoaderWriter.getEnvironment().orElse(null)).isNull();
}
@Test
public void isNukeAndPaveEnabledReturnsFalse() {
assertThat(new TestRepositoryCacheLoaderWriterSupport(this.mockCrudRepository)
.isNukeAndPaveEnabled()).isFalse();
}
@Test
public void isNukeAndPaveEnabledWhenEnvironmentPropertyIsSetReturnsTrue() {
System.setProperty(RepositoryCacheLoaderWriterSupport.NUKE_AND_PAVE_PROPERTY, String.valueOf(false));
assertThat(Boolean.parseBoolean(System.getProperty(RepositoryCacheLoaderWriterSupport.NUKE_AND_PAVE_PROPERTY)))
.isFalse();
Environment mockEnvironment = mock(Environment.class);
when(mockEnvironment.getProperty(eq(RepositoryCacheLoaderWriterSupport.NUKE_AND_PAVE_PROPERTY),
eq(Boolean.class))).thenReturn(true);
assertThat(new TestRepositoryCacheLoaderWriterSupport(this.mockCrudRepository)
.with(mockEnvironment).isNukeAndPaveEnabled()).isTrue();
verify(mockEnvironment, times(1))
.getProperty(eq(RepositoryCacheLoaderWriterSupport.NUKE_AND_PAVE_PROPERTY), eq(Boolean.class));
}
@Test
public void isNukeAndPaveEnabledWhenSystemPropertyIsSetReturnsTrue() {
System.setProperty(RepositoryCacheLoaderWriterSupport.NUKE_AND_PAVE_PROPERTY, String.valueOf(true));
assertThat(Boolean.parseBoolean(System.getProperty(RepositoryCacheLoaderWriterSupport.NUKE_AND_PAVE_PROPERTY)))
.isTrue();
assertThat(new TestRepositoryCacheLoaderWriterSupport(this.mockCrudRepository).isNukeAndPaveEnabled())
.isTrue();
}
@Test
public void doRepositoryOperationSuccessfully() {
Function<Object, Object> mockRepositoryOperationFunction = mock(Function.class);
when(mockRepositoryOperationFunction.apply(any())).thenReturn("TEST");
Object testEntity = new Object();
RepositoryCacheLoaderWriterSupport<Object, Object> cacheLoaderWriter =
new TestRepositoryCacheLoaderWriterSupport(this.mockCrudRepository);
assertThat(cacheLoaderWriter.doRepositoryOp(testEntity, mockRepositoryOperationFunction)).isEqualTo("TEST");
verify(mockRepositoryOperationFunction, times(1)).apply(eq(testEntity));
}
@Test
public void loadReturnsNull() {
LoaderHelper<?, ?> mockLoadHelper = mock(LoaderHelper.class);
assertThat(new TestRepositoryCacheLoaderWriterSupport(this.mockCrudRepository).load(mockLoadHelper)).isNull();
verifyNoInteractions(mockLoadHelper);
}
@Test(expected = CacheRuntimeException.class)
public void doRepositoryOperationThrowsException() {
Function<Object, Object> mockRepositoryOperationFunction = mock(Function.class);
when(mockRepositoryOperationFunction.apply(any())).thenThrow(new RuntimeException("TEST"));
Object testEntity = new Object();
RepositoryCacheLoaderWriterSupport<Object, Object> cacheLoaderWriter =
new TestRepositoryCacheLoaderWriterSupport(this.mockCrudRepository);
try {
cacheLoaderWriter.doRepositoryOp(testEntity, mockRepositoryOperationFunction);
}
catch (CacheRuntimeException expected) {
assertThat(expected).hasMessage(RepositoryCacheLoaderWriterSupport.DATA_ACCESS_ERROR, testEntity);
assertThat(expected).hasCauseInstanceOf(RuntimeException.class);
assertThat(expected.getCause()).hasMessage("TEST");
assertThat(expected.getCause()).hasNoCause();
throw expected;
}
finally {
verify(mockRepositoryOperationFunction, times(1)).apply(eq(testEntity));
}
}
static class TestRepositoryCacheLoaderWriterSupport<T, ID> extends RepositoryCacheLoaderWriterSupport<T, ID> {
TestRepositoryCacheLoaderWriterSupport(CrudRepository<T, ID> crudRepository) {
super(crudRepository);
}
@Override
protected CacheRuntimeException newCacheRuntimeException(Supplier<String> messageSupplier, Throwable cause) {
return new TestCacheRuntimeException(messageSupplier.get(), cause);
}
}
@SuppressWarnings("unused")
static final class TestCacheRuntimeException extends CacheRuntimeException {
public TestCacheRuntimeException() { }
public TestCacheRuntimeException(String message) {
super(message);
}
public TestCacheRuntimeException(Throwable cause) {
super(cause);
}
public TestCacheRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
}
| 32.615385 | 113 | 0.801101 |
ef3ad19a7b633e6992e0281e00c04ed921ce7b39 | 629 | package org.cloud.ssm.service;
import javax.annotation.Resource;
import org.cloud.ssm.entity.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:spring/applicationContext.xml"})
public class EmployeeServiceTest {
@Resource
private EmployeeService employeeService;
@Test
public void testAddEmployee() {
employeeService.addEmployee(new Employee(null, "zhangshan", "beijing1", 30));
}
}
| 26.208333 | 79 | 0.801272 |
61b535a77a95824db772a20200fd83d48186f763 | 17,666 | /*
* EventAdaptor.java --
*
* Base class for event adaptors classes generated by Tcl.
*
* Copyright (c) 1997 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
* RCS: @(#) $Id: EventAdaptor.java,v 1.3 2002/12/21 04:04:04 mdejong Exp $
*/
package tcl.lang;
import java.util.*;
import java.lang.reflect.*;
import java.beans.*;
/*
* This class is the base class for all event adaptors used by Tcl.
* It handles events generated by Java code and passes them to the Tcl
* interpreter.
*
* A subclass of EventAdaptor will implement a particular event interface
* and is usually generated on-the-fly by the AdaptorGen class.
*
* NOTE:
*
* + THIS CLASS MUST BE PUBLIC, otherwise some JVM may refuse to load
* subclasses of this class in the custom AdaptorClassLoader.
*
* + Some methods in this class are called by subclasses and thus must
* be public. All public methods are prefixed with "_" in order to
* avoid conflicts with method names in event interfaces. These methods
* are also declared "final", so that if a conflict does happen, it
* will be reported by the JVM as an attempt to redefine a final
* methood.
*/
public class EventAdaptor {
// true if the init() has been called, false otherwise.
private boolean initialized;
// The event should be fired to this interpreter.
Interp interp;
// The event source object.
Object source;
// Stores the callbacks that are currently being handled by the target.
Hashtable callbacks;
// If an Exception is throws during the execution of the event
// handler, it is stored in this member variable for later processing
// by _wrongException(). If no Exception is thrown, the value of this
// variable is null.
Throwable exception;
// The event set handled by this adaptor.
EventSetDescriptor eventDesc;
/*
*----------------------------------------------------------------------
*
* EventAdaptor --
*
* Creates a new EventAdaptor instance.
*
* Side effects:
* Member fields are initialized.
*
*----------------------------------------------------------------------
*/
public
EventAdaptor()
{
initialized = false;
}
/*
*----------------------------------------------------------------------
*
* init --
*
* Initialize the event adaptor object and register it as a
* listener to the event source.
*
* The initialization is carried out in this method instead of
* the constructor. This makes it easy to generate class data for
* the event adaptor subclasses.
*
* Results:
* None.
*
* Side effects:
* The adaptor is registered as a listener to the event source.
*
*----------------------------------------------------------------------
*/
void
init(
Interp i, // Interpreter in which the event should fire.
Object src, // Event source.
EventSetDescriptor desc) // Describes the event to listen to.
throws
TclException // Standard Tcl exception.
{
interp = i;
callbacks = new Hashtable();
eventDesc = desc;
source = src;
Method method = eventDesc.getAddListenerMethod();
if (method != null) {
Object args[] = new Object[1];
args[0] = this;
try {
method.invoke(source, args);
} catch (Exception e) {
throw new ReflectException(i, e);
}
}
initialized = true;
}
/*
*----------------------------------------------------------------------
*
* setCallback --
*
* Set the callback script of the given event.
*
* Results:
* None.
*
* Side effects:
* If a callback has already been installed for the given event,
* it will be replaced by the new callback.
*
*----------------------------------------------------------------------
*/
void
setCallback(
String eventName, // Name of the event for which a callback
// should be created.
TclObject command) // Tcl command to invoke when the given event
// fires.
{
check();
TclObject oldCmd = (TclObject) callbacks.get(eventName);
if (oldCmd != null) {
callbacks.remove(eventName);
}
// We use to preserve the passed in TclObject, but that leads
// to a memory leak in Tcl Blend because release was not called.
// Instead just use a TclString which is managed by Java.
TclObject str = TclString.newInstance(command.toString());
callbacks.put(eventName, str);
}
/*
*----------------------------------------------------------------------
*
* deleteCallback --
*
* Deletes the callback script of the given event, if one exists.
*
* Results:
* The number of events that are still handled after deleting
* the script for the given event.
*
* Side effects:
* If no events are handled after deleting the script for the
* given event, this event listener is removed from the object and
* the adaptor is uninitialized.
*
*----------------------------------------------------------------------
*/
int
deleteCallback(
String eventName) // Name of the event for which a callback
// should be created.
throws
TclException // Standard Tcl exception.
{
check();
TclObject oldCmd = (TclObject) callbacks.get(eventName);
if (oldCmd != null) {
callbacks.remove(eventName);
}
int size = callbacks.size();
if (size == 0) {
try {
Method method = eventDesc.getRemoveListenerMethod();
if (method != null) {
Object args[] = new Object[1];
args[0] = this;
method.invoke(source, args);
}
} catch (Exception e) {
throw new ReflectException(interp, e);
} finally {
initialized = false;
callbacks = null;
eventDesc = null;
interp = null;
source = null;
}
}
return size;
}
/*
*----------------------------------------------------------------------
*
* getCallback --
*
* Query the callback command for the given event.
*
* Results:
* The callback command for the given event, if any, or null
* if no callback was registered for the event.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
TclObject
getCallback(
String eventName) // Name of the event to query.
{
check();
return (TclObject)callbacks.get(eventName);
}
/*
*----------------------------------------------------------------------
*
* getHandledEvents --
*
* Query all the events that are currently handled by
* this adaptor.
*
* Results:
* None.
*
* Side effects:
* The full names of the handled events are appended to the list.
*
*----------------------------------------------------------------------
*/
void
getHandledEvents(
TclObject list) // TclList to store the name of the handled
// events.
{
check();
try {
String interfaceName = eventDesc.getListenerType().getName();
for (Enumeration e = callbacks.keys(); e.hasMoreElements(); ) {
String eventName = (String) e.nextElement();
TclList.append(null, list, TclString.newInstance(
interfaceName + "." + eventName));
}
} catch (TclException e) {
throw new TclRuntimeError("unexpected TclException: " + e);
}
}
/*
*----------------------------------------------------------------------
*
* processEvent --
*
* This method is called whenever an event is fired by the event
* source. If a callback has been registered, the Tcl command is
* executed.
*
* Results:
* None.
*
* Side effects:
* The callback script may have any side effect.
*
*----------------------------------------------------------------------
*/
public final void
_processEvent(
Object params[], // Event object associated with this event.
String eventName) // Name of the event.
throws
Throwable
{
check();
exception = null;
TclObject cmd = (TclObject) callbacks.get(eventName);
if (cmd != null) {
Class paramTypes[] = null;
Method methods[] = eventDesc.getListenerType().getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(eventName)) {
paramTypes = methods[i].getParameterTypes();
break;
}
}
BeanEvent evt = new BeanEvent(interp, paramTypes, params, cmd);
interp.getNotifier().queueEvent(evt, TCL.QUEUE_TAIL);
evt.sync();
exception = evt.exception;
if (exception != null) {
throw exception;
}
}
}
/*
*----------------------------------------------------------------------
*
* check --
*
* Sanity check. Make sure the init() method has been called on
* this object.
*
* Results:
* None.
*
* Side effects:
* TclRuntimeError is thrown if the init() method has not been caled.
*
*----------------------------------------------------------------------
*/
private final void
check()
{
if (!initialized) {
throw new TclRuntimeError("EventAdaptor not initialized");
}
}
/*
*----------------------------------------------------------------------
*
* _wrongException --
*
* This procedure is called if the binding script generates an
* exception which is not declared in the method's "throws" clause.
* If the exception is an unchecked exception (i.e., a subclass of
* java.lang.Error), it gets re-thrown. Otherwise, a Tcl bgerror
* is triggered and this procedure returns normally.
*
* Results:
* None.
*
* Side effects:
* unchecked exceptions will be re-thrown.
*
*----------------------------------------------------------------------
*/
public final void
_wrongException()
throws
Error, // If a Error was caught during the
// execution of the binding script, it
// is re-thrown.
RuntimeException // If a RuntimeException was caught during the
// execution of the binding script, it
// is re-thrown.
{
if (exception instanceof Error) {
throw (Error)exception;
}
if (exception instanceof RuntimeException) {
throw (RuntimeException)exception;
}
if (!(exception instanceof TclException)) {
interp.setResult("unexpected exception: " + exception);
} else {
// The error message is already in the interp in the case of
// a TclException, so there is no need to set it here.
}
interp.addErrorInfo("\n (command bound to event)");
interp.backgroundError();
}
/*
*----------------------------------------------------------------------
*
* _return_boolean --
*
* Converts the interp's result to a boolean value and returns it.
*
* Results:
* A boolean value from the interp's result; false if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final boolean
_return_boolean()
{
if (exception != null) {
// An unexpected exception had happen during the execution of
// the binding. We return an "undefined" value without looking
// at interp.getResult().
return false;
}
TclObject result = interp.getResult();
try {
return TclBoolean.get(interp, result);
} catch (TclException e) {
interp.addErrorInfo(
"\n (attempting to return boolean from binding)");
interp.backgroundError();
return false;
}
}
/*
*----------------------------------------------------------------------
*
* _return_byte --
*
* Converts the interp's result to a byte value and returns it.
*
* Results:
* A byte value from the interp's result; 0 if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final byte
_return_byte()
{
return (byte) _return_int();
}
/*
*----------------------------------------------------------------------
*
* _return_char --
*
* Converts the interp's result to a char value and returns it.
*
* Results:
* A char value from the interp's result; \0 if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final char
_return_char()
{
if (exception != null) {
// An unexpected exception had happen during the execution of
// the binding. We return an "undefined" value without looking
// at interp.getResult().
return '\0';
}
String s = interp.getResult().toString();
if (s.length() == 1) {
return s.charAt(0);
} else {
interp.setResult("expecting character but got \"" + s + "\"");
interp.addErrorInfo(
"\n (attempting to return character from binding)");
interp.backgroundError();
return '\0';
}
}
/*
*----------------------------------------------------------------------
*
* _return_double --
*
* Converts the interp's result to a double value and returns it.
*
* Results:
* A double value from the interp's result; 0.0 if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final double
_return_double()
{
if (exception != null) {
// An unexpected exception had happen during the execution of
// the binding. We return an "undefined" value without looking
// at interp.getResult().
return 0.0;
}
TclObject result = interp.getResult();
try {
return TclDouble.get(interp, result);
} catch (TclException e) {
interp.addErrorInfo(
"\n (attempting to return floating-point number from binding)");
interp.backgroundError();
return 0.0;
}
}
/*
*----------------------------------------------------------------------
*
* _return_float --
*
* Converts the interp's result to a float value and returns it.
*
* Results:
* A float value from the interp's result; 0.0 if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final float
_return_float()
{
return (float) _return_double();
}
/*
*----------------------------------------------------------------------
*
* _return_int --
*
* Converts the interp's result to a int value and returns it.
*
* Results:
* A int value from the interp's result; 0 if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final int
_return_int()
{
if (exception != null) {
// An unexpected exception had happen during the execution of
// the binding. We return an "undefined" value without looking
// at interp.getResult().
return 0;
}
TclObject result = interp.getResult();
try {
return TclInteger.get(interp, result);
} catch (TclException e) {
interp.addErrorInfo(
"\n (attempting to return integer number from binding)");
interp.backgroundError();
return 0;
}
}
/*
*----------------------------------------------------------------------
*
* _return_long --
*
* Converts the interp's result to a long value and returns it.
*
* Results:
* A long value from the interp's result; 0 if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final long
_return_long()
{
return (long) _return_int();
}
/*
*----------------------------------------------------------------------
*
* _return_short --
*
* Converts the interp's result to a short value and returns it.
*
* Results:
* A short value from the interp's result; 0 if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final short
_return_short()
{
return (short) _return_int();
}
/*
*----------------------------------------------------------------------
*
* _return_Object --
*
* Converts the interp's result to an instance of the given class
* and returns it.
*
* Results:
* A Object value from the interp's result; null if the
* conversion fails.
*
* Side effects:
* A background error is reported if the conversion fails.
*
*----------------------------------------------------------------------
*/
public final Object
_return_Object(
String className) // The name of the class that the object must
// belong to.
{
if (exception != null) {
// An unexpected exception had happen during the execution of
// the binding. We return an "undefined" value without looking
// at interp.getResult().
return null;
}
if (className.equals("java.lang.String")) {
return interp.getResult().toString();
}
Class cls = null;
try {
cls = Class.forName(className);
} catch (ClassNotFoundException e) {
// This exception should never happen here because the class
// of the given name should have already been referenced
// before execution comes to here (e.g, when a parameter of
// this class is passed to the method).
//
// If the exception indeed happens, our byte-code generator
// AdaptorGen must be at fault.
throw new TclRuntimeError("unexpected exception " + e);
}
try {
TclObject result = interp.getResult();
Object obj = ReflectObject.get(interp, result);
if (!cls.isInstance(obj)) {
throw new TclException(interp, "cannot cast object " +
result.toString() + " (" + obj.toString() +
") to required type " +
className);
}
return obj;
} catch (TclException e) {
interp.addErrorInfo(
"\n (attempting to return object from binding)");
interp.backgroundError();
return null;
}
}
} // end EventAdaptor
| 24.002717 | 75 | 0.570135 |
16d835214ab7702c5d9f788eed1251eaa52cf5e1 | 942 | /*
* generated by Xtext 2.9.2
*/
package org.lilychant.ide.contentassist.antlr;
import org.antlr.runtime.Token;
import org.antlr.runtime.TokenSource;
import org.eclipse.xtext.parser.antlr.AbstractIndentationTokenSource;
import org.lilychant.ide.contentassist.antlr.internal.InternalLilyChantParser;
public class LilyChantTokenSource extends AbstractIndentationTokenSource {
public LilyChantTokenSource(TokenSource delegate) {
super(delegate);
}
@Override
protected boolean shouldSplitTokenImpl(Token token) {
// TODO Review assumption
return token.getType() == InternalLilyChantParser.RULE_WS;
}
@Override
protected int getBeginTokenType() {
// TODO Review assumption
return InternalLilyChantParser.RULE_BEGIN;
}
@Override
protected int getEndTokenType() {
// TODO Review assumption
return InternalLilyChantParser.RULE_END;
}
@Override
protected boolean shouldEmitPendingEndTokens() {
return false;
}
}
| 23.55 | 78 | 0.791932 |
9fd160a21a863ad109879bf0969fb28acbcac5d0 | 2,279 | package org.jumpmind.db.platform.postgresql;
import java.util.Map;
import org.jumpmind.db.model.Column;
import org.jumpmind.db.platform.DatabaseInfo;
public class PostgreSqlDmlStatement95 extends PostgreSqlDmlStatement {
public PostgreSqlDmlStatement95(DmlType type, String catalogName, String schemaName, String tableName,
Column[] keysColumns, Column[] columns, boolean[] nullKeyValues, DatabaseInfo databaseInfo,
boolean useQuotedIdentifiers, String textColumnExpression) {
super(type, catalogName, schemaName, tableName, keysColumns, columns, nullKeyValues, databaseInfo, useQuotedIdentifiers,
textColumnExpression);
}
@Override
public String buildInsertSql(String tableName, Column[] keys, Column[] columns) {
StringBuilder sql = new StringBuilder("insert into " + tableName + " (");
appendColumns(sql, columns, false);
sql.append(") values (");
appendColumnParameters(sql, columns);
sql.append(") on conflict do nothing");
return sql.toString();
}
@Override
public Column[] getMetaData() {
if (dmlType == DmlType.INSERT) {
return getColumns();
} else {
return super.getMetaData();
}
}
@Override
public <T> T[] getValueArray(T[] columnValues, T[] keyValues) {
if (dmlType == DmlType.INSERT) {
return columnValues;
} else {
return super.getValueArray(columnValues, keyValues);
}
}
@Override
public Object[] getValueArray(Map<String, Object> params) {
if (dmlType == DmlType.INSERT) {
int index = 0;
Object[] args = new Object[columns.length];
for (Column column : columns) {
args[index++] = params.get(column.getName());
}
return args;
}
return super.getValueArray(params);
}
@Override
protected int[] buildTypes(Column[] keys, Column[] columns, boolean isDateOverrideToTimestamp) {
if (dmlType == DmlType.INSERT) {
return buildTypes(columns, isDateOverrideToTimestamp);
} else {
return super.buildTypes(keys, columns, isDateOverrideToTimestamp);
}
}
}
| 33.514706 | 128 | 0.627907 |
85320cbbd9fafee6f5d7d43be6e7ace10e64fe98 | 97 | /**
* Provides low- and high-level bindings to the DNAnexus Platform.
*/
package com.dnanexus;
| 19.4 | 66 | 0.721649 |
c548916367ace3c2a29df8f71e857c056315efd1 | 686 | package services;
import exceptions.DBException;
import exceptions.NotFoundException;
import models.Event;
import models.User;
import java.util.List;
public class UserService {
public Integer create(User newUser) throws DBException {
try{
newUser.save();
} catch (RuntimeException e) {
throw new DBException(e.getCause().getMessage());
}
return newUser.getId();
}
public User get(Integer userId) throws NotFoundException{
User retrievedUser = User.find.byId(userId);
if(retrievedUser == null) {
throw new NotFoundException(userId);
}
return retrievedUser;
}
}
| 19.6 | 61 | 0.641399 |
b453827a0c0e64dfd44012be819e126a8529c63d | 2,385 | package dev.hbeck.kdl.parse;
import dev.hbeck.kdl.TestUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
@RunWith(Parameterized.class)
public class TestGetEscaped {
public TestGetEscaped(String input, int expectedResult) {
this.input = input;
this.expectedResult = expectedResult;
}
@Parameterized.Parameters(name = "{0}")
public static List<Object[]> getCases() {
return Stream.of(
new Object[]{"n", '\n'},
new Object[]{"r", '\r'},
new Object[]{"t", '\t'},
new Object[]{"\\", '\\'},
new Object[]{"/", '/'},
new Object[]{"\"", '\"'},
new Object[]{"b", '\b'},
new Object[]{"f", '\f'},
new Object[]{"u{1}", '\u0001'},
new Object[]{"u{01}", '\u0001'},
new Object[]{"u{001}", '\u0001'},
new Object[]{"u{001}", '\u0001'},
new Object[]{"u{0001}", '\u0001'},
new Object[]{"u{00001}", '\u0001'},
new Object[]{"u{000001}", '\u0001'},
new Object[]{"u{10FFFF}", 0x10FFFF},
new Object[]{"i", -2},
new Object[]{"ux", -2},
new Object[]{"u{x}", -2},
new Object[]{"u{0001", -2},
new Object[]{"u{AX}", -2},
new Object[]{"u{}", -2},
new Object[]{"u{0000001}", -2},
new Object[]{"u{110000}", -2}
).collect(Collectors.toList());
}
private final String input;
private final int expectedResult;
@Test
public void doTest() throws IOException {
final KDLParseContext context = TestUtil.strToContext(input);
final int initial = context.read();
try {
final int result = TestUtil.parser.getEscaped(initial, context);
assertThat(result, equalTo(expectedResult));
} catch (KDLParseException e) {
if (expectedResult > 0) {
throw new KDLParseException("Expected no errors", e);
}
}
}
}
| 33.591549 | 76 | 0.514046 |
32e8bc1a18f089e02e76d2884602ce190fa4743f | 8,849 | /*
* Copyright (c) 2016-2020, MiLaboratory LLC
* All Rights Reserved
*
* Permission to use, copy, modify and distribute any part of this program for
* educational, research and non-profit purposes, by non-profit institutions
* only, without fee, and without a written agreement is hereby granted,
* provided that the above copyright notice, this paragraph and the following
* three paragraphs appear in all copies.
*
* Those desiring to incorporate this work into commercial products or use for
* commercial purposes should contact MiLaboratory LLC, which owns exclusive
* rights for distribution of this program for commercial purposes, using the
* following email address: [email protected].
*
* IN NO EVENT SHALL THE INVENTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
* SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
* ARISING OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE INVENTORS HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE SOFTWARE PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE INVENTORS HAS
* NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
* MODIFICATIONS. THE INVENTORS MAKES NO REPRESENTATIONS AND EXTENDS NO
* WARRANTIES OF ANY KIND, EITHER IMPLIED OR EXPRESS, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
* PARTICULAR PURPOSE, OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY
* PATENT, TRADEMARK OR OTHER RIGHTS.
*/
package com.milaboratory.minnn.consensus;
import com.milaboratory.core.io.sequence.*;
import com.milaboratory.core.sequence.*;
import com.milaboratory.minnn.outputconverter.*;
import com.milaboratory.minnn.pattern.*;
import gnu.trove.map.hash.TByteObjectHashMap;
import java.util.*;
import static com.milaboratory.minnn.util.SystemUtils.*;
public final class Consensus implements java.io.Serializable {
public final TByteObjectHashMap<SequenceWithAttributes> sequences;
public final List<Barcode> barcodes;
public final int consensusReadsNum;
public final ConsensusDebugData debugData;
public final boolean isConsensus;
public final ArrayList<DataFromParsedReadWithAllGroups> savedOriginalSequences = new ArrayList<>();
public final int numberOfTargets;
public final boolean finalConsensus;
public final long tempId;
private final boolean defaultGroupsOverride;
public Consensus(
TByteObjectHashMap<SequenceWithAttributes> sequences, List<Barcode> barcodes, int consensusReadsNum,
ConsensusDebugData debugData, int numberOfTargets, boolean finalConsensus, long tempId,
boolean defaultGroupsOverride) {
this.sequences = sequences;
this.barcodes = barcodes;
this.consensusReadsNum = consensusReadsNum;
this.debugData = debugData;
this.isConsensus = true;
this.numberOfTargets = numberOfTargets;
this.finalConsensus = finalConsensus;
this.tempId = tempId;
this.defaultGroupsOverride = defaultGroupsOverride;
}
public Consensus(ConsensusDebugData debugData, int numberOfTargets, boolean finalConsensus) {
this.sequences = null;
this.barcodes = null;
this.consensusReadsNum = 0;
this.debugData = debugData;
this.isConsensus = false;
this.numberOfTargets = numberOfTargets;
this.finalConsensus = finalConsensus;
this.tempId = -1;
this.defaultGroupsOverride = false;
}
public ParsedRead toParsedRead() {
if (!isConsensus || (sequences == null) || (barcodes == null))
throw exitWithError("toParsedRead() called for null consensus!");
SequenceRead originalRead;
SingleRead[] reads = new SingleRead[numberOfTargets];
ArrayList<MatchedGroupEdge> matchedGroupEdges = new ArrayList<>();
for (byte targetId = 1; targetId <= numberOfTargets; targetId++) {
SequenceWithAttributes currentSequence = sequences.get(targetId);
reads[targetId - 1] = new SingleReadImpl(currentSequence.getOriginalReadId(),
currentSequence.toNSequenceWithQuality(), "Consensus");
addReadGroupEdges(matchedGroupEdges, targetId, currentSequence.toNSequenceWithQuality());
}
for (Barcode barcode : barcodes) {
NSequenceWithQuality targetSequence = (barcode.targetId == -1) ? barcode.value.toNSequenceWithQuality()
: sequences.get(barcode.targetId).toNSequenceWithQuality();
addGroupEdges(matchedGroupEdges, barcode.targetId, barcode.groupName, targetSequence,
barcode.value.toNSequenceWithQuality());
}
if (numberOfTargets == 1)
originalRead = reads[0];
else if (numberOfTargets == 2)
originalRead = new PairedRead(reads);
else
originalRead = new MultiRead(reads);
Match bestMatch = new Match(numberOfTargets, 0, matchedGroupEdges);
return new ParsedRead(originalRead, false, defaultGroupsOverride ? numberOfTargets : -1,
bestMatch, consensusReadsNum);
}
/** Used only with --consensuses-to-separate-groups flag */
public List<ParsedRead> getReadsWithConsensuses() {
if (!isConsensus || (sequences == null) || (barcodes == null))
throw exitWithError("getReadsWithConsensuses() called for null consensus!");
List<ParsedRead> generatedReads = new ArrayList<>();
for (DataFromParsedReadWithAllGroups currentOriginalData : savedOriginalSequences) {
ArrayList<MatchedGroupEdge> matchedGroupEdges = new ArrayList<>();
SingleRead[] reads = new SingleRead[numberOfTargets];
for (byte targetId = 1; targetId <= numberOfTargets; targetId++) {
SequenceWithAttributes currentOriginalSequence = currentOriginalData.getSequences().get(targetId);
SequenceWithAttributes currentConsensusSequence = sequences.get(targetId);
reads[targetId - 1] = new SingleReadImpl(currentOriginalSequence.getOriginalReadId(),
currentOriginalSequence.toNSequenceWithQuality(), "");
addReadGroupEdges(matchedGroupEdges, targetId,
currentOriginalSequence.toNSequenceWithQuality());
addGroupEdges(matchedGroupEdges, targetId, "CR" + targetId,
currentOriginalSequence.toNSequenceWithQuality(),
currentConsensusSequence.toNSequenceWithQuality());
for (HashMap.Entry<String, SequenceWithAttributes> entry
: currentOriginalData.getOtherGroups().entrySet())
addGroupEdges(matchedGroupEdges, targetId, entry.getKey(),
currentOriginalSequence.toNSequenceWithQuality(),
entry.getValue().toNSequenceWithQuality());
}
for (Barcode barcode : barcodes) {
NSequenceWithQuality targetSequence = (barcode.targetId == -1) ? barcode.value.toNSequenceWithQuality()
: currentOriginalData.getSequences().get(barcode.targetId).toNSequenceWithQuality();
addGroupEdges(matchedGroupEdges, barcode.targetId, barcode.groupName, targetSequence,
barcode.value.toNSequenceWithQuality());
}
SequenceRead originalRead;
if (numberOfTargets == 1)
originalRead = reads[0];
else if (numberOfTargets == 2)
originalRead = new PairedRead(reads);
else
originalRead = new MultiRead(reads);
Match bestMatch = new Match(numberOfTargets, 0, matchedGroupEdges);
generatedReads.add(new ParsedRead(originalRead, false,
defaultGroupsOverride ? numberOfTargets : -1, bestMatch, consensusReadsNum));
}
return generatedReads;
}
private void addReadGroupEdges(ArrayList<MatchedGroupEdge> matchedGroupEdges, byte targetId,
NSequenceWithQuality seq) {
matchedGroupEdges.add(new MatchedGroupEdge(seq, targetId,
new GroupEdge("R" + targetId, true), 0));
matchedGroupEdges.add(new MatchedGroupEdge(null, targetId,
new GroupEdge("R" + targetId, false), seq.size()));
}
private void addGroupEdges(ArrayList<MatchedGroupEdge> matchedGroupEdges, byte targetId, String groupName,
NSequenceWithQuality target, NSequenceWithQuality value) {
matchedGroupEdges.add(new MatchedGroupEdge(target, targetId, new GroupEdge(groupName, true), value));
matchedGroupEdges.add(new MatchedGroupEdge(null, targetId,
new GroupEdge(groupName, false), null));
}
}
| 51.748538 | 119 | 0.682902 |
79e693e3693536936371891d0de9039ac3c49db6 | 1,163 | import java.util.Calendar;
import java.util.GregorianCalendar;
public class Person {
private String name;
private double height;
private int birthYear;
// Constructor Method
public Person (String name, int birthYear, double height) {
this.name = name;
this.height = height;
this.birthYear = birthYear;
}
//GET's Methods
public String getName() {
return this.name;
}
public int getBirthYear() {
return this.birthYear;
}
public double getHeight() {
return this.height;
}
//SET's Methods
public void setName(String name) {
this.name = name;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
public void setHeight(double height) {
this.height = height;
}
//Age Calculator
public int calcAge() {
Calendar cal = GregorianCalendar.getInstance();
return (cal.get(Calendar.YEAR) - this.birthYear);
}
public void introduceAttributes() {
System.out.printf("%nNome: %s%n", this.name);
System.out.printf("Altura: %.2fm %n", this.height);
System.out.println("Ano de nascimento: " + this.birthYear);
System.out.println("Idade: " + calcAge() + " anos");
}
} | 21.537037 | 61 | 0.676698 |
6c938dc436d04fb6dddf8193278a249d6045bd86 | 1,023 | /**
* iBizSys 5.0 用户自定义代码
* http://www.ibizsys.net
*/
package net.ibizsys.psrt.srv.common.demodel.service.uiaction;
import java.util.List;
import java.util.HashMap;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import net.ibizsys.paas.core.IDELogicActionContext;
import net.ibizsys.paas.core.DELogic;
import net.ibizsys.paas.entity.IEntity;
import net.ibizsys.paas.entity.SimpleEntity;
import net.ibizsys.paas.web.WebContext;
import net.ibizsys.paas.service.ServiceGlobal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 实体界面行为 StopService
*/
public class ServiceStopServiceUIActionModel extends ServiceStopServiceUIActionModelBase {
private static final Log log = LogFactory.getLog(ServiceStopServiceUIActionModel.class);
public ServiceStopServiceUIActionModel() {
super();
}
} | 26.230769 | 92 | 0.797654 |
8798d71f29de26a4b78305ae3267203012f3efb3 | 32,359 | /*
* Copyright (c) 2016-2018 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.authentication.impl.evaluator;
import java.util.Collection;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import com.evolveum.midpoint.authentication.impl.util.AuthSequenceUtil;
import com.evolveum.midpoint.model.api.ModelAuditRecorder;
import com.evolveum.midpoint.model.api.context.PreAuthenticationContext;
import com.evolveum.midpoint.security.api.Authorization;
import com.evolveum.midpoint.security.api.ConnectionEnvironment;
import com.evolveum.midpoint.security.api.MidPointPrincipal;
import com.evolveum.midpoint.security.api.SecurityUtil;
import com.evolveum.midpoint.model.api.util.AuthenticationEvaluatorUtil;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.equivalence.ParameterizedEquivalenceStrategy;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.authentication.api.config.AuthenticationEvaluator;
import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipalManager;
import com.evolveum.midpoint.model.api.context.AbstractAuthenticationContext;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
/**
* @author semancik
*
*/
public abstract class AuthenticationEvaluatorImpl<C extends AbstractCredentialType, T extends AbstractAuthenticationContext>
implements AuthenticationEvaluator<T>, MessageSourceAware {
private static final Trace LOGGER = TraceManager.getTrace(AuthenticationEvaluatorImpl.class);
@Autowired private Protector protector;
@Autowired private Clock clock;
@Autowired private ModelAuditRecorder securityHelper;
private GuiProfiledPrincipalManager focusProfileService;
protected MessageSourceAccessor messages;
@Autowired
public void setPrincipalManager(GuiProfiledPrincipalManager focusProfileService) {
this.focusProfileService = focusProfileService;
}
@Override
public void setMessageSource(@NotNull MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
protected abstract void checkEnteredCredentials(ConnectionEnvironment connEnv, T authCtx);
protected abstract boolean supportsAuthzCheck();
protected abstract C getCredential(CredentialsType credentials);
protected abstract void validateCredentialNotNull(
ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credential);
protected abstract boolean passwordMatches(ConnectionEnvironment connEnv,
@NotNull MidPointPrincipal principal, C passwordType, T authCtx);
protected abstract CredentialPolicyType getEffectiveCredentialPolicy(SecurityPolicyType securityPolicy, T authnCtx) throws SchemaException;
protected abstract boolean supportsActivation();
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(),
authnCtx.getPrincipalType(), authnCtx.isSupportActivationByChannel());
FocusType focusType = principal.getFocus();
CredentialsType credentials = focusType.getCredentials();
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
if (checkCredentials(principal, authnCtx, connEnv)) {
if(!AuthenticationEvaluatorUtil.checkRequiredAssignment(focusType.getAssignment(), authnCtx.getRequireAssignments())){
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "not contains required assignment", authnCtx.getPrincipalType(), false);
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "not contains required assignment", false);
throw new InternalAuthenticationServiceException("web.security.flexAuth.invalid.required.assignment");
}
} else {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "password mismatch", authnCtx.getPrincipalType(), false);
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch", false);
throw new BadCredentialsException("web.security.provider.invalid.credentials");
}
checkAuthorizations(principal, connEnv, authnCtx);
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, null, authnCtx.getPrincipalType(), true);
recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), false);
return new UsernamePasswordAuthenticationToken(principal, authnCtx.getEnteredCredential(), principal.getAuthorities());
}
@Override
@NotNull
public FocusType checkCredentials(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), authnCtx.getPrincipalType(), false);
FocusType focusType = principal.getFocus();
CredentialsType credentials = focusType.getCredentials();
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
if (!checkCredentials(principal, authnCtx, connEnv)) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "password mismatch", authnCtx.getPrincipalType(), false);
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch", false);
throw new BadCredentialsException("web.security.provider.invalid.credentials");
}
checkAuthorizations(principal, connEnv, authnCtx);
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "password mismatch", authnCtx.getPrincipalType(), true);
recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), false);
return focusType;
}
private void checkAuthorizations(MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv, AbstractAuthenticationContext authnCtx) {
if (supportsAuthzCheck()) {
// Authorizations
if (hasNoneAuthorization(principal)) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "no authorizations", authnCtx.getPrincipalType(),false);
throw new DisabledException("web.security.provider.access.denied");
}
}
}
private boolean checkCredentials(MidPointPrincipal principal, T authnCtx, ConnectionEnvironment connEnv) {
FocusType focusType = principal.getFocus();
CredentialsType credentials = focusType.getCredentials();
if (credentials == null || getCredential(credentials) == null) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "no credentials in user", authnCtx.getPrincipalType(), false);
throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid.credentials");
}
CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);
// Lockout
if (isLockedOut(getCredential(credentials), credentialsPolicy)) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "password locked-out", authnCtx.getPrincipalType(), false);
throw new LockedException("web.security.provider.locked");
}
// Password age
checkPasswordValidityAndAge(connEnv, principal, getCredential(credentials), credentialsPolicy);
return passwordMatches(connEnv, principal, getCredential(credentials), authnCtx);
}
private CredentialPolicyType getCredentialsPolicy(MidPointPrincipal principal, T authnCtx){
SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
CredentialPolicyType credentialsPolicy;
try {
credentialsPolicy = getEffectiveCredentialPolicy(securityPolicy, authnCtx);
} catch (SchemaException e) {
// TODO how to properly hanlde the error????
throw new AuthenticationServiceException("Bad config");
}
return credentialsPolicy;
}
/**
* Special-purpose method used for Web Service authentication based on javax.security callbacks.
*
* In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the
* AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work.
*/
public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String username)
throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, username, FocusType.class, true);
FocusType focusType = principal.getFocus();
CredentialsType credentials = focusType.getCredentials();
if (credentials == null) {
recordAuthenticationBehavior(username, null, connEnv, "no credentials in user", FocusType.class, false);
throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid.credentials");
}
PasswordType passwordType = credentials.getPassword();
SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
PasswordCredentialsPolicyType passwordCredentialsPolicy = SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy);
// Lockout
if (isLockedOut(passwordType, passwordCredentialsPolicy)) {
recordAuthenticationBehavior(username, null, connEnv, "password locked-out", FocusType.class,false);
throw new LockedException("web.security.provider.locked");
}
// Password age
checkPasswordValidityAndAge(connEnv, principal, passwordType.getValue(), passwordType.getMetadata(), passwordCredentialsPolicy);
String password = getPassword(connEnv, principal, passwordType.getValue());
// Authorizations
if (hasNoneAuthorization(principal)) {
recordAuthenticationBehavior(username, null, connEnv, "no authorizations", FocusType.class,false);
throw new InternalAuthenticationServiceException("web.security.provider.access.denied");
}
return password;
}
@Override
public PreAuthenticatedAuthenticationToken authenticateUserPreAuthenticated(ConnectionEnvironment connEnv, PreAuthenticationContext authnCtx) {
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(),
authnCtx.getPrincipalType(), authnCtx.isSupportActivationByChannel());
// Authorizations
if (hasNoneAuthorization(principal)) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "no authorizations", authnCtx.getPrincipalType(), false);
throw new InternalAuthenticationServiceException("web.security.provider.access.denied");
}
if(AuthenticationEvaluatorUtil.checkRequiredAssignment(principal.getFocus().getAssignment(), authnCtx.getRequireAssignments())){
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, null, principal.getAuthorities());
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, null, authnCtx.getPrincipalType(), true);
return token;
} else {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "not contains required assignment", authnCtx.getPrincipalType(), false);
throw new InternalAuthenticationServiceException("web.security.flexAuth.invalid.required.assignment");
}
}
@NotNull
protected MidPointPrincipal getAndCheckPrincipal(ConnectionEnvironment connEnv, String enteredUsername, Class<? extends FocusType> clazz,
boolean supportsActivationCheck) {
if (StringUtils.isBlank(enteredUsername)) {
recordAuthenticationFailure(enteredUsername, connEnv, "no username");
throw new UsernameNotFoundException("web.security.provider.invalid.credentials");
}
MidPointPrincipal principal;
try {
principal = focusProfileService.getPrincipal(enteredUsername, clazz);
} catch (ObjectNotFoundException e) {
recordAuthenticationFailure(enteredUsername, connEnv, "no focus");
throw new UsernameNotFoundException("web.security.provider.invalid.credentials");
} catch (SchemaException e) {
recordAuthenticationFailure(enteredUsername, connEnv, "schema error");
throw new InternalAuthenticationServiceException("web.security.provider.invalid");
} catch (CommunicationException e) {
recordAuthenticationFailure(enteredUsername, connEnv, "communication error");
throw new InternalAuthenticationServiceException("web.security.provider.invalid");
} catch (ConfigurationException e) {
recordAuthenticationFailure(enteredUsername, connEnv, "configuration error");
throw new InternalAuthenticationServiceException("web.security.provider.invalid");
} catch (SecurityViolationException e) {
recordAuthenticationFailure(enteredUsername, connEnv, "security violation");
throw new InternalAuthenticationServiceException("web.security.provider.invalid");
} catch (ExpressionEvaluationException e) {
recordAuthenticationFailure(enteredUsername, connEnv, "expression error");
throw new InternalAuthenticationServiceException("web.security.provider.invalid");
}
if (principal == null) {
recordAuthenticationBehavior(enteredUsername, null, connEnv, "no focus", clazz, false);
throw new UsernameNotFoundException("web.security.provider.invalid.credentials");
}
if (supportsActivationCheck && !principal.isEnabled()) {
recordAuthenticationBehavior(enteredUsername, principal, connEnv, "focus disabled", clazz, false);
throw new DisabledException("web.security.provider.disabled");
}
return principal;
}
protected boolean hasNoneAuthorization(MidPointPrincipal principal) {
Collection<Authorization> authorizations = principal.getAuthorities();
if (authorizations == null || authorizations.isEmpty()){
return true;
}
boolean exist = false;
for (Authorization auth : authorizations){
if (auth.getAction() != null && !auth.getAction().isEmpty()){
exist = true;
}
}
return !exist;
}
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credentials,
P passwordCredentialsPolicy) {
if (credentials == null) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "no stored credential value", principal.getFocus().getClass(), false);
throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad");
}
validateCredentialNotNull(connEnv, principal, credentials);
if (passwordCredentialsPolicy == null) {
return;
}
Duration maxAge = passwordCredentialsPolicy.getMaxAge();
if (maxAge != null) {
MetadataType credentialMetedata = credentials.getMetadata();
XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata);
if (changeTimestamp != null) {
XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
if (clock.isPast(passwordValidUntil)) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "password expired", principal.getFocus().getClass(), false);
throw new CredentialsExpiredException("web.security.provider.credential.expired");
}
}
}
}
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata,
CredentialPolicyType passwordCredentialsPolicy) {
if (protectedString == null) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "no stored password value", principal.getFocus().getClass(), false);
throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
}
if (passwordCredentialsPolicy == null) {
return;
}
Duration maxAge = passwordCredentialsPolicy.getMaxAge();
if (maxAge != null) {
XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata);
if (changeTimestamp != null) {
XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
if (clock.isPast(passwordValidUntil)) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "password expired", principal.getFocus().getClass(), false);
throw new CredentialsExpiredException("web.security.provider.credential.expired");
}
}
}
}
// protected boolean matchDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, String decryptedValue,
// String enteredPassword){
// return enteredPassword.equals(decryptedValue);
// }
//
protected boolean decryptAndMatch(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString,
String enteredPassword) {
ProtectedStringType entered = new ProtectedStringType();
entered.setClearValue(enteredPassword);
try {
return protector.compareCleartext(entered, protectedString);
} catch (SchemaException | EncryptionException e) {
// This is a serious error. It is not business as usual (e.g. wrong password or missing authorization).
// This is either bug or serious misconfiguration (e.g. missing decryption key in keystore).
// We do not want to just audit the failure. That would just log it on debug level.
// But that would be too hard for system administrator to figure out what is going on - especially
// if the administrator himself cannot log in. Therefore explicitly log those errors here.
LOGGER.error("Error dealing with credentials of user \"{}\" credentials: {}", principal.getUsername(), e.getMessage());
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "error decrypting password: "+e.getMessage(), principal.getFocus().getClass(), false);
throw new AuthenticationServiceException("web.security.provider.unavailable", e);
}
}
protected String getDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString) {
String decryptedPassword;
if (protectedString.getEncryptedDataType() != null) {
try {
decryptedPassword = protector.decryptString(protectedString);
} catch (EncryptionException e) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "error decrypting password: "+e.getMessage(), principal.getFocus().getClass(), false);
throw new AuthenticationServiceException("web.security.provider.unavailable", e);
}
} else {
LOGGER.warn("Authenticating user based on clear value. Please check objects, "
+ "this should not happen. Protected string should be encrypted.");
decryptedPassword = protectedString.getClearValue();
}
return decryptedPassword;
}
private String getPassword(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString) {
String decryptedPassword;
if (protectedString.getEncryptedDataType() != null) {
try {
decryptedPassword = protector.decryptString(protectedString);
} catch (EncryptionException e) {
recordAuthenticationBehavior(principal.getUsername(), principal, connEnv, "error decrypting password: "+e.getMessage(), principal.getFocus().getClass(), false);
throw new AuthenticationServiceException("web.security.provider.unavailable", e);
}
} else {
LOGGER.warn("Authenticating user based on clear value. Please check objects, "
+ "this should not happen. Protected string should be encrypted.");
decryptedPassword = protectedString.getClearValue();
}
return decryptedPassword;
}
private boolean isLockedOut(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) {
return isOverFailedLockoutAttempts(credentialsType, credentialsPolicy) && !isLockoutExpired(credentialsType, credentialsPolicy);
}
private boolean isOverFailedLockoutAttempts(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) {
int failedLogins = credentialsType.getFailedLogins() != null ? credentialsType.getFailedLogins() : 0;
return isOverFailedLockoutAttempts(failedLogins, credentialsPolicy);
}
private boolean isOverFailedLockoutAttempts(int failedLogins, CredentialPolicyType credentialsPolicy) {
return credentialsPolicy != null && credentialsPolicy.getLockoutMaxFailedAttempts() != null &&
credentialsPolicy.getLockoutMaxFailedAttempts() > 0 && failedLogins >= credentialsPolicy.getLockoutMaxFailedAttempts();
}
private boolean isLockoutExpired(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) {
Duration lockoutDuration = credentialsPolicy.getLockoutDuration();
if (lockoutDuration == null) {
return false;
}
LoginEventType lastFailedLogin = credentialsType.getLastFailedLogin();
if (lastFailedLogin == null) {
return true;
}
XMLGregorianCalendar lastFailedLoginTimestamp = lastFailedLogin.getTimestamp();
if (lastFailedLoginTimestamp == null) {
return true;
}
XMLGregorianCalendar lockedUntilTimestamp = XmlTypeConverter.addDuration(lastFailedLoginTimestamp, lockoutDuration);
return clock.isPast(lockedUntilTimestamp);
}
protected void recordPasswordAuthenticationSuccess(@NotNull MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv,
@NotNull AuthenticationBehavioralDataType behavioralData, boolean audit) {
FocusType focusBefore = principal.getFocus().clone();
Integer failedLogins = behavioralData.getFailedLogins();
boolean successLoginAfterFail = false;
if (failedLogins != null && failedLogins > 0) {
behavioralData.setFailedLogins(0);
successLoginAfterFail = true;
}
LoginEventType event = new LoginEventType();
event.setTimestamp(clock.currentTimeXMLGregorianCalendar());
event.setFrom(connEnv.getRemoteHostAddress());
behavioralData.setPreviousSuccessfulLogin(behavioralData.getLastSuccessfulLogin());
behavioralData.setLastSuccessfulLogin(event);
ActivationType activation = principal.getFocus().getActivation();
if (activation != null) {
if (LockoutStatusType.LOCKED.equals(activation.getLockoutStatus())) {
successLoginAfterFail = true;
}
activation.setLockoutStatus(LockoutStatusType.NORMAL);
activation.setLockoutExpirationTimestamp(null);
}
if (AuthSequenceUtil.isAllowUpdatingAuthBehavior(successLoginAfterFail)) {
focusProfileService.updateFocus(principal, computeModifications(focusBefore, principal.getFocus()));
}
if (audit) {
recordAuthenticationSuccess(principal, connEnv);
}
}
private void recordAuthenticationSuccess(@NotNull MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv) {
securityHelper.auditLoginSuccess(principal.getFocus(), connEnv);
}
public void recordAuthenticationBehavior(String username, MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv,
String reason, Class<? extends FocusType> focusType, boolean isSuccess) {
if (principal == null && focusType != null) {
try {
principal = focusProfileService.getPrincipal(username, focusType);
} catch (Exception e) {
//ignore if non-exist
}
}
if (principal != null) {
AuthenticationBehavioralDataType behavior = AuthenticationEvaluatorUtil.getBehavior(principal.getFocus());
if (isSuccess) {
recordPasswordAuthenticationSuccess(principal, connEnv, behavior, true);
} else {
recordPasswordAuthenticationFailure(principal, connEnv, behavior, null, reason, true);
}
} else {
recordAuthenticationFailure(username, connEnv, reason);
}
}
protected void recordPasswordAuthenticationFailure(@NotNull MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv,
@NotNull AuthenticationBehavioralDataType behavioralData, CredentialPolicyType credentialsPolicy, String reason, boolean audit) {
FocusType focusBefore = principal.getFocus().clone();
Integer failedLogins = behavioralData.getFailedLogins();
LoginEventType lastFailedLogin = behavioralData.getLastFailedLogin();
XMLGregorianCalendar lastFailedLoginTs = null;
if (lastFailedLogin != null) {
lastFailedLoginTs = lastFailedLogin.getTimestamp();
}
if (credentialsPolicy != null) {
Duration lockoutFailedAttemptsDuration = credentialsPolicy.getLockoutFailedAttemptsDuration();
if (lockoutFailedAttemptsDuration != null) {
if (lastFailedLoginTs != null) {
XMLGregorianCalendar failedLoginsExpirationTs = XmlTypeConverter.addDuration(lastFailedLoginTs, lockoutFailedAttemptsDuration);
if (clock.isPast(failedLoginsExpirationTs)) {
failedLogins = 0;
}
}
}
}
if (failedLogins == null) {
failedLogins = 1;
} else {
failedLogins++;
}
behavioralData.setFailedLogins(failedLogins);
LoginEventType event = new LoginEventType();
event.setTimestamp(clock.currentTimeXMLGregorianCalendar());
event.setFrom(connEnv.getRemoteHostAddress());
behavioralData.setLastFailedLogin(event);
ActivationType activationType = principal.getFocus().getActivation();
if (isOverFailedLockoutAttempts(failedLogins, credentialsPolicy)) {
if (activationType == null) {
activationType = new ActivationType();
principal.getFocus().setActivation(activationType);
}
activationType.setLockoutStatus(LockoutStatusType.LOCKED);
XMLGregorianCalendar lockoutExpirationTs = null;
Duration lockoutDuration = credentialsPolicy.getLockoutDuration();
if (lockoutDuration != null) {
lockoutExpirationTs = XmlTypeConverter.addDuration(event.getTimestamp(), lockoutDuration);
}
activationType.setLockoutExpirationTimestamp(lockoutExpirationTs);
}
if (AuthSequenceUtil.isAllowUpdatingAuthBehavior(true)) {
focusProfileService.updateFocus(principal, computeModifications(focusBefore, principal.getFocus()));
}
if (audit) {
recordAuthenticationFailure(principal, connEnv, reason);
}
}
protected void recordAuthenticationFailure(@NotNull MidPointPrincipal principal, ConnectionEnvironment connEnv, String reason) {
securityHelper.auditLoginFailure(principal.getUsername(), principal.getFocus(), connEnv, reason);
}
protected void recordAuthenticationFailure(String username, ConnectionEnvironment connEnv, String reason) {
securityHelper.auditLoginFailure(username, null, connEnv, reason);
}
private Collection<? extends ItemDelta<?, ?>> computeModifications(@NotNull FocusType before, @NotNull FocusType after) {
ObjectDelta<? extends FocusType> delta = ((PrismObject<FocusType>)before.asPrismObject())
.diff((PrismObject<FocusType>) after.asPrismObject(), ParameterizedEquivalenceStrategy.DATA);
assert delta.isModify();
return delta.getModifications();
}
}
| 54.20268 | 181 | 0.726784 |
74d023cf96f3bff80fb9b600a9454905e280900c | 1,807 | package net.ibizsys.paas.sysmodel;
import net.ibizsys.paas.codelist.ICodeList;
/**
* 全局字典代码表模型对象
* @author Administrator
*
*/
public class GlobalScopeDictCatCodeListModel extends DynamicCodeListModelBase
{
/**
* 词条类别
*/
private String strCat = "";
/**
* 所有者类型
*/
private String strOwnerType = "";
/**
* 所有者标识
*/
private String strOwnerId = "";
/**
* 获取分类
* @return the strCat
*/
public String getCat()
{
return strCat;
}
/**
* 设置分类
* @param strCat the strCat to set
*/
public void setCat(String strCat)
{
this.strCat = strCat;
}
/**
* 获取所有者类型
* @return the strOwnerType
*/
public String getOwnerType()
{
return strOwnerType;
}
/**
* 设置所有者类型
* @param strOwnerType the strOwnerType to set
*/
public void setOwnerType(String strOwnerType)
{
this.strOwnerType = strOwnerType;
}
/**
* 获取所有者标识
* @return the strOwnerId
*/
public String getOwnerId()
{
return strOwnerId;
}
/**
* 设置所有者标识
* @param strOwnerId the strOwnerId to set
*/
public void setOwnerId(String strOwnerId)
{
this.strOwnerId = strOwnerId;
}
/**
* 设置标识
* @param strId
*/
public void setId(String strId)
{
this.strId = strId;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.sysmodel.CodeListModelBase#getId()
*/
@Override
public String getId()
{
return this.strId;
}
/**
* 获取名称
* @param strName
*/
public void setName(String strName)
{
this.strName = strName;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.sysmodel.CodeListModelBase#getName()
*/
@Override
public String getName()
{
return this.strName;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.sysmodel.CodeListModelBase#getCodeListType()
*/
@Override
public String getCodeListType()
{
return ICodeList.CLTYPE_DYNAMIC;
}
}
| 13.9 | 77 | 0.645822 |
84b000288515131c14c244522e0fc3fcd692ff3d | 1,706 | package com.thamirestissot.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@Service
public class FilesStoreService {
private static final Logger LOGGER = LoggerFactory.getLogger(FilesStoreService.class);
private List<String> filesDone = new ArrayList<>();
@Autowired
private HandlerFile handlerFile;
public void store(Path path) {
filesDone.add(path.getFileName().toString());
}
public boolean isNewFile(Path path) {
return !filesDone.contains(path.getFileName().toString());
}
public boolean checkExistDirectories() {
Path pathIn = Paths.get(handlerFile.getDirectoryIn());
Path pathOut = Paths.get(handlerFile.getDirectoryOut());
if (Files.notExists(pathIn) || Files.notExists(pathOut)) {
LOGGER.debug("Both in/out directories must exists!");
return false;
}
return true;
}
public boolean createdDirectoriesSuccessfully() {
Path pathIn = Paths.get(handlerFile.getDirectoryIn());
Path pathOut = Paths.get(handlerFile.getDirectoryOut());
try {
if (Files.notExists(pathIn))
Files.createDirectory(pathIn);
if (Files.notExists(pathOut))
Files.createDirectory(pathOut);
} catch (IOException e) {
LOGGER.error("Error on create directory.", e);
}
return true;
}
} | 27.516129 | 90 | 0.669402 |
e5499aa5f1a7673c4cc8c8a22e1d3a4520ca0dda | 2,508 | /*
* Copyright 2022, TeamDev. 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
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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
* OWNER 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 io.spine.server.storage.datastore.record;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Message;
import java.util.function.Function;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.protobuf.Messages.isDefault;
import static io.spine.server.entity.FieldMasks.applyMask;
/**
* Applies the provided mask to Protobuf messages.
*/
public final class FieldMaskApplier {
private final FieldMask fieldMask;
private FieldMaskApplier(FieldMask fieldMask) {
this.fieldMask = fieldMask;
}
/**
* Creates a {@code Function} which applies the provided {@link FieldMask fieldMask}
* to the Protobuf messages stored in Datastore as records.
*/
public static <R extends Message> Function<R, R> recordMasker(FieldMask fieldMask) {
checkNotNull(fieldMask);
return new FieldMaskApplier(fieldMask)::mask;
}
private <R extends Message> R mask(R record) {
checkNotNull(record);
if (!isDefault(fieldMask)) {
return recordMasker(record);
}
return record;
}
private <R extends Message> R recordMasker(R record) {
var result = applyMask(fieldMask, record);
return result;
}
}
| 35.323944 | 88 | 0.726874 |
4016d528de50c7ae61d8394f7175a6c6d226dc08 | 654 | package test.com.b50.migrations.generators;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.b50.migrations.generators.MigrationClassGenerator;
public class MigrationClassGeneratorTest {
@Test
public void testGeneration() throws Exception {
MigrationClassGenerator generator = new MigrationClassGenerator("templates", "Migration.java.ftl");
String content = generator.generate("my.package", 1);
assertNotNull(content);
assertTrue(content.contains("package my.package;"));
assertTrue(content.contains("public class DBVersion1 extends AbstractMigration {"));
}
}
| 29.727273 | 101 | 0.795107 |
bb3fe213149dbbaeea52fbce79b76f3f5453de26 | 607 | package slidingwindows;
import java.util.*;
//https://leetcode.com/problems/longest-substring-without-repeating-characters/
public class NoRepeatSubstring {
public int lengthOfLongestSubstring(String str) {
HashMap<Character, Integer> map= new HashMap<>();
int n= str.length();
int max=0;
int j=0;
for (int i = 0; i <n ; i++) {
char c=str.charAt(i);
if(map.containsKey(c)){
j= Math.max(j, map.get(c)+1);
}
map.put(c,i);
max=Integer.max(max,i+1-j);
}
return max;
}
}
| 28.904762 | 79 | 0.540362 |
3545c8231db39c7636f609814c6df471a30b7950 | 2,984 | package net.ericsson.emovs.utilities.errors;
import static java.lang.String.format;
import static java.util.Locale.ENGLISH;
public enum ResponseCode {
OK(200, "OK", null),
DEVICE_LIMIT_EXCEEDED(400, "DEVICE_LIMIT_EXCEEDED", "The account is not allowed to register more devices"),
SESSION_LIMIT_EXCEEDED(400, "SESSION_LIMIT_EXCEEDED", "The account has maximum allowed sessions"),
UNKNOWN_DEVICE_ID(400, "UNKNOWN_DEVICE_ID", "Device body is missing or the device ID is not found"),
INVALID_JSON(400, "INVALID_JSON", "JSON received is not valid JSON"),
INCORRECT_CREDENTIALS(401, "INCORRECT_CREDENTIALS", "Underlying CRM does not accept the given credentials"),
UNKNOWN_BUSINESS_UNIT(404, "UNKNOWN_BUSINESS_UNIT", "The business unit can not be found"),
NO_SESSION_TOKEN(401, "NO_SESSION_TOKEN", "Session token is missing"),
INVALID_SESSION_TOKEN(401, "INVALID_SESSION_TOKEN", "Session token was provided but not valid"),
UNKNOWN_ASSET(404, "UNKNOWN_ASSET", "The asset was not found"),
NOT_ENTITLED(403, "NOT_ENTITLED", "User is not entitled to play this asset"),
DEVICE_BLOCKED(403, "DEVICE_BLOCKED", "The user device is not allowed to play the asset"),
GEO_BLOCKED(403, "GEO_BLOCKED", "The user is in a country that is not allowed to play the asset"),
LICENSE_EXPIRED(403, "LICENSE_EXPIRED", "Asset exists but is expired"),
NOT_ENABLED(403, "NOT_ENABLED", "Media is registered but is not enabled for streaming"),
DOWNLOAD_TOTAL_LIMIT_REACHED(403, "DOWNLOAD_TOTAL_LIMIT_REACHED", "User has reached the total limit on downloaded assets across devices"),
DOWNLOAD_ASSET_LIMIT_REACHED(403, "DOWNLOAD_ASSET_LIMIT_REACHED", "This asset has been downloaded the maximum number of times by this user."),
ALREADY_DOWNLOADED(403, "ALREADY_DOWNLOADED", "Asset downloaded and may not be streamed."),
DOWNLOAD_BLOCKED(403, "DOWNLOAD_BLOCKED", "This user is not allowed to download this asset"),
CONCURRENT_STREAMS_LIMIT_REACHED(403, "CONCURRENT_STREAMS_LIMIT_REACHED",
"The maximum number of concurrent stream limit is reached"),
NOT_AVAILABLE_IN_FORMAT(403, "NOT_AVAILABLE_IN_FORMAT",
"The media is not available in a format that can be played on this device"),
FORBIDDEN(403, "FORBIDDEN", "Request forbidden"),
CONNECTION_REFUSED(403, "", ""),
UNKNOWN_ERROR(-1, "UNKNOWN ERROR", "Unkown error");
public final int HttpCode;
public final String Code;
public final String Description;
ResponseCode(int httpCode, String code, String description) {
this.HttpCode = httpCode;
this.Code = code;
this.Description = description;
}
public String toString() {
if (Description != null) {
return format(ENGLISH, "(%d) %s - %s", HttpCode, Code, Description);
}
else {
return format(ENGLISH, "(%d) %s", HttpCode, Code);
}
}
}
| 55.259259 | 146 | 0.706769 |
06168950aeba5b0c254152ae32a0e22b0feae473 | 15,948 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.swarm.config.runtime.model;
import org.jboss.dmr.ModelNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* Wrapper for a DMR address which might contain multiple variable parts.
* <p/>
* An address template can be defined using the following BNF:
* <pre>
* <address template> ::= "/" | <segment>
* <segment> ::= <tuple> | <segment>"/"<tuple>
* <tuple> ::= <variable> | <key>"="<value>
* <variable> ::= "{"<alpha>"}"
* <key> ::= <alpha>
* <value> ::= <variable> | <alpha> | "*"
* <alpha> ::= <upper> | <lower>
* <upper> ::= "A" | "B" | … | "Z"
* <lower> ::= "a" | "b" | … | "z"
* </pre>
* <p/>
* Here are some examples for address templates:
* <pre>
* AddressTemplate a1 = AddressTemplate.of("/");
* AddressTemplate a2 = AddressTemplate.of("{selected.profile}");
* AddressTemplate a3 = AddressTemplate.of("{selected.profile}/subsystem=mail");
* AddressTemplate a4 = AddressTemplate.of("{selected.profile}/subsystem=mail/mail-session=*");
* </pre>
* <p/>
* To resolve a fully qualified address from an address template use the {@link #resolve(StatementContext, String...)} method.
*
* @author Harald Pehl
*/
public class AddressTemplate implements Comparable<AddressTemplate> {
// ------------------------------------------------------ factory
public static AddressTemplate of(String template) {
return new AddressTemplate(template);
}
// ------------------------------------------------------ template methods
private static final String OPT = "opt:/";
private final String template;
private final LinkedList<Token> tokens;
private final boolean optional;
private AddressTemplate(String template) {
assert template != null : "template must not be null";
this.tokens = parse(template);
this.optional = template.startsWith(OPT);
this.template = join(optional, tokens);
}
public Integer tokenLength() {
return tokens.size();
}
private LinkedList<Token> parse(String template) {
LinkedList<Token> tokens = new LinkedList<Token>();
if (template.equals("/")) {
return tokens;
}
String normalized = template.startsWith(OPT) ? template.substring(5) : template;
StringTokenizer tok = new StringTokenizer(normalized, "/");
while (tok.hasMoreTokens()) {
String nextToken = tok.nextToken();
if (nextToken.contains("=")) {
String[] split = nextToken.split("=");
tokens.add(new Token(split[0], split[1]));
} else {
tokens.add(new Token(nextToken));
}
}
return tokens;
}
private String join(boolean optional, LinkedList<Token> tokens) {
StringBuilder builder = new StringBuilder("/");
if (optional) {
builder.append(OPT);
}
return joinTokens(builder, tokens, "/");
}
private String joinTokens(StringBuilder builder, LinkedList<Token> tokens, String c) {
int size = tokens.size();
if (size == 1) {
builder.append(tokens.getFirst().toString());
}
else if (size > 1) {
for (int i=0; i<size-1; i++) {
builder.append(tokens.get(i).toString());
builder.append(c);
}
builder.append(tokens.getLast().toString());
}
// if size == 0 there's nothing to append
return builder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AddressTemplate)) return false;
AddressTemplate that = (AddressTemplate) o;
return optional == that.optional && template.equals(that.template);
}
@Override
public int hashCode() {
int result = template.hashCode();
result = 31 * result + (optional ? 1 : 0);
return result;
}
@Override
public String toString() {
return getTemplate();
}
/**
* Appends the specified template to this template and returns a new template. If the specified template does
* not start with a slash, "/" is automatically appended.
*
* @param template the template to append (makes no difference whether it starts with "/" or not)
* @return a new template
*/
public AddressTemplate append(String template) {
String slashTemplate = template.startsWith("/") ? template : "/" + template;
return AddressTemplate.of(this.template + slashTemplate);
}
/**
* Works like {@link List#subList(int, int)} over the tokens of this template and throws the same exceptions.
*
* @param fromIndex low endpoint (inclusive) of the sub template
* @param toIndex high endpoint (exclusive) of the sub template
* @return a new address template containing the specified tokens.
* @throws IndexOutOfBoundsException for an illegal endpoint index value
* (<tt>fromIndex < 0 || toIndex > size ||
* fromIndex > toIndex</tt>)
*/
public AddressTemplate subTemplate(int fromIndex, int toIndex) {
LinkedList<Token> subTokens = new LinkedList<>();
subTokens.addAll(this.tokens.subList(fromIndex, toIndex));
return AddressTemplate.of(join(this.optional, subTokens));
}
public AddressTemplate lastSubTemplate() {
return subTemplate(tokenLength() - 1, tokenLength());
}
/**
* Replaces one or more wildcards with the specified values starting from left to right and returns a new
* address template.
* <p/>
* This method does <em>not</em> resolve the address template. The returned template is still unresolved.
*
* @param wildcard the first wildcard (mandatory)
* @param wildcards more wildcards (optional)
* @return a new (still unresolved) address template with the wildcards replaced by the specified values.
*/
public AddressTemplate replaceWildcards(String wildcard, String... wildcards) {
List<String> allWildcards = new ArrayList<>();
allWildcards.add(wildcard);
if (wildcards != null) {
allWildcards.addAll(Arrays.asList(wildcards));
}
LinkedList<Token> replacedTokens = new LinkedList<>();
Iterator<String> wi = allWildcards.iterator();
for (Token token : tokens) {
if (wi.hasNext() && token.hasKey() && "*".equals(token.getValue())) {
replacedTokens.add(new Token(token.getKey(), wi.next()));
} else {
replacedTokens.add(new Token(token.key, token.value));
}
}
return AddressTemplate.of(join(this.optional, replacedTokens));
}
/**
* Returns the resource type of the last segment for this address template
*
* @return the resource type
*/
public String getResourceType() {
if (!tokens.isEmpty() && tokens.getLast().hasKey()) {
return tokens.getLast().getKey();
}
return null;
}
public String getResourceName() {
if (!tokens.isEmpty() && tokens.getLast().hasKey()) {
return tokens.getLast().getValue();
}
return null;
}
public String getTemplate() {
return template;
}
public boolean isOptional() {
return optional;
}
// ------------------------------------------------------ resolve
public ResourceAddress resolve(String... wildcards) {
return resolve(new StatementContext() {
@Override
public String get(String key) {
return null;
}
@Override
public String[] getTuple(String key) {
return null;
}
@Override
public String resolve(String key) {
return null;
}
@Override
public String[] resolveTuple(String key) {
return null;
}
@Override
public LinkedList<String> collect(String key) {
return null;
}
@Override
public LinkedList<String[]> collectTuples(String key) {
return null;
}
}, wildcards);
}
/**
* Resolve this address template against the specified statement context.
*
* @param context the statement context
* @param wildcards An optional list of wildcards which are used to resolve any wildcards in this address template
* @return a full qualified resource address which might be empty, but which does not contain any tokens
*/
public ResourceAddress resolve(StatementContext context, String... wildcards) {
int wildcardCount = 0;
ModelNode model = new ModelNode();
Memory<String[]> tupleMemory = new Memory<>();
Memory<String> valueMemory = new Memory<>();
for (Token token : tokens) {
if (!token.hasKey()) {
// a single token or token expression
String tokenRef = token.getValue();
String[] resolvedValue;
if (tokenRef.startsWith("{")) {
tokenRef = tokenRef.substring(1, tokenRef.length() - 1);
if (!tupleMemory.contains(tokenRef)) {
tupleMemory.memorize(tokenRef, context.collectTuples(tokenRef));
}
resolvedValue = tupleMemory.next(tokenRef);
} else {
assert tokenRef.contains("=") : "Invalid token expression " + tokenRef;
resolvedValue = tokenRef.split("=");
}
if (resolvedValue == null) {
System.out.println("Suppress token expression '" + tokenRef + "'. It cannot be resolved");
} else {
model.add(resolvedValue[0], resolvedValue[1]);
}
} else {
// a value expression. key and value of the expression might be resolved
String keyRef = token.getKey();
String valueRef = token.getValue();
String resolvedKey;
String resolvedValue;
if (keyRef.startsWith("{")) {
keyRef = keyRef.substring(1, keyRef.length() - 1);
if (!valueMemory.contains(keyRef)) {
valueMemory.memorize(keyRef, context.collect(keyRef));
}
resolvedKey = valueMemory.next(keyRef);
} else {
resolvedKey = keyRef;
}
if (valueRef.startsWith("{")) {
valueRef = valueRef.substring(1, valueRef.length() - 1);
if (!valueMemory.contains(valueRef)) {
valueMemory.memorize(valueRef, context.collect(valueRef));
}
resolvedValue = valueMemory.next(valueRef);
} else {
resolvedValue = valueRef;
}
if (resolvedKey == null) resolvedKey = "_blank";
if (resolvedValue == null) resolvedValue = "_blank";
// wildcards
String addressValue = resolvedValue;
if ("*".equals(resolvedValue) && wildcards != null && wildcards.length > 0 && wildcardCount < wildcards.length) {
addressValue = wildcards[wildcardCount];
wildcardCount++;
}
model.add(resolvedKey, addressValue);
}
}
return new ResourceAddress(model);
}
// ------------------------------------------------------ inner classes
private static class Token {
String key;
String value;
Token(String key, String value) {
this.key = key;
this.value = value;
}
Token(String value) {
this.key = null;
this.value = value;
}
boolean hasKey() {
return key != null;
}
String getKey() {
return key;
}
String getValue() {
return value;
}
@Override
public String toString() {
return hasKey() ? key + "=" + value : value;
}
}
private static class StringTokenizer {
private final String delim;
private final String s;
private final int len;
private int pos;
private String next;
StringTokenizer(String s, String delim) {
this.s = s;
this.delim = delim;
len = s.length();
}
String nextToken() {
if (!hasMoreTokens()) {
throw new NoSuchElementException();
}
String result = next;
next = null;
return result;
}
boolean hasMoreTokens() {
if (next != null) {
return true;
}
// skip leading delimiters
while (pos < len && delim.indexOf(s.charAt(pos)) != -1) {
pos++;
}
if (pos >= len) {
return false;
}
int p0 = pos++;
while (pos < len && delim.indexOf(s.charAt(pos)) == -1) {
pos++;
}
next = s.substring(p0, pos++);
return true;
}
}
private static class Memory<T> {
Map<String, LinkedList<T>> values = new HashMap<>();
Map<String, Integer> indexes = new HashMap<>();
boolean contains(String key) {
return values.containsKey(key);
}
void memorize(String key, LinkedList<T> resolved) {
int startIdx = resolved.isEmpty() ? 0 : resolved.size() - 1;
values.put(key, resolved);
indexes.put(key, startIdx);
}
T next(String key) {
T result = null;
LinkedList<T> items = values.get(key);
Integer idx = indexes.get(key);
if (!items.isEmpty() && idx >= 0) {
result = items.get(idx);
indexes.put(key, --idx);
}
return result;
}
}
@Override
public int compareTo(AddressTemplate o) {
return o.tokenLength().compareTo(this.tokenLength());
}
}
| 33.504202 | 129 | 0.552922 |
ddc37eaa8fb5ab12355fd51ac7b14e3901ea7221 | 2,876 | package edu.first.util.list;
/**
* An ordered collection (also known as a <i>sequence</i>). The user of this
* interface has precise control over where in the list each element is
* inserted. The user can access elements by their integer index (position in
* the list), and search for elements in the list.
*
* @since May 17 13
* @author Joel Gallant
*/
public interface List extends Collection {
/**
* Adds every element in the order of their {@link Collection#iterator()} at
* the specified {@code index} of this list. The list will expand and shift
* other elements to the right.
*
* @param index placement in the list
* @param c collection with elements to add
*/
void addAll(int index, Collection c);
/**
* Returns the element currently at {@code index}.
*
* @param index placement in the list
* @return element at the index
*/
Object get(int index);
/**
* Replaces the element at the index to the new element.
*
* @param index placement in the list
* @param element new object to place in the list
* @return old element that was in the list
*/
Object set(int index, Object element);
/**
* Adds the element to the list at the index, and shifts the elements to the
* right so that this element is then at the {@code index}.
*
* @param index placement in the list
* @param element new object to place at the index
*/
void add(int index, Object element);
/**
* Removes the object at the index. Returns the object that was removed.
*
* @param index placement in the list
* @return object that was removed
*/
Object remove(int index);
/**
* Returns the first index of the specified element. If it is not contained,
* returns {@code -1}.
*
* Uses {@link Object#equals(java.lang.Object)} to test whether the object
* is there.
*
* @param o element that is contained
* @return index of the element in the list
*/
int indexOf(Object o);
/**
* Returns the index of the very last instance of this element in the list.
* If it is not contained, returns {@code -1}.
*
* Uses {@link Object#equals(java.lang.Object)} to test whether the object
* is there.
*
* @param o element that is contained
* @return index of the last instance of the element in the list
*/
int lastIndexOf(Object o);
/**
* Returns a list that contains the elements from the {@code fromIndex} to
* the {@code toIndex} in the order they are in this list.
*
* @param fromIndex index of first element
* @param toIndex index of the last element
* @return list with every element from {@code fromIndex} to {@code toIndex}
*/
List subList(int fromIndex, int toIndex);
}
| 31.26087 | 80 | 0.637691 |
d48e1f4bcc92981e59869094e4dff7a195d21ee5 | 4,670 | package email.kleck.demo.jsainsburyplc.module.parser;
import email.kleck.demo.jsainsburyplc.module.parser.internal.Node;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Utility class
*/
public final class ParserUtil {
/**
* Generate a stack from the provided pattern to identify a node
*
* @param pattern the pattern to transform into a stack
* @return the transformed stack
*/
public static Stack<String> generateStackFromPattern(String pattern) {
Stack<String> stack = new Stack<>();
if (pattern != null) {
List<String> nodeSelectors = Arrays.asList(pattern.split(" "));
Collections.reverse(nodeSelectors);
nodeSelectors.forEach(stack::push);
}
return stack;
}
/**
* Search a single node by attribute definition
*
* @param nodesToSearch the nodes to iterate through
* @param nodeSelector the expression to select the node
* @return the single node if matched
*/
public static Node searchSingleNodeByAttribute(List<Node> nodesToSearch, Stack<String> nodeSelector) {
Node retVal = null;
if(nodeSelector.isEmpty()) {
return null;
}
String[] selectors = nodeSelector.peek().split("=");
Pattern pattern = selectors.length == 3 ? Pattern.compile(selectors[2]) : null;
String nodeType = selectors[0];
int nodeIndex = -1;
if (nodeType.contains("[")) {
nodeIndex = Integer.parseInt(nodeType.substring(nodeType.indexOf('[') + 1, nodeType.indexOf(']')));
nodeType = nodeType.substring(0, nodeType.indexOf('['));
}
// simple counter of identified nodes
int foundNodes = -1;
for (Node node : nodesToSearch) {
Map<String, String> attributeMap = node.getAttributeMap();
if (node.getType().matches(nodeType) && (selectors.length == 1 || attributeMap.containsKey(selectors[1]))) {
// pre-check the index
if (nodeIndex > -1) {
foundNodes++;
if (foundNodes != nodeIndex) {
continue;
}
}
Matcher matcher = pattern != null ? pattern.matcher(attributeMap.get((selectors[1]))) : null;
if (matcher == null || matcher.find()) {
if (nodeSelector.size() == 1) {
retVal = node;
break;
} else {
// get into next sub-node
nodeSelector.pop();
}
}
}
if (node.getChildren() != null) {
// might be within the children
retVal = searchSingleNodeByAttribute(node.getChildren(), nodeSelector);
}
if (retVal != null) {
break;
}
}
return retVal;
}
/**
* Search nodes for a specific identifier
* This method uses a 3-way identification string which consists of the following pattern:
* <tag-regex>=<attribute>=<attribute-value-regex>
*
* @param found the found nodes
* @param nodesToSearch the nodes to iterate through
* @param nodeSelector the expression to select the nodes
*/
public static void searchNodesByAttribute(List<Node> found, List<Node> nodesToSearch, Stack<String> nodeSelector) {
String[] selectors = nodeSelector.peek().split("=");
Pattern pattern = selectors.length == 3 ? Pattern.compile(selectors[2]) : null;
boolean foundNode = false;
for (Node node : nodesToSearch) {
Map<String, String> attributeMap = node.getAttributeMap();
if (node.getType().matches(selectors[0]) && (selectors.length == 1 || attributeMap.containsKey(selectors[1]))) {
Matcher matcher = pattern != null ? pattern.matcher(attributeMap.get((selectors[1]))) : null;
if (matcher == null || matcher.find()) {
if (nodeSelector.size() == 1) {
found.add(node);
foundNode = true;
} else {
// get into next sub-node
nodeSelector.pop();
}
}
}
if (!foundNode && node.getChildren() != null) {
// might be within the children
searchNodesByAttribute(found, node.getChildren(), nodeSelector);
}
}
}
}
| 38.595041 | 124 | 0.54561 |
a069a8a6ce9e952ed74cd924118be36eddbffc77 | 5,722 | /*
* Copyright 2020 Guo Chaosheng
*
* 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.nopasserby.fastminimq;
import static org.nopasserby.fastminimq.MQConstants.MQCommand.COMMAND_DATA_RES_CONTENT_OFFSET;
import static org.nopasserby.fastminimq.MQConstants.MQCommand.COMMAND_DATA_RES_STATUS_SELF_LENGTH;
import static org.nopasserby.fastminimq.MQUtil.throwableToString;
import org.nopasserby.fastminimq.MQConstants.Status;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
public abstract class MQExecutor {
public static abstract class MQDispatch extends MQExecutor {
@Override
protected void execute(ChannelDelegate channel, ByteBuf commandWrapper) throws Exception {
int commandCode = commandWrapper.readInt();
long commandId = commandWrapper.readLong();
int commandDataLength = commandWrapper.readInt();
int remaining = commandWrapper.readableBytes();
if (commandDataLength != remaining) {
throw new IllegalArgumentException();
}
ByteBuf commandData = commandWrapper;
dispatch(channel, commandCode, commandId, commandData);
}
@Override
protected void exceptionCaught(ChannelDelegate channel, Throwable cause) throws Exception {
}
protected abstract void dispatch(ChannelDelegate channel, int commandCode, long commandId, ByteBuf commandData) throws Exception;
}
protected abstract void execute(ChannelDelegate channel, ByteBuf commandWrapper) throws Exception;
protected abstract void exceptionCaught(ChannelDelegate channel, Throwable cause) throws Exception;
ChannelHandler channelHandler(int maxFrameLength) {
return new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(maxFrameLength, 12, 4, 0, 0))
.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object wrapper) throws Exception {
execute(delegate(ctx.channel()), (ByteBuf) wrapper);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
MQExecutor.this.exceptionCaught(delegate(ctx.channel()), cause);
}
});
}
};
}
private static final AttributeKey<ChannelDelegate> CHANNEL_DELEGATE_KEY = AttributeKey.valueOf("channel_delegate_key");
ChannelDelegate delegate(Channel channel) {
Attribute<ChannelDelegate> attr = channel.attr(CHANNEL_DELEGATE_KEY);
ChannelDelegate channelDelegate = attr.get();
if (channelDelegate == null) {
channelDelegate = new ChannelDelegate(channel);
attr.set(channelDelegate);
}
return channelDelegate;
}
ByteBuf buildErr(int commandCode, long commandId, Exception e) {
ByteBuf exception = encodeException(e);
ByteBuf buffer = Unpooled.buffer(COMMAND_DATA_RES_CONTENT_OFFSET + exception.readableBytes());
int commandLength = COMMAND_DATA_RES_STATUS_SELF_LENGTH + exception.readableBytes();
buffer.writeInt(commandCode);
buffer.writeLong(commandId);
buffer.writeInt(commandLength);
buffer.writeInt(Status.FAIL.ordinal());
buffer.writeBytes(exception);
return buffer;
}
ByteBuf encodeException(Exception e) {
return Unpooled.copiedBuffer(throwableToString(e).getBytes());
}
Exception decodeException(ByteBuf ebuf) {
int describeLength = ebuf.readableBytes();
byte[] trace = new byte[describeLength];
ebuf.readBytes(trace);
return new RuntimeException(new String(trace));
}
public static class ChannelDelegate {
final Channel channel;
public ChannelDelegate(Channel channel) {
this.channel = channel;
}
public void writeAndFlush(ByteBuf bytebuf) {
channel.writeAndFlush(bytebuf);
}
public void flush() {
channel.flush();
}
public void write(ByteBuf bytebuf) {
channel.write(bytebuf);
}
@Override
public String toString() {
return channel.localAddress() + "->" + channel.remoteAddress();
}
}
}
| 38.662162 | 137 | 0.65589 |
57ae4eabada13ce74f3b6e72e809a39be37606c2 | 1,780 | /**
* Copyright (C) 2013 Matija Mazi
*
* 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 si.mazi.rescu;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* @author Matija Mazi
*/
class InterceptedInvocationHandler implements InvocationHandler {
private final Interceptor interceptor;
private final InvocationHandler intercepted;
public InterceptedInvocationHandler(Interceptor interceptor, InvocationHandler intercepted) {
this.interceptor = interceptor;
this.intercepted = intercepted;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return interceptor.aroundInvoke(intercepted, proxy, method, args);
}
}
| 39.555556 | 97 | 0.757303 |
ed829163b3d7af4737e76d1e898fe1171050b28a | 839 | package net.padaf.preflight.font;
import net.padaf.preflight.ValidationConstants;
import org.apache.pdfbox.pdmodel.font.PDFont;
/**
* Because Type3 font program is an inner type of the PDF file,
* this font container is quite different from the other because
* all character/glyph are already checked.
*
*/
public class Type3FontContainer extends AbstractFontContainer {
public Type3FontContainer(PDFont fd) {
super(fd);
}
@Override
public void checkCID(int cid) throws GlyphException {
if (!isAlreadyComputedCid(cid)) {
// missing glyph
GlyphException e = new GlyphException(ValidationConstants.ERROR_FONTS_GLYPH_MISSING, cid,
"There are no glyph in the Type 3 font for the character \"" + cid + "\"");
addKnownCidElement(new GlyphDetail(cid, e));
throw e;
}
}
} | 28.931034 | 98 | 0.709178 |
5f98c0a3d7a268531b54f1a8fdffd76f59b7c8ea | 1,991 | /*
* Copyright 2015 Ignacio del Valle Alles [email protected].
*
* 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.brutusin.fleadb.sort;
import org.brutusin.json.spi.JsonNode;
import org.brutusin.fleadb.Schema;
/**
*
* @author Ignacio del Valle Alles [email protected]
*/
public class SortField {
private final String field;
private final boolean reverse;
public SortField(String field, boolean reverse) {
this.field = field;
this.reverse = reverse;
}
public org.apache.lucene.search.SortField getLuceneSortField(Schema schema) {
JsonNode.Type jsonType = schema.getIndexFields().get(field);
if (jsonType == null) {
throw new IllegalArgumentException("Unknown sort field '" + field + "' found. Supported field are: " + schema.getIndexFields().keySet());
}
org.apache.lucene.search.SortField.Type type;
switch (jsonType) {
case BOOLEAN:
case STRING:
type = org.apache.lucene.search.SortField.Type.STRING;
break;
case NUMBER:
type = org.apache.lucene.search.SortField.Type.DOUBLE;
break;
case INTEGER:
type = org.apache.lucene.search.SortField.Type.LONG;
break;
default:
throw new AssertionError();
}
return new org.apache.lucene.search.SortField(field, type, reverse);
}
}
| 34.327586 | 149 | 0.650427 |
5202187b0326d0122970bfc490b191daa0b21b33 | 2,238 | package lt.lb.luceneindexandsearch.config;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
/**
*
* @author laim0nas100
*/
public interface DocumentFieldsConfig {
public default String[] getContentFieldsArray() {
return getContentFieldNames().stream().toArray(s -> new String[s]);
}
public String getMainIdFieldName();
public Collection<String> getContentFieldNames();
public Collection<IndexedFieldConfig> getFields();
public Optional<IndexedFieldConfig> getField(String fieldName);
public default Collection<String> getMandatoryFieldNames() {
return getFields().stream()
.filter(field -> !field.isOptional()).map(m -> m.getName())
.collect(Collectors.toList());
}
public default Collection<String> getFieldNames() {
return getFields().stream()
.map(m -> m.getName())
.collect(Collectors.toList());
}
public default Document createDocument(Map<String, String> fieldContent) {
ArrayList<Field> fields = new ArrayList<>();
HashSet<String> unusedFields = new HashSet<>(getMandatoryFieldNames());
for (Map.Entry<String, String> fc : fieldContent.entrySet()) {
String name = fc.getKey();
String content = fc.getValue();
getField(name).map(m -> m.makeField(content));
Optional<IndexedFieldConfig> fieldConfig = getField(name);
if (!fieldConfig.isPresent()) {
throw new IllegalArgumentException("No such field defined:" + name);
}
Field field = fieldConfig.get().makeField(content);
fields.add(field);
unusedFields.remove(name);
}
if (!unusedFields.isEmpty()) {
throw new IllegalArgumentException("Not all mandatory fields has been supplied:"+unusedFields);
}
Document doc = new Document();
for (Field field : fields) {
doc.add(field);
}
return doc;
}
}
| 31.083333 | 107 | 0.634942 |
365017a009f81a64a2a38043bc58f4dc611bfe41 | 1,634 | package com.game.persistence.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* @author pachi
* Modelo de la tabla requisitos.
*/
@Entity
public class Requisitos {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id_requisito;
@Column(nullable = false)
private String sistema_operativo;
@Column(nullable = false)
private String procesador;
@Column(nullable = false)
private String memoria;
@Column(nullable = false)
private String grafica;
@Column(nullable = false)
private String almacenamiento;
/*
* ------ Getter and Setter ------
*/
public long getId_requisitos() {
return id_requisito;
}
public void setId_requisitos(long id_requisitos) {
this.id_requisito = id_requisitos;
}
public String getSistema_operativo() {
return sistema_operativo;
}
public void setSistema_operativo(String sistema_operativo) {
this.sistema_operativo = sistema_operativo;
}
public String getProcesador() {
return procesador;
}
public void setProcesador(String procesador) {
this.procesador = procesador;
}
public String getMemoria() {
return memoria;
}
public void setMemoria(String memoria) {
this.memoria = memoria;
}
public String getGrafica() {
return grafica;
}
public void setGrafica(String grafica) {
this.grafica = grafica;
}
public String getAlmacenamiento() {
return almacenamiento;
}
public void setAlmacenamiento(String alamcenamiento) {
this.almacenamiento = alamcenamiento;
}
}
| 18.359551 | 61 | 0.741126 |
d551f0c6dba06ae839767c0c0303a4edb94b0f75 | 282 | package ru.sipivr.core.result;
/**
* Created by Karpukhin on 01.01.2016.
*/
public class Conference extends AbstractResult {
private String name;
public Conference(String name) {
this.name = name;
}
public String getName() {
return name;
}
} | 17.625 | 48 | 0.634752 |
905974d9c1c43999f30ddc5999cb9ad257d7f363 | 742 | package br.com.carlos.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import br.com.carlos.dto.ComboBoxDTO;
import br.com.carlos.model.Functionality;
@Repository
public interface FunctionalityRepository extends JpaRepository<Functionality, Long> {
@Query("SELECT"
+ " new br.com.carlos.dto.ComboBoxDTO(f.id, f.name)"
+ " FROM Functionality f")
List<ComboBoxDTO> comboBox();
@Query("SELECT"
+ " new br.com.carlos.model.Functionality(f.id, f.name)"
+ " FROM Functionality f"
+ " where f.id in (:ids)")
List<Functionality> findFunctionalityByIds(List<Long> ids);
} | 28.538462 | 85 | 0.756065 |
b596a80488dd456e3477ac0fea1fd2945e1878f9 | 1,159 | package org.infinispan.persistence.jdbc.mixed;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.persistence.BaseStoreFunctionalTest;
import org.infinispan.persistence.jdbc.configuration.JdbcMixedStoreConfigurationBuilder;
import org.infinispan.test.fwk.UnitTestDatabaseManager;
import org.testng.annotations.Test;
@Test(groups = {"functional", "smoke"}, testName = "persistence.jdbc.mixed.JdbcMixedStoreFunctionalTest")
public class JdbcMixedStoreFunctionalTest extends BaseStoreFunctionalTest {
@Override
protected PersistenceConfigurationBuilder createCacheStoreConfig(PersistenceConfigurationBuilder persistence, boolean preload) {
JdbcMixedStoreConfigurationBuilder store = persistence
.addStore(JdbcMixedStoreConfigurationBuilder.class)
.preload(preload);
UnitTestDatabaseManager.setDialect(store);
UnitTestDatabaseManager.buildTableManipulation(store.binaryTable(), true);
UnitTestDatabaseManager.buildTableManipulation(store.stringTable(), false);
UnitTestDatabaseManager.configureUniqueConnectionFactory(store);
return persistence;
}
}
| 46.36 | 131 | 0.823123 |
a45aa3b8aae7488b875ab4da5ed19d474dce989d | 2,478 | package de.sanandrew.mods.turretmod.client.gui.element.tcu;
import com.google.gson.JsonObject;
import de.sanandrew.mods.sanlib.lib.client.gui.GuiElementInst;
import de.sanandrew.mods.sanlib.lib.client.gui.IGui;
import de.sanandrew.mods.sanlib.lib.client.gui.element.Text;
import de.sanandrew.mods.sanlib.lib.client.util.GuiUtils;
import de.sanandrew.mods.sanlib.lib.util.JsonUtils;
import de.sanandrew.mods.sanlib.lib.util.LangUtils;
import de.sanandrew.mods.turretmod.api.TmrConstants;
import de.sanandrew.mods.turretmod.api.client.tcu.IGuiTcuInst;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
public class TcuTurretName
extends Text
{
public static final ResourceLocation ID = new ResourceLocation(TmrConstants.ID, "turret_name");
private long marqueeTime;
private int textfieldLength;
@Override
public void bakeData(IGui gui, JsonObject data, GuiElementInst inst) {
super.bakeData(gui, data, inst);
this.textfieldLength = JsonUtils.getIntVal(data.get("textfieldLength"), 144);
}
@Override
public void render(IGui gui, float partTicks, int x, int y, int mouseX, int mouseY, JsonObject data) {
String name = this.getDynamicText(gui, "");
int strWidth = this.fontRenderer.getStringWidth(name);
if( strWidth > this.textfieldLength ) {
long currTime = System.currentTimeMillis();
if( this.marqueeTime < 1L ) {
this.marqueeTime = currTime;
}
int marquee = -this.textfieldLength + (int) (currTime - this.marqueeTime) / 25;
if( marquee > strWidth ) {
this.marqueeTime = currTime;
}
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GuiUtils.glScissor(gui.getScreenPosX() + x, gui.getScreenPosY() + y, this.textfieldLength, 12);
this.fontRenderer.drawString(name, x - marquee, y, this.color, false);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
} else {
this.fontRenderer.drawString(name, x + (this.textfieldLength - this.fontRenderer.getStringWidth(name)) / 2.0F, y, this.color, false);
}
}
@Override
public String getBakedText(IGui gui, JsonObject data) {
return "";
}
@Override
public String getDynamicText(IGui gui, String originalText) {
return LangUtils.translate(LangUtils.ENTITY_NAME.get(((IGuiTcuInst<?>) gui).getTurretInst().getTurret().getId()));
}
}
| 39.333333 | 145 | 0.684019 |
0022d5fe9d29f0abfb8096c758af70baa6dc4a77 | 1,385 | /*
* Copyright © 2014-2020 Vladlen V. Larionov and others as noted.
*
* 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 colesico.framework.introspection.codegen;
import colesico.framework.assist.codegen.FrameworkAbstractParser;
import colesico.framework.assist.codegen.model.ClassElement;
import colesico.framework.introspection.codegen.model.IntrospectedElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.processing.ProcessingEnvironment;
/**
* @author Vladlen Larionov
*/
public class IntrospectionParser extends FrameworkAbstractParser {
private Logger logger = LoggerFactory.getLogger(IntrospectionParser.class);
public IntrospectionParser(ProcessingEnvironment processingEnv) {
super(processingEnv);
}
public IntrospectedElement parse(ClassElement target) {
return null;
}
}
| 31.477273 | 79 | 0.771119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.