text
stringlengths 7
1.01M
|
|---|
package xx.demo.activity.view;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import heighten.HeightenView;
import util.PxUtil;
import xx.demo.R;
import xx.demo.activity.BaseActivity;
public class HeightenActivity extends BaseActivity
{
private HeightenView mItemView;
@Override
public void createChildren(FrameLayout parent, FrameLayout.LayoutParams params)
{
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.opengl_test_6);
mItemView = new HeightenView(parent.getContext());
mItemView.setBitmap(bitmap);
mItemView.setBackgroundColor(Color.GRAY);
params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, PxUtil.sV_1080p(1440));
params.topMargin = PxUtil.sV_1080p(100);
parent.addView(mItemView, params);
Button btn = new Button(parent.getContext());
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
ViewGroup.LayoutParams layoutParams = mItemView.getLayoutParams();
layoutParams.height += 100;
mItemView.requestLayout();
}
});
btn.setText("增加 100 高度");
params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.BOTTOM;
parent.addView(btn, params);
btn = new Button(parent.getContext());
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
ViewGroup.LayoutParams layoutParams = mItemView.getLayoutParams();
layoutParams.height -= 100;
mItemView.requestLayout();
}
});
btn.setText("减少 100 高度");
params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.BOTTOM | Gravity.END;
parent.addView(btn, params);
btn = new Button(parent.getContext());
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mItemView.showHeightChanged(true);
mItemView.setIncreasedHeight(100);
mItemView.update();
}
});
btn.setText("拉伸 100");
params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
parent.addView(btn, params);
btn = new Button(parent.getContext());
btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mItemView.showHeightChanged(true);
mItemView.setIncreasedHeight(-100);
mItemView.update();
}
});
btn.setText("缩短 100");
params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
parent.addView(btn, params);
}
}
|
//: net/mindview/util/CountingGenerator.java
// Simple generator implementations.
package com.thinkinginjava.source.net.mindview.util;
public class CountingGenerator {
public static class
Boolean implements Generator<java.lang.Boolean> {
private boolean value = false;
public java.lang.Boolean next() {
value = !value; // Just flips back and forth
return value;
}
}
public static class
Byte implements Generator<java.lang.Byte> {
private byte value = 0;
public java.lang.Byte next() { return value++; }
}
static char[] chars = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
public static class
Character implements Generator<java.lang.Character> {
int index = -1;
public java.lang.Character next() {
index = (index + 1) % chars.length;
return chars[index];
}
}
public static class
String implements Generator<java.lang.String> {
private int length = 7;
Generator<java.lang.Character> cg = new Character();
public String() {}
public String(int length) { this.length = length; }
public java.lang.String next() {
char[] buf = new char[length];
for(int i = 0; i < length; i++)
buf[i] = cg.next();
return new java.lang.String(buf);
}
}
public static class
Short implements Generator<java.lang.Short> {
private short value = 0;
public java.lang.Short next() { return value++; }
}
public static class
Integer implements Generator<java.lang.Integer> {
private int value = 0;
public java.lang.Integer next() { return value++; }
}
public static class
Long implements Generator<java.lang.Long> {
private long value = 0;
public java.lang.Long next() { return value++; }
}
public static class
Float implements Generator<java.lang.Float> {
private float value = 0;
public java.lang.Float next() {
float result = value;
value += 1.0;
return result;
}
}
public static class
Double implements Generator<java.lang.Double> {
private double value = 0.0;
public java.lang.Double next() {
double result = value;
value += 1.0;
return result;
}
}
} ///:~
|
/*
* Prog for extracting values from a CSV string.
*/
package ssmith.util;
import java.util.*;
public class CSVString {
private String str;
private ArrayList elements;
private String separator;
public CSVString(String newStr) {
this(newStr, ",");
}
public CSVString(String newStr, String sep) {
if (sep.length() != 1) {
throw new RuntimeException("Tokenizer not one character long!");
}
if (newStr == null) {
throw new RuntimeException("newStr is null!");
}
this.str = newStr;
this.separator = sep;
this.elements = new ArrayList();
StringTokenizer strtkn = new StringTokenizer(newStr, sep);
while (strtkn.hasMoreElements()) {
elements.add(strtkn.nextToken());
}
}
public int getNoOfSections() {
return elements.size();
}
public String getString() {
return this.str;
}
public String toString() {
return this.str;
}
public String getFirstSection() {
return getSection(0);
}
public String getSection(int section) {
//System.out.println("getting section"+section);
try {
return (String) elements.get(section);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String getSections(int start, int finish) {
StringBuffer sb = new StringBuffer();
for (int i=start ; i<finish ; i++) {
sb.append(this.getSection(i));
if (i<finish-1) {
sb.append(separator);
}
}
return sb.toString();
}
public String getLastSection() {
return this.getSection(this.getNoOfSections()-1);
}
public static void main(String args[]) {
System.out.println(new ssmith.util.CSVString("thix#hello#me","#").getSection(2));
}
}
|
/*
* Copyright 1999-2019 Seata.io Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.seata.rm.datasource.exec;
import io.seata.common.DefaultValues;
import io.seata.config.ConfigurationChangeEvent;
import io.seata.core.constants.ConfigurationKeys;
import io.seata.core.context.GlobalLockConfigHolder;
import io.seata.core.model.GlobalLockConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author selfishlover
*/
public class LockRetryControllerTest {
private GlobalLockConfig config;
private final int defaultRetryInternal = DefaultValues.DEFAULT_CLIENT_LOCK_RETRY_INTERVAL;
private final int defaultRetryTimes = DefaultValues.DEFAULT_CLIENT_LOCK_RETRY_TIMES;
@BeforeEach
void setUp() {
config = new GlobalLockConfig();
config.setLockRetryInternal(10);
config.setLockRetryTimes(3);
GlobalLockConfigHolder.setAndReturnPrevious(config);
}
@Test
void testRetryNotExceeded() {
LockRetryController controller = new LockRetryController();
assertDoesNotThrow(() -> {
for (int times = 0; times < config.getLockRetryTimes(); times++) {
controller.sleep(new RuntimeException("test"));
}
}, "should not throw anything when retry not exceeded");
}
@Test
void testRetryExceeded() {
LockRetryController controller = new LockRetryController();
assertThrows(LockWaitTimeoutException.class, () -> {
for (int times = 0; times <= config.getLockRetryTimes(); times++) {
controller.sleep(new RuntimeException("test"));
}
}, "should throw LockWaitTimeoutException when retry exceeded");
}
@Test
void testNoCustomizedConfig() {
GlobalLockConfigHolder.remove();
LockRetryController controller = new LockRetryController();
String message = "should use global config when there is no customized config";
assertEquals(defaultRetryInternal, controller.getLockRetryInternal(), message);
assertEquals(defaultRetryTimes, controller.getLockRetryTimes(), message);
}
@Test
void testLockConfigListener() {
LockRetryController.GlobalConfig config = new LockRetryController.GlobalConfig();
ConfigurationChangeEvent event = new ConfigurationChangeEvent();
event.setDataId(ConfigurationKeys.CLIENT_LOCK_RETRY_INTERVAL);
int retryInterval = 100;
event.setNewValue(retryInterval + "");
config.onChangeEvent(event);
String message1 = "lock config listener fail to update latest value of CLIENT_LOCK_RETRY_INTERVAL";
assertEquals(retryInterval, config.getGlobalLockRetryInternal(), message1);
event.setDataId(ConfigurationKeys.CLIENT_LOCK_RETRY_TIMES);
int retryTimes = 5;
event.setNewValue(retryTimes + "");
config.onChangeEvent(event);
String message2 = "lock config listener fail to update latest value of CLIENT_LOCK_RETRY_TIMES";
assertEquals(retryTimes, config.getGlobalLockRetryTimes(), message2);
event.setDataId(ConfigurationKeys.CLIENT_LOCK_RETRY_INTERVAL);
event.setNewValue("not a number");
config.onChangeEvent(event);
String message3 = "should fallback to default value when receive an illegal config value of CLIENT_LOCK_RETRY_INTERVAL";
assertEquals(defaultRetryInternal, config.getGlobalLockRetryInternal(), message3);
event.setDataId(ConfigurationKeys.CLIENT_LOCK_RETRY_TIMES);
event.setNewValue("not a number");
config.onChangeEvent(event);
String message4 = "should fallback to default value when receive an illegal config value of CLIENT_LOCK_RETRY_TIMES";
assertEquals(defaultRetryTimes, config.getGlobalLockRetryTimes(), message4);
}
}
|
package com.thoughtworks.gaia.system.endpoint;
import com.thoughtworks.gaia.product.entity.Product;
import com.thoughtworks.gaia.system.service.SystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Created by hwwei on 16/11/4.
*/
@Component
@Path("system")
@Api(value = "system", description = "Access to system resource")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class SystemEndpoint {
@Autowired
private SystemService systemService;
@Path("/")
@ApiOperation(value = "Get status by id", response = boolean.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Get product successfully"),
@ApiResponse(code = 404, message = "No product matches given id")
})
@GET
public Response getStatus() {
boolean st = systemService.getOpenStatus();
return Response.ok(st).build();
}
@Path("/{status}")
@ApiOperation(value = "update status ", response = Product.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Get product successfully"),
@ApiResponse(code = 404, message = "No product matches given id")
})
@PUT
public Response updateStatus(@PathParam("status") boolean status) {
systemService.updateOpenStatus(status);
return Response.noContent().build();
}
}
|
package to.augmented.reality.android.ardb.sourcefacade.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to specify a field or method that contains or returns a host network address (IP or DNS name).
* Example:
* <code>
* @Password private String getHost();
* </code>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target( {ElementType.METHOD, ElementType.FIELD} )
public @interface Host { }
|
package com.jagex;
import com.jagex.Class174_Sub2;
import jaggl.OpenGL;
public class Class139 {
int anInt1659;
void method1643(int var1) {
OpenGL.glNewList(this.anInt1659 + var1, 4864);
}
void method1644(int var1) {
OpenGL.glNewList(this.anInt1659 + var1, 4864);
}
void method1645(char var1) {
OpenGL.glCallList(this.anInt1659 + var1);
}
void method1646(int var1) {
OpenGL.glNewList(this.anInt1659 + var1, 4864);
}
void method1647() {
OpenGL.glEndList();
}
void method1648() {
OpenGL.glEndList();
}
Class139(Class174_Sub2 var1, int var2) {
this.anInt1659 = OpenGL.glGenLists(var2);
}
}
|
package com.ke.css.cimp.fwb.fwb11;
/* -----------------------------------------------------------------------------
* Rule_OTHER_PARTY_MSG_OFFICE_DESIG.java
* -----------------------------------------------------------------------------
*
* Producer : com.parse2.aparse.Parser 2.5
* Produced : Tue Mar 06 10:36:50 KST 2018
*
* -----------------------------------------------------------------------------
*/
import java.util.ArrayList;
final public class Rule_OTHER_PARTY_MSG_OFFICE_DESIG extends Rule
{
public Rule_OTHER_PARTY_MSG_OFFICE_DESIG(String spelling, ArrayList<Rule> rules)
{
super(spelling, rules);
}
public Object accept(Visitor visitor)
{
return visitor.visit(this);
}
public static Rule_OTHER_PARTY_MSG_OFFICE_DESIG parse(ParserContext context)
{
context.push("OTHER_PARTY_MSG_OFFICE_DESIG");
boolean parsed = true;
int s0 = context.index;
ParserAlternative a0 = new ParserAlternative(s0);
ArrayList<ParserAlternative> as1 = new ArrayList<ParserAlternative>();
parsed = false;
{
int s1 = context.index;
ParserAlternative a1 = new ParserAlternative(s1);
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 2 && f1; i1++)
{
Rule rule = Rule_Typ_Mixed.parse(context);
if ((f1 = rule != null))
{
a1.add(rule, context.index);
c1++;
}
}
parsed = c1 == 2;
}
if (parsed)
{
as1.add(a1);
}
context.index = s1;
}
ParserAlternative b = ParserAlternative.getBest(as1);
parsed = b != null;
if (parsed)
{
a0.add(b.rules, b.end);
context.index = b.end;
}
Rule rule = null;
if (parsed)
{
rule = new Rule_OTHER_PARTY_MSG_OFFICE_DESIG(context.text.substring(a0.start, a0.end), a0.rules);
}
else
{
context.index = s0;
}
context.pop("OTHER_PARTY_MSG_OFFICE_DESIG", parsed);
return (Rule_OTHER_PARTY_MSG_OFFICE_DESIG)rule;
}
}
/* -----------------------------------------------------------------------------
* eof
* -----------------------------------------------------------------------------
*/
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7.widget;
import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.support.annotation.RestrictTo;
import android.support.v7.appcompat.R;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
/**
* A popup window displaying a text message aligned to a specified view.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
class TooltipPopup {
private static final String TAG = "TooltipPopup";
private final Context mContext;
private final View mContentView;
private final TextView mMessageView;
private final WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams();
private final Rect mTmpDisplayFrame = new Rect();
private final int[] mTmpAnchorPos = new int[2];
private final int[] mTmpAppPos = new int[2];
TooltipPopup(Context context) {
mContext = context;
mContentView = LayoutInflater.from(mContext).inflate(R.layout.tooltip, null);
mMessageView = (TextView) mContentView.findViewById(R.id.message);
mLayoutParams.setTitle(getClass().getSimpleName());
mLayoutParams.packageName = mContext.getPackageName();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mLayoutParams.format = PixelFormat.TRANSLUCENT;
mLayoutParams.windowAnimations = R.style.Animation_AppCompat_Tooltip;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
}
void show(View anchorView, int anchorX, int anchorY, boolean fromTouch,
CharSequence tooltipText) {
if (isShowing()) {
hide();
}
mMessageView.setText(tooltipText);
computePosition(anchorView, anchorX, anchorY, fromTouch, mLayoutParams);
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
wm.addView(mContentView, mLayoutParams);
}
void hide() {
if (!isShowing()) {
return;
}
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(mContentView);
}
boolean isShowing() {
return mContentView.getParent() != null;
}
private void computePosition(View anchorView, int anchorX, int anchorY, boolean fromTouch,
WindowManager.LayoutParams outParams) {
final int tooltipPreciseAnchorThreshold = mContext.getResources().getDimensionPixelOffset(
R.dimen.tooltip_precise_anchor_threshold);
final int offsetX;
if (anchorView.getWidth() >= tooltipPreciseAnchorThreshold) {
// Wide view. Align the tooltip horizontally to the precise X position.
offsetX = anchorX;
} else {
// Otherwise anchor the tooltip to the view center.
offsetX = anchorView.getWidth() / 2; // Center on the view horizontally.
}
final int offsetBelow;
final int offsetAbove;
if (anchorView.getHeight() >= tooltipPreciseAnchorThreshold) {
// Tall view. Align the tooltip vertically to the precise Y position.
final int offsetExtra = mContext.getResources().getDimensionPixelOffset(
R.dimen.tooltip_precise_anchor_extra_offset);
offsetBelow = anchorY + offsetExtra;
offsetAbove = anchorY - offsetExtra;
} else {
// Otherwise anchor the tooltip to the view center.
offsetBelow = anchorView.getHeight(); // Place below the view in most cases.
offsetAbove = 0; // Place above the view if the tooltip does not fit below.
}
outParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
final int tooltipOffset = mContext.getResources().getDimensionPixelOffset(
fromTouch ? R.dimen.tooltip_y_offset_touch : R.dimen.tooltip_y_offset_non_touch);
final View appView = getAppRootView(anchorView);
if (appView == null) {
Log.e(TAG, "Cannot find app view");
return;
}
appView.getWindowVisibleDisplayFrame(mTmpDisplayFrame);
if (mTmpDisplayFrame.left < 0 && mTmpDisplayFrame.top < 0) {
// No meaningful display frame, the anchor view is probably in a subpanel
// (such as a popup window). Use the screen frame as a reasonable approximation.
final Resources res = mContext.getResources();
final int statusBarHeight;
int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId != 0) {
statusBarHeight = res.getDimensionPixelSize(resourceId);
} else {
statusBarHeight = 0;
}
final DisplayMetrics metrics = res.getDisplayMetrics();
mTmpDisplayFrame.set(0, statusBarHeight, metrics.widthPixels, metrics.heightPixels);
}
appView.getLocationOnScreen(mTmpAppPos);
anchorView.getLocationOnScreen(mTmpAnchorPos);
mTmpAnchorPos[0] -= mTmpAppPos[0];
mTmpAnchorPos[1] -= mTmpAppPos[1];
// mTmpAnchorPos is now relative to the main app window.
outParams.x = mTmpAnchorPos[0] + offsetX - mTmpDisplayFrame.width() / 2;
final int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
mContentView.measure(spec, spec);
final int tooltipHeight = mContentView.getMeasuredHeight();
final int yAbove = mTmpAnchorPos[1] + offsetAbove - tooltipOffset - tooltipHeight;
final int yBelow = mTmpAnchorPos[1] + offsetBelow + tooltipOffset;
if (fromTouch) {
if (yAbove >= 0) {
outParams.y = yAbove;
} else {
outParams.y = yBelow;
}
} else {
if (yBelow + tooltipHeight <= mTmpDisplayFrame.height()) {
outParams.y = yBelow;
} else {
outParams.y = yAbove;
}
}
}
private static View getAppRootView(View anchorView) {
Context context = anchorView.getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
return ((Activity) context).getWindow().getDecorView();
} else {
context = ((ContextWrapper) context).getBaseContext();
}
}
return anchorView.getRootView();
}
}
|
/*
* Copyright (c) 2016 - Qeo LLC
*
* The source code form of this Qeo Open Source Project component is subject
* to the terms of the Clear BSD license.
*
* You can redistribute it and/or modify it under the terms of the Clear BSD
* License (http://directory.fsf.org/wiki/License:ClearBSD). See LICENSE file
* for more details.
*
* The Qeo Open Source Project also includes third party Open Source Software.
* See LICENSE file for more details.
*/
package org.qeo.sample.simplechat;
/**
* A simple chat message.
*/
public class ChatMessage
{
/**
* The user sending the message.
*/
public String from;
/**
* The message.
*/
public String message;
/**
* A default constructor is <b>required</b> in Qeo.
*
* It is used to create a new instance of this object before filling in the variables that originate from Qeo.
**/
public ChatMessage()
{
}
@Override
public boolean equals(Object obj)
{
if (obj == this) {
return true;
}
if ((obj == null) || (obj.getClass() != this.getClass())) {
return false;
}
final ChatMessage myObj = (ChatMessage) obj;
if (!from.equals(myObj.from)) {
return false;
}
if (!message.equals(myObj.message)) {
return false;
}
return true;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((from == null) ? 0 : from.hashCode());
result = prime * result + ((message == null) ? 0 : message.hashCode());
return result;
}
}
|
package br.edu.utfpr.cp.emater.midmipsystem.repository.security;
import org.springframework.data.jpa.repository.JpaRepository;
import br.edu.utfpr.cp.emater.midmipsystem.entity.security.Authority;
public interface AuthorityRepository extends JpaRepository<Authority, Long>{
public Authority findByName (String name);
}
|
/*
* This file is auto-generated by h2o-3/h2o-bindings/bin/gen_java.py
* Copyright 2016 H2O.ai; Apache License Version 2.0 (see LICENSE for details)
*/
package water.bindings.pojos;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.*;
public class XGBoostModelOutputV3 extends ModelOutputSchemaV3 {
/**
* Variable Importances
*/
@SerializedName("variable_importances")
public TwoDimTableV3 variableImportances;
/*------------------------------------------------------------------------------------------------------------------
// INHERITED
//------------------------------------------------------------------------------------------------------------------
// Column names
public String[] names;
// Domains for categorical columns
public String[][] domains;
// Cross-validation models (model ids)
public ModelKeyV3[] crossValidationModels;
// Cross-validation predictions, one per cv model (deprecated, use cross_validation_holdout_predictions_frame_id
// instead)
public FrameKeyV3[] crossValidationPredictions;
// Cross-validation holdout predictions (full out-of-sample predictions on training data)
public FrameKeyV3 crossValidationHoldoutPredictionsFrameId;
// Cross-validation fold assignment (each row is assigned to one holdout fold)
public FrameKeyV3 crossValidationFoldAssignmentFrameId;
// Category of the model (e.g., Binomial)
public ModelCategory modelCategory;
// Model summary
public TwoDimTableV3 modelSummary;
// Scoring history
public TwoDimTableV3 scoringHistory;
// Training data model metrics
public ModelMetricsBaseV3 trainingMetrics;
// Validation data model metrics
public ModelMetricsBaseV3 validationMetrics;
// Cross-validation model metrics
public ModelMetricsBaseV3 crossValidationMetrics;
// Cross-validation model metrics summary
public TwoDimTableV3 crossValidationMetricsSummary;
// Job status
public String status;
// Start time in milliseconds
public long startTime;
// End time in milliseconds
public long endTime;
// Runtime in milliseconds
public long runTime;
// Help information for output fields
public Map<String,String> help;
*/
/**
* Public constructor
*/
public XGBoostModelOutputV3() {
status = "";
startTime = 0L;
endTime = 0L;
runTime = 0L;
}
/**
* Return the contents of this object as a JSON String.
*/
@Override
public String toString() {
return new GsonBuilder().serializeSpecialFloatingPointValues().create().toJson(this);
}
}
|
package com.blakebr0.extendedcrafting.item;
import com.blakebr0.cucumber.helper.NBTHelper;
import com.blakebr0.cucumber.iface.IEnableable;
import com.blakebr0.cucumber.item.BaseItem;
import com.blakebr0.cucumber.lib.Localizable;
import com.blakebr0.cucumber.lib.Tooltips;
import com.blakebr0.extendedcrafting.config.ModConfigs;
import com.blakebr0.extendedcrafting.lib.ModTooltips;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.util.ActionResult;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.List;
import java.util.function.Function;
public class RecipeMakerItem extends BaseItem implements IEnableable {
private static final String NEW_LINE = System.lineSeparator() + "\t";
public RecipeMakerItem(Function<Properties, Properties> properties) {
super(properties.compose(p -> p.maxStackSize(1)));
}
@Override
public boolean isEnabled() {
return ModConfigs.ENABLE_RECIPE_MAKER.get();
}
@Override
public void fillItemGroup(ItemGroup group, NonNullList<ItemStack> items) {
if (this.isInGroup(group)) {
ItemStack stack = new ItemStack(this);
NBTHelper.setBoolean(stack, "Shapeless", false);
items.add(stack);
}
}
@Override
public ActionResultType onItemUseFirst(ItemStack stack, ItemUseContext context) {
PlayerEntity player = context.getPlayer();
BlockPos pos = context.getPos();
Direction facing = context.getFace();
if (player == null || !player.canPlayerEdit(pos.offset(facing), facing, stack))
return ActionResultType.PASS;
// TODO: Implement recipe maker functionality
// TileEntity tile = world.getTileEntity(pos);
// if (tile != null && tile instanceof IExtendedTable) {
// if (world.isRemote) {
// setClipboard(tile, stack);
// player.sendMessage(new TextComponentTranslation("message.ec.copied_recipe"));
//
// if (ModConfigs.confRMNBT && !Loader.isModLoaded("crafttweaker")) {
// player.sendMessage(new TextComponentTranslation("message.ec.nbt_requires_crafttweaker"));
// }
// }
//
// return ActionResultType.SUCCESS;
// }
return ActionResultType.PASS; }
@Override
public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
if (player.isCrouching()) {
ItemStack stack = player.getHeldItem(hand);
NBTHelper.flipBoolean(stack, "Shapeless");
if (world.isRemote()) {
player.sendMessage(Localizable.of("message.extendedcrafting.changed_mode").args(this.getModeString(stack)).build());
}
}
return super.onItemRightClick(world, player, hand);
}
@OnlyIn(Dist.CLIENT)
@Override
public void addInformation(ItemStack stack, World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
tooltip.add(Tooltips.NOT_YET_IMPLEMENTED.build());
tooltip.add(ModTooltips.MODE.args(this.getModeString(stack)).build());
}
// private void setClipboard(TileEntity table, ItemStack stack) {
// if (Desktop.isDesktopSupported()) {
// String string = "mods.extendedcrafting." + (table instanceof EnderCrafterTileEntity ? "EnderCrafting" : "TableCrafting");
//
// if (isShapeless(stack)) {
// string += ".addShapeless(0, <>, [" + makeItemArrayShapeless((IExtendedTable) table);
// } else {
// string += ".addShaped(0, <>, [" + NEW_LINE + makeItemArrayShaped((IExtendedTable) table);
// }
//
// string += "]);";
//
// StringSelection stringSelection = new StringSelection(string);
// Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// clipboard.setContents(stringSelection, null);
// }
// }
//
// private String makeItemArrayShaped(IExtendedTable table) {
// String string = "";
// NonNullList<ItemStack> matrix = table.getMatrix();
// for (int i = 0; i < matrix.size(); i++) {
// int sr = (int) Math.sqrt(matrix.size());
// if (i == 0 || i % sr == 0) {
// string += "[";
// }
//
// ItemStack stack = matrix.get(i);
//
// String item = "";
// if (ModConfigs.confRMOredict && !stack.isEmpty()) {
// int[] oreIds = OreDictionary.getOreIDs(stack);
// if (oreIds.length > 0) {
// item = "ore:" + OreDictionary.getOreName(oreIds[0]);
// }
// }
//
// if (item.isEmpty()) {
// String reg = stack.getItem().getRegistryName().toString();
// item = stack.isEmpty() ? "null" : reg;
// if (!stack.isEmpty() && stack.getMetadata() > 0) {
// item += ":" + stack.getMetadata();
// }
// }
//
// if (!item.equalsIgnoreCase("null")) {
// string += "<" + item + ">";
//
// if (ModConfigs.confRMNBT && !stack.isEmpty() && stack.hasTagCompound() && Loader.isModLoaded("crafttweaker")) {
// NBTBase nbt = stack.serializeNBT().getTag("tag");
// String tag = CraftTweakerUtils.writeTag(nbt);
// string += ".withTag(" + tag + ")";
// }
// } else {
// string += item;
// }
//
// if ((i + 1) % sr != 0) {
// string += ", ";
// }
//
// if (i + 1 == sr || (i + 1) % sr == 0) {
// string += "]";
// if (i + 1 < matrix.size()) {
// string += ", ";
// string += NEW_LINE;
// } else {
// string += System.lineSeparator();
// }
// }
// }
//
// return string;
// }
//
// private String makeItemArrayShapeless(IExtendedTable table) {
// String string = "";
// NonNullList<ItemStack> matrix = table.getMatrix();
// ArrayList<Integer> slots = new ArrayList<>();
// int lastSlot = 0;
// for (int i = 0; i < matrix.size(); i++) {
// ItemStack stack = matrix.get(i);
// if (!stack.isEmpty()) {
// slots.add(i);
// lastSlot = i;
// }
// }
//
// for (int i : slots) {
// ItemStack stack = matrix.get(i);
// int[] oreIds = OreDictionary.getOreIDs(stack);
// String item = "";
// if (ModConfigs.confRMOredict && oreIds.length > 0) {
// item = "ore:" + OreDictionary.getOreName(oreIds[0]);
// } else {
// String reg = stack.getItem().getRegistryName().toString();
// item = stack.isEmpty() ? "null" : reg;
// if (!stack.isEmpty() && stack.getMetadata() > 0) {
// item += ":" + stack.getMetadata();
// }
// }
//
// string += "<" + item + ">";
//
// if (ModConfigs.confRMNBT && !stack.isEmpty() && stack.hasTagCompound() && Loader.isModLoaded("crafttweaker")) {
// NBTBase nbt = stack.serializeNBT().getTag("tag");
// String tag = CraftTweakerUtils.writeTag(nbt);
// string += ".withTag(" + tag + ")";
// }
//
// if (i != lastSlot) {
// string += ", ";
// }
// }
//
// return string;
// }
//
private String getModeString(ItemStack stack) {
return this.isShapeless(stack) ? "Shapeless" : "Shaped";
}
private boolean isShapeless(ItemStack stack) {
return NBTHelper.getBoolean(stack, "Shapeless");
}
}
|
/*
* Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.crypto.provider;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import javax.crypto.*;
import javax.crypto.spec.*;
/**
* This class represents password-based encryption as defined by the PKCS #5
* standard.
*
* @author Jan Luehe
*
*
* @see javax.crypto.Cipher
*/
final class PBES1Core {
// the encapsulated DES cipher
private CipherCore cipher;
private MessageDigest md;
private int blkSize;
private String algo = null;
private byte[] salt = null;
private int iCount = 10;
/**
* Creates an instance of PBE Cipher using the specified CipherSpi
* instance.
*
*/
PBES1Core(String cipherAlg) throws NoSuchAlgorithmException,
NoSuchPaddingException {
algo = cipherAlg;
if (algo.equals("DES")) {
cipher = new CipherCore(new DESCrypt(),
DESConstants.DES_BLOCK_SIZE);
} else if (algo.equals("DESede")) {
cipher = new CipherCore(new DESedeCrypt(),
DESConstants.DES_BLOCK_SIZE);
} else {
throw new NoSuchAlgorithmException("No Cipher implementation " +
"for PBEWithMD5And" + algo);
}
cipher.setMode("CBC");
cipher.setPadding("PKCS5Padding");
// get instance of MD5
md = MessageDigest.getInstance("MD5");
}
/**
* Sets the mode of this cipher. This algorithm can only be run in CBC
* mode.
*
* @param mode the cipher mode
*
* @exception NoSuchAlgorithmException if the requested cipher mode is
* invalid
*/
void setMode(String mode) throws NoSuchAlgorithmException {
cipher.setMode(mode);
}
/**
* Sets the padding mechanism of this cipher. This algorithm only uses
* PKCS #5 padding.
*
* @param paddingScheme the padding mechanism
*
* @exception NoSuchPaddingException if the requested padding mechanism
* is invalid
*/
void setPadding(String paddingScheme) throws NoSuchPaddingException {
cipher.setPadding(paddingScheme);
}
/**
* Returns the block size (in bytes).
*
* @return the block size (in bytes)
*/
int getBlockSize() {
return DESConstants.DES_BLOCK_SIZE;
}
/**
* Returns the length in bytes that an output buffer would need to be in
* order to hold the result of the next <code>update</code> or
* <code>doFinal</code> operation, given the input length
* <code>inputLen</code> (in bytes).
*
* <p>This call takes into account any unprocessed (buffered) data from a
* previous <code>update</code> call, and padding.
*
* <p>The actual output length of the next <code>update</code> or
* <code>doFinal</code> call may be smaller than the length returned by
* this method.
*
* @param inputLen the input length (in bytes)
*
* @return the required output buffer size (in bytes)
*
*/
int getOutputSize(int inputLen) {
return cipher.getOutputSize(inputLen);
}
/**
* Returns the initialization vector (IV) in a new buffer.
*
* <p> This is useful in the case where a random IV has been created
* (see <a href = "#init">init</a>),
* or in the context of password-based encryption or
* decryption, where the IV is derived from a user-supplied password.
*
* @return the initialization vector in a new buffer, or null if the
* underlying algorithm does not use an IV, or if the IV has not yet
* been set.
*/
byte[] getIV() {
return cipher.getIV();
}
/**
* Returns the parameters used with this cipher.
*
* <p>The returned parameters may be the same that were used to initialize
* this cipher, or may contain the default set of parameters or a set of
* randomly generated parameters used by the underlying cipher
* implementation (provided that the underlying cipher implementation
* uses a default set of parameters or creates new parameters if it needs
* parameters but was not initialized with any).
*
* @return the parameters used with this cipher, or null if this cipher
* does not use any parameters.
*/
AlgorithmParameters getParameters() {
AlgorithmParameters params = null;
if (salt == null) {
salt = new byte[8];
SunJCE.getRandom().nextBytes(salt);
}
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, iCount);
try {
params = AlgorithmParameters.getInstance("PBEWithMD5And" +
(algo.equalsIgnoreCase("DES")? "DES":"TripleDES"),
SunJCE.getInstance());
params.init(pbeSpec);
} catch (NoSuchAlgorithmException nsae) {
// should never happen
throw new RuntimeException("SunJCE called, but not configured");
} catch (InvalidParameterSpecException ipse) {
// should never happen
throw new RuntimeException("PBEParameterSpec not supported");
}
return params;
}
/**
* Initializes this cipher with a key, a set of
* algorithm parameters, and a source of randomness.
* The cipher is initialized for one of the following four operations:
* encryption, decryption, key wrapping or key unwrapping, depending on
* the value of <code>opmode</code>.
*
* <p>If this cipher (including its underlying feedback or padding scheme)
* requires any random bytes, it will get them from <code>random</code>.
*
* @param opmode the operation mode of this cipher (this is one of
* the following:
* <code>ENCRYPT_MODE</code>, <code>DECRYPT_MODE</code>),
* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>)
* @param key the encryption key
* @param params the algorithm parameters
* @param random the source of randomness
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher
*/
void init(int opmode, Key key, AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
if (((opmode == Cipher.DECRYPT_MODE) ||
(opmode == Cipher.UNWRAP_MODE)) && (params == null)) {
throw new InvalidAlgorithmParameterException("Parameters "
+ "missing");
}
if (key == null) {
throw new InvalidKeyException("Null key");
}
byte[] derivedKey;
byte[] passwdBytes = key.getEncoded();
try {
if ((passwdBytes == null) ||
!(key.getAlgorithm().regionMatches(true, 0, "PBE", 0, 3))) {
throw new InvalidKeyException("Missing password");
}
if (params == null) {
// create random salt and use default iteration count
salt = new byte[8];
random.nextBytes(salt);
} else {
if (!(params instanceof PBEParameterSpec)) {
throw new InvalidAlgorithmParameterException
("Wrong parameter type: PBE expected");
}
salt = ((PBEParameterSpec) params).getSalt();
// salt must be 8 bytes long (by definition)
if (salt.length != 8) {
throw new InvalidAlgorithmParameterException
("Salt must be 8 bytes long");
}
iCount = ((PBEParameterSpec) params).getIterationCount();
if (iCount <= 0) {
throw new InvalidAlgorithmParameterException
("IterationCount must be a positive number");
}
}
derivedKey = deriveCipherKey(passwdBytes);
} finally {
if (passwdBytes != null) Arrays.fill(passwdBytes, (byte) 0x00);
}
// use all but the last 8 bytes as the key value
SecretKeySpec cipherKey = new SecretKeySpec(derivedKey, 0,
derivedKey.length-8, algo);
// use the last 8 bytes as the IV
IvParameterSpec ivSpec = new IvParameterSpec(derivedKey,
derivedKey.length-8,
8);
// initialize the underlying cipher
cipher.init(opmode, cipherKey, ivSpec, random);
}
private byte[] deriveCipherKey(byte[] passwdBytes) {
byte[] result = null;
if (algo.equals("DES")) {
// P || S (password concatenated with salt)
md.update(passwdBytes);
md.update(salt);
// digest P || S with iCount iterations
// first iteration
byte[] toBeHashed = md.digest(); // this resets the digest
// remaining (iCount - 1) iterations
for (int i = 1; i < iCount; ++i) {
md.update(toBeHashed);
try {
md.digest(toBeHashed, 0, toBeHashed.length);
} catch (DigestException e) {
throw new ProviderException("Internal error", e);
}
}
result = toBeHashed;
} else if (algo.equals("DESede")) {
// if the 2 salt halves are the same, invert one of them
int i;
for (i=0; i<4; i++) {
if (salt[i] != salt[i+4])
break;
}
if (i==4) { // same, invert 1st half
for (i=0; i<2; i++) {
byte tmp = salt[i];
salt[i] = salt[3-i];
salt[3-i] = tmp;
}
}
// Now digest each half (concatenated with password). For each
// half, go through the loop as many times as specified by the
// iteration count parameter (inner for loop).
// Concatenate the output from each digest round with the
// password, and use the result as the input to the next digest
// operation.
byte[] toBeHashed = null;
result = new byte[DESedeKeySpec.DES_EDE_KEY_LEN +
DESConstants.DES_BLOCK_SIZE];
for (i = 0; i < 2; i++) {
// first iteration
md.update(salt, i * (salt.length / 2), salt.length / 2);
md.update(passwdBytes);
toBeHashed = md.digest();
// remaining (iCount - 1) iterations
for (int j = 1; j < iCount; ++j) {
md.update(toBeHashed);
md.update(passwdBytes);
try {
md.digest(toBeHashed, 0, toBeHashed.length);
} catch (DigestException e) {
throw new ProviderException("Internal error", e);
}
}
System.arraycopy(toBeHashed, 0, result, i*16,
toBeHashed.length);
}
}
// clear data used in message
md.reset();
return result;
}
void init(int opmode, Key key, AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
PBEParameterSpec pbeSpec = null;
if (params != null) {
try {
pbeSpec = params.getParameterSpec(PBEParameterSpec.class);
} catch (InvalidParameterSpecException ipse) {
throw new InvalidAlgorithmParameterException("Wrong parameter "
+ "type: PBE "
+ "expected");
}
}
init(opmode, key, pbeSpec, random);
}
/**
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, are processed, and the
* result is stored in a new buffer.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result
*
*/
byte[] update(byte[] input, int inputOffset, int inputLen) {
return cipher.update(input, inputOffset, inputLen);
}
/**
* Continues a multiple-part encryption or decryption operation
* (depending on how this cipher was initialized), processing another data
* part.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, are processed, and the
* result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code>.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
*/
int update(byte[] input, int inputOffset, int inputLen,
byte[] output, int outputOffset)
throws ShortBufferException {
return cipher.update(input, inputOffset, inputLen,
output, outputOffset);
}
/**
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, and any input bytes that
* may have been buffered during a previous <code>update</code> operation,
* are processed, with padding (if requested) being applied.
* The result is stored in a new buffer.
*
* <p>The cipher is reset to its initial state (uninitialized) after this
* call.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
*
* @return the new buffer with the result
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size
* @exception BadPaddingException if decrypting and padding is chosen,
* but the last input data does not have proper padding bytes.
*/
byte[] doFinal(byte[] input, int inputOffset, int inputLen)
throws IllegalBlockSizeException, BadPaddingException {
return cipher.doFinal(input, inputOffset, inputLen);
}
/**
* Encrypts or decrypts data in a single-part operation,
* or finishes a multiple-part operation.
* The data is encrypted or decrypted, depending on how this cipher was
* initialized.
*
* <p>The first <code>inputLen</code> bytes in the <code>input</code>
* buffer, starting at <code>inputOffset</code>, and any input bytes that
* may have been buffered during a previous <code>update</code> operation,
* are processed, with padding (if requested) being applied.
* The result is stored in the <code>output</code> buffer, starting at
* <code>outputOffset</code>.
*
* <p>The cipher is reset to its initial state (uninitialized) after this
* call.
*
* @param input the input buffer
* @param inputOffset the offset in <code>input</code> where the input
* starts
* @param inputLen the input length
* @param output the buffer for the result
* @param outputOffset the offset in <code>output</code> where the result
* is stored
*
* @return the number of bytes stored in <code>output</code>
*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size
* @exception ShortBufferException if the given output buffer is too small
* to hold the result
* @exception BadPaddingException if decrypting and padding is chosen,
* but the last input data does not have proper padding bytes.
*/
int doFinal(byte[] input, int inputOffset, int inputLen,
byte[] output, int outputOffset)
throws ShortBufferException, IllegalBlockSizeException,
BadPaddingException {
return cipher.doFinal(input, inputOffset, inputLen,
output, outputOffset);
}
/**
* Wrap a key.
*
* @param key the key to be wrapped.
*
* @return the wrapped key.
*
* @exception IllegalBlockSizeException if this cipher is a block
* cipher, no padding has been requested, and the length of the
* encoding of the key to be wrapped is not a
* multiple of the block size.
*
* @exception InvalidKeyException if it is impossible or unsafe to
* wrap the key with this cipher (e.g., a hardware protected key is
* being passed to a software only cipher).
*/
byte[] wrap(Key key)
throws IllegalBlockSizeException, InvalidKeyException {
byte[] result = null;
byte[] encodedKey = null;
try {
encodedKey = key.getEncoded();
if ((encodedKey == null) || (encodedKey.length == 0)) {
throw new InvalidKeyException("Cannot get an encoding of " +
"the key to be wrapped");
}
result = doFinal(encodedKey, 0, encodedKey.length);
} catch (BadPaddingException e) {
// Should never happen
} finally {
if (encodedKey != null) Arrays.fill(encodedKey, (byte)0x00);
}
return result;
}
/**
* Unwrap a previously wrapped key.
*
* @param wrappedKey the key to be unwrapped.
*
* @param wrappedKeyAlgorithm the algorithm the wrapped key is for.
*
* @param wrappedKeyType the type of the wrapped key.
* This is one of <code>Cipher.SECRET_KEY</code>,
* <code>Cipher.PRIVATE_KEY</code>, or <code>Cipher.PUBLIC_KEY</code>.
*
* @return the unwrapped key.
*
* @exception NoSuchAlgorithmException if no installed providers
* can create keys of type <code>wrappedKeyType</code> for the
* <code>wrappedKeyAlgorithm</code>.
*
* @exception InvalidKeyException if <code>wrappedKey</code> does not
* represent a wrapped key of type <code>wrappedKeyType</code> for
* the <code>wrappedKeyAlgorithm</code>.
*/
Key unwrap(byte[] wrappedKey,
String wrappedKeyAlgorithm,
int wrappedKeyType)
throws InvalidKeyException, NoSuchAlgorithmException {
byte[] encodedKey;
try {
encodedKey = doFinal(wrappedKey, 0, wrappedKey.length);
} catch (BadPaddingException ePadding) {
throw new InvalidKeyException("The wrapped key is not padded " +
"correctly");
} catch (IllegalBlockSizeException eBlockSize) {
throw new InvalidKeyException("The wrapped key does not have " +
"the correct length");
}
return ConstructKeys.constructKey(encodedKey, wrappedKeyAlgorithm,
wrappedKeyType);
}
}
|
package com.technicise;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for River.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="River">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="x-MRC"/>
* <enumeration value="x-MOV"/>
* <enumeration value="x-YUM"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "River")
@XmlEnum
public enum River {
@XmlEnumValue("x-MRC")
X_MRC("x-MRC"),
@XmlEnumValue("x-MOV")
X_MOV("x-MOV"),
@XmlEnumValue("x-YUM")
X_YUM("x-YUM");
private final String value;
River(String v) {
value = v;
}
public String value() {
return value;
}
public static River fromValue(String v) {
for (River c: River.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
package org.jlibsedml;
/**
* Supports the SED-ML 'Curve' element representing a trace on a 2D Plot.
*/
public class Curve extends AbstractIdentifiableElement{
@Override
public String toString() {
return "Curve [id=" + getId() + ", logX=" + logX + ", logY=" + logY
+ ", name=" + getName() + ", xDataReference=" + xDataReference
+ ", yDataReference=" + yDataReference + "]";
}
/**
* Setter for whether the x-axis of this curve is on a log scale.
* @param logX A <code>boolean</code>.
* @since 1.2.0
*/
public void setLogX(boolean logX) {
this.logX = logX;
}
/**
* Setter for whether the y-axis of this curve is on a log scale.
* @param logY A <code>boolean</code>.
* @since 1.2.0
*/
public void setLogY(boolean logY) {
this.logY = logY;
}
/**
* Setter for the x-axis data generator.
* @param xDataReference A non-null <code>String</code> that is an identifier of a {@link DataGenerator}
* element.
* @since 1.2.0
*/
public void setxDataReference(String xDataReference) {
if(SEDMLElementFactory.getInstance().isStrictCreation()){
Assert.checkNoNullArgs( xDataReference);
Assert.stringsNotEmpty( xDataReference);
}
this.xDataReference = xDataReference;
}
/**
* Setter for the y-axis data generator.
* @param yDataReference A non-null <code>String</code> that is an identifier of a {@link DataGenerator}
* element.
* @since 1.2.0
*/
public void setyDataReference(String yDataReference) {
this.yDataReference = yDataReference;
}
private boolean logX = false;
private boolean logY = false;
private String xDataReference = null; // DataGenerator.id
private String yDataReference = null; // DataGenerator.id
/**
*
* @param argId An identifier that is unique in this document.
* @param argName An optional name
* @param logX <code>boolean</code> as to whether x-axis is a log scale.
* @param logY <code>boolean</code> as to whether y-axis is a log scale.
* @param xDataReference A <code>String</code> reference to the {@link DataGenerator} for the x-axis.
* @param yDataReference A <code>String</code> reference to the {@link DataGenerator} for the y-axis.
* @throws IllegalArgumentException if any argument except <code>name</code> is null or empty.
*/
public Curve(String argId, String argName, boolean logX, boolean logY, String xDataReference, String yDataReference) {
super(argId,argName);
if(SEDMLElementFactory.getInstance().isStrictCreation()){
Assert.checkNoNullArgs(argId, logX, logY, xDataReference, yDataReference);
Assert.stringsNotEmpty(argId, xDataReference, yDataReference);
}
this.logX = logX;
this.logY = logY;
this.xDataReference = xDataReference;
this.yDataReference = yDataReference;
}
/**
* @return the reference to the {@link DataGenerator} for the x-axis
*/
public String getXDataReference() {
return xDataReference;
}
/**
* @return the reference to the {@link DataGenerator} for the y-axis
*/
public String getYDataReference() {
return yDataReference;
}
/**
* @return <code>true</code> if the x-axis is a log scale, <code>false</code> otherwise.
*/
public boolean getLogX() {
return logX;
}
/**
* @return <code>true</code> if the y-axis is a log scale, <code>false</code> otherwise.
*/
public boolean getLogY() {
return logY;
}
@Override
public String getElementName() {
return SEDMLTags.OUTPUT_CURVE;
}
public boolean accept(SEDMLVisitor visitor) {
return visitor.visit(this);
}
}
|
/**
* GetBudgetsByIdsResponse.java
* <p>
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.microsoft.bingads.v11.campaignmanagement;
public class GetBudgetsByIdsResponse implements java.io.Serializable {
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(GetBudgetsByIdsResponse.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v11", ">GetBudgetsByIdsResponse"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("budgets");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v11", "Budgets"));
elemField.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v11", "Budget"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
elemField.setItemQName(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v11", "Budget"));
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("partialErrors");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v11", "PartialErrors"));
elemField.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v11", "BatchError"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
elemField.setItemQName(new javax.xml.namespace.QName("https://bingads.microsoft.com/CampaignManagement/v11", "BatchError"));
typeDesc.addFieldDesc(elemField);
}
private com.microsoft.bingads.v11.campaignmanagement.Budget[] budgets;
private com.microsoft.bingads.v11.campaignmanagement.BatchError[] partialErrors;
private java.lang.Object __equalsCalc = null;
private boolean __hashCodeCalc = false;
public GetBudgetsByIdsResponse() {
}
public GetBudgetsByIdsResponse(
com.microsoft.bingads.v11.campaignmanagement.Budget[] budgets,
com.microsoft.bingads.v11.campaignmanagement.BatchError[] partialErrors) {
this.budgets = budgets;
this.partialErrors = partialErrors;
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
/**
* Gets the budgets value for this GetBudgetsByIdsResponse.
*
* @return budgets
*/
public com.microsoft.bingads.v11.campaignmanagement.Budget[] getBudgets() {
return budgets;
}
/**
* Sets the budgets value for this GetBudgetsByIdsResponse.
*
* @param budgets
*/
public void setBudgets(com.microsoft.bingads.v11.campaignmanagement.Budget[] budgets) {
this.budgets = budgets;
}
/**
* Gets the partialErrors value for this GetBudgetsByIdsResponse.
*
* @return partialErrors
*/
public com.microsoft.bingads.v11.campaignmanagement.BatchError[] getPartialErrors() {
return partialErrors;
}
/**
* Sets the partialErrors value for this GetBudgetsByIdsResponse.
*
* @param partialErrors
*/
public void setPartialErrors(com.microsoft.bingads.v11.campaignmanagement.BatchError[] partialErrors) {
this.partialErrors = partialErrors;
}
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof GetBudgetsByIdsResponse)) return false;
GetBudgetsByIdsResponse other = (GetBudgetsByIdsResponse) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.budgets == null && other.getBudgets() == null) ||
(this.budgets != null &&
java.util.Arrays.equals(this.budgets, other.getBudgets()))) &&
((this.partialErrors == null && other.getPartialErrors() == null) ||
(this.partialErrors != null &&
java.util.Arrays.equals(this.partialErrors, other.getPartialErrors())));
__equalsCalc = null;
return _equals;
}
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getBudgets() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getBudgets());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getBudgets(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getPartialErrors() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getPartialErrors());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getPartialErrors(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
}
|
package com.mill.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import com.mill.storager.SharedPreferencesImpl;
import java.util.Map;
import java.util.Set;
public class SPUtils {
private static final String TAG = "SPUtils";
private static final String MAIN_PROC_NAME = "com.mill";
/**
* 保存在手机里面的文件名o
*/
private static final String FILE_NAME = "share_data";
/**
* 暴露一个由外部传入editor 的方法
*/
public static void applyEditor(Editor editor) {
editor.apply();
}
/**
* 非主进程调用请使用带文件名参数的方法
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*/
public static void put(String key, Object object) {
put(ContextUtils.getApplicationContext(), key, object);
}
/**
* 非主进程调用请使用带文件名参数的方法
*/
public static void put(Context context, String key, Object object) {
put(FILE_NAME, context, key, object);
}
public static void put(String fileName, Context context, String key, Object object) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(fileName),
Context.MODE_PRIVATE);
Editor editor = sp.edit();
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
editor.putFloat(key, (Float) object);
} else if (object instanceof Long) {
editor.putLong(key, (Long) object);
} else if (object instanceof Set) {
editor.putStringSet(key, (Set) object);
} else if (object == null) {
editor.remove(key);
}
editor.apply();
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*/
public static Object get(String key, Object defaultObject) {
return get(ContextUtils.getApplicationContext(), key, defaultObject);
}
public static Object get(Context context, String key, Object defaultObject) {
return get(FILE_NAME, context, key, defaultObject);
}
public static Object get(String fileName, Context context, String key, Object defaultObject) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(fileName),
Context.MODE_PRIVATE);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
} else if (defaultObject instanceof Set) {
return sp.getStringSet(key, (Set) defaultObject);
} else if (null == defaultObject) {
return sp.getString(key, null);
}
return null;
}
public static String getString(String fileName, Context context, String key, String defValue) {
return (String) get(fileName, context, key, defValue);
}
public static void setString(String fileName, Context context, String key, String value) {
put(fileName, context, key, value);
}
public static int getInt(String fileName, Context context, String key, int defValue) {
return (int) get(fileName, context, key, defValue);
}
public static void setInt(String fileName, Context context, String key, int value) {
put(fileName, context, key, value);
}
public static long getLong(String fileName, Context context, String key, long defValue) {
Object val = get(fileName, context, key, defValue);
long ret = 0;
if (val != null) {
if (val instanceof Long) {
ret = (long) val;
} else {
// CrashHandler.getInstance().tryCatch(new RuntimeException(), "getLong_" + val);
}
}
return ret;
}
public static void setLong(String fileName, Context context, String key, long value) {
put(fileName, context, key, value);
}
public static boolean getBoolean(String fileName, Context context, String key, boolean defValue) {
return (boolean) get(fileName, context, key, defValue);
}
public static void setBoolean(String fileName, Context context, String key, boolean value) {
put(fileName, context, key, value);
}
public static float getFloat(String fileName, Context context, String key, float defValue) {
return (float) get(fileName, context, key, defValue);
}
public static void setFloat(String fileName, Context context, String key, float value) {
put(fileName, context, key, value);
}
public static Set<String> getSet(String fileName, Context context, String key, Set<String> defValue) {
return (Set<String>) get(fileName, context, key, defValue);
}
public static void setSet(String fileName, Context context, String key, Set<String> value) {
put(fileName, context, key, value);
}
/**
* 移除某个key值已经对应的值
*/
public static void remove(String key) {
remove(ContextUtils.getApplicationContext(), key);
}
public static void remove(Context context, String key) {
remove(FILE_NAME, context, key);
}
public static void remove(String fileName, Context context, String key) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(fileName),
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.remove(key);
editor.apply();
}
/**
* 清除所有数据
*/
public static void clear(Context context) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(),
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.clear();
editor.apply();
}
public static void clear(Context context, String fileName) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(fileName),
Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.clear();
editor.apply();
}
/**
* 查询某个key是否已经存在
*/
public static boolean contains(String key) {
return contains(ContextUtils.getApplicationContext(), key);
}
public static boolean contains(Context context, String key) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(),
Context.MODE_PRIVATE);
return sp.contains(key);
}
public static boolean contains(Context context, String fileName, String key) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(fileName),
Context.MODE_PRIVATE);
return sp.contains(key);
}
/**
* 返回所有的键值对
*/
public static Map<String, ?> getAll(Context context) {
return getAll(context, FILE_NAME);
}
public static Map<String, ?> getAll(Context context, String fileName) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(fileName),
Context.MODE_PRIVATE);
return sp.getAll();
}
public static boolean clearKey(Context context, String fileName, String key) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(fileName),
Context.MODE_PRIVATE);
sp.edit().remove(key).apply();
return true;
}
public static Editor getEditor(String fileName, Context context) {
SharedPreferences sp = SharedPreferencesImpl.getSharedPreferences(context, getFileName(fileName),
Context.MODE_PRIVATE);
return sp.edit();
}
private static String getFileName(String fileName) {
if (TextUtils.isEmpty(fileName) || FILE_NAME.equals(fileName)) {
return getFileName();
}
return fileName;
}
private static String getFileName() {
// String procName = ProcessUtils.getCurrentProcessName();
// LogUtils.safeCheck(!TextUtils.isEmpty(procName));
// if(!TextUtils.isEmpty(procName) && !MAIN_PROC_NAME.equals(procName)){
// StringBuilder stringBuilder = new StringBuilder(FILE_NAME);
// stringBuilder.append("_").append(procName);
// return stringBuilder.toString();
// }
return FILE_NAME;
}
}
|
package exceptions;
/**
* <pre>
* author : wangzhichao
* e-mail : wangzhichao@adups.com
* time : 2019/08/21
* desc :
* version: 1.0
* </pre>
*/
class MyException2 extends Exception {
private int x;
public MyException2() {
}
public MyException2(String msg) {
super(msg);
}
public MyException2(String msg, int x) {
super(msg);
this.x = x;
}
public int val() {
return x;
}
public String getMessage() {
return "Detail Message: " + x + " " + super.getMessage();
}
}
public class ExtraFeatures {
static void f() throws MyException2 {
System.out.println("Throwing MyException2 from f()");
throw new MyException2();
}
static void g() throws MyException2 {
System.out.println("Throwing MyException2 from g()");
throw new MyException2("Originated in g()");
}
static void h() throws MyException2 {
System.out.println("Throwing MyException2 from h()");
throw new MyException2("Originated in h()",47);
}
public static void main(String[] args) {
try {
f();
} catch (MyException2 e) {
e.printStackTrace(System.out);
}
try {
g();
} catch (MyException2 e) {
e.printStackTrace(System.out);
}
try {
h();
} catch (MyException2 e) {
e.printStackTrace(System.out);
System.out.println("e.val() = " + e.val());
}
}
}
|
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.javarosa.core.model.data.DateData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.odk.collect.android.R;
import org.odk.collect.android.utilities.DateTimeUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Date;
import timber.log.Timber;
import static android.content.Context.ACCESSIBILITY_SERVICE;
/**
* Displays a DatePicker widget. DateWidget handles leap years and does not allow dates that do not
* exist.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
@SuppressLint("ViewConstructor")
public class DateWidget extends QuestionWidget implements DatePickerDialog.OnDateSetListener {
private DatePickerDialog datePickerDialog;
private Button dateButton;
private TextView dateTextView;
private boolean hideDay;
private boolean hideMonth;
private boolean showCalendar;
private int year;
private int month;
private int dayOfMonth;
private boolean nullAnswer;
public DateWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
setGravity(Gravity.START);
readAppearance();
createDateButton();
dateTextView = getAnswerTextView();
createDatePickerDialog();
hideDayFieldIfNotInFormat();
addViews();
}
private void readAppearance() {
String appearance = formEntryPrompt.getQuestion().getAppearanceAttr();
if ("month-year".equals(appearance)) {
hideDay = true;
} else if ("year".equals(appearance)) {
hideDay = true;
hideMonth = true;
} else if (!"no-calendar".equals(appearance)) {
showCalendar = true;
}
}
private void hideDayFieldIfNotInFormat() {
if (hideDay) {
datePickerDialog.getDatePicker().findViewById(
Resources.getSystem().getIdentifier("day", "id", "android"))
.setVisibility(View.GONE);
}
if (hideMonth) {
datePickerDialog.getDatePicker().findViewById(
Resources.getSystem().getIdentifier("month", "id", "android"))
.setVisibility(View.GONE);
}
}
@Override
public void clearAnswer() {
nullAnswer = true;
dateTextView.setText(R.string.no_date_selected);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
if (nullAnswer) {
return null;
} else {
// This is LDT but TimeWidget is just DT. Seems like we should make these consistent.
LocalDateTime ldt = new LocalDateTime()
.withYear(year)
.withMonthOfYear(hideMonth ? 1 : month)
.withDayOfMonth((hideMonth || hideDay) ? 1 : dayOfMonth)
.withHourOfDay(0)
.withMinuteOfHour(0);
return new DateData(ldt.toDate());
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
dateButton.setOnLongClickListener(l);
dateTextView.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
dateButton.cancelLongPress();
dateTextView.cancelLongPress();
}
private void createDateButton() {
dateButton = getSimpleButton(getContext().getString(R.string.select_date));
dateButton.setEnabled(!formEntryPrompt.isReadOnly());
dateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (nullAnswer) {
setDateToCurrent();
} else {
updateDate(year, month, dayOfMonth, true);
}
datePickerDialog.show();
}
});
}
private void addViews() {
LinearLayout linearLayout = new LinearLayout(getContext());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(dateButton);
linearLayout.addView(dateTextView);
addAnswerView(linearLayout);
}
public void setDateLabel() {
nullAnswer = false;
dateTextView.setText(DateTimeUtils.getDateTimeBasedOnUserLocale(
(Date) getAnswer().getValue(), formEntryPrompt.getQuestion().getAppearanceAttr(), false));
}
private int getTheme() {
int theme = 0;
// https://github.com/opendatakit/collect/issues/1424
// https://github.com/opendatakit/collect/issues/1367
if (!isBrokenSamsungDevice() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
theme = android.R.style.Theme_Material_Light_Dialog;
}
if (!showCalendar || (isBrokenSamsungDevice() && isTalkBackActive())) {
theme = android.R.style.Theme_Holo_Light_Dialog;
}
return theme;
}
private void createDatePickerDialog() {
datePickerDialog = new CustomDatePickerDialog(getContext(), getTheme(), this, 1971, 1, 1); // placeholder date that is valid
datePickerDialog.setCanceledOnTouchOutside(false);
if (formEntryPrompt.getAnswerValue() == null) {
clearAnswer();
} else {
Date date = (Date) formEntryPrompt.getAnswerValue().getValue();
// This is LDT but TimeWidget is just DT, why?:
LocalDateTime localDateTime = new LocalDateTime(date);
updateDate(localDateTime.getYear(), localDateTime.getMonthOfYear(), localDateTime.getDayOfMonth(), true);
}
}
// https://stackoverflow.com/questions/28618405/datepicker-crashes-on-my-device-when-clicked-with-personal-app
private boolean isBrokenSamsungDevice() {
return (Build.MANUFACTURER.equalsIgnoreCase("samsung")
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
&& Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1);
}
// https://stackoverflow.com/a/34853067/5479029
private boolean isTalkBackActive() {
return ((AccessibilityManager) getContext().getSystemService(ACCESSIBILITY_SERVICE)).isTouchExplorationEnabled();
}
public boolean isDayHidden() {
return hideDay;
}
public boolean isMonthHidden() {
return hideMonth;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return dayOfMonth;
}
public boolean isNullAnswer() {
return nullAnswer;
}
public void setDateToCurrent() {
updateDate(DateTime.now(), false);
}
public void updateDate(DateTime dateTime) {
updateDate(dateTime, true);
}
public void updateDate(DateTime dateTime, boolean shouldUpdateLabel) {
updateDate(dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth(), shouldUpdateLabel);
}
public void updateDate(int year, int month, int dayOfMonth, boolean shouldUpdateLabel) {
this.year = year;
this.month = month;
this.dayOfMonth = dayOfMonth;
datePickerDialog.updateDate(year, month - 1, dayOfMonth);
if (shouldUpdateLabel) {
setDateLabel();
}
}
// Exposed for testing purposes to avoid reflection.
public void setDatePickerDialog(DatePickerDialog datePickerDialog) {
this.datePickerDialog = datePickerDialog;
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
this.year = year;
this.month = month + 1;
this.dayOfMonth = dayOfMonth;
setDateLabel();
}
private class CustomDatePickerDialog extends DatePickerDialog {
private String dialogTitle = getContext().getString(R.string.select_date);
private int theme;
CustomDatePickerDialog(Context context, int theme, OnDateSetListener listener, int year, int month, int dayOfMonth) {
super(context, theme, listener, year, month, dayOfMonth);
this.theme = theme;
if (theme == android.R.style.Theme_Holo_Light_Dialog) {
setTitle(dialogTitle);
fixSpinner(context, year, month, dayOfMonth);
Window window = getWindow();
if (window != null) {
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
//noinspection deprecation
getDatePicker().setCalendarViewShown(false);
}
}
public void setTitle(CharSequence title) {
if (theme == android.R.style.Theme_Holo_Light_Dialog) {
super.setTitle(dialogTitle);
}
}
/**
* Workaround for this bug: https://code.google.com/p/android/issues/detail?id=222208
* In Android 7.0 Nougat, spinner mode for the DatePicker in DatePickerDialog is
* incorrectly displayed as calendar, even when the theme specifies otherwise.
* <p>
* Source: https://gist.github.com/jeffdgr8/6bc5f990bf0c13a7334ce385d482af9f
*/
private void fixSpinner(Context context, int year, int month, int dayOfMonth) {
// The spinner vs not distinction probably started in lollipop but applying this
// for versions < nougat leads to a crash trying to get DatePickerSpinnerDelegate
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
try {
// Get the theme's android:datePickerMode
final int MODE_SPINNER = 2;
Class<?> styleableClass = Class.forName("com.android.internal.R$styleable");
Field datePickerStyleableField = styleableClass.getField("DatePicker");
int[] datePickerStyleable = (int[]) datePickerStyleableField.get(null);
final TypedArray a = context.obtainStyledAttributes(null, datePickerStyleable,
android.R.attr.datePickerStyle, 0);
Field datePickerModeStyleableField = styleableClass.getField("DatePicker_datePickerMode");
int datePickerModeStyleable = datePickerModeStyleableField.getInt(null);
final int mode = a.getInt(datePickerModeStyleable, MODE_SPINNER);
a.recycle();
if (mode == MODE_SPINNER) {
Field datePickerField = findField(DatePickerDialog.class,
DatePicker.class, "mDatePicker");
if (datePickerField == null) {
Timber.w("Reflection failed: couldn't find 'mDatePicker' field on DatePickerDialog.");
return;
}
DatePicker datePicker = (DatePicker) datePickerField.get(this);
Class<?> delegateClass = Class.forName("android.widget.DatePicker$DatePickerDelegate");
Field delegateField = findField(DatePicker.class, delegateClass, "mDelegate");
if (delegateField == null) {
Timber.w("Reflection failed: couldn't find 'mDelegate' field on DatePickerDialog.");
return;
}
Object delegate = delegateField.get(datePicker);
Class<?> spinnerDelegateClass = Class.forName("android.widget.DatePickerSpinnerDelegate");
// In 7.0 Nougat for some reason the datePickerMode is ignored and the
// delegate is DatePickerCalendarDelegate
if (delegate.getClass() != spinnerDelegateClass) {
delegateField.set(datePicker, null); // throw out the DatePickerCalendarDelegate!
datePicker.removeAllViews(); // remove the DatePickerCalendarDelegate views
Constructor spinnerDelegateConstructor = spinnerDelegateClass
.getDeclaredConstructor(DatePicker.class, Context.class,
AttributeSet.class, int.class, int.class);
spinnerDelegateConstructor.setAccessible(true);
// Instantiate a DatePickerSpinnerDelegate
delegate = spinnerDelegateConstructor.newInstance(datePicker, context,
null, android.R.attr.datePickerStyle, 0);
// set the DatePicker.mDelegate to the spinner delegate
delegateField.set(datePicker, delegate);
// Set up the DatePicker again, with the DatePickerSpinnerDelegate
datePicker.updateDate(year, month, dayOfMonth);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private Field findField(Class objectClass, Class fieldClass, String expectedName) {
try {
Field field = objectClass.getDeclaredField(expectedName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
Timber.i(e); // ignore
}
// search for it if it wasn't found under the expected ivar name
for (Field searchField : objectClass.getDeclaredFields()) {
if (searchField.getType() == fieldClass) {
searchField.setAccessible(true);
return searchField;
}
}
return null;
}
}
}
|
/**
* 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
* <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.apache.activemq.artemis.tests.integration.amqp;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.utils.Wait;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
public class TopicDurableTests extends JMSClientTestSupport {
@Override
protected void addConfiguration(ActiveMQServer server) {
server.getConfiguration().setAddressQueueScanPeriod(100);
}
@Test
public void testMessageDurableSubscription() throws Exception {
JmsConnectionFactory connectionFactory = new JmsConnectionFactory(getBrokerQpidJMSConnectionURI() + "?jms.clientID=jmsTopicClient");
Connection connection = connectionFactory.createConnection();
connection.start();
instanceLog.debug("testMessageDurableSubscription");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic testTopic = session.createTopic("jmsTopic");
String sub1ID = "sub1DurSub";
String sub2ID = "sub2DurSub";
MessageConsumer subscriber1 = session.createDurableSubscriber(testTopic, sub1ID);
MessageConsumer subscriber2 = session.createDurableSubscriber(testTopic, sub2ID);
MessageProducer messageProducer = session.createProducer(testTopic);
int count = 100;
String batchPrefix = "First";
List<Message> listMsgs = generateMessages(session, batchPrefix, count);
sendMessages(messageProducer, listMsgs);
instanceLog.debug("First batch messages sent");
List<Message> recvd1 = receiveMessages(subscriber1, count);
List<Message> recvd2 = receiveMessages(subscriber2, count);
assertThat(recvd1.size(), is(count));
assertMessageContent(recvd1, batchPrefix);
instanceLog.debug(sub1ID + " :First batch messages received");
assertThat(recvd2.size(), is(count));
assertMessageContent(recvd2, batchPrefix);
instanceLog.debug(sub2ID + " :First batch messages received");
subscriber1.close();
instanceLog.debug(sub1ID + " : closed");
batchPrefix = "Second";
listMsgs = generateMessages(session, batchPrefix, count);
sendMessages(messageProducer, listMsgs);
instanceLog.debug("Second batch messages sent");
recvd2 = receiveMessages(subscriber2, count);
assertThat(recvd2.size(), is(count));
assertMessageContent(recvd2, batchPrefix);
instanceLog.debug(sub2ID + " :Second batch messages received");
subscriber1 = session.createDurableSubscriber(testTopic, sub1ID);
instanceLog.debug(sub1ID + " :connected");
recvd1 = receiveMessages(subscriber1, count);
assertThat(recvd1.size(), is(count));
assertMessageContent(recvd1, batchPrefix);
instanceLog.debug(sub1ID + " :Second batch messages received");
subscriber1.close();
subscriber2.close();
session.unsubscribe(sub1ID);
session.unsubscribe(sub2ID);
}
@Test
public void testSharedNonDurableSubscription() throws Exception {
int iterations = 10;
for (int i = 0; i < iterations; i++) {
instanceLog.debug("testSharedNonDurableSubscription; iteration: " + i);
//SETUP-START
JmsConnectionFactory connectionFactory1 = new JmsConnectionFactory(getBrokerQpidJMSConnectionURI());
Connection connection1 = connectionFactory1.createConnection();
Hashtable env2 = new Hashtable<Object, Object>();
env2.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
env2.put("connectionfactory.qpidConnectionFactory", "amqp://localhost:5672");
env2.put("topic." + "jmsTopic", "jmsTopic");
Context context2 = new InitialContext(env2);
ConnectionFactory connectionFactory2 = (ConnectionFactory) context2.lookup("qpidConnectionFactory");
Connection connection2 = connectionFactory2.createConnection();
connection1.start();
connection2.start();
Session session = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic testTopic = session.createTopic("jmsTopic");
//SETUP-END
//BODY-S
String subID = "sharedConsumerNonDurable123";
MessageConsumer subscriber1 = session.createSharedConsumer(testTopic, subID);
MessageConsumer subscriber2 = session2.createSharedConsumer(testTopic, subID);
MessageConsumer subscriber3 = session2.createSharedConsumer(testTopic, subID);
MessageProducer messageProducer = session.createProducer(testTopic);
messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
int count = 10;
List<Message> listMsgs = generateMessages(session, count);
List<CompletableFuture<List<Message>>> results = receiveMessagesAsync(count, subscriber1, subscriber2, subscriber3);
sendMessages(messageProducer, listMsgs);
instanceLog.debug("messages sent");
assertThat("Each message should be received only by one consumer",
results.get(0).get(20, TimeUnit.SECONDS).size() +
results.get(1).get(20, TimeUnit.SECONDS).size() +
results.get(2).get(20, TimeUnit.SECONDS).size(),
is(count));
instanceLog.debug("messages received");
//BODY-E
//TEAR-DOWN-S
connection1.stop();
connection2.stop();
subscriber1.close();
subscriber2.close();
session.close();
session2.close();
connection1.close();
connection2.close();
//TEAR-DOWN-E
// ensure the topic is auto-deleted before continuing to the next iteration
Wait.assertTrue(() -> server.getAddressInfo(SimpleString.toSimpleString("jmsTopic")) == null, 2000, 100);
}
}
private void sendMessages(MessageProducer producer, List<Message> messages) {
messages.forEach(m -> {
try {
producer.send(m);
} catch (JMSException e) {
e.printStackTrace();
}
});
}
protected List<Message> receiveMessages(MessageConsumer consumer, int count) {
return receiveMessages(consumer, count, 0);
}
protected List<Message> receiveMessages(MessageConsumer consumer, int count, long timeout) {
List<Message> recvd = new ArrayList<>();
IntStream.range(0, count).forEach(i -> {
try {
recvd.add(timeout > 0 ? consumer.receive(timeout) : consumer.receive());
} catch (JMSException e) {
e.printStackTrace();
}
});
return recvd;
}
protected void assertMessageContent(List<Message> msgs, String content) {
msgs.forEach(m -> {
try {
assertTrue(((TextMessage) m).getText().contains(content));
} catch (JMSException e) {
e.printStackTrace();
}
});
}
protected List<Message> generateMessages(Session session, int count) {
return generateMessages(session, "", count);
}
protected List<Message> generateMessages(Session session, String prefix, int count) {
List<Message> messages = new ArrayList<>();
StringBuilder sb = new StringBuilder();
IntStream.range(0, count).forEach(i -> {
try {
messages.add(session.createTextMessage(sb.append(prefix).append("testMessage").append(i).toString()));
sb.setLength(0);
} catch (JMSException e) {
e.printStackTrace();
}
});
return messages;
}
protected List<CompletableFuture<List<Message>>> receiveMessagesAsync(int count, MessageConsumer... consumer) throws JMSException {
AtomicInteger totalCount = new AtomicInteger(count);
List<CompletableFuture<List<Message>>> resultsList = new ArrayList<>();
List<List<Message>> receivedResList = new ArrayList<>();
for (int i = 0; i < consumer.length; i++) {
final int index = i;
resultsList.add(new CompletableFuture<>());
receivedResList.add(new ArrayList<>());
MessageListener myListener = message -> {
instanceLog.debug("Mesages received" + message + " count: " + totalCount.get());
receivedResList.get(index).add(message);
if (totalCount.decrementAndGet() == 0) {
for (int j = 0; j < consumer.length; j++) {
resultsList.get(j).complete(receivedResList.get(j));
}
}
};
consumer[i].setMessageListener(myListener);
}
return resultsList;
}
}
|
package io.micronaut.inject.qualifiers.replaces.defaultimpl;
import io.micronaut.context.annotation.DefaultImplementation;
@DefaultImplementation(F1.class)
public interface F extends E {
}
|
/*
* Copyright (C) 2017 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.exec.store.parquet;
import static java.util.Arrays.asList;
import org.junit.Ignore;
import org.junit.Test;
import com.dremio.BaseTestQuery;
import com.dremio.TestBuilder;
import com.dremio.exec.ExecConstants;
public class TestParquetComplex extends BaseTestQuery {
private static final String DATAFILE = "cp.`store/parquet/complex/complex.parquet`";
@Test
public void sort() throws Exception {
String query = String.format("select * from %s order by amount", DATAFILE);
testBuilder()
.sqlQuery(query)
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline_sorted.json")
.build()
.run();
}
@Test
public void topN() throws Exception {
String query = String.format("select * from %s order by amount limit 5", DATAFILE);
testBuilder()
.sqlQuery(query)
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline_sorted.json")
.build()
.run();
}
@Test
public void hashJoin() throws Exception{
String query = String.format("select t1.amount, t1.`date`, t1.marketing_info, t1.`time`, t1.trans_id, t1.trans_info, t1.user_info " +
"from %s t1, %s t2 where t1.amount = t2.amount", DATAFILE, DATAFILE);
testBuilder()
.sqlQuery(query)
.unOrdered()
.jsonBaselineFile("store/parquet/complex/baseline.json")
.build()
.run();
}
@Test
public void filterNonComplexColumn() throws Exception {
// default batch size
runFilterNonComplexColumn();
// with different batch sizes
for(Long batchSize : asList(2L, 1L, 3L, 5L)) {
try (AutoCloseable op1 = withOption(ExecConstants.TARGET_BATCH_RECORDS_MIN, batchSize);
AutoCloseable op2 = withOption(ExecConstants.TARGET_BATCH_RECORDS_MAX, batchSize)) {
runFilterNonComplexColumn();
}
}
}
private void runFilterNonComplexColumn() throws Exception {
String query = String.format("select t1.user_info.cust_id as cust_id from %s t1 where t1.trans_id > 0 and " +
"t1.trans_id < 4",
DATAFILE);
TestBuilder builder = testBuilder()
.sqlQuery(query)
.unOrdered()
.jsonBaselineFile("store/parquet/complex/baseline.json")
.baselineColumns("cust_id");
builder.baselineValues(86623L)
.baselineValues(11L)
.baselineValues(666L).build().run();
}
@Ignore("DX-3852")
@Test
public void mergeJoin() throws Exception{
test("alter session set `planner.enable_hashjoin` = false");
String query = String.format("select t1.amount, t1.`date`, t1.marketing_info, t1.`time`, t1.trans_id, t1.trans_info, t1.user_info " +
"from %s t1, %s t2 where t1.amount = t2.amount", DATAFILE, DATAFILE);
testBuilder()
.sqlQuery(query)
.unOrdered()
.jsonBaselineFile("store/parquet/complex/baseline.json")
.build()
.run();
}
@Test
public void selectAllColumns() throws Exception {
String query = String.format("select amount, `date`, marketing_info, `time`, trans_id, trans_info, user_info from %s", DATAFILE);
testBuilder()
.sqlQuery(query)
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline.json")
.build()
.run();
}
@Test
public void q() throws Exception {
test("select p.marketing_info from cp.`store/parquet/complex/complex.parquet` p");
}
@Test
public void selectMap() throws Exception {
String query = "select marketing_info from cp.`store/parquet/complex/complex.parquet`";
testBuilder()
.sqlQuery(query)
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline5.json")
.build()
.run();
}
@Test
public void selectMapAndElements() throws Exception {
String query = "select marketing_info, t.marketing_info.camp_id as camp_id, t.marketing_info.keywords[2] as keyword2 from cp.`store/parquet/complex/complex.parquet` t";
testBuilder()
.sqlQuery(query)
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline6.json")
.build()
.run();
}
@Test
public void selectMultiElements() throws Exception {
String query = "select t.marketing_info.camp_id as camp_id, t.marketing_info.keywords as keywords from cp.`store/parquet/complex/complex.parquet` t";
testBuilder()
.sqlQuery(query)
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline7.json")
.build()
.run();
}
@Test
public void testStar() throws Exception {
testBuilder()
.sqlQuery("select * from cp.`store/parquet/complex/complex.parquet`")
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline.json")
.build()
.run();
}
@Test
@Ignore
public void missingColumnInMap() throws Exception {
String query = "select t.trans_info.keywords as keywords from cp.`store/parquet/complex/complex.parquet` t";
String[] columns = {"keywords"};
testBuilder()
.sqlQuery(query)
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline2.json")
.baselineColumns(columns)
.build()
.run();
}
@Test
public void secondElementInMap() throws Exception {
String query = String.format("select t.`marketing_info`.keywords as keywords from %s t", DATAFILE);
String[] columns = {"keywords"};
testBuilder()
.sqlQuery(query)
.ordered()
.jsonBaselineFile("store/parquet/complex/baseline3.json")
.baselineColumns(columns)
.build()
.run();
}
@Test
public void elementsOfArray() throws Exception {
String query = String.format("select t.`marketing_info`.keywords[0] as keyword0, t.`marketing_info`.keywords[2] as keyword2 from %s t", DATAFILE);
String[] columns = {"keyword0", "keyword2"};
testBuilder()
.sqlQuery(query)
.unOrdered()
.jsonBaselineFile("store/parquet/complex/baseline4.json")
.baselineColumns(columns)
.build()
.run();
}
@Test
public void elementsOfArrayCaseInsensitive() throws Exception {
String query = String.format("select t.`MARKETING_INFO`.keywords[0] as keyword0, t.`Marketing_Info`.Keywords[2] as keyword2 from %s t", DATAFILE);
String[] columns = {"keyword0", "keyword2"};
testBuilder()
.sqlQuery(query)
.unOrdered()
.jsonBaselineFile("store/parquet/complex/baseline4.json")
.baselineColumns(columns)
.build()
.run();
}
@Test //DRILL-3533
@Ignore("json null type")
public void notxistsField() throws Exception {
String query = String.format("select t.`marketing_info`.notexists as notexists, t.`marketing_info`.camp_id as id from %s t", DATAFILE);
String[] columns = {"notexists", "id"};
testBuilder()
.sqlQuery(query)
.unOrdered()
.jsonBaselineFile("store/parquet/complex/baseline8.json")
.baselineColumns(columns)
.build()
.run();
}
/**
* Test to confirm we can read repeated maps. The parquet file has the following schema:
* <pre>
* message root {
* repeated group rep_map {
* optional binary str1 (UTF8);
* optional binary str2 (UTF8);
* ...
* }
* }
* </pre>
*/
@Test
public void testLegacyRepeatedMap() throws Exception {
final String query = "SELECT sub.fmap.str1 as str FROM (" +
"SELECT flatten(t.rep_map) fmap FROM cp.`/parquet/alltypes-repeated.parquet` t) sub";
testBuilder()
.unOrdered()
.sqlQuery(query)
.baselineColumns("str")
.baselineValues("1xJmosVH6baysHAmuhGitWQwX")
.baselineValues("OOOkN1rz5K0HmTdlpFLVXoJwr")
.go();
}
}
|
/*
* 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.ignite.internal.binary;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.ignite.IgniteBinary;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.binary.BinaryObject;
import org.apache.ignite.binary.BinaryObjectBuilder;
import org.apache.ignite.binary.BinaryObjectException;
import org.apache.ignite.binary.BinaryType;
import org.apache.ignite.configuration.BinaryConfiguration;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.MarshallerPlatformIds;
import org.apache.ignite.internal.binary.builder.BinaryBuilderEnum;
import org.apache.ignite.internal.binary.builder.BinaryObjectBuilderImpl;
import org.apache.ignite.internal.binary.mutabletest.GridBinaryMarshalerAwareTestClass;
import org.apache.ignite.internal.binary.mutabletest.GridBinaryTestClasses;
import org.apache.ignite.internal.binary.test.GridBinaryTestClass2;
import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl;
import org.apache.ignite.internal.processors.cache.binary.IgniteBinaryImpl;
import org.apache.ignite.internal.util.lang.GridMapEntry;
import org.apache.ignite.marshaller.MarshallerContext;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Assert;
import org.junit.Test;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheMode.REPLICATED;
/**
*
*/
public class BinaryObjectBuilderAdditionalSelfTest extends GridCommonAbstractTest {
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
CacheConfiguration cacheCfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
cacheCfg.setCacheMode(REPLICATED);
CacheConfiguration cacheCfg2 = new CacheConfiguration("partitioned");
cacheCfg2.setCacheMode(PARTITIONED);
cfg.setCacheConfiguration(cacheCfg, cacheCfg2);
BinaryConfiguration bCfg = new BinaryConfiguration();
bCfg.setCompactFooter(compactFooter());
bCfg.setClassNames(Arrays.asList("org.apache.ignite.internal.binary.mutabletest.*"));
cfg.setMarshaller(new BinaryMarshaller());
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
startGrids(1);
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
jcache(0).clear();
}
/**
* @return Compact footer.
*/
protected boolean compactFooter() {
return true;
}
/**
* @return Binaries API.
*/
protected IgniteBinary binaries() {
return grid(0).binary();
}
/**
* @throws Exception If failed.
*/
@Test
public void testSimpleTypeFieldRead() throws Exception {
GridBinaryTestClasses.TestObjectAllTypes exp = new GridBinaryTestClasses.TestObjectAllTypes();
exp.setDefaultData();
BinaryObjectBuilder mutPo = wrap(exp);
for (Field field : GridBinaryTestClasses.TestObjectAllTypes.class.getDeclaredFields()) {
Object expVal = field.get(exp);
Object actVal = mutPo.getField(field.getName());
switch (field.getName()) {
case "anEnum":
assertEquals(((BinaryBuilderEnum)actVal).getOrdinal(), ((Enum)expVal).ordinal());
break;
case "enumArr": {
BinaryBuilderEnum[] actArr = (BinaryBuilderEnum[])actVal;
Enum[] expArr = (Enum[])expVal;
assertEquals(expArr.length, actArr.length);
for (int i = 0; i < actArr.length; i++)
assertEquals(expArr[i].ordinal(), actArr[i].getOrdinal());
break;
}
}
}
}
/**
*
*/
@Test
public void testSimpleTypeFieldSerialize() {
GridBinaryTestClasses.TestObjectAllTypes exp = new GridBinaryTestClasses.TestObjectAllTypes();
exp.setDefaultData();
BinaryObjectBuilderImpl mutPo = wrap(exp);
GridBinaryTestClasses.TestObjectAllTypes res = mutPo.build().deserialize();
GridTestUtils.deepEquals(exp, res);
}
/**
* @throws Exception If any error occurs.
*/
@Test
public void testSimpleTypeFieldOverride() throws Exception {
GridBinaryTestClasses.TestObjectAllTypes exp = new GridBinaryTestClasses.TestObjectAllTypes();
exp.setDefaultData();
BinaryObjectBuilderImpl mutPo = wrap(new GridBinaryTestClasses.TestObjectAllTypes());
for (Field field : GridBinaryTestClasses.TestObjectAllTypes.class.getDeclaredFields())
mutPo.setField(field.getName(), field.get(exp));
GridBinaryTestClasses.TestObjectAllTypes res = mutPo.build().deserialize();
GridTestUtils.deepEquals(exp, res);
}
/**
* @throws Exception If any error occurs.
*/
@Test
public void testSimpleTypeFieldSetNull() throws Exception {
GridBinaryTestClasses.TestObjectAllTypes exp = new GridBinaryTestClasses.TestObjectAllTypes();
exp.setDefaultData();
BinaryObjectBuilderImpl mutPo = wrap(exp);
for (Field field : GridBinaryTestClasses.TestObjectAllTypes.class.getDeclaredFields()) {
if (!field.getType().isPrimitive())
mutPo.setField(field.getName(), null);
}
GridBinaryTestClasses.TestObjectAllTypes res = mutPo.build().deserialize();
for (Field field : GridBinaryTestClasses.TestObjectAllTypes.class.getDeclaredFields()) {
if (!field.getType().isPrimitive())
assertNull(field.getName(), field.get(res));
}
}
/**
* @throws IgniteCheckedException If any error occurs.
*/
@Test
public void testMakeCyclicDependency() throws IgniteCheckedException {
GridBinaryTestClasses.TestObjectOuter outer = new GridBinaryTestClasses.TestObjectOuter();
outer.inner = new GridBinaryTestClasses.TestObjectInner();
BinaryObjectBuilderImpl mutOuter = wrap(outer);
BinaryObjectBuilderImpl mutInner = mutOuter.getField("inner");
mutInner.setField("outer", mutOuter);
mutInner.setField("foo", mutInner);
GridBinaryTestClasses.TestObjectOuter res = mutOuter.build().deserialize();
assertEquals(res, res.inner.outer);
assertEquals(res.inner, res.inner.foo);
}
/**
*
*/
@Test
public void testDateArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.dateArr = new Date[] {new Date(11111), new Date(11111), new Date(11111)};
BinaryObjectBuilderImpl mutObj = wrap(obj);
Date[] arr = mutObj.getField("dateArr");
arr[0] = new Date(22222);
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new Date[] {new Date(22222), new Date(11111), new Date(11111)}, res.dateArr);
}
/**
*
*/
@Test
public void testTimestampArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.tsArr = new Timestamp[] {new Timestamp(111222333), new Timestamp(222333444)};
BinaryObjectBuilderImpl mutObj = wrap(obj);
Timestamp[] arr = mutObj.getField("tsArr");
arr[0] = new Timestamp(333444555);
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new Timestamp[] {new Timestamp(333444555), new Timestamp(222333444)}, res.tsArr);
}
/**
*
*/
@Test
public void testUUIDArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.uuidArr = new UUID[] {new UUID(1, 1), new UUID(1, 1), new UUID(1, 1)};
BinaryObjectBuilderImpl mutObj = wrap(obj);
UUID[] arr = mutObj.getField("uuidArr");
arr[0] = new UUID(2, 2);
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new UUID[] {new UUID(2, 2), new UUID(1, 1), new UUID(1, 1)}, res.uuidArr);
}
/**
*
*/
@Test
public void testDecimalArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.bdArr = new BigDecimal[] {new BigDecimal(1000), new BigDecimal(1000), new BigDecimal(1000)};
BinaryObjectBuilderImpl mutObj = wrap(obj);
BigDecimal[] arr = mutObj.getField("bdArr");
arr[0] = new BigDecimal(2000);
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new BigDecimal[] {new BigDecimal(1000), new BigDecimal(1000), new BigDecimal(1000)},
res.bdArr);
}
/**
*
*/
@Test
public void testBooleanArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.zArr = new boolean[] {false, false, false};
BinaryObjectBuilderImpl mutObj = wrap(obj);
boolean[] arr = mutObj.getField("zArr");
arr[0] = true;
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
boolean[] expected = new boolean[] {true, false, false};
assertEquals(expected.length, res.zArr.length);
for (int i = 0; i < expected.length; i++)
assertEquals(expected[i], res.zArr[i]);
}
/**
*
*/
@Test
public void testCharArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.cArr = new char[] {'a', 'a', 'a'};
BinaryObjectBuilderImpl mutObj = wrap(obj);
char[] arr = mutObj.getField("cArr");
arr[0] = 'b';
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new char[] {'b', 'a', 'a'}, res.cArr);
}
/**
*
*/
@Test
public void testDoubleArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.dArr = new double[] {1.0, 1.0, 1.0};
BinaryObjectBuilderImpl mutObj = wrap(obj);
double[] arr = mutObj.getField("dArr");
arr[0] = 2.0;
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new double[] {2.0, 1.0, 1.0}, res.dArr, 0);
}
/**
*
*/
@Test
public void testFloatArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.fArr = new float[] {1.0f, 1.0f, 1.0f};
BinaryObjectBuilderImpl mutObj = wrap(obj);
float[] arr = mutObj.getField("fArr");
arr[0] = 2.0f;
BinaryObject resBinary = mutObj.build();
GridBinaryTestClasses.TestObjectAllTypes res = resBinary.deserialize();
Assert.assertArrayEquals(new float[] {2.0f, 1.0f, 1.0f}, res.fArr, 0);
}
/**
*
*/
@Test
public void testLongArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.lArr = new long[] {1, 1, 1};
BinaryObjectBuilderImpl mutObj = wrap(obj);
long[] arr = mutObj.getField("lArr");
arr[0] = 2;
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new long[] {2, 1, 1}, res.lArr);
}
/**
*
*/
@Test
public void testIntArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.iArr = new int[] {1, 1, 1};
BinaryObjectBuilderImpl mutObj = wrap(obj);
int[] arr = mutObj.getField("iArr");
arr[0] = 2;
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new int[] {2, 1, 1}, res.iArr);
}
/**
*
*/
@Test
public void testShortArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.sArr = new short[] {1, 1, 1};
BinaryObjectBuilderImpl mutObj = wrap(obj);
short[] arr = mutObj.getField("sArr");
arr[0] = 2;
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new short[] {2, 1, 1}, res.sArr);
}
/**
*
*/
@Test
public void testByteArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.bArr = new byte[] {1, 1, 1};
BinaryObjectBuilderImpl mutObj = wrap(obj);
byte[] arr = mutObj.getField("bArr");
arr[0] = 2;
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new byte[] {2, 1, 1}, res.bArr);
}
/**
*
*/
@Test
public void testStringArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.strArr = new String[] {"a", "a", "a"};
BinaryObjectBuilderImpl mutObj = wrap(obj);
String[] arr = mutObj.getField("strArr");
arr[0] = "b";
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(new String[] {"b", "a", "a"}, res.strArr);
}
/**
*
*/
@Test
public void testModifyObjectArray() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = new Object[] {"a"};
BinaryObjectBuilderImpl mutObj = wrap(obj);
Object[] arr = mutObj.getField("foo");
Assert.assertArrayEquals(new Object[] {"a"}, arr);
arr[0] = "b";
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
Assert.assertArrayEquals(new Object[] {"b"}, (Object[])res.foo);
}
/**
*
*/
@Test
public void testOverrideObjectArrayField() {
BinaryObjectBuilderImpl mutObj = wrap(new GridBinaryTestClasses.TestObjectContainer());
Object[] createdArr = {mutObj, "a", 1, new String[] {"s", "s"}, new byte[] {1, 2}, new UUID(3, 0)};
mutObj.setField("foo", createdArr.clone(), Object.class);
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
createdArr[0] = res;
assertTrue(Objects.deepEquals(createdArr, res.foo));
}
/**
*
*/
@Test
public void testDeepArray() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = new Object[] {new Object[] {"a", obj}};
BinaryObjectBuilderImpl mutObj = wrap(obj);
Object[] arr = (Object[])mutObj.<Object[]>getField("foo")[0];
assertEquals("a", arr[0]);
assertSame(mutObj, arr[1]);
arr[0] = mutObj;
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
arr = (Object[])((Object[])res.foo)[0];
assertSame(arr[0], res);
assertSame(arr[0], arr[1]);
}
/**
*
*/
@Test
public void testArrayListRead() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Lists.newArrayList(obj, "a");
BinaryObjectBuilderImpl mutObj = wrap(obj);
List<Object> list = mutObj.getField("foo");
assert list.equals(Lists.newArrayList(mutObj, "a"));
}
/**
*
*/
@Test
public void testArrayListOverride() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutObj = wrap(obj);
ArrayList<Object> list = Lists.newArrayList(mutObj, "a", Lists.newArrayList(1, 2));
mutObj.setField("foo", list, Object.class);
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
list.set(0, res);
assertNotSame(list, res.foo);
assertEquals(list, res.foo);
}
/**
*
*/
@Test
public void testArrayListModification() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Lists.newArrayList("a", "b", "c");
BinaryObjectBuilderImpl mutObj = wrap(obj);
List<String> list = mutObj.getField("foo");
list.add("!"); // "a", "b", "c", "!"
list.add(0, "_"); // "_", "a", "b", "c", "!"
String s = list.remove(1); // "_", "b", "c", "!"
assertEquals("a", s);
assertEquals(Arrays.asList("c", "!"), list.subList(2, 4));
assertEquals(1, list.indexOf("b"));
assertEquals(1, list.lastIndexOf("b"));
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
assertTrue(res.foo instanceof ArrayList);
assertEquals(Arrays.asList("_", "b", "c", "!"), res.foo);
}
/**
*
*/
@Test
public void testArrayListClear() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Lists.newArrayList("a", "b", "c");
BinaryObjectBuilderImpl mutObj = wrap(obj);
List<String> list = mutObj.getField("foo");
list.clear();
Assert.assertEquals(Collections.emptyList(), mutObj.build().<GridBinaryTestClasses.TestObjectContainer>deserialize().foo);
}
/**
*
*/
@Test
public void testArrayListWriteUnmodifiable() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
ArrayList<Object> src = Lists.newArrayList(obj, "a", "b", "c");
obj.foo = src;
BinaryObjectBuilderImpl mutObj = wrap(obj);
GridBinaryTestClasses.TestObjectContainer deserialized = mutObj.build().deserialize();
List<Object> res = (List<Object>)deserialized.foo;
src.set(0, deserialized);
assertEquals(src, res);
}
/**
*
*/
@Test
public void testLinkedListRead() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Lists.newLinkedList(Arrays.asList(obj, "a"));
BinaryObjectBuilderImpl mutObj = wrap(obj);
List<Object> list = mutObj.getField("foo");
assert list.equals(Lists.newLinkedList(Arrays.asList(mutObj, "a")));
}
/**
*
*/
@Test
public void testLinkedListOverride() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutObj = wrap(obj);
List<Object> list = Lists.newLinkedList(Arrays.asList(mutObj, "a", Lists.newLinkedList(Arrays.asList(1, 2))));
mutObj.setField("foo", list, Object.class);
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
list.set(0, res);
assertNotSame(list, res.foo);
assertEquals(list, res.foo);
}
/**
*
*/
@Test
public void testLinkedListModification() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Lists.newLinkedList(Arrays.asList("a", "b", "c"));
BinaryObjectBuilderImpl mutObj = wrap(obj);
List<String> list = mutObj.getField("foo");
list.add("!"); // "a", "b", "c", "!"
list.add(0, "_"); // "_", "a", "b", "c", "!"
String s = list.remove(1); // "_", "b", "c", "!"
assertEquals("a", s);
assertEquals(Arrays.asList("c", "!"), list.subList(2, 4));
assertEquals(1, list.indexOf("b"));
assertEquals(1, list.lastIndexOf("b"));
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
assertTrue(res.foo instanceof LinkedList);
assertEquals(Arrays.asList("_", "b", "c", "!"), res.foo);
}
/**
*
*/
@Test
public void testLinkedListWriteUnmodifiable() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
LinkedList<Object> src = Lists.newLinkedList(Arrays.asList(obj, "a", "b", "c"));
obj.foo = src;
BinaryObjectBuilderImpl mutObj = wrap(obj);
GridBinaryTestClasses.TestObjectContainer deserialized = mutObj.build().deserialize();
List<Object> res = (List<Object>)deserialized.foo;
src.set(0, deserialized);
assertEquals(src, res);
}
/**
*
*/
@Test
public void testHashSetRead() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Sets.newHashSet(obj, "a");
BinaryObjectBuilderImpl mutObj = wrap(obj);
Set<Object> set = mutObj.getField("foo");
assert set.equals(Sets.newHashSet(mutObj, "a"));
}
/**
*
*/
@Test
public void testHashSetOverride() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutObj = wrap(obj);
Set<Object> c = Sets.newHashSet(mutObj, "a", Sets.newHashSet(1, 2));
mutObj.setField("foo", c, Object.class);
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
c.remove(mutObj);
c.add(res);
assertNotSame(c, res.foo);
assertEquals(c, res.foo);
}
/**
*
*/
@Test
public void testHashSetModification() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Sets.newHashSet("a", "b", "c");
BinaryObjectBuilderImpl mutObj = wrap(obj);
Set<String> set = mutObj.getField("foo");
set.remove("b");
set.add("!");
assertEquals(Sets.newHashSet("a", "!", "c"), set);
assertTrue(set.contains("a"));
assertTrue(set.contains("!"));
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
assertTrue(res.foo instanceof HashSet);
assertEquals(Sets.newHashSet("a", "!", "c"), res.foo);
}
/**
*
*/
@Test
public void testHashSetWriteUnmodifiable() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
Set<Object> src = Sets.newHashSet(obj, "a", "b", "c");
obj.foo = src;
GridBinaryTestClasses.TestObjectContainer deserialized = wrap(obj).build().deserialize();
Set<Object> res = (Set<Object>)deserialized.foo;
src.remove(obj);
src.add(deserialized);
assertEquals(src, res);
}
/**
*
*/
@Test
public void testMapRead() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Maps.newHashMap(ImmutableMap.of(obj, "a", "b", obj));
BinaryObjectBuilderImpl mutObj = wrap(obj);
Map<Object, Object> map = mutObj.getField("foo");
assert map.equals(ImmutableMap.of(mutObj, "a", "b", mutObj));
}
/**
*
*/
@Test
public void testMapOverride() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutObj = wrap(obj);
Map<Object, Object> map = Maps.newHashMap(ImmutableMap.of(mutObj, "a", "b", mutObj));
mutObj.setField("foo", map, Object.class);
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
assertEquals(ImmutableMap.of(res, "a", "b", res), res.foo);
}
/**
*
*/
@Test
public void testMapModification() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Maps.newHashMap(ImmutableMap.of(1, "a", 2, "b"));
BinaryObjectBuilderImpl mutObj = wrap(obj);
Map<Object, Object> map = mutObj.getField("foo");
map.put(3, mutObj);
Object rmv = map.remove(1);
assertEquals("a", rmv);
GridBinaryTestClasses.TestObjectContainer res = mutObj.build().deserialize();
assertEquals(ImmutableMap.of(2, "b", 3, res), res.foo);
}
/**
*
*/
@Test
public void testEnumArrayModification() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.enumArr =
new GridBinaryTestClasses.TestObjectEnum[] {GridBinaryTestClasses.TestObjectEnum.A, GridBinaryTestClasses.TestObjectEnum.B};
BinaryObjectBuilderImpl mutObj = wrap(obj);
BinaryBuilderEnum[] arr = mutObj.getField("enumArr");
arr[0] = new BinaryBuilderEnum(mutObj.typeId(), GridBinaryTestClasses.TestObjectEnum.B);
GridBinaryTestClasses.TestObjectAllTypes res = mutObj.build().deserialize();
Assert.assertArrayEquals(
new GridBinaryTestClasses.TestObjectEnum[] {GridBinaryTestClasses.TestObjectEnum.A, GridBinaryTestClasses.TestObjectEnum.B},
res.enumArr
);
}
/**
*
*/
@Test
public void testEditObjectWithRawData() {
GridBinaryMarshalerAwareTestClass obj = new GridBinaryMarshalerAwareTestClass();
obj.s = "a";
obj.sRaw = "aa";
BinaryObjectBuilderImpl mutableObj = wrap(obj);
mutableObj.setField("s", "z");
GridBinaryMarshalerAwareTestClass res = mutableObj.build().deserialize();
assertEquals("z", res.s);
assertEquals("aa", res.sRaw);
}
/**
*
*/
@Test
public void testHashCode() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutableObj = wrap(obj);
BinaryObject bo = mutableObj.build();
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(bo), bo.hashCode());
}
/**
*
*/
@Test
public void testCollectionsInCollection() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Lists.newArrayList(
Lists.newArrayList(1, 2),
Lists.newLinkedList(Arrays.asList(1, 2)),
Sets.newHashSet("a", "b"),
Sets.newLinkedHashSet(Arrays.asList("a", "b")),
Maps.newHashMap(ImmutableMap.of(1, "a", 2, "b")));
GridBinaryTestClasses.TestObjectContainer deserialized = wrap(obj).build().deserialize();
assertEquals(obj.foo, deserialized.foo);
}
/**
*
*/
@Test
public void testMapEntryOverride() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutableObj = wrap(obj);
mutableObj.setField("foo", new GridMapEntry<>(1, "a"));
GridBinaryTestClasses.TestObjectContainer res = mutableObj.build().deserialize();
assertEquals(new GridMapEntry<>(1, "a"), res.foo);
}
/**
*
*/
@Test
public void testMetadataChangingDoublePut() {
BinaryObjectBuilderImpl mutableObj = wrap(new GridBinaryTestClasses.TestObjectContainer());
mutableObj.setField("xx567", "a");
mutableObj.setField("xx567", "b");
mutableObj.build();
BinaryType metadata = binaries().type(GridBinaryTestClasses.TestObjectContainer.class);
assertEquals("String", metadata.fieldTypeName("xx567"));
}
/**
*
*/
@Test
public void testMetadataChangingDoublePut2() {
BinaryObjectBuilderImpl mutableObj = wrap(new GridBinaryTestClasses.TestObjectContainer());
mutableObj.setField("xx567", "a");
mutableObj.setField("xx567", "b");
mutableObj.build();
BinaryType metadata = binaries().type(GridBinaryTestClasses.TestObjectContainer.class);
assertEquals("String", metadata.fieldTypeName("xx567"));
}
/**
*
*/
@Test
public void testMetadataChanging() {
GridBinaryTestClasses.TestObjectContainer c = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutableObj = wrap(c);
mutableObj.setField("intField", 1);
mutableObj.setField("intArrField", new int[] {1});
mutableObj.setField("arrField", new String[] {"1"});
mutableObj.setField("strField", "1");
mutableObj.setField("colField", Lists.newArrayList("1"));
mutableObj.setField("mapField", Maps.newHashMap(ImmutableMap.of(1, "1")));
mutableObj.setField("enumField", GridBinaryTestClasses.TestObjectEnum.A);
mutableObj.setField("enumArrField", new Enum[] {GridBinaryTestClasses.TestObjectEnum.A});
mutableObj.build();
BinaryType metadata = binaries().type(c.getClass());
assertTrue(metadata.fieldNames().containsAll(Arrays.asList("intField", "intArrField", "arrField", "strField",
"colField", "mapField", "enumField", "enumArrField")));
assertEquals("int", metadata.fieldTypeName("intField"));
assertEquals("int[]", metadata.fieldTypeName("intArrField"));
assertEquals("String[]", metadata.fieldTypeName("arrField"));
assertEquals("String", metadata.fieldTypeName("strField"));
assertEquals("Collection", metadata.fieldTypeName("colField"));
assertEquals("Map", metadata.fieldTypeName("mapField"));
assertEquals("Enum", metadata.fieldTypeName("enumField"));
assertEquals("Enum[]", metadata.fieldTypeName("enumArrField"));
}
/**
*
*/
@Test
public void testWrongMetadataNullField() {
BinaryObjectBuilder builder = binaries().builder("SomeType");
builder.setField("dateField", null);
builder.setField("objectField", null, Integer.class);
builder.build();
try {
builder = binaries().builder("SomeType");
builder.setField("dateField", new Date());
builder.build();
}
catch (BinaryObjectException ex) {
assertTrue(ex.getMessage().startsWith("Wrong value has been set"));
}
builder = binaries().builder("SomeType");
try {
builder.setField("objectField", new GridBinaryTestClasses.Company());
builder.build();
fail("BinaryObjectBuilder accepted wrong metadata");
}
catch (BinaryObjectException ex) {
assertTrue(ex.getMessage().startsWith("Wrong value has been set"));
}
}
/**
*
*/
@Test
public void testWrongMetadataNullField2() {
BinaryObjectBuilder builder = binaries().builder("SomeType1");
builder.setField("dateField", null);
builder.setField("objectField", null, Integer.class);
BinaryObject obj = builder.build();
try {
builder = binaries().builder(obj);
builder.setField("dateField", new Date());
builder.build();
}
catch (BinaryObjectException ex) {
assertTrue(ex.getMessage().startsWith("Wrong value has been set"));
}
builder = binaries().builder(obj);
try {
builder.setField("objectField", new GridBinaryTestClasses.Company());
builder.build();
fail("BinaryObjectBuilder accepted wrong metadata");
}
catch (BinaryObjectException ex) {
assertTrue(ex.getMessage().startsWith("Wrong value has been set"));
}
}
/**
*
*/
@Test
public void testCorrectMetadataNullField() {
BinaryObjectBuilder builder = binaries().builder("SomeType2");
builder.setField("dateField", null, Date.class);
builder.setField("objectField", null, GridBinaryTestClasses.Company.class);
builder.build();
builder = binaries().builder("SomeType2");
builder.setField("dateField", new Date());
builder.setField("objectField", new GridBinaryTestClasses.Company());
builder.build();
}
/**
*
*/
@Test
public void testCorrectMetadataNullField2() {
BinaryObjectBuilder builder = binaries().builder("SomeType3");
builder.setField("dateField", null, Date.class);
builder.setField("objectField", null, GridBinaryTestClasses.Company.class);
BinaryObject obj = builder.build();
builder = binaries().builder(obj);
builder.setField("dateField", new Date());
builder.setField("objectField", new GridBinaryTestClasses.Company());
builder.build();
}
/**
*
*/
@Test
public void testDateInObjectField() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = new Date();
BinaryObjectBuilderImpl mutableObj = wrap(obj);
assertEquals(Date.class, mutableObj.getField("foo").getClass());
}
/**
*
*/
@Test
public void testTimestampInObjectField() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = new Timestamp(100020003);
BinaryObjectBuilderImpl mutableObj = wrap(obj);
assertEquals(Timestamp.class, mutableObj.getField("foo").getClass());
}
/**
*
*/
@Test
public void testDateInCollection() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Lists.newArrayList(new Date());
BinaryObjectBuilderImpl mutableObj = wrap(obj);
assertEquals(Date.class, ((List<?>)mutableObj.getField("foo")).get(0).getClass());
}
/**
*
*/
@Test
public void testTimestampInCollection() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
obj.foo = Lists.newArrayList(new Timestamp(100020003));
BinaryObjectBuilderImpl mutableObj = wrap(obj);
assertEquals(Timestamp.class, ((List<?>)mutableObj.getField("foo")).get(0).getClass());
}
/**
*
*/
@Test
public void testDateArrayOverride() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutableObj = wrap(obj);
Date[] arr = {new Date()};
mutableObj.setField("foo", arr, Object.class);
GridBinaryTestClasses.TestObjectContainer res = mutableObj.build().deserialize();
assertEquals(Date[].class, res.foo.getClass());
assertTrue(Objects.deepEquals(arr, res.foo));
}
/**
*
*/
@Test
public void testTimestampArrayOverride() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl mutableObj = wrap(obj);
Timestamp[] arr = {new Timestamp(100020003)};
mutableObj.setField("foo", arr, Object.class);
GridBinaryTestClasses.TestObjectContainer res = mutableObj.build().deserialize();
assertEquals(Timestamp[].class, res.foo.getClass());
assertTrue(Objects.deepEquals(arr, res.foo));
}
/**
*
*/
@Test
public void testChangeMap() {
GridBinaryTestClasses.Addresses addrs = new GridBinaryTestClasses.Addresses();
addrs.addCompany(new GridBinaryTestClasses.Company(1, "Google inc", 100,
new GridBinaryTestClasses.Address("Saint-Petersburg", "Torzhkovskya", 1, 53), "occupation"));
addrs.addCompany(new GridBinaryTestClasses.Company(2, "Apple inc", 100,
new GridBinaryTestClasses.Address("Saint-Petersburg", "Torzhkovskya", 1, 54), "occupation"));
addrs.addCompany(new GridBinaryTestClasses.Company(3, "Microsoft", 100,
new GridBinaryTestClasses.Address("Saint-Petersburg", "Torzhkovskya", 1, 55), "occupation"));
addrs.addCompany(new GridBinaryTestClasses.Company(4, "Oracle", 100,
new GridBinaryTestClasses.Address("Saint-Petersburg", "Nevskiy", 1, 1), "occupation"));
BinaryObjectBuilderImpl binaryAddres = wrap(addrs);
Map<String, BinaryObjectBuilderImpl> map = binaryAddres.getField("companyByStreet");
BinaryObjectBuilderImpl binaryCompanies = map.get("Torzhkovskya");
List<BinaryObjectBuilderImpl> binaryCompaniesList = binaryCompanies.getField("companies");
BinaryObjectBuilderImpl company = binaryCompaniesList.get(0);
assert "Google inc".equals(company.<String>getField("name"));
binaryCompaniesList.remove(0);
GridBinaryTestClasses.Addresses res = binaryAddres.build().deserialize();
assertEquals(Arrays.asList("Nevskiy", "Torzhkovskya"), new ArrayList<>(res.getCompanyByStreet().keySet()));
GridBinaryTestClasses.Companies torzhkovskyaCompanies = res.getCompanyByStreet().get("Torzhkovskya");
assertEquals(2, torzhkovskyaCompanies.size());
assertEquals("Apple inc", torzhkovskyaCompanies.get(0).name);
}
/**
*
*/
@Test
public void testSavingObjectWithNotZeroStart() {
GridBinaryTestClasses.TestObjectOuter out = new GridBinaryTestClasses.TestObjectOuter();
GridBinaryTestClasses.TestObjectInner inner = new GridBinaryTestClasses.TestObjectInner();
out.inner = inner;
inner.outer = out;
BinaryObjectBuilderImpl builder = wrap(out);
BinaryObjectBuilderImpl innerBuilder = builder.getField("inner");
GridBinaryTestClasses.TestObjectInner res = innerBuilder.build().deserialize();
assertSame(res, res.outer.inner);
}
/**
*
*/
@Test
public void testBinaryObjectField() {
GridBinaryTestClasses.TestObjectContainer container =
new GridBinaryTestClasses.TestObjectContainer(toBinary(new GridBinaryTestClasses.TestObjectArrayList()));
BinaryObjectBuilderImpl wrapper = wrap(container);
assertTrue(wrapper.getField("foo") instanceof BinaryObject);
GridBinaryTestClasses.TestObjectContainer deserialized = wrapper.build().deserialize();
assertTrue(deserialized.foo instanceof BinaryObject);
}
/**
*
*/
@Test
public void testAssignBinaryObject() {
GridBinaryTestClasses.TestObjectContainer container = new GridBinaryTestClasses.TestObjectContainer();
BinaryObjectBuilderImpl wrapper = wrap(container);
wrapper.setField("foo", toBinary(new GridBinaryTestClasses.TestObjectArrayList()));
GridBinaryTestClasses.TestObjectContainer deserialized = wrapper.build().deserialize();
assertTrue(deserialized.foo instanceof GridBinaryTestClasses.TestObjectArrayList);
}
/**
*
*/
@Test
public void testRemoveFromNewObject() {
BinaryObjectBuilderImpl wrapper = newWrapper(GridBinaryTestClasses.TestObjectAllTypes.class);
wrapper.setField("str", "a");
wrapper.removeField("str");
Assert.assertNull(wrapper.build().<GridBinaryTestClasses.TestObjectAllTypes>deserialize().str);
}
/**
*
*/
@Test
public void testRemoveFromExistingObject() {
GridBinaryTestClasses.TestObjectAllTypes obj = new GridBinaryTestClasses.TestObjectAllTypes();
obj.setDefaultData();
BinaryObjectBuilderImpl wrapper = wrap(toBinary(obj));
wrapper.removeField("str");
Assert.assertNull(wrapper.build().<GridBinaryTestClasses.TestObjectAllTypes>deserialize().str);
}
/**
*
*/
@Test
public void testCyclicArrays() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
Object[] arr1 = new Object[1];
Object[] arr2 = new Object[] {arr1};
arr1[0] = arr2;
obj.foo = arr1;
GridBinaryTestClasses.TestObjectContainer res = toBinary(obj).deserialize();
Object[] resArr = (Object[])res.foo;
assertSame(((Object[])resArr[0])[0], resArr);
}
/**
*
*/
@SuppressWarnings("TypeMayBeWeakened")
@Test
public void testCyclicArrayList() {
GridBinaryTestClasses.TestObjectContainer obj = new GridBinaryTestClasses.TestObjectContainer();
List<Object> arr1 = new ArrayList<>();
List<Object> arr2 = new ArrayList<>();
arr1.add(arr2);
arr2.add(arr1);
obj.foo = arr1;
GridBinaryTestClasses.TestObjectContainer res = toBinary(obj).deserialize();
List<?> resArr = (List<?>)res.foo;
assertSame(((List<Object>)resArr.get(0)).get(0), resArr);
}
/**
* @throws Exception If failed.
*/
@Test
public void testSameBinaryKey() throws Exception {
IgniteCache<BinaryObject, BinaryObject> replicatedCache =
jcache(0).withKeepBinary();
IgniteCache<BinaryObject, BinaryObject> partitionedCache =
jcache(0, "partitioned").withKeepBinary();
BinaryObjectBuilder keyBuilder = ignite(0).binary().builder("keyType")
.setField("F1", "V1");
BinaryObjectBuilder valBuilder = ignite(0).binary().builder("valueType")
.setField("F2", "V2")
.setField("F3", "V3");
BinaryObject key = keyBuilder.build();
BinaryObject val = valBuilder.build();
replicatedCache.put(key, val);
partitionedCache.put(key, val);
assertNotNull(replicatedCache.get(key));
assertNotNull(partitionedCache.get(key));
}
/**
* Ensure that object w/o schema can be re-built.
*/
@Test
public void testBuildFromObjectWithoutSchema() {
BinaryObjectBuilderImpl binBuilder = wrap(new GridBinaryTestClass2());
BinaryObject binObj = binBuilder.build();
BinaryObjectBuilderImpl binBuilder2 = wrap(binObj);
binBuilder2.build();
}
/**
* @param obj Object.
* @return Object in binary format.
*/
private BinaryObject toBinary(Object obj) {
return binaries().toBinary(obj);
}
/**
* @param obj Object.
* @return GridMutableBinaryObject.
*/
private BinaryObjectBuilderImpl wrap(Object obj) {
return BinaryObjectBuilderImpl.wrap(toBinary(obj));
}
/**
* @param aCls Class.
* @return Wrapper.
*/
private BinaryObjectBuilderImpl newWrapper(Class<?> aCls) {
return newWrapper(aCls.getName());
}
/**
* @param typeName Type name.
* @return Wrapper.
*/
private BinaryObjectBuilderImpl newWrapper(String typeName) {
CacheObjectBinaryProcessorImpl processor = (CacheObjectBinaryProcessorImpl)(
(IgniteBinaryImpl)binaries()).processor();
return new BinaryObjectBuilderImpl(processor.binaryContext(), processor.typeId(typeName),
processor.binaryContext().userTypeName(typeName));
}
/** */
private void clearBinaryMeta() {
BinaryContext binCtx = ((CacheObjectBinaryProcessorImpl)((IgniteBinaryImpl)binaries()).processor()).binaryContext();
binCtx.unregisterBinarySchemas();
binCtx.unregisterUserTypeDescriptors();
}
/**
* Check that correct type is stored in binary object.
*/
@Test
public void testCollectionsSerialization() {
final BinaryObjectBuilder root = newWrapper(BigInteger.class);
final List<Integer> arrList = new ArrayList<>();
arrList.add(Integer.MAX_VALUE);
final List<Integer> linkedList = new LinkedList<>();
linkedList.add(Integer.MAX_VALUE);
final Set<Integer> hashSet = new HashSet<>();
hashSet.add(Integer.MAX_VALUE);
final Set<Integer> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add(Integer.MAX_VALUE);
final Map<String, String> hashMap = new HashMap<>();
hashMap.put("key", "val");
final Map<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("key", "val");
// collections
root.setField("arrayList", arrList);
root.setField("linkedList", linkedList);
root.setField("hashSet", hashSet);
root.setField("linkedHashSet", linkedHashSet);
root.setField("singletonList", Collections.singletonList(Integer.MAX_VALUE), Collection.class);
root.setField("singletonSet", Collections.singleton(Integer.MAX_VALUE), Collection.class);
// maps
root.setField("hashMap", hashMap);
root.setField("linkedHashMap", linkedHashMap);
root.setField("singletonMap", Collections.singletonMap("key", "val"), Map.class);
// objects
root.setField("asList", Collections.singletonList(Integer.MAX_VALUE));
root.setField("asSet", Collections.singleton(Integer.MAX_VALUE));
root.setField("asMap", Collections.singletonMap("key", "val"));
root.setField("asListHint", Collections.singletonList(Integer.MAX_VALUE), List.class);
root.setField("asSetHint", Collections.singleton(Integer.MAX_VALUE), Set.class);
root.setField("asMapHint", (AbstractMap)Collections.singletonMap("key", "val"), AbstractMap.class);
BinaryObject binaryObj = root.build();
final String COL = "Collection";
final String MAP = "Map";
final String OBJ = "Object";
assert COL.equals(binaryObj.type().fieldTypeName("arrayList"));
assert COL.equals(binaryObj.type().fieldTypeName("linkedList"));
assert COL.equals(binaryObj.type().fieldTypeName("hashSet"));
assert COL.equals(binaryObj.type().fieldTypeName("linkedHashSet"));
assert COL.equals(binaryObj.type().fieldTypeName("linkedHashSet"));
assert COL.equals(binaryObj.type().fieldTypeName("linkedHashSet"));
assert COL.equals(binaryObj.type().fieldTypeName("singletonList"));
assert COL.equals(binaryObj.type().fieldTypeName("singletonSet"));
assert MAP.equals(binaryObj.type().fieldTypeName("singletonMap"));
assert COL.equals(binaryObj.type().fieldTypeName("asList"));
assert OBJ.equals(binaryObj.type().fieldTypeName("asSet"));
assert OBJ.equals(binaryObj.type().fieldTypeName("asMap"));
assert OBJ.equals(binaryObj.type().fieldTypeName("asListHint"));
assert OBJ.equals(binaryObj.type().fieldTypeName("asSetHint"));
assert OBJ.equals(binaryObj.type().fieldTypeName("asMapHint"));
}
/**
* Checks that externalizable value is correctly serialized/deserialized.
*
* @throws Exception If failed.
*/
@Test
public void testBuilderExternalizable() throws Exception {
BinaryObjectBuilder builder = newWrapper("TestType");
final TestObjectExternalizable exp = new TestObjectExternalizable("test");
final TestObjectExternalizable[] expArr = new TestObjectExternalizable[]{
new TestObjectExternalizable("test1"), new TestObjectExternalizable("test2")};
BinaryObject extObj = builder.setField("extVal", exp).setField("extArr", expArr).build();
assertEquals(exp, extObj.field("extVal"));
Assert.assertArrayEquals(expArr, (Object[])extObj.field("extArr"));
builder = extObj.toBuilder();
extObj = builder.setField("intVal", 10).build();
assertEquals(exp, extObj.field("extVal"));
Assert.assertArrayEquals(expArr, (Object[])extObj.field("extArr"));
assertEquals(Integer.valueOf(10), extObj.field("intVal"));
builder = extObj.toBuilder();
extObj = builder.setField("strVal", "some string").build();
assertEquals(exp, extObj.field("extVal"));
Assert.assertArrayEquals(expArr, (Object[])extObj.field("extArr"));
assertEquals(Integer.valueOf(10), extObj.field("intVal"));
assertEquals("some string", extObj.field("strVal"));
}
/**
* Checks correct serialization/deserialization of enums in builder.
*/
@Test
public void testEnum() {
try {
BinaryObjectBuilder builder = newWrapper(TestClsWithEnum.class.getName());
TestEnum[] expArr = {TestEnum.A, TestEnum.B};
BinaryObject enumObj = builder
.setField("testEnumA", TestEnum.A)
.setField("testEnumB", TestEnum.B)
.setField("testEnumArr", expArr)
.build();
Assert.assertSame(TestEnum.A, ((BinaryObject)enumObj.field("testEnumA")).deserialize());
Assert.assertSame(TestEnum.B, ((BinaryObject)enumObj.field("testEnumB")).deserialize());
Assert.assertArrayEquals(expArr, deserializeEnumBinaryArray(enumObj.field("testEnumArr")));
Assert.assertSame(TestEnum.A, ((TestClsWithEnum)enumObj.deserialize()).testEnumA);
Assert.assertSame(TestEnum.B, ((TestClsWithEnum)enumObj.deserialize()).testEnumB);
Assert.assertArrayEquals(expArr, ((TestClsWithEnum)enumObj.deserialize()).testEnumArr);
builder = newWrapper(enumObj.type().typeName());
enumObj = builder
.setField("testEnumA", (Object)enumObj.field("testEnumA"))
.setField("testEnumB", (Object)enumObj.field("testEnumB"))
.setField("testEnumArr", (Object)enumObj.field("testEnumArr"))
.build();
Assert.assertSame(TestEnum.A, ((BinaryObject)enumObj.field("testEnumA")).deserialize());
Assert.assertSame(TestEnum.B, ((BinaryObject)enumObj.field("testEnumB")).deserialize());
Assert.assertArrayEquals(expArr, deserializeEnumBinaryArray(enumObj.field("testEnumArr")));
Assert.assertSame(TestEnum.A, ((TestClsWithEnum)enumObj.deserialize()).testEnumA);
Assert.assertSame(TestEnum.B, ((TestClsWithEnum)enumObj.deserialize()).testEnumB);
Assert.assertArrayEquals(expArr, ((TestClsWithEnum)enumObj.deserialize()).testEnumArr);
builder = newWrapper(enumObj.type().typeName());
expArr = new TestEnum[0];
enumObj = builder.setField("testEnumArr", expArr).build();
Assert.assertArrayEquals(expArr, deserializeEnumBinaryArray(enumObj.field("testEnumArr")));
Assert.assertArrayEquals(expArr, ((TestClsWithEnum)enumObj.deserialize()).testEnumArr);
enumObj = builder.setField("testEnumArr", (Object)enumObj.field("testEnumArr")).build();
Assert.assertArrayEquals(expArr, deserializeEnumBinaryArray(enumObj.field("testEnumArr")));
Assert.assertArrayEquals(expArr, ((TestClsWithEnum)enumObj.deserialize()).testEnumArr);
}
finally {
clearBinaryMeta();
}
}
/** */
@Test
public void testEnum2() {
try {
BinaryObjectBuilder builder = newWrapper(TestClsWithEnum.class.getName());
Object[] expArr = new TestEnum[0];
BinaryObject enumObj = builder.setField("testEnumArr", expArr).build();
Assert.assertArrayEquals(expArr, deserializeEnumBinaryArray(enumObj.field("testEnumArr")));
Assert.assertArrayEquals(expArr, ((TestClsWithEnum)enumObj.deserialize()).testEnumArr);
builder = newWrapper(enumObj.type().typeName());
enumObj = builder.setField("testEnumArr", (Object)enumObj.field("testEnumArr")).build();
Assert.assertArrayEquals(expArr, deserializeEnumBinaryArray(enumObj.field("testEnumArr")));
Assert.assertArrayEquals(expArr, ((TestClsWithEnum)enumObj.deserialize()).testEnumArr);
expArr = new TestEnum[] {TestEnum.A, TestEnum.B};
builder = newWrapper(enumObj.type().typeName());
enumObj = builder.setField("testEnumArr", expArr).build();
Assert.assertArrayEquals(expArr, deserializeEnumBinaryArray(enumObj.field("testEnumArr")));
Assert.assertArrayEquals(expArr, ((TestClsWithEnum)enumObj.deserialize()).testEnumArr);
builder = newWrapper(enumObj.type().typeName());
enumObj = builder.setField("testEnumArr", (Object)enumObj.field("testEnumArr")).build();
Assert.assertArrayEquals(expArr, deserializeEnumBinaryArray(enumObj.field("testEnumArr")));
Assert.assertArrayEquals(expArr, ((TestClsWithEnum)enumObj.deserialize()).testEnumArr);
}
finally {
clearBinaryMeta();
}
}
/**
* Test {@link BinaryObjectBuilder#build()} adds type mapping to the binary marshaller's cache.
*/
@Test
public void testMarshallerMappings() throws IgniteCheckedException, ClassNotFoundException {
String typeName = "TestType";
int typeId = BinaryContext.defaultIdMapper().typeId(typeName);
BinaryObjectBuilder builder = newWrapper(typeName);
builder.build();
MarshallerContext marshCtx = grid(0).context().marshallerContext();
String actualTypeName = marshCtx.getClassName(MarshallerPlatformIds.JAVA_ID, typeId);
assertEquals(typeName, actualTypeName);
}
/**
* @param obj BinaryObject array.
* @return Deserialized enums.
*/
private TestEnum[] deserializeEnumBinaryArray(Object obj) {
Object[] arr = (Object[])obj;
final TestEnum[] res = new TestEnum[arr.length];
for (int i = 0; i < arr.length; i++)
res[i] = ((BinaryObject)arr[i]).deserialize();
return res;
}
/**
* @throws Exception If fails
*/
@Test
public void testBuilderReusage() throws Exception {
// Check: rewrite null field value.
BinaryObjectBuilder builder = newWrapper("SimpleCls1");
builder.setField("f1", null, Object.class);
assertNull(builder.build().field("f1"));
builder.setField("f1", "val1");
assertEquals("val1", builder.build().field("f1"));
// Check: rewrite non-null field value to null and back.
builder = newWrapper("SimpleCls2");
builder.setField("f1", "val1", String.class);
assertEquals("val1", builder.build().field("f1"));
builder.setField("f1", null);
assertNull(builder.build().field("f1"));
builder.setField("f1", "val2");
assertEquals("val2", builder.build().field("f1"));
}
/**
*
*/
private static class TestObjectExternalizable implements Externalizable {
/** */
private String val;
/**
*
*/
public TestObjectExternalizable() {
}
/**
* @param val Value.
*/
public TestObjectExternalizable(final String val) {
this.val = val;
}
/** {@inheritDoc} */
@Override public void writeExternal(final ObjectOutput out) throws IOException {
out.writeUTF(val);
}
/** {@inheritDoc} */
@Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
val = in.readUTF();
}
/** {@inheritDoc} */
@Override public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final TestObjectExternalizable that = (TestObjectExternalizable)o;
return val != null ? val.equals(that.val) : that.val == null;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return val != null ? val.hashCode() : 0;
}
/** {@inheritDoc} */
@Override public String toString() {
return "TestObjectExternalizable{" +
"val='" + val + '\'' +
'}';
}
}
/** Test class with enum and array of enums. */
public static class TestClsWithEnum {
/** */
private final TestEnum testEnumA;
/** */
private final TestEnum testEnumB;
/** */
private final TestEnum[] testEnumArr;
/** */
public TestClsWithEnum(TestEnum testEnumA, TestEnum testEnumB, TestEnum[] testEnumArr) {
this.testEnumA = testEnumA;
this.testEnumB = testEnumB;
this.testEnumArr = testEnumArr;
}
}
/**
*
*/
private enum TestEnum {
/** */
A {
/**
* An empty function is needed so that {@link TestEnum#A}
* becomes a subclass.
*/
public void foo() {
}
},
/** */
B
}
}
|
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.passes;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.Iterables;
import com.google.template.soy.SoyFileSetParserBuilder;
import com.google.template.soy.base.internal.SoyFileKind;
import com.google.template.soy.base.internal.SoyFileSupplier;
import com.google.template.soy.error.ErrorReporter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link CheckTemplateVisibility}.
*
* @author brndn@google.com (Brendan Linn)
*/
@RunWith(JUnit4.class)
public final class CheckTemplateVisibilityTest {
@Test
public void testCallPrivateTemplateFromSameFile() {
SoyFileSetParserBuilder.forFileContents(
"{namespace ns}\n"
+ "/** Private template. */\n"
+ "{template .foo visibility=\"private\"}\n"
+ "oops!\n"
+ "{/template}\n"
+ "/** Public template. */\n"
+ "{template .bar}\n"
+ "{call .foo /}\n"
+ "{/template}")
.errorReporter(ErrorReporter.exploding())
.parse();
}
@Test
public void testCallPrivateTemplateFromSameNamespaceButDifferentFile() {
ErrorReporter errorReporter = ErrorReporter.createForTest();
SoyFileSetParserBuilder.forFileContents(
"{namespace ns}\n"
+ "/** Private template. */\n"
+ "{template .foo visibility=\"private\"}\n"
+ "oops!\n"
+ "{/template}",
"{namespace ns}\n"
+ "/** Public template. */\n"
+ "{template .bar}\n"
+ "{call .foo /}\n"
+ "{/template}")
.errorReporter(errorReporter)
.parse();
assertThat(errorReporter.getErrors()).hasSize(1);
assertThat(Iterables.getOnlyElement(errorReporter.getErrors()).message())
.isEqualTo("ns.foo has private access in no-path.");
}
@Test
public void testCallPrivateTemplateDifferentFile() {
ErrorReporter errorReporter = ErrorReporter.createForTest();
SoyFileSetParserBuilder.forFileContents(
"{namespace ns}\n"
+ "/** Private template. */\n"
+ "{template .foo visibility=\"private\"}\n"
+ "oops!\n"
+ "{/template}",
"{namespace ns2}\n"
+ "/** Public template. */\n"
+ "{template .bar}\n"
+ "{call ns.foo /}\n"
+ "{/template}")
.errorReporter(errorReporter)
.parse();
assertThat(errorReporter.getErrors()).hasSize(1);
assertThat(Iterables.getOnlyElement(errorReporter.getErrors()).message())
.isEqualTo("ns.foo has private access in no-path.");
}
// There was a bug in the visibility pass where you could call private templates if the caller was
// defined in a file with the same name irrespective of directory
@Test
public void testCallPrivateTemplateSameFileNameDifferentDirectory() {
ErrorReporter errorReporter = ErrorReporter.createForTest();
SoyFileSetParserBuilder.forSuppliers(
SoyFileSupplier.Factory.create(
"{namespace ns}\n"
+ "/** Private template. */\n"
+ "{template .foo visibility=\"private\"}\n"
+ "oops!\n"
+ "{/template}",
SoyFileKind.SRC,
"foo/bar.soy"),
SoyFileSupplier.Factory.create(
"{namespace ns2}\n"
+ "/** Public template. */\n"
+ "{template .bar}\n"
+ "{call ns.foo /}\n"
+ "{/template}",
SoyFileKind.SRC,
"baz/bar.soy"))
.errorReporter(errorReporter)
.parse();
assertThat(errorReporter.getErrors()).hasSize(1);
assertThat(Iterables.getOnlyElement(errorReporter.getErrors()).message())
.isEqualTo("ns.foo has private access in foo/bar.soy.");
}
}
|
/*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.server;
import com.thoughtworks.go.helpers.FileSystemUtils;
import com.thoughtworks.go.server.util.GoCipherSuite;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.validators.Validation;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mortbay.component.Container;
import org.mortbay.jetty.*;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.webapp.WebAppContext;
import org.xml.sax.SAXException;
import javax.net.ssl.SSLSocketFactory;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(Theories.class)
public class GoServerContextHandlersTest {
private SSLSocketFactory sslSocketFactory;
private File addonDir = new File("test-addons");
@Before
public void setUp() throws Exception {
sslSocketFactory = mock(SSLSocketFactory.class);
when(sslSocketFactory.getSupportedCipherSuites()).thenReturn(new String[0]);
addonDir.mkdirs();
}
@After
public void tearDown() throws Exception {
FileUtils.deleteDirectory(addonDir);
}
@Test
public void shouldRegisterAllHandlers() throws Exception {
final JettyServer server = mock(JettyServer.class);
when(server.getContainer()).thenReturn(new Container());
when(server.getServer()).thenReturn(mock(Server.class));
SystemEnvironment environment = spy(new SystemEnvironment());
final WebAppContext mainWebapp = mock(WebAppContext.class);
final GoServer.GoServerWelcomeFileHandler welcomeHandler = mock(GoServer.GoServerWelcomeFileHandler.class);
final GoServer.LegacyUrlRequestHandler legacyRequestHandler = mock(GoServer.LegacyUrlRequestHandler.class);
GoServer goServer = new GoServer(environment, new GoCipherSuite(sslSocketFactory), null) {
@Override JettyServer createServer() {
return server;
}
@Override WebAppContext webApp() throws IOException, SAXException, ClassNotFoundException, UnavailableException {
return mainWebapp;
}
@Override ContextHandler welcomeFileHandler() {
return welcomeHandler;
}
@Override public ContextHandler legacyRequestHandler() {
return legacyRequestHandler;
}
@Override
Validation validate() {
return Validation.SUCCESS;
}
};
assertThat(goServer.configureServer(), sameInstance(server));
verify(server).addHandler(welcomeHandler);
verify(server).addHandler(legacyRequestHandler);
verify(server).addWebAppHandler(mainWebapp);
}
@Test
public void shouldStopServerAndThrowExceptionWhenServerFailsToStartWithAnUnhandledException() throws Exception {
final JettyServer server = mock(JettyServer.class);
final WebAppContext webAppContext = mock(WebAppContext.class);
when(server.getContainer()).thenReturn(new Container());
when(server.getServer()).thenReturn(mock(Server.class));
GoServer goServer = new GoServer() {
@Override
WebAppContext webApp() throws IOException, SAXException, ClassNotFoundException, UnavailableException {
return webAppContext;
}
@Override
JettyServer createServer() {
return server;
}
};
doNothing().when(server).start();
doNothing().when(server).stop();
doReturn(webAppContext).when(server).webAppContext();
when(webAppContext.getUnavailableException()).thenReturn(new RuntimeException("Some unhandled server startup exception"));
try {
goServer.startServer();
fail("Should have thrown an exception");
} catch (RuntimeException e) {
assertThat(e.getMessage(), is("Failed to start Go server."));
assertThat(e.getCause().getMessage(), is("Some unhandled server startup exception"));
}
InOrder inOrder = inOrder(server, webAppContext);
inOrder.verify(server).start();
inOrder.verify(webAppContext).getUnavailableException();
inOrder.verify(server).stop();
}
@Test
public void shouldRedirectRootRequestsToWelcomePage() throws IOException, ServletException {
GoServer goServer = new GoServer(new SystemEnvironment(), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
Handler welcomeHandler = goServer.welcomeFileHandler();
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream output = new ByteArrayOutputStream();
when(response.getWriter()).thenReturn(new PrintWriter(output));
welcomeHandler.handle("/", mock(HttpServletRequest.class), response, Handler.REQUEST);
String responseBody = new String(output.toByteArray());
assertThat(responseBody, is("redirecting.."));
verify(response).setHeader("Location", "/go/home");
verify(response).setStatus(HttpStatus.ORDINAL_301_Moved_Permanently);
verify(response).setHeader(HttpHeaders.CONTENT_TYPE, "text/html");
verify(response).getWriter();
verifyNoMoreInteractions(response);
}
@Test
public void shouldMatchRootUrlAsHandlerContextForWelcomePage() {
GoServer goServer = new GoServer(new SystemEnvironment(), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
ContextHandler handler = goServer.welcomeFileHandler();
assertThat(handler.getContextPath(), is("/"));
}
@Test
public void shouldMatchCruiseUrlContextAsHandlerContextForLegacyRequestHandler() {
GoServer goServer = new GoServer(new SystemEnvironment(), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
ContextHandler handler = goServer.legacyRequestHandler();
assertThat(handler.getContextPath(), is("/cruise"));
}
@Test
public void shouldNotRedirectNonRootRequestsToWelcomePage() throws IOException, ServletException {
GoServer goServer = new GoServer(new SystemEnvironment(), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
Handler welcomeHandler = goServer.welcomeFileHandler();
HttpServletResponse response = mock(HttpServletResponse.class);
welcomeHandler.handle("/foo", mock(HttpServletRequest.class), response, Handler.REQUEST);
verifyNoMoreInteractions(response);
}
@Test
public void shouldNotRedirectNonCruiseRequestsToGoPage() throws IOException, ServletException {
GoServer goServer = new GoServer(new SystemEnvironment(), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
Handler legacyRequestHandler = goServer.legacyRequestHandler();
HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getWriter()).thenReturn(new PrintWriter(new ByteArrayOutputStream()));
HttpServletRequest req = mock(HttpServletRequest.class);
when(req.getMethod()).thenReturn(HttpMethods.GET);
legacyRequestHandler.handle("/cruise_but_not_quite", req, response, Handler.REQUEST);
verifyNoMoreInteractions(response);
legacyRequestHandler.handle("/something_totally_different", req, response, Handler.REQUEST);
verifyNoMoreInteractions(response);
}
@Test
public void shouldLoadAllJarsInTheAddonsDirectoryIntoClassPath() throws Exception {
File addonsDirectory = createInAddonDir("some-addon-dir");
FileSystemUtils.createFile("addon-1.JAR", addonsDirectory);
FileSystemUtils.createFile("addon-2.jar", addonsDirectory);
FileSystemUtils.createFile("addon-3.jAR", addonsDirectory);
FileSystemUtils.createFile("some-file-which-does-not-end-with-dot-jar.txt", addonsDirectory);
File oneAddonDirectory = createInAddonDir("one-addon-dir");
FileSystemUtils.createFile("addon-1.jar", oneAddonDirectory);
File noAddonDirectory = createInAddonDir("no-addon-dir");
GoServer goServerWithMultipleAddons = new GoServer(setJRubyJarsTo(setAddonsPathTo(addonsDirectory)), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
assertExtraClasspath(goServerWithMultipleAddons.webApp(), "test-addons/some-addon-dir/addon-1.JAR", "test-addons/some-addon-dir/addon-2.jar", "test-addons/some-addon-dir/addon-3.jAR");
GoServer goServerWithOneAddon = new GoServer(setJRubyJarsTo(setAddonsPathTo(oneAddonDirectory)), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
assertExtraClasspath(goServerWithOneAddon.webApp(), "test-addons/one-addon-dir/addon-1.jar");
GoServer goServerWithNoAddon = new GoServer(setJRubyJarsTo(setAddonsPathTo(noAddonDirectory)), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
assertThat(goServerWithNoAddon.webApp().getExtraClasspath(), is(""));
GoServer goServerWithInaccessibleAddonDir = new GoServer(setJRubyJarsTo(setAddonsPathTo(new File("non-existent-directory"))), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
assertThat(goServerWithInaccessibleAddonDir.webApp().getExtraClasspath(), is(""));
}
@Test
public void shouldToggleRailsToOldOneWhenTheNewOneIsNotSpecified() throws Exception {
SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);
when(systemEnvironment.get(SystemEnvironment.ADDONS_PATH)).thenReturn("some-non-existent-directory");
when(systemEnvironment.get(SystemEnvironment.USE_NEW_RAILS)).thenReturn(false);
GoServer goServer = new GoServer(systemEnvironment, new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
WebAppContext webApp = goServer.webApp();
assertThat(webApp.getInitParameter("rails.root"), is("/WEB-INF/rails"));
}
@Test
public void shouldToggleRailsToOldOneWhenTheNewOneIsSpecified() throws Exception {
SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);
when(systemEnvironment.get(SystemEnvironment.ADDONS_PATH)).thenReturn("some-non-existent-directory");
when(systemEnvironment.get(SystemEnvironment.USE_NEW_RAILS)).thenReturn(true);
GoServer goServer = new GoServer(systemEnvironment, new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
WebAppContext webApp = goServer.webApp();
assertThat(webApp.getInitParameter("rails.root"), is("/WEB-INF/rails.new"));
}
private void assertExtraClasspath(WebAppContext context, String... expectedClassPathJars) {
List<String> actualExtraClassPath = Arrays.asList(context.getExtraClasspath().split(","));
assertEquals("Number of jars wrong. Expected: " + Arrays.asList(expectedClassPathJars) + ". Actual: " + actualExtraClassPath, expectedClassPathJars.length, actualExtraClassPath.size());
for (String expectedClassPathJar : expectedClassPathJars) {
String platformIndependantNameOfExpectedJar = expectedClassPathJar.replace("/", File.separator);
assertTrue("Expected " + context.getExtraClasspath() + " to contain: " + platformIndependantNameOfExpectedJar, actualExtraClassPath.contains(platformIndependantNameOfExpectedJar));
}
}
private File createInAddonDir(String dirInsideAddonDir) {
File dirWhichWillContainAddons = new File(addonDir, dirInsideAddonDir);
dirWhichWillContainAddons.mkdirs();
return dirWhichWillContainAddons;
}
private SystemEnvironment setAddonsPathTo(File path) {
SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);
doReturn(path.getPath()).when(systemEnvironment).get(SystemEnvironment.ADDONS_PATH);
return systemEnvironment;
}
static class HttpCall {
final String url;
final String method;
final int expectedResponse;
final boolean shouldRedirect;
HttpCall(String url, String method, int expectedResponse, boolean shouldRedirect) {
this.url = url;
this.method = method;
this.expectedResponse = expectedResponse;
this.shouldRedirect = shouldRedirect;
}
@Override public String toString() {
return "HttpCall{" +
"url='" + url + '\'' +
", method='" + method + '\'' +
", expectedResponse=" + expectedResponse +
", shouldRedirect=" + shouldRedirect +
'}';
}
}
@DataPoint public static final HttpCall GET_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.GET, HttpStatus.ORDINAL_301_Moved_Permanently, true);
@DataPoint public static final HttpCall GET_CALL_TO_CRUISE_WITH_NO_SUBPATH = new HttpCall("", HttpMethods.GET, HttpStatus.ORDINAL_301_Moved_Permanently, true);
@DataPoint public static final HttpCall HEAD_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.HEAD, HttpStatus.ORDINAL_301_Moved_Permanently, true);
@DataPoint public static final HttpCall HEAD_CALL_TO_CRUISE_WITH_NO_SUBPATH = new HttpCall("", HttpMethods.HEAD, HttpStatus.ORDINAL_301_Moved_Permanently, true);
@DataPoint public static final HttpCall PUT_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.PUT, HttpStatus.ORDINAL_404_Not_Found, false);
@DataPoint public static final HttpCall POST_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.POST, HttpStatus.ORDINAL_404_Not_Found, false);
@DataPoint public static final HttpCall DELETE_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.DELETE, HttpStatus.ORDINAL_404_Not_Found, false);
@DataPoint public static final HttpCall OPTIONS_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.OPTIONS, HttpStatus.ORDINAL_404_Not_Found, false);
@DataPoint public static final HttpCall TRACE_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.TRACE, HttpStatus.ORDINAL_404_Not_Found, false);
@DataPoint public static final HttpCall CONNECT_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.CONNECT, HttpStatus.ORDINAL_404_Not_Found, false);
@DataPoint public static final HttpCall MOVE_CALL_TO_CRUISE = new HttpCall("/foo/bar?baz=quux", HttpMethods.MOVE, HttpStatus.ORDINAL_404_Not_Found, false);
@Theory
public void shouldRedirectCruiseContextTargetedRequestsToCorrespondingGoUrl(HttpCall httpCall) throws IOException, ServletException {
GoServer goServer = new GoServer(new SystemEnvironment(), new GoCipherSuite(sslSocketFactory), mock(GoWebXmlConfiguration.class));
Handler legacyHandler = goServer.legacyRequestHandler();
HttpServletResponse response = mock(HttpServletResponse.class);
ByteArrayOutputStream output = new ByteArrayOutputStream();
when(response.getWriter()).thenReturn(new PrintWriter(output));
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getMethod()).thenReturn(httpCall.method);
legacyHandler.handle("/cruise" + httpCall.url, request, response, Handler.REQUEST);
String responseBody = new String(output.toByteArray());
assertThat(responseBody, is("Url(s) starting in '/cruise' have been permanently moved to '/go', please use the new path."));
verify(response).setStatus(httpCall.expectedResponse);
if (httpCall.shouldRedirect) {
verify(response).setHeader("Location", "/go" + httpCall.url);
}
verify(response).setHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
verify(response).getWriter();
verifyNoMoreInteractions(response);
}
private SystemEnvironment setJRubyJarsTo(SystemEnvironment mockSystemEnvironment) {
when(mockSystemEnvironment.get(SystemEnvironment.USE_NEW_RAILS)).thenReturn(false);
return mockSystemEnvironment;
}
}
|
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
package com.esotericsoftware.spine;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.SerializationException;
import com.esotericsoftware.spine.Animation.AttachmentTimeline;
import com.esotericsoftware.spine.Animation.ColorTimeline;
import com.esotericsoftware.spine.Animation.CurveTimeline;
import com.esotericsoftware.spine.Animation.DeformTimeline;
import com.esotericsoftware.spine.Animation.DrawOrderTimeline;
import com.esotericsoftware.spine.Animation.EventTimeline;
import com.esotericsoftware.spine.Animation.IkConstraintTimeline;
import com.esotericsoftware.spine.Animation.PathConstraintMixTimeline;
import com.esotericsoftware.spine.Animation.PathConstraintPositionTimeline;
import com.esotericsoftware.spine.Animation.PathConstraintSpacingTimeline;
import com.esotericsoftware.spine.Animation.RotateTimeline;
import com.esotericsoftware.spine.Animation.ScaleTimeline;
import com.esotericsoftware.spine.Animation.ShearTimeline;
import com.esotericsoftware.spine.Animation.Timeline;
import com.esotericsoftware.spine.Animation.TransformConstraintTimeline;
import com.esotericsoftware.spine.Animation.TranslateTimeline;
import com.esotericsoftware.spine.Animation.TwoColorTimeline;
import com.esotericsoftware.spine.BoneData.TransformMode;
import com.esotericsoftware.spine.PathConstraintData.PositionMode;
import com.esotericsoftware.spine.PathConstraintData.RotateMode;
import com.esotericsoftware.spine.PathConstraintData.SpacingMode;
import com.esotericsoftware.spine.attachments.AtlasAttachmentLoader;
import com.esotericsoftware.spine.attachments.Attachment;
import com.esotericsoftware.spine.attachments.AttachmentLoader;
import com.esotericsoftware.spine.attachments.AttachmentType;
import com.esotericsoftware.spine.attachments.BoundingBoxAttachment;
import com.esotericsoftware.spine.attachments.ClippingAttachment;
import com.esotericsoftware.spine.attachments.MeshAttachment;
import com.esotericsoftware.spine.attachments.PathAttachment;
import com.esotericsoftware.spine.attachments.PointAttachment;
import com.esotericsoftware.spine.attachments.RegionAttachment;
import com.esotericsoftware.spine.attachments.VertexAttachment;
/** Loads skeleton data in the Spine JSON format.
* <p>
* See <a href="http://esotericsoftware.com/spine-json-format">Spine JSON format</a> and
* <a href="http://esotericsoftware.com/spine-loading-skeleton-data#JSON-and-binary-data">JSON and binary data</a> in the Spine
* Runtimes Guide. */
public class SkeletonJson {
private final AttachmentLoader attachmentLoader;
private float scale = 1;
private Array<LinkedMesh> linkedMeshes = new Array();
public SkeletonJson (TextureAtlas atlas) {
attachmentLoader = new AtlasAttachmentLoader(atlas);
}
public SkeletonJson (AttachmentLoader attachmentLoader) {
if (attachmentLoader == null) throw new IllegalArgumentException("attachmentLoader cannot be null.");
this.attachmentLoader = attachmentLoader;
}
/** Scales bone positions, image sizes, and translations as they are loaded. This allows different size images to be used at
* runtime than were used in Spine.
* <p>
* See <a href="http://esotericsoftware.com/spine-loading-skeleton-data#Scaling">Scaling</a> in the Spine Runtimes Guide. */
public float getScale () {
return scale;
}
public void setScale (float scale) {
this.scale = scale;
}
protected JsonValue parse (FileHandle file) {
return new JsonReader().parse(file);
}
public SkeletonData readSkeletonData (FileHandle file) {
if (file == null) throw new IllegalArgumentException("file cannot be null.");
float scale = this.scale;
SkeletonData skeletonData = new SkeletonData();
skeletonData.name = file.nameWithoutExtension();
JsonValue root = parse(file);
// Skeleton.
JsonValue skeletonMap = root.get("skeleton");
if (skeletonMap != null) {
skeletonData.hash = skeletonMap.getString("hash", null);
skeletonData.version = skeletonMap.getString("spine", null);
skeletonData.width = skeletonMap.getFloat("width", 0);
skeletonData.height = skeletonMap.getFloat("height", 0);
skeletonData.fps = skeletonMap.getFloat("fps", 30);
skeletonData.imagesPath = skeletonMap.getString("images", null);
skeletonData.audioPath = skeletonMap.getString("audio", null);
}
// Bones.
for (JsonValue boneMap = root.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
BoneData parent = null;
String parentName = boneMap.getString("parent", null);
if (parentName != null) {
parent = skeletonData.findBone(parentName);
if (parent == null) throw new SerializationException("Parent bone not found: " + parentName);
}
BoneData data = new BoneData(skeletonData.bones.size, boneMap.getString("name"), parent);
data.length = boneMap.getFloat("length", 0) * scale;
data.x = boneMap.getFloat("x", 0) * scale;
data.y = boneMap.getFloat("y", 0) * scale;
data.rotation = boneMap.getFloat("rotation", 0);
data.scaleX = boneMap.getFloat("scaleX", 1);
data.scaleY = boneMap.getFloat("scaleY", 1);
data.shearX = boneMap.getFloat("shearX", 0);
data.shearY = boneMap.getFloat("shearY", 0);
data.transformMode = TransformMode.valueOf(boneMap.getString("transform", TransformMode.normal.name()));
String color = boneMap.getString("color", null);
if (color != null) data.getColor().set(Color.valueOf(color));
skeletonData.bones.add(data);
}
// Slots.
for (JsonValue slotMap = root.getChild("slots"); slotMap != null; slotMap = slotMap.next) {
String slotName = slotMap.getString("name");
String boneName = slotMap.getString("bone");
BoneData boneData = skeletonData.findBone(boneName);
if (boneData == null) throw new SerializationException("Slot bone not found: " + boneName);
SlotData data = new SlotData(skeletonData.slots.size, slotName, boneData);
String color = slotMap.getString("color", null);
if (color != null) data.getColor().set(Color.valueOf(color));
String dark = slotMap.getString("dark", null);
if (dark != null) data.setDarkColor(Color.valueOf(dark));
data.attachmentName = slotMap.getString("attachment", null);
data.blendMode = BlendMode.valueOf(slotMap.getString("blend", BlendMode.normal.name()));
skeletonData.slots.add(data);
}
// IK constraints.
for (JsonValue constraintMap = root.getChild("ik"); constraintMap != null; constraintMap = constraintMap.next) {
IkConstraintData data = new IkConstraintData(constraintMap.getString("name"));
data.order = constraintMap.getInt("order", 0);
for (JsonValue boneMap = constraintMap.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
String boneName = boneMap.asString();
BoneData bone = skeletonData.findBone(boneName);
if (bone == null) throw new SerializationException("IK bone not found: " + boneName);
data.bones.add(bone);
}
String targetName = constraintMap.getString("target");
data.target = skeletonData.findBone(targetName);
if (data.target == null) throw new SerializationException("IK target bone not found: " + targetName);
data.mix = constraintMap.getFloat("mix", 1);
data.bendDirection = constraintMap.getBoolean("bendPositive", true) ? 1 : -1;
data.compress = constraintMap.getBoolean("compress", false);
data.stretch = constraintMap.getBoolean("stretch", false);
data.uniform = constraintMap.getBoolean("uniform", false);
skeletonData.ikConstraints.add(data);
}
// Transform constraints.
for (JsonValue constraintMap = root.getChild("transform"); constraintMap != null; constraintMap = constraintMap.next) {
TransformConstraintData data = new TransformConstraintData(constraintMap.getString("name"));
data.order = constraintMap.getInt("order", 0);
for (JsonValue boneMap = constraintMap.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
String boneName = boneMap.asString();
BoneData bone = skeletonData.findBone(boneName);
if (bone == null) throw new SerializationException("Transform constraint bone not found: " + boneName);
data.bones.add(bone);
}
String targetName = constraintMap.getString("target");
data.target = skeletonData.findBone(targetName);
if (data.target == null) throw new SerializationException("Transform constraint target bone not found: " + targetName);
data.local = constraintMap.getBoolean("local", false);
data.relative = constraintMap.getBoolean("relative", false);
data.offsetRotation = constraintMap.getFloat("rotation", 0);
data.offsetX = constraintMap.getFloat("x", 0) * scale;
data.offsetY = constraintMap.getFloat("y", 0) * scale;
data.offsetScaleX = constraintMap.getFloat("scaleX", 0);
data.offsetScaleY = constraintMap.getFloat("scaleY", 0);
data.offsetShearY = constraintMap.getFloat("shearY", 0);
data.rotateMix = constraintMap.getFloat("rotateMix", 1);
data.translateMix = constraintMap.getFloat("translateMix", 1);
data.scaleMix = constraintMap.getFloat("scaleMix", 1);
data.shearMix = constraintMap.getFloat("shearMix", 1);
skeletonData.transformConstraints.add(data);
}
// Path constraints.
for (JsonValue constraintMap = root.getChild("path"); constraintMap != null; constraintMap = constraintMap.next) {
PathConstraintData data = new PathConstraintData(constraintMap.getString("name"));
data.order = constraintMap.getInt("order", 0);
for (JsonValue boneMap = constraintMap.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
String boneName = boneMap.asString();
BoneData bone = skeletonData.findBone(boneName);
if (bone == null) throw new SerializationException("Path bone not found: " + boneName);
data.bones.add(bone);
}
String targetName = constraintMap.getString("target");
data.target = skeletonData.findSlot(targetName);
if (data.target == null) throw new SerializationException("Path target slot not found: " + targetName);
data.positionMode = PositionMode.valueOf(constraintMap.getString("positionMode", "percent"));
data.spacingMode = SpacingMode.valueOf(constraintMap.getString("spacingMode", "length"));
data.rotateMode = RotateMode.valueOf(constraintMap.getString("rotateMode", "tangent"));
data.offsetRotation = constraintMap.getFloat("rotation", 0);
data.position = constraintMap.getFloat("position", 0);
if (data.positionMode == PositionMode.fixed) data.position *= scale;
data.spacing = constraintMap.getFloat("spacing", 0);
if (data.spacingMode == SpacingMode.length || data.spacingMode == SpacingMode.fixed) data.spacing *= scale;
data.rotateMix = constraintMap.getFloat("rotateMix", 1);
data.translateMix = constraintMap.getFloat("translateMix", 1);
skeletonData.pathConstraints.add(data);
}
// Skins.
for (JsonValue skinMap = root.getChild("skins"); skinMap != null; skinMap = skinMap.next) {
Skin skin = new Skin(skinMap.name);
for (JsonValue slotEntry = skinMap.child; slotEntry != null; slotEntry = slotEntry.next) {
SlotData slot = skeletonData.findSlot(slotEntry.name);
if (slot == null) throw new SerializationException("Slot not found: " + slotEntry.name);
for (JsonValue entry = slotEntry.child; entry != null; entry = entry.next) {
try {
Attachment attachment = readAttachment(entry, skin, slot.index, entry.name, skeletonData);
if (attachment != null) skin.addAttachment(slot.index, entry.name, attachment);
} catch (Throwable ex) {
throw new SerializationException("Error reading attachment: " + entry.name + ", skin: " + skin, ex);
}
}
}
skeletonData.skins.add(skin);
if (skin.name.equals("default")) skeletonData.defaultSkin = skin;
}
// Linked meshes.
for (int i = 0, n = linkedMeshes.size; i < n; i++) {
LinkedMesh linkedMesh = linkedMeshes.get(i);
Skin skin = linkedMesh.skin == null ? skeletonData.getDefaultSkin() : skeletonData.findSkin(linkedMesh.skin);
if (skin == null) throw new SerializationException("Skin not found: " + linkedMesh.skin);
Attachment parent = skin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent);
if (parent == null) throw new SerializationException("Parent mesh not found: " + linkedMesh.parent);
linkedMesh.mesh.setParentMesh((MeshAttachment)parent);
linkedMesh.mesh.updateUVs();
}
linkedMeshes.clear();
// Events.
for (JsonValue eventMap = root.getChild("events"); eventMap != null; eventMap = eventMap.next) {
EventData data = new EventData(eventMap.name);
data.intValue = eventMap.getInt("int", 0);
data.floatValue = eventMap.getFloat("float", 0f);
data.stringValue = eventMap.getString("string", "");
data.audioPath = eventMap.getString("audio", null);
if (data.audioPath != null) {
data.volume = eventMap.getFloat("volume", 1);
data.balance = eventMap.getFloat("balance", 0);
}
skeletonData.events.add(data);
}
// Animations.
for (JsonValue animationMap = root.getChild("animations"); animationMap != null; animationMap = animationMap.next) {
try {
readAnimation(animationMap, animationMap.name, skeletonData);
} catch (Throwable ex) {
throw new SerializationException("Error reading animation: " + animationMap.name, ex);
}
}
skeletonData.bones.shrink();
skeletonData.slots.shrink();
skeletonData.skins.shrink();
skeletonData.events.shrink();
skeletonData.animations.shrink();
skeletonData.ikConstraints.shrink();
return skeletonData;
}
private Attachment readAttachment (JsonValue map, Skin skin, int slotIndex, String name, SkeletonData skeletonData) {
float scale = this.scale;
name = map.getString("name", name);
String type = map.getString("type", AttachmentType.region.name());
switch (AttachmentType.valueOf(type)) {
case region: {
String path = map.getString("path", name);
RegionAttachment region = attachmentLoader.newRegionAttachment(skin, name, path);
if (region == null) return null;
region.setPath(path);
region.setX(map.getFloat("x", 0) * scale);
region.setY(map.getFloat("y", 0) * scale);
region.setScaleX(map.getFloat("scaleX", 1));
region.setScaleY(map.getFloat("scaleY", 1));
region.setRotation(map.getFloat("rotation", 0));
region.setWidth(map.getFloat("width") * scale);
region.setHeight(map.getFloat("height") * scale);
String color = map.getString("color", null);
if (color != null) region.getColor().set(Color.valueOf(color));
region.updateOffset();
return region;
}
case boundingbox: {
BoundingBoxAttachment box = attachmentLoader.newBoundingBoxAttachment(skin, name);
if (box == null) return null;
readVertices(map, box, map.getInt("vertexCount") << 1);
String color = map.getString("color", null);
if (color != null) box.getColor().set(Color.valueOf(color));
return box;
}
case mesh:
case linkedmesh: {
String path = map.getString("path", name);
MeshAttachment mesh = attachmentLoader.newMeshAttachment(skin, name, path);
if (mesh == null) return null;
mesh.setPath(path);
String color = map.getString("color", null);
if (color != null) mesh.getColor().set(Color.valueOf(color));
mesh.setWidth(map.getFloat("width", 0) * scale);
mesh.setHeight(map.getFloat("height", 0) * scale);
String parent = map.getString("parent", null);
if (parent != null) {
mesh.setInheritDeform(map.getBoolean("deform", true));
linkedMeshes.add(new LinkedMesh(mesh, map.getString("skin", null), slotIndex, parent));
return mesh;
}
float[] uvs = map.require("uvs").asFloatArray();
readVertices(map, mesh, uvs.length);
mesh.setTriangles(map.require("triangles").asShortArray());
mesh.setRegionUVs(uvs);
mesh.updateUVs();
if (map.has("hull")) mesh.setHullLength(map.require("hull").asInt() * 2);
if (map.has("edges")) mesh.setEdges(map.require("edges").asShortArray());
return mesh;
}
case path: {
PathAttachment path = attachmentLoader.newPathAttachment(skin, name);
if (path == null) return null;
path.setClosed(map.getBoolean("closed", false));
path.setConstantSpeed(map.getBoolean("constantSpeed", true));
int vertexCount = map.getInt("vertexCount");
readVertices(map, path, vertexCount << 1);
float[] lengths = new float[vertexCount / 3];
int i = 0;
for (JsonValue curves = map.require("lengths").child; curves != null; curves = curves.next)
lengths[i++] = curves.asFloat() * scale;
path.setLengths(lengths);
String color = map.getString("color", null);
if (color != null) path.getColor().set(Color.valueOf(color));
return path;
}
case point: {
PointAttachment point = attachmentLoader.newPointAttachment(skin, name);
if (point == null) return null;
point.setX(map.getFloat("x", 0) * scale);
point.setY(map.getFloat("y", 0) * scale);
point.setRotation(map.getFloat("rotation", 0));
String color = map.getString("color", null);
if (color != null) point.getColor().set(Color.valueOf(color));
return point;
}
case clipping: {
ClippingAttachment clip = attachmentLoader.newClippingAttachment(skin, name);
if (clip == null) return null;
String end = map.getString("end", null);
if (end != null) {
SlotData slot = skeletonData.findSlot(end);
if (slot == null) throw new SerializationException("Clipping end slot not found: " + end);
clip.setEndSlot(slot);
}
readVertices(map, clip, map.getInt("vertexCount") << 1);
String color = map.getString("color", null);
if (color != null) clip.getColor().set(Color.valueOf(color));
return clip;
}
}
return null;
}
private void readVertices (JsonValue map, VertexAttachment attachment, int verticesLength) {
attachment.setWorldVerticesLength(verticesLength);
float[] vertices = map.require("vertices").asFloatArray();
if (verticesLength == vertices.length) {
if (scale != 1) {
for (int i = 0, n = vertices.length; i < n; i++)
vertices[i] *= scale;
}
attachment.setVertices(vertices);
return;
}
FloatArray weights = new FloatArray(verticesLength * 3 * 3);
IntArray bones = new IntArray(verticesLength * 3);
for (int i = 0, n = vertices.length; i < n;) {
int boneCount = (int)vertices[i++];
bones.add(boneCount);
for (int nn = i + boneCount * 4; i < nn; i += 4) {
bones.add((int)vertices[i]);
weights.add(vertices[i + 1] * scale);
weights.add(vertices[i + 2] * scale);
weights.add(vertices[i + 3]);
}
}
attachment.setBones(bones.toArray());
attachment.setVertices(weights.toArray());
}
private void readAnimation (JsonValue map, String name, SkeletonData skeletonData) {
float scale = this.scale;
Array<Timeline> timelines = new Array();
float duration = 0;
// Slot timelines.
for (JsonValue slotMap = map.getChild("slots"); slotMap != null; slotMap = slotMap.next) {
SlotData slot = skeletonData.findSlot(slotMap.name);
if (slot == null) throw new SerializationException("Slot not found: " + slotMap.name);
for (JsonValue timelineMap = slotMap.child; timelineMap != null; timelineMap = timelineMap.next) {
String timelineName = timelineMap.name;
if (timelineName.equals("attachment")) {
AttachmentTimeline timeline = new AttachmentTimeline(timelineMap.size);
timeline.slotIndex = slot.index;
int frameIndex = 0;
for (JsonValue valueMap = timelineMap.child; valueMap != null; valueMap = valueMap.next)
timeline.setFrame(frameIndex++, valueMap.getFloat("time"), valueMap.getString("name"));
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[timeline.getFrameCount() - 1]);
} else if (timelineName.equals("color")) {
ColorTimeline timeline = new ColorTimeline(timelineMap.size);
timeline.slotIndex = slot.index;
int frameIndex = 0;
for (JsonValue valueMap = timelineMap.child; valueMap != null; valueMap = valueMap.next) {
Color color = Color.valueOf(valueMap.getString("color"));
timeline.setFrame(frameIndex, valueMap.getFloat("time"), color.r, color.g, color.b, color.a);
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[(timeline.getFrameCount() - 1) * ColorTimeline.ENTRIES]);
} else if (timelineName.equals("twoColor")) {
TwoColorTimeline timeline = new TwoColorTimeline(timelineMap.size);
timeline.slotIndex = slot.index;
int frameIndex = 0;
for (JsonValue valueMap = timelineMap.child; valueMap != null; valueMap = valueMap.next) {
Color light = Color.valueOf(valueMap.getString("light"));
Color dark = Color.valueOf(valueMap.getString("dark"));
timeline.setFrame(frameIndex, valueMap.getFloat("time"), light.r, light.g, light.b, light.a, dark.r, dark.g,
dark.b);
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[(timeline.getFrameCount() - 1) * TwoColorTimeline.ENTRIES]);
} else
throw new RuntimeException("Invalid timeline type for a slot: " + timelineName + " (" + slotMap.name + ")");
}
}
// Bone timelines.
for (JsonValue boneMap = map.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
BoneData bone = skeletonData.findBone(boneMap.name);
if (bone == null) throw new SerializationException("Bone not found: " + boneMap.name);
for (JsonValue timelineMap = boneMap.child; timelineMap != null; timelineMap = timelineMap.next) {
String timelineName = timelineMap.name;
if (timelineName.equals("rotate")) {
RotateTimeline timeline = new RotateTimeline(timelineMap.size);
timeline.boneIndex = bone.index;
int frameIndex = 0;
for (JsonValue valueMap = timelineMap.child; valueMap != null; valueMap = valueMap.next) {
timeline.setFrame(frameIndex, valueMap.getFloat("time"), valueMap.getFloat("angle"));
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[(timeline.getFrameCount() - 1) * RotateTimeline.ENTRIES]);
} else if (timelineName.equals("translate") || timelineName.equals("scale") || timelineName.equals("shear")) {
TranslateTimeline timeline;
float timelineScale = 1;
if (timelineName.equals("scale"))
timeline = new ScaleTimeline(timelineMap.size);
else if (timelineName.equals("shear"))
timeline = new ShearTimeline(timelineMap.size);
else {
timeline = new TranslateTimeline(timelineMap.size);
timelineScale = scale;
}
timeline.boneIndex = bone.index;
int frameIndex = 0;
for (JsonValue valueMap = timelineMap.child; valueMap != null; valueMap = valueMap.next) {
float x = valueMap.getFloat("x", 0), y = valueMap.getFloat("y", 0);
timeline.setFrame(frameIndex, valueMap.getFloat("time"), x * timelineScale, y * timelineScale);
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[(timeline.getFrameCount() - 1) * TranslateTimeline.ENTRIES]);
} else
throw new RuntimeException("Invalid timeline type for a bone: " + timelineName + " (" + boneMap.name + ")");
}
}
// IK constraint timelines.
for (JsonValue constraintMap = map.getChild("ik"); constraintMap != null; constraintMap = constraintMap.next) {
IkConstraintData constraint = skeletonData.findIkConstraint(constraintMap.name);
IkConstraintTimeline timeline = new IkConstraintTimeline(constraintMap.size);
timeline.ikConstraintIndex = skeletonData.getIkConstraints().indexOf(constraint, true);
int frameIndex = 0;
for (JsonValue valueMap = constraintMap.child; valueMap != null; valueMap = valueMap.next) {
timeline.setFrame(frameIndex, valueMap.getFloat("time"), valueMap.getFloat("mix", 1),
valueMap.getBoolean("bendPositive", true) ? 1 : -1, valueMap.getBoolean("compress", false),
valueMap.getBoolean("stretch", false));
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[(timeline.getFrameCount() - 1) * IkConstraintTimeline.ENTRIES]);
}
// Transform constraint timelines.
for (JsonValue constraintMap = map.getChild("transform"); constraintMap != null; constraintMap = constraintMap.next) {
TransformConstraintData constraint = skeletonData.findTransformConstraint(constraintMap.name);
TransformConstraintTimeline timeline = new TransformConstraintTimeline(constraintMap.size);
timeline.transformConstraintIndex = skeletonData.getTransformConstraints().indexOf(constraint, true);
int frameIndex = 0;
for (JsonValue valueMap = constraintMap.child; valueMap != null; valueMap = valueMap.next) {
timeline.setFrame(frameIndex, valueMap.getFloat("time"), valueMap.getFloat("rotateMix", 1),
valueMap.getFloat("translateMix", 1), valueMap.getFloat("scaleMix", 1), valueMap.getFloat("shearMix", 1));
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration,
timeline.getFrames()[(timeline.getFrameCount() - 1) * TransformConstraintTimeline.ENTRIES]);
}
// Path constraint timelines.
for (JsonValue constraintMap = map.getChild("paths"); constraintMap != null; constraintMap = constraintMap.next) {
PathConstraintData data = skeletonData.findPathConstraint(constraintMap.name);
if (data == null) throw new SerializationException("Path constraint not found: " + constraintMap.name);
int index = skeletonData.pathConstraints.indexOf(data, true);
for (JsonValue timelineMap = constraintMap.child; timelineMap != null; timelineMap = timelineMap.next) {
String timelineName = timelineMap.name;
if (timelineName.equals("position") || timelineName.equals("spacing")) {
PathConstraintPositionTimeline timeline;
float timelineScale = 1;
if (timelineName.equals("spacing")) {
timeline = new PathConstraintSpacingTimeline(timelineMap.size);
if (data.spacingMode == SpacingMode.length || data.spacingMode == SpacingMode.fixed) timelineScale = scale;
} else {
timeline = new PathConstraintPositionTimeline(timelineMap.size);
if (data.positionMode == PositionMode.fixed) timelineScale = scale;
}
timeline.pathConstraintIndex = index;
int frameIndex = 0;
for (JsonValue valueMap = timelineMap.child; valueMap != null; valueMap = valueMap.next) {
timeline.setFrame(frameIndex, valueMap.getFloat("time"), valueMap.getFloat(timelineName, 0) * timelineScale);
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration,
timeline.getFrames()[(timeline.getFrameCount() - 1) * PathConstraintPositionTimeline.ENTRIES]);
} else if (timelineName.equals("mix")) {
PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(timelineMap.size);
timeline.pathConstraintIndex = index;
int frameIndex = 0;
for (JsonValue valueMap = timelineMap.child; valueMap != null; valueMap = valueMap.next) {
timeline.setFrame(frameIndex, valueMap.getFloat("time"), valueMap.getFloat("rotateMix", 1),
valueMap.getFloat("translateMix", 1));
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration,
timeline.getFrames()[(timeline.getFrameCount() - 1) * PathConstraintMixTimeline.ENTRIES]);
}
}
}
// Deform timelines.
for (JsonValue deformMap = map.getChild("deform"); deformMap != null; deformMap = deformMap.next) {
Skin skin = skeletonData.findSkin(deformMap.name);
if (skin == null) throw new SerializationException("Skin not found: " + deformMap.name);
for (JsonValue slotMap = deformMap.child; slotMap != null; slotMap = slotMap.next) {
SlotData slot = skeletonData.findSlot(slotMap.name);
if (slot == null) throw new SerializationException("Slot not found: " + slotMap.name);
for (JsonValue timelineMap = slotMap.child; timelineMap != null; timelineMap = timelineMap.next) {
VertexAttachment attachment = (VertexAttachment)skin.getAttachment(slot.index, timelineMap.name);
if (attachment == null) throw new SerializationException("Deform attachment not found: " + timelineMap.name);
boolean weighted = attachment.getBones() != null;
float[] vertices = attachment.getVertices();
int deformLength = weighted ? vertices.length / 3 * 2 : vertices.length;
DeformTimeline timeline = new DeformTimeline(timelineMap.size);
timeline.slotIndex = slot.index;
timeline.attachment = attachment;
int frameIndex = 0;
for (JsonValue valueMap = timelineMap.child; valueMap != null; valueMap = valueMap.next) {
float[] deform;
JsonValue verticesValue = valueMap.get("vertices");
if (verticesValue == null)
deform = weighted ? new float[deformLength] : vertices;
else {
deform = new float[deformLength];
int start = valueMap.getInt("offset", 0);
System.arraycopy(verticesValue.asFloatArray(), 0, deform, start, verticesValue.size);
if (scale != 1) {
for (int i = start, n = i + verticesValue.size; i < n; i++)
deform[i] *= scale;
}
if (!weighted) {
for (int i = 0; i < deformLength; i++)
deform[i] += vertices[i];
}
}
timeline.setFrame(frameIndex, valueMap.getFloat("time"), deform);
readCurve(valueMap, timeline, frameIndex);
frameIndex++;
}
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[timeline.getFrameCount() - 1]);
}
}
}
// Draw order timeline.
JsonValue drawOrdersMap = map.get("drawOrder");
if (drawOrdersMap == null) drawOrdersMap = map.get("draworder");
if (drawOrdersMap != null) {
DrawOrderTimeline timeline = new DrawOrderTimeline(drawOrdersMap.size);
int slotCount = skeletonData.slots.size;
int frameIndex = 0;
for (JsonValue drawOrderMap = drawOrdersMap.child; drawOrderMap != null; drawOrderMap = drawOrderMap.next) {
int[] drawOrder = null;
JsonValue offsets = drawOrderMap.get("offsets");
if (offsets != null) {
drawOrder = new int[slotCount];
for (int i = slotCount - 1; i >= 0; i--)
drawOrder[i] = -1;
int[] unchanged = new int[slotCount - offsets.size];
int originalIndex = 0, unchangedIndex = 0;
for (JsonValue offsetMap = offsets.child; offsetMap != null; offsetMap = offsetMap.next) {
SlotData slot = skeletonData.findSlot(offsetMap.getString("slot"));
if (slot == null) throw new SerializationException("Slot not found: " + offsetMap.getString("slot"));
// Collect unchanged items.
while (originalIndex != slot.index)
unchanged[unchangedIndex++] = originalIndex++;
// Set changed items.
drawOrder[originalIndex + offsetMap.getInt("offset")] = originalIndex++;
}
// Collect remaining unchanged items.
while (originalIndex < slotCount)
unchanged[unchangedIndex++] = originalIndex++;
// Fill in unchanged items.
for (int i = slotCount - 1; i >= 0; i--)
if (drawOrder[i] == -1) drawOrder[i] = unchanged[--unchangedIndex];
}
timeline.setFrame(frameIndex++, drawOrderMap.getFloat("time"), drawOrder);
}
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[timeline.getFrameCount() - 1]);
}
// Event timeline.
JsonValue eventsMap = map.get("events");
if (eventsMap != null) {
EventTimeline timeline = new EventTimeline(eventsMap.size);
int frameIndex = 0;
for (JsonValue eventMap = eventsMap.child; eventMap != null; eventMap = eventMap.next) {
EventData eventData = skeletonData.findEvent(eventMap.getString("name"));
if (eventData == null) throw new SerializationException("Event not found: " + eventMap.getString("name"));
Event event = new Event(eventMap.getFloat("time"), eventData);
event.intValue = eventMap.getInt("int", eventData.intValue);
event.floatValue = eventMap.getFloat("float", eventData.floatValue);
event.stringValue = eventMap.getString("string", eventData.stringValue);
if (event.getData().audioPath != null) {
event.volume = eventMap.getFloat("volume", eventData.volume);
event.balance = eventMap.getFloat("balance", eventData.balance);
}
timeline.setFrame(frameIndex++, event);
}
timelines.add(timeline);
duration = Math.max(duration, timeline.getFrames()[timeline.getFrameCount() - 1]);
}
timelines.shrink();
skeletonData.animations.add(new Animation(name, timelines, duration));
}
void readCurve (JsonValue map, CurveTimeline timeline, int frameIndex) {
JsonValue curve = map.get("curve");
if (curve == null) return;
if (curve.isString() && curve.asString().equals("stepped"))
timeline.setStepped(frameIndex);
else if (curve.isArray()) {
timeline.setCurve(frameIndex, curve.getFloat(0), curve.getFloat(1), curve.getFloat(2), curve.getFloat(3));
}
}
static class LinkedMesh {
String parent, skin;
int slotIndex;
MeshAttachment mesh;
public LinkedMesh (MeshAttachment mesh, String skin, int slotIndex, String parent) {
this.mesh = mesh;
this.skin = skin;
this.slotIndex = slotIndex;
this.parent = parent;
}
}
}
|
package com.twelvemonkeys.imageio.plugins.xwd;
import com.twelvemonkeys.imageio.spi.ReaderWriterProviderInfo;
import com.twelvemonkeys.imageio.spi.ReaderWriterProviderInfoTest;
public class XWDProviderInfoTest extends ReaderWriterProviderInfoTest {
@Override
protected ReaderWriterProviderInfo createProviderInfo() {
return new XWDProviderInfo();
}
}
|
package org.apache.ofbiz.humanres.ability.service.base;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.apache.ofbiz.common.ExecuteFindService.In;
import org.apache.ofbiz.common.ExecuteFindService.Out;
import org.apache.ofbiz.common.ExecuteFindService;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import org.apache.commons.collections4.CollectionUtils;
import java.util.Optional;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.condition.EntityConditionList;
import org.apache.ofbiz.entity.condition.EntityExpr;
import org.apache.ofbiz.entity.condition.EntityOperator;
import com.github.yuri0x7c1.uxcrm.util.OfbizUtil;
import org.apache.ofbiz.humanres.ability.SkillType;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.ofbiz.humanres.recruitment.JobRequisition;
import org.apache.ofbiz.humanres.ability.PartySkill;
import org.apache.ofbiz.order.quote.QuoteItem;
import org.apache.ofbiz.workeffort.workeffort.WorkEffortSkillStandard;
@Slf4j
@Component
@SuppressWarnings("unchecked")
public class SkillTypeBaseService {
protected ExecuteFindService executeFindService;
@Autowired
public SkillTypeBaseService(ExecuteFindService executeFindService) {
this.executeFindService = executeFindService;
}
/**
* Count SkillTypes
*/
public Integer count(EntityConditionList conditions) {
In in = new In();
in.setEntityName(SkillType.NAME);
if (conditions == null) {
in.setNoConditionFind(OfbizUtil.Y);
} else {
in.setEntityConditionList(conditions);
}
Out out = executeFindService.runSync(in);
return out.getListSize();
}
/**
* Find SkillTypes
*/
public List<SkillType> find(Integer start, Integer number,
List<String> orderBy, EntityConditionList conditions) {
List<SkillType> entityList = Collections.emptyList();
In in = new In();
in.setEntityName(SkillType.NAME);
if (start == null) {
start = OfbizUtil.DEFAULT_FIND_START;
}
if (number == null) {
number = OfbizUtil.DEFAULT_FIND_NUMBER;
}
in.setOrderByList(orderBy);
if (conditions == null) {
in.setNoConditionFind(OfbizUtil.Y);
} else {
in.setEntityConditionList(conditions);
}
Out out = executeFindService.runSync(in);
try {
if (out.getListIt() != null) {
entityList = SkillType.fromValues(out.getListIt()
.getPartialList(start, number));
out.getListIt().close();
}
} catch (GenericEntityException e) {
log.error(e.getMessage(), e);
}
return entityList;
}
/**
* Find one SkillType
*/
public Optional<SkillType> findOne(Object skillTypeId) {
List<SkillType> entityList = null;
In in = new In();
in.setEntityName(SkillType.NAME);
in.setEntityConditionList(new EntityConditionList<>(Arrays
.asList(new EntityExpr("skillTypeId", EntityOperator.EQUALS,
skillTypeId)), EntityOperator.AND));
Out out = executeFindService.runSync(in);
try {
if (out.getListIt() != null) {
entityList = SkillType.fromValues(out.getListIt()
.getCompleteList());
out.getListIt().close();
}
} catch (GenericEntityException e) {
log.error(e.getMessage(), e);
}
if (CollectionUtils.isNotEmpty(entityList)) {
return Optional.of(entityList.get(0));
}
return Optional.empty();
}
/**
* Get parent skill type
*/
public Optional<SkillType> getParentSkillType(SkillType skillType) {
List<SkillType> entityList = null;
In in = new In();
in.setEntityName(SkillType.NAME);
in.setEntityConditionList(new EntityConditionList<>(Arrays
.asList(new EntityExpr("skillTypeId", EntityOperator.EQUALS,
skillType.getParentTypeId())), EntityOperator.AND));
Out out = executeFindService.runSync(in);
try {
if (out.getListIt() != null) {
entityList = SkillType.fromValues(out.getListIt()
.getCompleteList());
out.getListIt().close();
}
} catch (GenericEntityException e) {
log.error(e.getMessage(), e);
}
if (CollectionUtils.isNotEmpty(entityList)) {
return Optional.of(entityList.get(0));
}
return Optional.empty();
}
/**
* Get job requisitions
*/
public List<JobRequisition> getJobRequisitions(SkillType skillType,
Integer start, Integer number, List<String> orderBy) {
List<JobRequisition> entityList = Collections.emptyList();
In in = new In();
in.setEntityName(JobRequisition.NAME);
if (start == null) {
start = OfbizUtil.DEFAULT_FIND_START;
}
if (number == null) {
number = OfbizUtil.DEFAULT_FIND_NUMBER;
}
in.setOrderByList(orderBy);
in.setEntityConditionList(new EntityConditionList<>(Arrays
.asList(new EntityExpr("skillTypeId", EntityOperator.EQUALS,
skillType.getSkillTypeId())), EntityOperator.AND));
Out out = executeFindService.runSync(in);
try {
if (out.getListIt() != null) {
entityList = JobRequisition.fromValues(out.getListIt()
.getPartialList(start, number));
out.getListIt().close();
}
} catch (GenericEntityException e) {
log.error(e.getMessage(), e);
}
return entityList;
}
/**
* Get party skills
*/
public List<PartySkill> getPartySkills(SkillType skillType, Integer start,
Integer number, List<String> orderBy) {
List<PartySkill> entityList = Collections.emptyList();
In in = new In();
in.setEntityName(PartySkill.NAME);
if (start == null) {
start = OfbizUtil.DEFAULT_FIND_START;
}
if (number == null) {
number = OfbizUtil.DEFAULT_FIND_NUMBER;
}
in.setOrderByList(orderBy);
in.setEntityConditionList(new EntityConditionList<>(Arrays
.asList(new EntityExpr("skillTypeId", EntityOperator.EQUALS,
skillType.getSkillTypeId())), EntityOperator.AND));
Out out = executeFindService.runSync(in);
try {
if (out.getListIt() != null) {
entityList = PartySkill.fromValues(out.getListIt()
.getPartialList(start, number));
out.getListIt().close();
}
} catch (GenericEntityException e) {
log.error(e.getMessage(), e);
}
return entityList;
}
/**
* Get quote items
*/
public List<QuoteItem> getQuoteItems(SkillType skillType, Integer start,
Integer number, List<String> orderBy) {
List<QuoteItem> entityList = Collections.emptyList();
In in = new In();
in.setEntityName(QuoteItem.NAME);
if (start == null) {
start = OfbizUtil.DEFAULT_FIND_START;
}
if (number == null) {
number = OfbizUtil.DEFAULT_FIND_NUMBER;
}
in.setOrderByList(orderBy);
in.setEntityConditionList(new EntityConditionList<>(Arrays
.asList(new EntityExpr("skillTypeId", EntityOperator.EQUALS,
skillType.getSkillTypeId())), EntityOperator.AND));
Out out = executeFindService.runSync(in);
try {
if (out.getListIt() != null) {
entityList = QuoteItem.fromValues(out.getListIt()
.getPartialList(start, number));
out.getListIt().close();
}
} catch (GenericEntityException e) {
log.error(e.getMessage(), e);
}
return entityList;
}
/**
* Get child skill types
*/
public List<SkillType> getChildSkillTypes(SkillType skillType,
Integer start, Integer number, List<String> orderBy) {
List<SkillType> entityList = Collections.emptyList();
In in = new In();
in.setEntityName(SkillType.NAME);
if (start == null) {
start = OfbizUtil.DEFAULT_FIND_START;
}
if (number == null) {
number = OfbizUtil.DEFAULT_FIND_NUMBER;
}
in.setOrderByList(orderBy);
in.setEntityConditionList(new EntityConditionList<>(Arrays
.asList(new EntityExpr("parentTypeId", EntityOperator.EQUALS,
skillType.getSkillTypeId())), EntityOperator.AND));
Out out = executeFindService.runSync(in);
try {
if (out.getListIt() != null) {
entityList = SkillType.fromValues(out.getListIt()
.getPartialList(start, number));
out.getListIt().close();
}
} catch (GenericEntityException e) {
log.error(e.getMessage(), e);
}
return entityList;
}
/**
* Get work effort skill standards
*/
public List<WorkEffortSkillStandard> getWorkEffortSkillStandards(
SkillType skillType, Integer start, Integer number,
List<String> orderBy) {
List<WorkEffortSkillStandard> entityList = Collections.emptyList();
In in = new In();
in.setEntityName(WorkEffortSkillStandard.NAME);
if (start == null) {
start = OfbizUtil.DEFAULT_FIND_START;
}
if (number == null) {
number = OfbizUtil.DEFAULT_FIND_NUMBER;
}
in.setOrderByList(orderBy);
in.setEntityConditionList(new EntityConditionList<>(Arrays
.asList(new EntityExpr("skillTypeId", EntityOperator.EQUALS,
skillType.getSkillTypeId())), EntityOperator.AND));
Out out = executeFindService.runSync(in);
try {
if (out.getListIt() != null) {
entityList = WorkEffortSkillStandard.fromValues(out.getListIt()
.getPartialList(start, number));
out.getListIt().close();
}
} catch (GenericEntityException e) {
log.error(e.getMessage(), e);
}
return entityList;
}
}
|
package composite1;
/**
* 文本文件类:叶子构件
* Created by fengyuwusong on 2017/11/8 11:40.
*/
public class TextFile extends AbstractFile {
private String name;
public TextFile(String name) {
this.name = name;
}
@Override
public void add(AbstractFile file) {
System.out.println("对不起,不支持该方法!");
}
@Override
public void remove(AbstractFile file) {
System.out.println("对不起,不支持该方法!");
}
@Override
public AbstractFile getChild(int i) {
System.out.println("对不起,不支持该方法!");
return null;
}
@Override
public void killVirus() {
//模拟杀毒
System.out.println("---对文本文件'" + name + "'" + "进行杀毒");
}
}
|
/*
* eZmax API Definition (Full)
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.7
* Contact: support-api@ezmax.ca
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.ezmax.api.model;
import java.util.Objects;
import java.util.Arrays;
import com.ezmax.api.model.EzsigntemplatepackagesignermembershipCreateObjectV1ResponseMPayload;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import eZmaxAPI.JSON;
/**
* EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2022-05-17T16:00:12.138084Z[Etc/UTC]")
public class EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf {
public static final String SERIALIZED_NAME_M_PAYLOAD = "mPayload";
@SerializedName(SERIALIZED_NAME_M_PAYLOAD)
private EzsigntemplatepackagesignermembershipCreateObjectV1ResponseMPayload mPayload;
public EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf() {
}
public EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf mPayload(EzsigntemplatepackagesignermembershipCreateObjectV1ResponseMPayload mPayload) {
this.mPayload = mPayload;
return this;
}
/**
* Get mPayload
* @return mPayload
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "")
public EzsigntemplatepackagesignermembershipCreateObjectV1ResponseMPayload getmPayload() {
return mPayload;
}
public void setmPayload(EzsigntemplatepackagesignermembershipCreateObjectV1ResponseMPayload mPayload) {
this.mPayload = mPayload;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf ezsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf = (EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf) o;
return Objects.equals(this.mPayload, ezsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf.mPayload);
}
@Override
public int hashCode() {
return Objects.hash(mPayload);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf {\n");
sb.append(" mPayload: ").append(toIndentedString(mPayload)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("mPayload");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("mPayload");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf.openapiRequiredFields.isEmpty()) {
return;
} else { // has required fields
throw new IllegalArgumentException(String.format("The required field(s) %s in EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf is not found in the empty JSON string", EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
// validate the optional field `mPayload`
if (jsonObj.getAsJsonObject("mPayload") != null) {
EzsigntemplatepackagesignermembershipCreateObjectV1ResponseMPayload.validateJsonObject(jsonObj.getAsJsonObject("mPayload"));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf.class));
return (TypeAdapter<T>) new TypeAdapter<EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf>() {
@Override
public void write(JsonWriter out, EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf given an JSON string
*
* @param jsonString JSON string
* @return An instance of EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf
* @throws IOException if the JSON string is invalid with respect to EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf
*/
public static EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf.class);
}
/**
* Convert an instance of EzsigntemplatepackagesignermembershipCreateObjectV1ResponseAllOf to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
|
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.profilers.cpu.systemtrace;
import java.io.File;
import trebuchet.io.BufferProducer;
/**
* Interface to wrap producers of trebuchet buffers.
* This interface allows us to better handle errors by not forcing parsing to be done in the constructor instead it is done
* in the {@link #parseFile(File)} method.
*/
public interface TrebuchetBufferProducer extends BufferProducer {
/**
* Called from {@link AtraceParser#parseModelIfNeeded(File)}. This method should trigger the parsing of the supplied file.
* @return true on sucessfull parsing, false otherwise. If false is returned an entry should be logged to the standard error log.
*/
boolean parseFile(File file);
}
|
// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import static com.google.gerrit.server.project.ProjectCache.illegalState;
import com.google.common.collect.Iterables;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.entities.Account;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.LabelType;
import com.google.gerrit.entities.LabelTypes;
import com.google.gerrit.entities.PatchSetApproval;
import com.google.gerrit.entities.Project;
import com.google.gerrit.exceptions.EmailException;
import com.google.gerrit.extensions.api.changes.DeleteReviewerInput;
import com.google.gerrit.extensions.api.changes.NotifyHandling;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.server.ChangeMessagesUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.PatchSetUtil;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.approval.ApprovalsUtil;
import com.google.gerrit.server.extensions.events.ReviewerDeleted;
import com.google.gerrit.server.mail.send.DeleteReviewerSender;
import com.google.gerrit.server.mail.send.MessageIdGenerator;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gerrit.server.notedb.ReviewerStateInternal;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.RemoveReviewerControl;
import com.google.gerrit.server.update.ChangeContext;
import com.google.gerrit.server.update.PostUpdateContext;
import com.google.gerrit.server.update.RepoView;
import com.google.gerrit.server.util.AccountTemplateUtil;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class DeleteReviewerOp extends ReviewerOp {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public interface Factory {
DeleteReviewerOp create(Account reviewerAccount, DeleteReviewerInput input);
}
private final ApprovalsUtil approvalsUtil;
private final PatchSetUtil psUtil;
private final ChangeMessagesUtil cmUtil;
private final ReviewerDeleted reviewerDeleted;
private final Provider<IdentifiedUser> user;
private final DeleteReviewerSender.Factory deleteReviewerSenderFactory;
private final RemoveReviewerControl removeReviewerControl;
private final ProjectCache projectCache;
private final MessageIdGenerator messageIdGenerator;
private final AccountCache accountCache;
private final Account reviewer;
private final DeleteReviewerInput input;
String mailMessage;
Change currChange;
Map<String, Short> newApprovals = new HashMap<>();
Map<String, Short> oldApprovals = new HashMap<>();
@Inject
DeleteReviewerOp(
ApprovalsUtil approvalsUtil,
PatchSetUtil psUtil,
ChangeMessagesUtil cmUtil,
ReviewerDeleted reviewerDeleted,
Provider<IdentifiedUser> user,
DeleteReviewerSender.Factory deleteReviewerSenderFactory,
RemoveReviewerControl removeReviewerControl,
ProjectCache projectCache,
MessageIdGenerator messageIdGenerator,
AccountCache accountCache,
@Assisted Account reviewerAccount,
@Assisted DeleteReviewerInput input) {
this.approvalsUtil = approvalsUtil;
this.psUtil = psUtil;
this.cmUtil = cmUtil;
this.reviewerDeleted = reviewerDeleted;
this.user = user;
this.deleteReviewerSenderFactory = deleteReviewerSenderFactory;
this.removeReviewerControl = removeReviewerControl;
this.projectCache = projectCache;
this.messageIdGenerator = messageIdGenerator;
this.accountCache = accountCache;
this.reviewer = reviewerAccount;
this.input = input;
}
@Override
public boolean updateChange(ChangeContext ctx)
throws AuthException, ResourceNotFoundException, PermissionBackendException, IOException {
Account.Id reviewerId = reviewer.id();
// Check of removing this reviewer (even if there is no vote processed by the loop below) is OK
removeReviewerControl.checkRemoveReviewer(ctx.getNotes(), ctx.getUser(), reviewerId);
if (!approvalsUtil.getReviewers(ctx.getNotes()).all().contains(reviewerId)) {
throw new ResourceNotFoundException(
String.format(
"Reviewer %s doesn't exist in the change, hence can't delete it",
reviewer.getName()));
}
currChange = ctx.getChange();
setPatchSet(psUtil.current(ctx.getNotes()));
LabelTypes labelTypes =
projectCache
.get(ctx.getProject())
.orElseThrow(illegalState(ctx.getProject()))
.getLabelTypes(ctx.getNotes());
// removing a reviewer will remove all her votes
for (LabelType lt : labelTypes.getLabelTypes()) {
newApprovals.put(lt.getName(), (short) 0);
}
String ccOrReviewer =
approvalsUtil
.getReviewers(ctx.getNotes())
.byState(ReviewerStateInternal.CC)
.contains(reviewerId)
? "cc"
: "reviewer";
StringBuilder msg = new StringBuilder();
msg.append(
String.format(
"Removed %s %s", ccOrReviewer, AccountTemplateUtil.getAccountTemplate(reviewer.id())));
StringBuilder removedVotesMsg = new StringBuilder();
removedVotesMsg.append(" with the following votes:\n\n");
boolean votesRemoved = false;
for (PatchSetApproval a : approvals(ctx, reviewerId)) {
// Check if removing this vote is OK
removeReviewerControl.checkRemoveReviewer(ctx.getNotes(), ctx.getUser(), a);
if (a.patchSetId().equals(patchSet.id()) && a.value() != 0) {
oldApprovals.put(a.label(), a.value());
removedVotesMsg
.append("* ")
.append(a.label())
.append(formatLabelValue(a.value()))
.append(" by ")
.append(AccountTemplateUtil.getAccountTemplate(a.accountId()))
.append("\n");
votesRemoved = true;
}
}
if (votesRemoved) {
msg.append(removedVotesMsg);
} else {
msg.append(".");
}
ChangeUpdate update = ctx.getUpdate(patchSet.id());
update.removeReviewer(reviewerId);
mailMessage =
cmUtil.setChangeMessage(ctx, msg.toString(), ChangeMessagesUtil.TAG_DELETE_REVIEWER);
return true;
}
@Override
public void postUpdate(PostUpdateContext ctx) {
opResult = Result.builder().setDeletedReviewer(reviewer.id()).build();
NotifyResolver.Result notify = ctx.getNotify(currChange.getId());
if (sendEmail) {
if (input.notify == null
&& currChange.isWorkInProgress()
&& !oldApprovals.isEmpty()
&& notify.handling().compareTo(NotifyHandling.OWNER) < 0) {
// Override NotifyHandling from the context to notify owner if votes were removed on a WIP
// change.
notify = notify.withHandling(NotifyHandling.OWNER);
}
try {
if (notify.shouldNotify()) {
emailReviewers(
ctx.getProject(),
currChange,
mailMessage,
Timestamp.from(ctx.getWhen()),
notify,
ctx.getRepoView());
}
} catch (Exception err) {
logger.atSevere().withCause(err).log(
"Cannot email update for change %s", currChange.getId());
}
}
NotifyHandling notifyHandling = notify.handling();
eventSender =
() ->
reviewerDeleted.fire(
ctx.getChangeData(currChange),
patchSet,
accountCache.get(reviewer.id()).orElse(AccountState.forAccount(reviewer)),
ctx.getAccount(),
mailMessage,
newApprovals,
oldApprovals,
notifyHandling,
Timestamp.from(ctx.getWhen()));
if (sendEvent) {
sendEvent();
}
}
private Iterable<PatchSetApproval> approvals(ChangeContext ctx, Account.Id accountId) {
Iterable<PatchSetApproval> approvals;
approvals = ctx.getNotes().getApprovalsWithCopied().values();
return Iterables.filter(approvals, psa -> accountId.equals(psa.accountId()));
}
private String formatLabelValue(short value) {
if (value > 0) {
return "+" + value;
}
return Short.toString(value);
}
private void emailReviewers(
Project.NameKey projectName,
Change change,
String mailMessage,
Timestamp timestamp,
NotifyResolver.Result notify,
RepoView repoView)
throws EmailException {
Account.Id userId = user.get().getAccountId();
if (userId.equals(reviewer.id())) {
// The user knows they removed themselves, don't bother emailing them.
return;
}
DeleteReviewerSender emailSender =
deleteReviewerSenderFactory.create(projectName, change.getId());
emailSender.setFrom(userId);
emailSender.addReviewers(Collections.singleton(reviewer.id()));
emailSender.setChangeMessage(mailMessage, timestamp.toInstant());
emailSender.setNotify(notify);
emailSender.setMessageId(
messageIdGenerator.fromChangeUpdate(repoView, change.currentPatchSetId()));
emailSender.send();
}
}
|
/*-
Copyright 2018 Adobe. All rights reserved.
This file is licensed 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
package com.adobe.ride.config.management;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.IncompleteArgumentException;
/**
*
* @author hook
*
*/
public class Validation {
private static Pattern uuidGuidWithDashesPattern = Pattern.compile(
"(?!0{6})[A-Fa-f0-9]{8}\\-(?!0{6})[A-Fa-f0-9]{4}\\-(?!0{6})[A-Fa-f0-9]{4}\\-(?!0{6})[A-Fa-f0-9]{4}\\-(?!0{6})[A-Fa-f0-9]{12}",
Pattern.CASE_INSENSITIVE);
private static Pattern uuidGuidPattern =
Pattern.compile("[A-Fa-f0-9]{32}", Pattern.CASE_INSENSITIVE);
protected Validation() {}
/**
* Check for empty or null parameter.
*
* @param <T> the generic type
* @param parameter the parameter
*/
public static <T> void isNullOrEmptyParameter(T parameter) {
if (parameter == null) {
throw new IllegalArgumentException("A parameter value has been assigned a null value");
}
if (parameter.getClass().equals(String.class) && parameter.toString().isEmpty()) {
throw new IllegalArgumentException("A parameter value has been assigned an empty value");
}
}
/**
* Checks if is null or empty parameter.
*
* @param <T> the generic type
* @param parameterName the name of the parameter that is missing the incoming value
* @param parameter the actual parameter to test if null or empty
*/
public static <T> void isNullOrEmptyParameter(String parameterName, T parameter) {
if (parameter == null) {
throw new IllegalArgumentException(
String.format("%s parameter has been assigned a null value", parameterName));
}
if (parameter.getClass().equals(String.class) && parameter.toString().isEmpty()) {
throw new IllegalArgumentException(
String.format("%s parameter has been assigned an empty value", parameterName));
}
}
/**
* Checks if is null or empty list.
*
* @param <T> the generic type
* @param list the list
*/
public static <T> void isNullOrEmptyList(List<T> list) {
isNullList(list);
if (list.size() == 0) {
throw new NullOrEmptyListException("Incoming parameter list is empty");
}
}
/**
* Checks if is null or empty list.
*
* @param <T> the generic type
* @param listName the name of the list name
* @param list the list
*/
public static <T> void isNullOrEmptyList(String listName, List<T> list) {
isNullList(list);
if (list.size() == 0) {
throw new NullOrEmptyListException(
String.format("Incoming parameter list %s is empty", listName));
}
}
/**
* Checks if is null or empty map.
*
* @param <T> the generic type
* @param <K> the key type
* @param map the map
*/
public static <T, K> void isNullOrEmptyMap(Map<T, K> map) {
isNullMap(map);
if (map.size() == 0) {
throw new NullOrEmptyListException("Incoming parameter map is empty");
}
}
/**
* Checks if is null or empty map.
*
* @param <T> the generic type
* @param <K> the key type
* @param mapName the map name
* @param map the map
*/
public static <T, K> void isNullOrEmptyMap(String mapName, Map<T, K> map) {
isNullMap(map);
if (map.size() == 0) {
throw new NullOrEmptyListException(
String.format("Incoming parameter map %s is empty", mapName));
}
}
/**
* Checks if is null map.
*
* @param <T> the generic type
* @param <K> the key type
* @param map the map
*/
public static <T, K> void isNullMap(Map<T, K> map) {
if (map == null) {
throw new NullOrEmptyListException("Incoming parameter map is null");
}
}
/**
* Checks if is null list.
*
* @param <T> the generic type
* @param list the list
*/
public static <T> void isNullList(List<T> list) {
if (list == null) {
throw new NullOrEmptyListException("Incoming parameter list is null");
}
}
/**
* Represents the case where a method takes in a parameter that has a number of properties, some
* of which have not been set.
*
* @param <T> the generic type
* @param property the property value to validate against
*/
public static <T> void isIncompleteArgument(T property) {
if (property == null) {
throw new IncompleteArgumentException(
"A property of an incoming parameter has been assigned a null value");
}
if (property.getClass().equals(String.class) && property.toString().isEmpty()) {
throw new IncompleteArgumentException(
"A property of an incoming parameter has been assigned an empty value");
}
}
/**
* Represents the case where a method takes in a parameter that has a number of properties, some
* of which have not been set.
*
* @param <T> the generic type
* @param parameterName the name of the actual parameter to which the property belongs
* @param propertyName the property name
* @param property the property value to validate against
*/
public static <T> void isIncompleteArgument(String parameterName, String propertyName,
T property) {
if (property == null) {
throw new IncompleteArgumentException(String.format(
"%s::%s is incomplete and has been assigned a null value", parameterName, propertyName));
}
if (property.getClass().equals(String.class) && property.toString().isEmpty()) {
throw new IncompleteArgumentException(
String.format("%s::%s is incomplete and has been assigned an empty value", parameterName,
propertyName));
}
}
/**
* Validate if an incoming universally unique identifier is in the correct format (GUID/UUID).
*
* @param identifier the identifier can be in the form (A-Z, a-z or 0-9) 36 (with dashes)
* @return true, if the pattern is a complete match, otherwise return value
*/
public static boolean isValidUUID(String identifier) {
if (StringUtilities.isEmpty(identifier)) {
return false;
}
Matcher matcher = uuidGuidWithDashesPattern.matcher(identifier);
return matcher.matches();
}
/**
* Validate if an incoming universally unique identifier is in the correct format (GUID/UUID).
*
* @param identifier the identifier can be in the form (A-Z, a-z or 0-9) 32 (**without** dashes)
* @return true, if the pattern is a complete match, otherwise return value
*/
public static boolean isValidUUIDWithoutDashes(String identifier) {
if (StringUtilities.isEmpty(identifier)) {
return false;
}
Matcher matcher = uuidGuidPattern.matcher(identifier);
return matcher.matches();
}
}
|
/*
* 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.camel.component.cxf;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.SSLContextParametersAware;
import org.apache.camel.component.cxf.common.message.CxfConstants;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.HeaderFilterStrategyComponent;
import org.apache.camel.util.PropertiesHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Defines the <a href="http://camel.apache.org/cxf.html">CXF Component</a>
*/
@Component("cxf")
public class CxfComponent extends HeaderFilterStrategyComponent implements SSLContextParametersAware {
private static final Logger LOG = LoggerFactory.getLogger(CxfComponent.class);
@Metadata(label = "advanced")
private Boolean allowStreaming;
@Metadata(label = "security", defaultValue = "false")
private boolean useGlobalSslContextParameters;
public CxfComponent() {
}
public CxfComponent(CamelContext context) {
super(context);
}
/**
* This option controls whether the CXF component, when running in PAYLOAD mode, will DOM parse the incoming messages
* into DOM Elements or keep the payload as a javax.xml.transform.Source object that would allow streaming in some cases.
*/
public void setAllowStreaming(Boolean allowStreaming) {
this.allowStreaming = allowStreaming;
}
public Boolean getAllowStreaming() {
return allowStreaming;
}
@Override
public boolean isUseGlobalSslContextParameters() {
return this.useGlobalSslContextParameters;
}
/**
* Enable usage of global SSL context parameters.
*/
@Override
public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) {
this.useGlobalSslContextParameters = useGlobalSslContextParameters;
}
/**
* Create a {@link CxfEndpoint} which, can be a Spring bean endpoint having
* URI format cxf:bean:<i>beanId</i> or transport address endpoint having URI format
* cxf://<i>transportAddress</i>.
*/
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
CxfEndpoint result;
Object value = parameters.remove("setDefaultBus");
if (value != null) {
LOG.warn("The option setDefaultBus is @deprecated, use name defaultBus instead");
if (!parameters.containsKey("defaultBus")) {
parameters.put("defaultBus", value);
}
}
if (allowStreaming != null && !parameters.containsKey("allowStreaming")) {
parameters.put("allowStreaming", Boolean.toString(allowStreaming));
}
if (remaining.startsWith(CxfConstants.SPRING_CONTEXT_ENDPOINT)) {
// Get the bean from the Spring context
String beanId = remaining.substring(CxfConstants.SPRING_CONTEXT_ENDPOINT.length());
if (beanId.startsWith("//")) {
beanId = beanId.substring(2);
}
result = createCxfSpringEndpoint(beanId);
result.setBeanId(beanId);
} else {
// endpoint URI does not specify a bean
result = createCxfEndpoint(remaining);
}
result.setComponent(this);
result.setCamelContext(getCamelContext());
setEndpointHeaderFilterStrategy(result);
setProperties(result, parameters);
// extract the properties.xxx and set them as properties
Map<String, Object> properties = PropertiesHelper.extractProperties(parameters, "properties.");
result.setProperties(properties);
// use global ssl config if set
if (result.getSslContextParameters() == null) {
result.setSslContextParameters(retrieveGlobalSslContextParameters());
}
return result;
}
protected CxfEndpoint createCxfSpringEndpoint(String beanId) throws Exception {
return CamelContextHelper.mandatoryLookup(getCamelContext(), beanId, CxfEndpoint.class);
}
protected CxfEndpoint createCxfEndpoint(String remaining) {
return new CxfEndpoint(remaining, this);
}
@Override
protected void afterConfiguration(String uri, String remaining, Endpoint endpoint, Map<String, Object> parameters) throws Exception {
CxfEndpoint cxfEndpoint = (CxfEndpoint) endpoint;
cxfEndpoint.updateEndpointUri(uri);
}
}
|
package org.jhipster.health.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Objects;
/**
* A Points.
*/
@Entity
@Table(name = "points")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "points")
public class Points implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Column(name = "jhi_date", nullable = false)
private LocalDate date;
@Column(name = "exercise")
private Integer exercise;
@Column(name = "meals")
private Integer meals;
@Column(name = "alcohol")
private Integer alcohol;
@Size(max = 140)
@Column(name = "notes", length = 140)
private String notes;
@ManyToOne
@JsonIgnoreProperties("")
private User user;
public Points() {}
public Points(LocalDate date, Integer exercise, Integer meals, Integer alcohol, User user) {
this.date = date;
this.exercise = exercise;
this.meals = meals;
this.alcohol = alcohol;
this.user = user;
}
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getDate() {
return date;
}
public Points date(LocalDate date) {
this.date = date;
return this;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Integer getExercise() {
return exercise;
}
public Points exercise(Integer exercise) {
this.exercise = exercise;
return this;
}
public void setExercise(Integer exercise) {
this.exercise = exercise;
}
public Integer getMeals() {
return meals;
}
public Points meals(Integer meals) {
this.meals = meals;
return this;
}
public void setMeals(Integer meals) {
this.meals = meals;
}
public Integer getAlcohol() {
return alcohol;
}
public Points alcohol(Integer alcohol) {
this.alcohol = alcohol;
return this;
}
public void setAlcohol(Integer alcohol) {
this.alcohol = alcohol;
}
public String getNotes() {
return notes;
}
public Points notes(String notes) {
this.notes = notes;
return this;
}
public void setNotes(String notes) {
this.notes = notes;
}
public User getUser() {
return user;
}
public Points user(User user) {
this.user = user;
return this;
}
public void setUser(User user) {
this.user = user;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Points points = (Points) o;
if (points.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), points.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Points{" +
"id=" + getId() +
", date='" + getDate() + "'" +
", exercise=" + getExercise() +
", meals=" + getMeals() +
", alcohol=" + getAlcohol() +
", notes='" + getNotes() + "'" +
"}";
}
}
|
package com.umeng.analytics.pro;
public abstract class dt
{
public abstract int a(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
throws du;
public void a(int paramInt) {}
public abstract boolean a();
public abstract void b()
throws du;
public void b(byte[] paramArrayOfByte)
throws du
{
b(paramArrayOfByte, 0, paramArrayOfByte.length);
}
public abstract void b(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
throws du;
public abstract void c();
public int d(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
throws du
{
int i = 0;
while (i < paramInt2)
{
int j = a(paramArrayOfByte, paramInt1 + i, paramInt2 - i);
if (j <= 0) {
throw new du("Cannot read. Remote side has closed. Tried to read " + paramInt2 + " bytes, but only got " + i + " bytes. (This is often indicative of an internal error on the server side. Please check your server logs.)");
}
i += j;
}
return i;
}
public void d()
throws du
{}
public byte[] f()
{
return null;
}
public int g()
{
return 0;
}
public int h()
{
return -1;
}
public boolean i()
{
return a();
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/umeng/analytics/pro/dt.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.intellij.ide.util.importProject;
import com.intellij.ide.util.projectWizard.importSources.DetectedProjectRoot;
import com.intellij.ide.util.projectWizard.importSources.DetectedSourceRoot;
import com.intellij.ide.util.projectWizard.importSources.JavaModuleSourceRoot;
import com.intellij.ide.util.projectWizard.importSources.JavaSourceRootDetectionUtil;
import com.intellij.lang.java.JavaParserDefinition;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.module.StdModuleTypes;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.JavaTokenType;
import com.intellij.util.Consumer;
import com.intellij.util.StringBuilderSpinAllocator;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class JavaModuleInsight extends ModuleInsight {
private final Lexer myLexer;
public JavaModuleInsight(@Nullable final ProgressIndicator progress,
Set<String> existingModuleNames,
Set<String> existingProjectLibraryNames) {
super(progress, existingModuleNames, existingProjectLibraryNames);
myLexer = JavaParserDefinition.createLexer(LanguageLevel.JDK_1_5);
}
@Override
protected boolean isSourceFile(final File file) {
return StringUtil.endsWithIgnoreCase(file.getName(), ".java");
}
@Override
protected boolean isLibraryFile(final String fileName) {
return StringUtil.endsWithIgnoreCase(fileName, ".jar") || StringUtil.endsWithIgnoreCase(fileName, ".zip");
}
@Override
protected void scanSourceFileForImportedPackages(final CharSequence chars, final Consumer<String> result) {
myLexer.start(chars);
JavaSourceRootDetectionUtil.skipWhiteSpaceAndComments(myLexer);
if (myLexer.getTokenType() == JavaTokenType.PACKAGE_KEYWORD) {
advanceLexer(myLexer);
if (readPackageName(chars, myLexer) == null) {
return;
}
}
while (true) {
if (myLexer.getTokenType() == JavaTokenType.SEMICOLON) {
advanceLexer(myLexer);
}
if (myLexer.getTokenType() != JavaTokenType.IMPORT_KEYWORD) {
return;
}
advanceLexer(myLexer);
boolean isStaticImport = false;
if (myLexer.getTokenType() == JavaTokenType.STATIC_KEYWORD) {
isStaticImport = true;
advanceLexer(myLexer);
}
final String packageName = readPackageName(chars, myLexer);
if (packageName == null) {
return;
}
if (packageName.endsWith(".*")) {
result.consume(packageName.substring(0, packageName.length() - ".*".length()));
}
else {
int lastDot = packageName.lastIndexOf('.');
if (lastDot > 0) {
String _packageName = packageName.substring(0, lastDot);
if (isStaticImport) {
lastDot = _packageName.lastIndexOf('.');
if (lastDot > 0) {
result.consume(_packageName.substring(0, lastDot));
}
}
else {
result.consume(_packageName);
}
}
}
}
}
@Nullable
private static String readPackageName(final CharSequence text, final Lexer lexer) {
final StringBuilder buffer = StringBuilderSpinAllocator.alloc();
try {
while (true) {
if (lexer.getTokenType() != JavaTokenType.IDENTIFIER && lexer.getTokenType() != JavaTokenType.ASTERISK) {
break;
}
buffer.append(text, lexer.getTokenStart(), lexer.getTokenEnd());
advanceLexer(lexer);
if (lexer.getTokenType() != JavaTokenType.DOT) {
break;
}
buffer.append('.');
advanceLexer(lexer);
}
String packageName = buffer.toString();
if (packageName.length() == 0 || StringUtil.endsWithChar(packageName, '.') || StringUtil.startsWithChar(packageName, '*')) {
return null;
}
return packageName;
}
finally {
StringBuilderSpinAllocator.dispose(buffer);
}
}
private static void advanceLexer(final Lexer lexer) {
lexer.advance();
JavaSourceRootDetectionUtil.skipWhiteSpaceAndComments(lexer);
}
@Override
protected void scanLibraryForDeclaredPackages(File file, Consumer<String> result) throws IOException {
final ZipFile zip = new ZipFile(file);
try {
final Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
final String entryName = entries.nextElement().getName();
if (StringUtil.endsWithIgnoreCase(entryName, ".class")) {
final int index = entryName.lastIndexOf('/');
if (index > 0) {
final String packageName = entryName.substring(0, index).replace('/', '.');
result.consume(packageName);
}
}
}
}
finally {
zip.close();
}
}
protected ModuleDescriptor createModuleDescriptor(final File moduleContentRoot, final Collection<DetectedSourceRoot> sourceRoots) {
return new ModuleDescriptor(moduleContentRoot, StdModuleTypes.JAVA, sourceRoots);
}
public boolean isApplicableRoot(final DetectedProjectRoot root) {
return root instanceof JavaModuleSourceRoot;
}
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.ml;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.template.put.PutComposableIndexTemplateAction;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterModule;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.ComposableIndexTemplate;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.CollectionUtils;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xcontent.NamedXContentRegistry;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xpack.core.ilm.LifecycleAction;
import org.elasticsearch.xpack.core.ilm.RolloverAction;
import org.elasticsearch.xpack.core.ml.MlStatsIndex;
import org.elasticsearch.xpack.core.ml.job.persistence.AnomalyDetectorsIndexFields;
import org.junit.Before;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MlIndexTemplateRegistryTests extends ESTestCase {
private final DiscoveryNode node = new DiscoveryNode("node", ESTestCase.buildNewFakeTransportAddress(), Version.CURRENT);
private final DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build();
private NamedXContentRegistry xContentRegistry;
private ClusterService clusterService;
private ThreadPool threadPool;
private Client client;
private ArgumentCaptor<PutComposableIndexTemplateAction.Request> putIndexTemplateRequestCaptor;
@Before
public void setUpMocks() {
threadPool = mock(ThreadPool.class);
when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY));
when(threadPool.generic()).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE);
client = mock(Client.class);
when(client.threadPool()).thenReturn(threadPool);
AdminClient adminClient = mock(AdminClient.class);
IndicesAdminClient indicesAdminClient = mock(IndicesAdminClient.class);
when(adminClient.indices()).thenReturn(indicesAdminClient);
when(client.admin()).thenReturn(adminClient);
doAnswer(withResponse(AcknowledgedResponse.TRUE)).when(indicesAdminClient).putTemplate(any(), any());
clusterService = mock(ClusterService.class);
xContentRegistry = new NamedXContentRegistry(
CollectionUtils.appendToCopy(
ClusterModule.getNamedXWriteables(),
new NamedXContentRegistry.Entry(LifecycleAction.class, new ParseField(RolloverAction.NAME), RolloverAction::parse)
)
);
putIndexTemplateRequestCaptor = ArgumentCaptor.forClass(PutComposableIndexTemplateAction.Request.class);
}
public void testStateTemplate() {
MlIndexTemplateRegistry registry = new MlIndexTemplateRegistry(
Settings.EMPTY,
clusterService,
threadPool,
client,
xContentRegistry
);
registry.clusterChanged(createClusterChangedEvent(nodes));
verify(client, times(4)).execute(same(PutComposableIndexTemplateAction.INSTANCE), putIndexTemplateRequestCaptor.capture(), any());
PutComposableIndexTemplateAction.Request req = putIndexTemplateRequestCaptor.getAllValues()
.stream()
.filter(r -> r.name().equals(AnomalyDetectorsIndexFields.STATE_INDEX_PREFIX))
.findFirst()
.orElseThrow(() -> new AssertionError("expected the ml state index template to be put"));
ComposableIndexTemplate indexTemplate = req.indexTemplate();
assertThat(indexTemplate.template().settings().get("index.lifecycle.name"), equalTo("ml-size-based-ilm-policy"));
assertThat(indexTemplate.template().settings().get("index.lifecycle.rollover_alias"), equalTo(".ml-state-write"));
}
public void testStatsTemplate() {
MlIndexTemplateRegistry registry = new MlIndexTemplateRegistry(
Settings.EMPTY,
clusterService,
threadPool,
client,
xContentRegistry
);
registry.clusterChanged(createClusterChangedEvent(nodes));
verify(client, times(4)).execute(same(PutComposableIndexTemplateAction.INSTANCE), putIndexTemplateRequestCaptor.capture(), any());
PutComposableIndexTemplateAction.Request req = putIndexTemplateRequestCaptor.getAllValues()
.stream()
.filter(r -> r.name().equals(MlStatsIndex.TEMPLATE_NAME))
.findFirst()
.orElseThrow(() -> new AssertionError("expected the ml stats index template to be put"));
ComposableIndexTemplate indexTemplate = req.indexTemplate();
assertThat(indexTemplate.template().settings().get("index.lifecycle.name"), equalTo("ml-size-based-ilm-policy"));
assertThat(indexTemplate.template().settings().get("index.lifecycle.rollover_alias"), equalTo(".ml-stats-write"));
}
@SuppressWarnings("unchecked")
private static <Response> Answer<Response> withResponse(Response response) {
return invocationOnMock -> {
ActionListener<Response> listener = (ActionListener<Response>) invocationOnMock.getArguments()[1];
listener.onResponse(response);
return null;
};
}
private static ClusterChangedEvent createClusterChangedEvent(DiscoveryNodes nodes) {
return new ClusterChangedEvent(
"created-from-test",
ClusterState.builder(new ClusterName("test")).nodes(nodes).build(),
ClusterState.builder(new ClusterName("test")).build()
);
}
}
|
package it.univaq.mwt.business.model;
import static javax.persistence.AccessType.PROPERTY;
import static javax.persistence.CascadeType.PERSIST;
import static javax.persistence.CascadeType.REFRESH;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Access;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
@Entity
@Access(PROPERTY)
public class Tour implements Serializable {
private int id;
private String nome;
private int durata;
private Set<Evento> eventi = new HashSet<Evento>();
private Gruppo gruppo;
private static final long serialVersionUID = 1L;
public Tour() {
super();
}
public Tour(int id, String nome, int durata, Set<Evento> eventi, Gruppo gruppo) {
super();
this.id = id;
this.nome = nome;
this.durata = durata;
this.eventi = eventi;
this.gruppo = gruppo;
}
public Tour(String nome, int durata, Set<Evento> eventi, Gruppo gruppo) {
super();
this.nome = nome;
this.durata = durata;
this.eventi = eventi;
this.gruppo = gruppo;
}
public Tour(int id, String nome, int durata) {
super();
this.id = id;
this.nome = nome;
this.durata = durata;
}
public Tour(String nome, int durata) {
super();
this.nome = nome;
this.durata = durata;
}
@Id
// @GeneratedValue(strategy=GenerationType.SEQUENCE)
@GeneratedValue(generator = "TourSeq")
@SequenceGenerator(name = "TourSeq", sequenceName = "TOUR_SEQ", allocationSize = 1)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getDurata() {
return durata;
}
public void setDurata(int durata) {
this.durata = durata;
}
@OneToMany(fetch = FetchType.LAZY, cascade = { PERSIST, REFRESH }, mappedBy = "tour")
public Set<Evento> getEventi() {
return eventi;
}
public void setEventi(Set<Evento> eventi) {
this.eventi = eventi;
}
@ManyToOne
public Gruppo getGruppo() {
return gruppo;
}
public void setGruppo(Gruppo gruppo) {
this.gruppo = gruppo;
}
}
|
/*
* 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.
*/
/**
* Micropayment channels allow for rapid tiny payments to be made to a third party once a channel has been set up, using
* some of the advanced features of the Bitcoin protocol.
*/
package org.pivxj.protocols.channels;
|
package uk.gov.hmcts.reform.bulkscanprocessor.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
@ConfigurationProperties("accesstoken")
public class AccessTokenProperties {
private List<TokenConfig> serviceConfig;
public List<TokenConfig> getServiceConfig() {
return serviceConfig;
}
public void setServiceConfig(List<TokenConfig> serviceConfig) {
this.serviceConfig = serviceConfig;
}
public static class TokenConfig {
private String serviceName;
private int validity;
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public int getValidity() {
return validity;
}
public void setValidity(int validity) {
this.validity = validity;
}
}
}
|
/*
* Copyright 2010 sasc
*
* 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 sasc.emv;
import sasc.iso7816.Tag;
/**
*
* Contains Tags specific to a Tag Authority
* The authority is identified either by Issuer Identification Number or RID
*
* Example authorities:
* VISA
* MasterCard
* GlobalPlatform
* ISO7816
* EMV
*
* @author sasc
*/
public interface TagProvider {
/**
* If the tag is not found, this method returns the "[UNHANDLED TAG]" containing 'tagBytes'
*
* @param tagBytes
* @return
*/
public Tag getNotNull(byte[] tagBytes);
/**
* Returns null if Tag not found
*/
public Tag find(byte[] tagBytes);
}
|
package org.pitest.bytecode;
import org.objectweb.asm.ClassWriter;
public class FrameOptions {
private static final int JAVA_7 = 51;
/**
* Java 7 and above require frame info for class version above 7. The ASM compute
* frame options does not support the JSR opcode used by some pre 7 compilers
* when generating java 5 bytecode.
*
* We dodge this issue by only computing frames for classes with a version
* above 6.
*
* @param bs a class
* @return appropriate flags
*/
public static int pickFlags(byte[] bs) {
if ( needsFrames(bs) ) {
return ClassWriter.COMPUTE_FRAMES;
}
return ClassWriter.COMPUTE_MAXS;
}
public static boolean needsFrames(byte[] bs) {
short majorVersion =(short)( ((bs[6]&0xFF)<<8) | (bs[7]&0xFF) );
return majorVersion >= JAVA_7;
}
}
|
/**
* 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.kafka.clients.consumer.internals;
import org.apache.kafka.clients.ClientRequest;
import org.apache.kafka.clients.ClientResponse;
import org.apache.kafka.clients.KafkaClient;
import org.apache.kafka.clients.Metadata;
import org.apache.kafka.clients.RequestCompletionHandler;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.errors.DisconnectException;
import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.protocol.ApiKeys;
import org.apache.kafka.common.requests.AbstractRequest;
import org.apache.kafka.common.requests.RequestHeader;
import org.apache.kafka.common.requests.RequestSend;
import org.apache.kafka.common.utils.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Higher level consumer access to the network layer with basic support for futures and
* task scheduling. NOT thread-safe!
*
* TODO: The current implementation is simplistic in that it provides a facility for queueing requests
* prior to delivery, but it makes no effort to retry requests which cannot be sent at the time
* {@link #poll(long)} is called. This makes the behavior of the queue predictable and easy to
* understand, but there are opportunities to provide timeout or retry capabilities in the future.
* How we do this may depend on KAFKA-2120, so for now, we retain the simplistic behavior.
*/
public class ConsumerNetworkClient implements Closeable {
private static final Logger log = LoggerFactory.getLogger(ConsumerNetworkClient.class);
private final KafkaClient client;
private final AtomicBoolean wakeup = new AtomicBoolean(false);
private final DelayedTaskQueue delayedTasks = new DelayedTaskQueue();
private final Map<Node, List<ClientRequest>> unsent = new HashMap<>();
private final Metadata metadata;
private final Time time;
private final long retryBackoffMs;
// wakeup enabled flag need to be volatile since it is allowed to be accessed concurrently
volatile private boolean wakeupsEnabled = true;
public ConsumerNetworkClient(KafkaClient client,
Metadata metadata,
Time time,
long retryBackoffMs) {
this.client = client;
this.metadata = metadata;
this.time = time;
this.retryBackoffMs = retryBackoffMs;
}
/**
* Schedule a new task to be executed at the given time. This is "best-effort" scheduling and
* should only be used for coarse synchronization.
* @param task The task to be scheduled
* @param at The time it should run
*/
public void schedule(DelayedTask task, long at) {
delayedTasks.add(task, at);
}
/**
* Unschedule a task. This will remove all instances of the task from the task queue.
* This is a no-op if the task is not scheduled.
* @param task The task to be unscheduled.
*/
public void unschedule(DelayedTask task) {
delayedTasks.remove(task);
}
/**
* Send a new request. Note that the request is not actually transmitted on the
* network until one of the {@link #poll(long)} variants is invoked. At this
* point the request will either be transmitted successfully or will fail.
* Use the returned future to obtain the result of the send. Note that there is no
* need to check for disconnects explicitly on the {@link ClientResponse} object;
* instead, the future will be failed with a {@link DisconnectException}.
* @param node The destination of the request
* @param api The Kafka API call
* @param request The request payload
* @return A future which indicates the result of the send.
*/
public RequestFuture<ClientResponse> send(Node node,
ApiKeys api,
AbstractRequest request) {
long now = time.milliseconds();
RequestFutureCompletionHandler future = new RequestFutureCompletionHandler();
RequestHeader header = client.nextRequestHeader(api);
RequestSend send = new RequestSend(node.idString(), header, request.toStruct());
put(node, new ClientRequest(now, true, send, future));
return future;
}
private void put(Node node, ClientRequest request) {
List<ClientRequest> nodeUnsent = unsent.get(node);
if (nodeUnsent == null) {
nodeUnsent = new ArrayList<>();
unsent.put(node, nodeUnsent);
}
nodeUnsent.add(request);
}
public Node leastLoadedNode() {
return client.leastLoadedNode(time.milliseconds());
}
/**
* Block until the metadata has been refreshed.
*/
public void awaitMetadataUpdate() {
int version = this.metadata.requestUpdate();
do {
poll(Long.MAX_VALUE);
} while (this.metadata.version() == version);
}
/**
* Ensure our metadata is fresh (if an update is expected, this will block
* until it has completed).
*/
public void ensureFreshMetadata() {
if (this.metadata.timeToNextUpdate(time.milliseconds()) == 0)
awaitMetadataUpdate();
}
/**
* Wakeup an active poll. This will cause the polling thread to throw an exception either
* on the current poll if one is active, or the next poll.
*/
public void wakeup() {
this.wakeup.set(true);
this.client.wakeup();
}
/**
* Block indefinitely until the given request future has finished.
* @param future The request future to await.
* @throws WakeupException if {@link #wakeup()} is called from another thread
*/
public void poll(RequestFuture<?> future) {
while (!future.isDone())
poll(Long.MAX_VALUE);
}
/**
* Block until the provided request future request has finished or the timeout has expired.
* @param future The request future to wait for
* @param timeout The maximum duration (in ms) to wait for the request
* @return true if the future is done, false otherwise
* @throws WakeupException if {@link #wakeup()} is called from another thread
*/
public boolean poll(RequestFuture<?> future, long timeout) {
long begin = time.milliseconds();
long remaining = timeout;
long now = begin;
do {
poll(remaining, now, true);
now = time.milliseconds();
long elapsed = now - begin;
remaining = timeout - elapsed;
} while (!future.isDone() && remaining > 0);
return future.isDone();
}
/**
* Poll for any network IO. All send requests will either be transmitted on the network
* or failed when this call completes.
* @param timeout The maximum time to wait for an IO event.
* @throws WakeupException if {@link #wakeup()} is called from another thread
*/
public void poll(long timeout) {
poll(timeout, time.milliseconds(), true);
}
/**
* Poll for network IO and return immediately. This will not trigger wakeups,
* nor will it execute any delayed tasks.
*/
public void quickPoll() {
disableWakeups();
poll(0, time.milliseconds(), false);
enableWakeups();
}
private void poll(long timeout, long now, boolean executeDelayedTasks) {
// send all the requests we can send now
trySend(now);
// ensure we don't poll any longer than the deadline for
// the next scheduled task
timeout = Math.min(timeout, delayedTasks.nextTimeout(now));
clientPoll(timeout, now);
now = time.milliseconds();
// handle any disconnects by failing the active requests. note that disconects must
// be checked immediately following poll since any subsequent call to client.ready()
// will reset the disconnect status
checkDisconnects(now);
// execute scheduled tasks
if (executeDelayedTasks)
delayedTasks.poll(now);
// try again to send requests since buffer space may have been
// cleared or a connect finished in the poll
trySend(now);
// fail all requests that couldn't be sent
failUnsentRequests();
}
/**
* Block until all pending requests from the given node have finished.
* @param node The node to await requests from
*/
public void awaitPendingRequests(Node node) {
while (pendingRequestCount(node) > 0)
poll(retryBackoffMs);
}
/**
* Get the count of pending requests to the given node. This includes both request that
* have been transmitted (i.e. in-flight requests) and those which are awaiting transmission.
* @param node The node in question
* @return The number of pending requests
*/
public int pendingRequestCount(Node node) {
List<ClientRequest> pending = unsent.get(node);
int unsentCount = pending == null ? 0 : pending.size();
return unsentCount + client.inFlightRequestCount(node.idString());
}
/**
* Get the total count of pending requests from all nodes. This includes both requests that
* have been transmitted (i.e. in-flight requests) and those which are awaiting transmission.
* @return The total count of pending requests
*/
public int pendingRequestCount() {
int total = 0;
for (List<ClientRequest> requests: unsent.values())
total += requests.size();
return total + client.inFlightRequestCount();
}
private void checkDisconnects(long now) {
// any disconnects affecting requests that have already been transmitted will be handled
// by NetworkClient, so we just need to check whether connections for any of the unsent
// requests have been disconnected; if they have, then we complete the corresponding future
// and set the disconnect flag in the ClientResponse
Iterator<Map.Entry<Node, List<ClientRequest>>> iterator = unsent.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Node, List<ClientRequest>> requestEntry = iterator.next();
Node node = requestEntry.getKey();
if (client.connectionFailed(node)) {
for (ClientRequest request : requestEntry.getValue()) {
RequestFutureCompletionHandler handler =
(RequestFutureCompletionHandler) request.callback();
handler.onComplete(new ClientResponse(request, now, true, null));
}
iterator.remove();
}
}
}
private void failUnsentRequests() {
// clear all unsent requests and fail their corresponding futures
for (Map.Entry<Node, List<ClientRequest>> requestEntry: unsent.entrySet()) {
Iterator<ClientRequest> iterator = requestEntry.getValue().iterator();
while (iterator.hasNext()) {
ClientRequest request = iterator.next();
RequestFutureCompletionHandler handler =
(RequestFutureCompletionHandler) request.callback();
handler.raise(SendFailedException.INSTANCE);
iterator.remove();
}
}
unsent.clear();
}
private boolean trySend(long now) {
// send any requests that can be sent now
boolean requestsSent = false;
for (Map.Entry<Node, List<ClientRequest>> requestEntry: unsent.entrySet()) {
Node node = requestEntry.getKey();
Iterator<ClientRequest> iterator = requestEntry.getValue().iterator();
while (iterator.hasNext()) {
ClientRequest request = iterator.next();
if (client.ready(node, now)) {
client.send(request, now);
iterator.remove();
requestsSent = true;
}
}
}
return requestsSent;
}
private void clientPoll(long timeout, long now) {
client.poll(timeout, now);
if (wakeupsEnabled && wakeup.get()) {
failUnsentRequests();
wakeup.set(false);
throw new WakeupException();
}
}
public void disableWakeups() {
this.wakeupsEnabled = false;
}
public void enableWakeups() {
this.wakeupsEnabled = true;
// re-wakeup the client if the flag was set since previous wake-up call
// could be cleared by poll(0) while wakeups were disabled
if (wakeup.get())
this.client.wakeup();
}
@Override
public void close() throws IOException {
client.close();
}
/**
* Find whether a previous connection has failed. Note that the failure state will persist until either
* {@link #tryConnect(Node)} or {@link #send(Node, ApiKeys, AbstractRequest)} has been called.
* @param node Node to connect to if possible
*/
public boolean connectionFailed(Node node) {
return client.connectionFailed(node);
}
/**
* Initiate a connection if currently possible. This is only really useful for resetting the failed
* status of a socket. If there is an actual request to send, then {@link #send(Node, ApiKeys, AbstractRequest)}
* should be used.
* @param node The node to connect to
*/
public void tryConnect(Node node) {
client.ready(node, time.milliseconds());
}
public static class RequestFutureCompletionHandler
extends RequestFuture<ClientResponse>
implements RequestCompletionHandler {
@Override
public void onComplete(ClientResponse response) {
if (response.wasDisconnected()) {
ClientRequest request = response.request();
RequestSend send = request.request();
ApiKeys api = ApiKeys.forId(send.header().apiKey());
int correlation = send.header().correlationId();
log.debug("Cancelled {} request {} with correlation id {} due to node {} being disconnected",
api, request, correlation, send.destination());
raise(DisconnectException.INSTANCE);
} else {
complete(response);
}
}
}
}
|
package com.pi4j.io.gpio.digital;
/*-
* #%L
* **********************************************************************
* ORGANIZATION : Pi4J
* PROJECT : Pi4J :: LIBRARY :: Java Library (CORE)
* FILENAME : DigitalConfig.java
*
* This file is part of the Pi4J project. More information about
* this project can be found here: https://pi4j.com/
* **********************************************************************
*
* 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.
* #L%
*/
import com.pi4j.config.Config;
import com.pi4j.io.gpio.GpioConfig;
/**
* <p>DigitalConfig interface.</p>
*
* @author Robert Savage (<a href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>)
* @version $Id: $Id
*/
public interface DigitalConfig<CONFIG_TYPE extends Config> extends GpioConfig<CONFIG_TYPE> {
/** Constant <code>ON_STATE_KEY="onstate"</code> */
String ON_STATE_KEY = "onstate";
/**
* <p>onState.</p>
*
* @return a {@link com.pi4j.io.gpio.digital.DigitalState} object.
*/
DigitalState onState();
/**
* <p>getOnState.</p>
*
* @return a {@link com.pi4j.io.gpio.digital.DigitalState} object.
*/
default DigitalState getOnState(){
return this.onState();
}
}
|
/*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 Board of Regents of the University of
* Wisconsin-Madison and University of Konstanz.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
* #L%
*/
package net.imagej.ops;
import net.imglib2.FinalInterval;
import net.imglib2.img.Img;
import net.imglib2.img.array.ArrayImg;
import net.imglib2.img.array.ArrayImgs;
import net.imglib2.img.basictypeaccess.array.FloatArray;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Intervals;
import org.junit.After;
import org.junit.Before;
import org.scijava.Context;
import org.scijava.plugin.Parameter;
/**
* Base class for {@link Op} unit testing.
* <p>
* <i>All</i> {@link Op} unit tests need to have an {@link OpService} instance.
* Following the DRY principle, we should implement it only once. Here.
* </p>
*
* @author Johannes Schindelin
* @author Curtis Rueden
*/
public abstract class AbstractOpTest {
@Parameter
protected Context context;
@Parameter
protected OpService ops;
@Parameter
protected OpMatchingService matcher;
/** Subclasses can override to create a context with different services. */
protected Context createContext() {
return new Context(OpService.class, OpMatchingService.class);
}
/** Sets up a SciJava context with {@link OpService}. */
@Before
public void setUp() {
createContext().inject(this);
}
/**
* Disposes of the {@link OpService} that was initialized in {@link #setUp()}.
*/
@After
public synchronized void cleanUp() {
if (context != null) {
context.dispose();
context = null;
ops = null;
matcher = null;
}
}
private int seed;
private int pseudoRandom() {
return seed = 3170425 * seed + 132102;
}
public Img<ByteType> generateByteTestImg(final boolean fill,
final long... dims)
{
final byte[] array =
new byte[(int) Intervals.numElements(new FinalInterval(dims))];
if (fill) {
seed = 17;
for (int i = 0; i < array.length; i++) {
array[i] = (byte) pseudoRandom();
}
}
return ArrayImgs.bytes(array, dims);
}
public Img<UnsignedByteType> generateUnsignedByteTestImg(final boolean fill,
final long... dims)
{
final byte[] array =
new byte[(int) Intervals.numElements(new FinalInterval(dims))];
if (fill) {
seed = 17;
for (int i = 0; i < array.length; i++) {
array[i] = (byte) pseudoRandom();
}
}
return ArrayImgs.unsignedBytes(array, dims);
}
public ArrayImg<FloatType, FloatArray> generateFloatArrayTestImg(
final boolean fill, final long... dims)
{
final float[] array =
new float[(int) Intervals.numElements(new FinalInterval(dims))];
if (fill) {
seed = 17;
for (int i = 0; i < array.length; i++) {
array[i] = (float) pseudoRandom() / (float) Integer.MAX_VALUE;
}
}
return ArrayImgs.floats(array, dims);
}
}
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.soap.mail.type;
import com.google.common.base.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import com.zimbra.common.soap.MailConstants;
@XmlAccessorType(XmlAccessType.NONE)
public class FreeBusyUserSpec {
/**
* @zm-api-field-tag calendar-folder-id
* @zm-api-field-description Calendar folder ID; if omitted, get f/b on all calendar folders
*/
@XmlAttribute(name=MailConstants.A_FOLDER /* l */, required=false)
private Integer folderId;
/**
* @zm-api-field-tag zimbra-id
* @zm-api-field-description Zimbra ID Either "name" or "id" must be specified
*/
@XmlAttribute(name=MailConstants.A_ID /* id */, required=false)
private String id;
/**
* @zm-api-field-tag email
* @zm-api-field-description Email address. Either "name" or "id" must be specified
*/
@XmlAttribute(name=MailConstants.A_NAME /* name */, required=false)
private String name;
public FreeBusyUserSpec() {
}
public void setFolderId(Integer folderId) { this.folderId = folderId; }
public void setId(String id) { this.id = id; }
public void setName(String name) { this.name = name; }
public Integer getFolderId() { return folderId; }
public String getId() { return id; }
public String getName() { return name; }
public Objects.ToStringHelper addToStringInfo(Objects.ToStringHelper helper) {
return helper
.add("folderId", folderId)
.add("id", id)
.add("name", name);
}
@Override
public String toString() {
return addToStringInfo(Objects.toStringHelper(this)).toString();
}
}
|
package org.lisasp.basics.test.jre.io;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.lisasp.basics.jre.io.ActualFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Comparator;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ActualFileTest {
private ActualFile actualFile;
private Path filename;
private Path dirname;
private Path fileInDirectory1;
private Path fileInDirectory2;
private Path fileInDirectory3;
@BeforeEach
void prepare() throws IOException {
File tempFile = File.createTempFile("ActualFileTest-", "-test");
filename = tempFile.toPath();
Files.deleteIfExists(filename);
File tmpDir = File.createTempFile("ActualFileTest-", "-directory");
dirname = tmpDir.toPath();
Files.deleteIfExists(dirname);
Files.createDirectories(dirname);
fileInDirectory1 = dirname.resolve("file1.txt");
fileInDirectory2 = dirname.resolve("file2.dat");
fileInDirectory3 = dirname.resolve("file3.bin");
Files.write(fileInDirectory1, new byte[0]);
Files.write(fileInDirectory2, new byte[0]);
Files.write(fileInDirectory3, new byte[0]);
actualFile = new ActualFile();
}
@AfterEach
void cleanup() throws IOException {
Files.deleteIfExists(filename);
deleteDirectory(dirname);
}
@Nested
class AppendTest {
@Test
void singleExecution() throws IOException {
actualFile.append(filename, (byte) 0x01);
assertEquals(1, getFileSize());
}
@Test
void multipleExecution() throws IOException {
actualFile.append(filename, (byte) 0x04);
actualFile.append(filename, (byte) 0x03);
actualFile.append(filename, (byte) 0x02);
actualFile.append(filename, (byte) 0x01);
assertEquals(4, getFileSize());
}
@Test
void nullTest() {
assertThrows(NullPointerException.class, () -> actualFile.append(null, (byte) 0x00));
}
}
@Nested
class PutTest {
@Test
void singleExecution() throws IOException {
actualFile.put(filename, (byte) 0x01);
assertEquals(1, getFileSize());
}
@Test
void multipleExecution() throws IOException {
actualFile.put(filename, (byte) 0x04);
actualFile.put(filename, (byte) 0x03);
assertEquals(1, getFileSize());
}
@Test
void nullTest() {
assertThrows(NullPointerException.class, () -> actualFile.put(null, (byte) 0x00));
}
}
@Nested
class GetTest {
@Test
void read() throws IOException {
Files.write(filename,
new byte[]{0x02, 0x03, 0x05, 0x06},
StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);
byte[] actual = actualFile.get(filename);
assertArrayEquals(new byte[]{0x02, 0x03, 0x05, 0x06}, actual);
}
@Test
void readNonExisting() throws IOException {
byte[] actual = actualFile.get(filename);
assertArrayEquals(new byte[0], actual);
}
@Test
void nullTest() {
assertThrows(NullPointerException.class, () -> actualFile.get(null));
}
}
@Nested
class ExistsTest {
@Test
void exists() throws IOException {
File tempFile = File.createTempFile("ActualFileExistsTest-", "-test");
tempFile.deleteOnExit();
Path pathToExistingFile = tempFile.toPath();
boolean exists = actualFile.exists(pathToExistingFile);
assertTrue(exists);
}
@Test
void doesNotExist() throws IOException {
boolean exists = actualFile.exists(filename);
assertFalse(exists);
}
@Test
void nullTest() {
assertThrows(NullPointerException.class, () -> actualFile.exists(null));
}
}
@Nested
class CreateDirectoriesTest {
@Test
void exists() throws IOException {
actualFile.createDirectories(dirname);
assertTrue(Files.exists(dirname));
}
@Test
void depth1() throws IOException {
Path newDirectory = dirname.resolve("abc");
actualFile.createDirectories(newDirectory);
assertTrue(Files.exists(newDirectory));
}
@Test
void depth2() throws IOException {
Path newDirectory = dirname.resolve("abc").resolve("def");
actualFile.createDirectories(newDirectory);
assertTrue(Files.exists(newDirectory));
}
@Test
void nullTest() {
assertThrows(NullPointerException.class, () -> actualFile.createDirectories(null));
}
}
@Nested
class FindTest {
@ParameterizedTest
@ValueSource(ints = {0, 1, 2})
void findDirectoriesTest(int maxDepth) throws IOException {
List<Path> files = actualFile.find(dirname, maxDepth, (path, basicFileAttributes) -> basicFileAttributes.isDirectory()).toList();
assertTrue(files.contains(dirname));
assertEquals(1, files.size());
}
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void findFilesTest(int maxDepth) throws IOException {
List<Path> files = actualFile.find(dirname, maxDepth, (path, basicFileAttributes) -> basicFileAttributes.isRegularFile()).toList();
assertTrue(files.contains(fileInDirectory1));
assertTrue(files.contains(fileInDirectory2));
assertTrue(files.contains(fileInDirectory3));
assertEquals(3, files.size());
}
@Test
void findFilesWithDepth0Test() throws IOException {
List<Path> files = actualFile.find(dirname, 0, (path, basicFileAttributes) -> basicFileAttributes.isRegularFile()).toList();
assertEquals(0, files.size());
}
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void findTest(int maxDepth) throws IOException {
List<Path> files = actualFile.find(dirname, maxDepth, (path, basicFileAttributes) -> true).toList();
assertTrue(files.contains(dirname));
assertTrue(files.contains(fileInDirectory1));
assertTrue(files.contains(fileInDirectory2));
assertTrue(files.contains(fileInDirectory3));
assertEquals(4, files.size());
}
@Test
void findWithDepth0Test() throws IOException {
List<Path> files = actualFile.find(dirname, 0, (path, basicFileAttributes) -> true).toList();
assertTrue(files.contains(dirname));
assertEquals(1, files.size());
}
@Test
void pathNullTest() {
assertThrows(NullPointerException.class,
() -> actualFile.find(null, 0, (path, basicFileAttributes) -> true));
}
@Test
void matcherNullTest() {
assertThrows(NullPointerException.class,
() -> actualFile.find(dirname, 0, null));
}
}
private void deleteDirectory(Path pathToBeDeleted) throws IOException {
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
private long getFileSize() throws IOException {
return Files.size(filename);
}
}
|
package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
/*
Copyright 2003-2014 Bo Zimmerman
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.
*/
public class GenBanker extends StdBanker
{
@Override public String ID(){return "GenBanker";}
protected String PrejudiceFactors="";
protected String bankChain="GenBank";
private String IgnoreMask="";
public GenBanker()
{
super();
username="a generic banker";
setDescription("He looks like he wants your money.");
setDisplayText("A generic banker stands here.");
basePhyStats().setAbility(11); // his only off-default
}
@Override public boolean isGeneric(){return true;}
@Override
public String text()
{
if(CMProps.getBoolVar(CMProps.Bool.MOBCOMPRESS))
miscText=CMLib.encoder().compressString(CMLib.coffeeMaker().getPropertiesStr(this,false));
else
miscText=CMLib.coffeeMaker().getPropertiesStr(this,false);
return super.text();
}
@Override public String prejudiceFactors(){return PrejudiceFactors;}
@Override public void setPrejudiceFactors(String factors){PrejudiceFactors=factors;}
@Override public String ignoreMask(){return IgnoreMask;}
@Override public void setIgnoreMask(String factors){IgnoreMask=factors;}
@Override public String bankChain(){return bankChain;}
@Override public void setBankChain(String name){bankChain=name;}
@Override
public void setMiscText(String newText)
{
super.setMiscText(newText);
CMLib.coffeeMaker().resetGenMOB(this,newText);
}
private final static String[] MYCODES={"WHATISELL","PREJUDICE","BANKCHAIN","COININT","ITEMINT","IGNOREMASK","LOANINT","PRICEMASKS"};
@Override
public String getStat(String code)
{
if(CMLib.coffeeMaker().getGenMobCodeNum(code)>=0)
return CMLib.coffeeMaker().getGenMobStat(this,code);
switch(getCodeNum(code))
{
case 0: return ""+getWhatIsSoldMask();
case 1: return prejudiceFactors();
case 2: return bankChain();
case 3: return ""+getCoinInterest();
case 4: return ""+getItemInterest();
case 5: return ignoreMask();
case 6: return ""+getLoanInterest();
case 7: return CMParms.toStringList(itemPricingAdjustments());
default:
return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code);
}
}
@Override
public void setStat(String code, String val)
{
if(CMLib.coffeeMaker().getGenMobCodeNum(code)>=0)
CMLib.coffeeMaker().setGenMobStat(this,code,val);
else
switch(getCodeNum(code))
{
case 0:{
if((val.length()==0)||(CMath.isLong(val)))
setWhatIsSoldMask(CMath.s_long(val));
else
if(CMParms.containsIgnoreCase(ShopKeeper.DEAL_DESCS,val))
setWhatIsSoldMask(CMParms.indexOfIgnoreCase(ShopKeeper.DEAL_DESCS,val));
break;
}
case 1: setPrejudiceFactors(val); break;
case 2: setBankChain(val); break;
case 3: setCoinInterest(CMath.s_double(val)); break;
case 4: setItemInterest(CMath.s_double(val)); break;
case 5: setIgnoreMask(val); break;
case 6: setLoanInterest(CMath.s_double(val)); break;
case 7: setItemPricingAdjustments((val.trim().length()==0)?new String[0]:CMParms.toStringArray(CMParms.parseCommas(val,true))); break;
default:
CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val);
break;
}
}
@Override
protected int getCodeNum(String code)
{
for(int i=0;i<MYCODES.length;i++)
if(code.equalsIgnoreCase(MYCODES[i]))
return i;
return -1;
}
private static String[] codes=null;
@Override
public String[] getStatCodes()
{
if(codes!=null)
return codes;
final String[] MYCODES=CMProps.getStatCodesList(GenBanker.MYCODES,this);
final String[] superCodes=GenericBuilder.GENMOBCODES;
codes=new String[superCodes.length+MYCODES.length];
int i=0;
for(;i<superCodes.length;i++)
codes[i]=superCodes[i];
for(int x=0;x<MYCODES.length;i++,x++)
codes[i]=MYCODES[x];
return codes;
}
@Override
public boolean sameAs(Environmental E)
{
if(!(E instanceof GenBanker))
return false;
final String[] codes=getStatCodes();
for(int i=0;i<codes.length;i++)
if(!E.getStat(codes[i]).equals(getStat(codes[i])))
return false;
return true;
}
}
|
/*
* #%L
* Maven Integration for Eclipse CDT
* %%
* Copyright (C) 2014 Stephen Edwards
* %%
* 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.
* #L%
*/
package com.github.sdedwards.m2e_nar.internal;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.maven_nar.EclipseNarLayout;
import com.github.maven_nar.ICompiler;
import com.github.maven_nar.ILib;
import com.github.maven_nar.ILibrary;
import com.github.maven_nar.ILinker;
import com.github.maven_nar.INarCompileMojo;
import com.github.maven_nar.ISysLib;
import com.github.maven_nar.ITest;
import com.github.maven_nar.IncludePath;
import com.github.sdedwards.m2e_nar.MavenNarPlugin;
import com.github.sdedwards.m2e_nar.internal.cdt.CdtUtils;
import com.github.sdedwards.m2e_nar.internal.model.NarBuildArtifact;
import com.github.sdedwards.m2e_nar.internal.model.NarCompiler;
import com.github.sdedwards.m2e_nar.internal.model.NarExecution;
import com.github.sdedwards.m2e_nar.internal.model.NarLib;
import com.github.sdedwards.m2e_nar.internal.model.NarLinker;
import com.github.sdedwards.m2e_nar.internal.model.NarSysLib;
public class NarExecutionBuilder implements INarExecutionBuilder {
private static final Logger logger = LoggerFactory.getLogger(NarExecutionBuilder.class);
private final INarCompileMojo narCompileMojo;
private final MojoExecution mojoExecution;
private int narMajorVersion = -1;
private int narMinorVersion = -1;
public NarExecutionBuilder(final AbstractMojo compileMojo, final MojoExecution mojoExceution) {
this.narCompileMojo = (INarCompileMojo) compileMojo;
this.mojoExecution = mojoExceution;
parseNarVersionNumbers();
}
public NarExecution build(final String buildType) throws CoreException {
try {
NarExecution settings = new NarExecution(mojoExecution);
settings.setSkip(narCompileMojo.isSkip());
settings.setOS(narCompileMojo.getOS());
settings.setLinkerName(narCompileMojo.getLinker().getName());
List<NarBuildArtifact> artifactSettings = settings.getArtifactSettings();
if (NarExecution.MAIN.equals(buildType)) {
List<?> libraries = narCompileMojo.getLibraries();
for (Iterator<?> iter = libraries.iterator(); iter.hasNext();) {
ILibrary library = (ILibrary) iter.next();
NarBuildArtifact buildArtifact = buildArtifactSettings(library.getType(), buildType, library.linkCPP(), null);
buildArtifact.setArtifactName(narCompileMojo.getOutput(library.getType()));
buildArtifact.setConfigName(CdtUtils.getConfigName(mojoExecution, buildArtifact));
artifactSettings.add(buildArtifact);
}
} else if (NarExecution.TEST.equals(buildType)) {
List<?> tests = narCompileMojo.getTests();
for (Iterator<?> iter = tests.iterator(); iter.hasNext();) {
ITest test = (ITest) iter.next();
NarBuildArtifact buildArtifact = buildArtifactSettings(NarBuildArtifact.EXECUTABLE, buildType, true, test);
buildArtifact.setArtifactName(test.getName());
buildArtifact.setConfigName(CdtUtils.getTestConfigName(mojoExecution, buildArtifact));
artifactSettings.add(buildArtifact);
}
}
return settings;
} catch (MojoFailureException e) {
throw new CoreException(new Status(IStatus.ERROR, MavenNarPlugin.PLUGIN_ID, "Mojo failure", e));
} catch (MojoExecutionException e) {
throw new CoreException(new Status(IStatus.ERROR, MavenNarPlugin.PLUGIN_ID, "Mojo execution failed", e));
}
}
@SuppressWarnings("unchecked")
private NarBuildArtifact buildArtifactSettings(final String type, final String buildType, final boolean linkCPP, final ITest test)
throws MojoExecutionException, MojoFailureException {
NarBuildArtifact settings = new NarBuildArtifact();
settings.setType(type);
List<String> projectRefs = settings.getProjectReferences();
List<com.github.maven_nar.NarArtifact> narArtifacts = narCompileMojo.getNarArtifacts();
for (com.github.maven_nar.NarArtifact artifact : narArtifacts) {
if (artifact.getNarLayout() instanceof EclipseNarLayout) {
EclipseNarLayout layout = (EclipseNarLayout) artifact.getNarLayout();
projectRefs.add(layout.getProject().getProject().getName());
}
}
settings.setLinkerSettings(buildLinkerSettings(narCompileMojo.getLinker(), linkCPP, test));
settings.setCppSettings(buildCompilerSettings(narCompileMojo.getCpp(), buildType, test));
settings.setCSettings(buildCompilerSettings(narCompileMojo.getC(), buildType, test));
List<String> javahIncludePaths = settings.getJavahIncludePaths();
javahIncludePaths.addAll(narCompileMojo.getJavahIncludePaths());
List<String> javaIncludePaths = settings.getJavaIncludePaths();
javaIncludePaths.addAll(narCompileMojo.getJavaIncludePaths());
List<File> dependencyIncludePaths = settings.getDependencyIncludePaths();
logger.debug("include paths size " + narCompileMojo.getDependencyIncludePaths().size());
dependencyIncludePaths.addAll(narCompileMojo.getDependencyIncludePaths());
List<NarLib> dependencyLibs = settings.getDependencyLibs();
logger.debug("library size " + narCompileMojo.getDependencyLibs(type, test).size());
for (Iterator<?> it = narCompileMojo.getDependencyLibs(type, test).iterator(); it.hasNext();) {
dependencyLibs.add(buildLibSettings((ILib) it.next()));
}
List<NarSysLib> dependencySysLibs = settings.getDependencySysLibs();
for (Iterator<?> it = narCompileMojo.getDependencySysLibs(type).iterator(); it.hasNext();) {
dependencySysLibs.add(buildSysLibSettings((ISysLib) it.next()));
}
List<String> dependencyOptions = settings.getDependencyOptions();
dependencyOptions.addAll(narCompileMojo.getDependencyOptions(type));
return settings;
}
@SuppressWarnings("unchecked")
public NarLinker buildLinkerSettings(final ILinker linker, final boolean linkCpp, final ITest test) throws MojoFailureException, MojoExecutionException {
NarLinker settings = new NarLinker();
settings.setName(linker.getName());
List<NarLib> libs = settings.getLibs();
for (Iterator<?> it = linker.getLibs().iterator(); it.hasNext();) {
libs.add(buildLibSettings((ILib) it.next()));
}
List<NarSysLib> sysLibs = settings.getSysLibs();
for (Iterator<?> it = linker.getSysLibs().iterator(); it.hasNext();) {
sysLibs.add(buildSysLibSettings((ISysLib) it.next()));
}
settings.setIncremental(linker.isIncremental());
settings.setMap(linker.isMap());
List<String> options = settings.getOptions();
options.addAll(linker.getOptions());
if (test != null) {
List<String> testOptions = linker.getTestOptions();
if (testOptions != null) {
options.addAll(testOptions);
}
}
settings.setLinkCpp(linkCpp);
return settings;
}
@SuppressWarnings("unchecked")
private NarCompiler buildCompilerSettings(final ICompiler compiler, final String buildType, final ITest test) throws MojoFailureException,
MojoExecutionException {
NarCompiler settings = new NarCompiler();
settings.setName(compiler.getName());
List<String> includePaths = settings.getIncludePaths();
for (Object obj : compiler.getIncludePaths(buildType)) {
IncludePath includePath = (IncludePath)obj;
includePaths.add(includePath.getPath());
}
List<String> systemIncludes = compiler.getSystemIncludePaths();
if (systemIncludes != null) {
List<String> systemIncludePaths = settings.getSystemIncludePaths();
systemIncludePaths.addAll(systemIncludes);
}
List<File> sourceDirectories = settings.getSourceDirectories();
sourceDirectories.addAll(compiler.getSourceDirectories(buildType));
// The meaning of clearDefaultOptions changed in nar-maven-plugin-3.1.0.
// Now it means not only clear the default options from AOL properties
// but also ignore the multithread, debug, exceptions, rtti and optimization
// elements from the configuration.
if (narMajorVersion > 3 || (narMajorVersion == 3 && narMinorVersion >= 1)) {
settings.setIgnoreOptionElements(compiler.isClearDefaultOptions());
}
settings.setDebug(compiler.isDebug());
settings.setRtti(compiler.isRtti());
settings.setOptimize(NarCompiler.OptimizationLevel.valueOf(compiler.getOptimize().toUpperCase()));
settings.setMultiThreaded(compiler.isMultiThreaded());
settings.setExceptions(compiler.isExceptions());
List<String> defines = settings.getDefines();
defines.addAll(compiler.getDefines());
List<String> undefines = settings.getUndefines();
undefines.addAll(compiler.getUndefines());
List<String> options = settings.getOptions();
options.addAll(compiler.getOptions());
if (test != null) {
List<String> testOptions = compiler.getTestOptions();
if (testOptions != null) {
options.addAll(testOptions);
}
}
Set<String> includes = settings.getIncludes();
for (Object include : compiler.getIncludes(buildType)) {
String includeStr = (String) include;
if (includeStr.trim().length() > 0) {
includes.add(includeStr);
}
}
Set<String> excludes = settings.getExcludes();
for (Object exclude : compiler.getExcludes(buildType, test)) {
String excludeStr = (String) exclude;
if (excludeStr.trim().length() > 0) {
excludes.add(excludeStr);
}
}
return settings;
}
public NarLib buildLibSettings(final ILib lib) {
logger.debug("NAR library: " + lib.getName());
NarLib settings = new NarLib();
settings.setName(lib.getName());
settings.setType(lib.getType());
settings.setDirectory(lib.getDirectory());
return settings;
}
public NarSysLib buildSysLibSettings(final ISysLib syslib) {
logger.debug("NAR sys library: " + syslib.getName());
NarSysLib settings = new NarSysLib();
settings.setName(syslib.getName());
settings.setType(syslib.getType());
return settings;
}
private void parseNarVersionNumbers() {
final String version = mojoExecution.getVersion();
String[] versions = version.split("\\.");
if (versions.length > 0) {
try {
narMajorVersion = Integer.parseInt(versions[0]);
logger.info("narMajorVersion=" + narMajorVersion);
} catch (NumberFormatException e) {
logger.error("Failed to parse NAR major version number", e);
}
}
if (versions.length > 1) {
try {
narMinorVersion = Integer.parseInt(versions[1]);
logger.info("narMinorVersion=" + narMinorVersion);
} catch (NumberFormatException e) {
logger.error("Failed to parse NAR minor version number", e);
}
}
}
}
|
/*
* 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.tools.ant.types.selectors;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Parameter;
/**
* Tests Date Selectors.
*
*/
public class DateSelectorTest extends BaseSelectorTest {
public DateSelectorTest(String name) {
super(name);
}
/**
* Factory method from base class. This is overriden in child
* classes to return a specific Selector class.
*/
public BaseSelector getInstance() {
return new DateSelector();
}
/**
* Test the code that validates the selector.
*/
public void testValidate() {
DateSelector s = (DateSelector)getInstance();
try {
s.isSelected(basedir,filenames[0],files[0]);
fail("DateSelector did not check for required fields");
} catch (BuildException be1) {
assertEquals("You must provide a datetime or the number of "
+ "milliseconds.", be1.getMessage());
}
s = (DateSelector)getInstance();
s.setDatetime("01/01/1969 01:01 AM");
try {
s.isSelected(basedir,filenames[0],files[0]);
fail("DateSelector did not check for Datetime being in the "
+ "allowable range");
} catch (BuildException be2) {
assertEquals("Date of 01/01/1969 01:01 AM results in negative "
+ "milliseconds value relative to epoch (January 1, "
+ "1970, 00:00:00 GMT).", be2.getMessage());
}
s = (DateSelector)getInstance();
s.setDatetime("this is not a date");
try {
s.isSelected(basedir,filenames[0],files[0]);
fail("DateSelector did not check for Datetime being in a "
+ "valid format");
} catch (BuildException be3) {
assertEquals("Date of this is not a date"
+ " Cannot be parsed correctly. It should be in"
+ " MM/DD/YYYY HH:MM AM_PM format.", be3.getMessage());
}
s = (DateSelector)getInstance();
Parameter param = new Parameter();
param.setName("garbage in");
param.setValue("garbage out");
Parameter[] params = new Parameter[1];
params[0] = param;
s.setParameters(params);
try {
s.isSelected(basedir,filenames[0],files[0]);
fail("DateSelector did not check for valid parameter element");
} catch (BuildException be4) {
assertEquals("Invalid parameter garbage in", be4.getMessage());
}
s = (DateSelector)getInstance();
param = new Parameter();
param.setName("millis");
param.setValue("garbage out");
params[0] = param;
s.setParameters(params);
try {
s.isSelected(basedir,filenames[0],files[0]);
fail("DateSelector did not check for valid millis parameter");
} catch (BuildException be5) {
assertEquals("Invalid millisecond setting garbage out",
be5.getMessage());
}
s = (DateSelector)getInstance();
param = new Parameter();
param.setName("granularity");
param.setValue("garbage out");
params[0] = param;
s.setParameters(params);
try {
s.isSelected(basedir,filenames[0],files[0]);
fail("DateSelector did not check for valid granularity parameter");
} catch (BuildException be6) {
assertEquals("Invalid granularity setting garbage out",
be6.getMessage());
}
}
/**
* Tests to make sure that the selector is selecting files correctly.
*/
public void testSelectionBehaviour() {
DateSelector s;
String results;
DateSelector.TimeComparisons before = new
DateSelector.TimeComparisons();
before.setValue("before");
DateSelector.TimeComparisons equal = new
DateSelector.TimeComparisons();
equal.setValue("equal");
DateSelector.TimeComparisons after = new
DateSelector.TimeComparisons();
after.setValue("after");
try {
makeBed();
s = (DateSelector)getInstance();
s.setDatetime("10/10/1999 1:45 PM");
s.setWhen(before);
results = selectionString(s);
assertEquals("TFFFFFFFFFFT", results);
s = (DateSelector)getInstance();
s.setDatetime("10/10/1999 1:45 PM");
s.setWhen(before);
s.setCheckdirs(true);
results = selectionString(s);
assertEquals("FFFFFFFFFFFF", results);
s = (DateSelector)getInstance();
s.setDatetime("10/10/1999 1:45 PM");
s.setWhen(after);
results = selectionString(s);
assertEquals("TTTTTTTTTTTT", results);
s = (DateSelector)getInstance();
s.setDatetime("11/21/2001 4:54 AM");
s.setWhen(before);
results = selectionString(s);
assertEquals("TFTFFFFFFFFT", results);
s = (DateSelector)getInstance();
s.setDatetime("11/21/2001 4:55 AM");
long milliseconds = s.getMillis();
s.setWhen(equal);
results = selectionString(s);
assertEquals("TTFFTFFFTTTT", results);
s = (DateSelector)getInstance();
s.setMillis(milliseconds);
s.setWhen(equal);
results = selectionString(s);
assertEquals("TTFFTFFFTTTT", results);
s = (DateSelector)getInstance();
s.setDatetime("11/21/2001 4:56 AM");
s.setWhen(after);
results = selectionString(s);
assertEquals("TFFTFTTTFFFT", results);
s = (DateSelector)getInstance();
Parameter param1 = new Parameter();
Parameter param2 = new Parameter();
param1.setName("datetime");
param1.setValue("11/21/2001 4:56 AM");
param2.setName("when");
param2.setValue("after");
Parameter[] params = {param1,param2};
s.setParameters(params);
results = selectionString(s);
assertEquals("TFFTFTTTFFFT", results);
try {
makeMirror();
s = (DateSelector)getInstance();
long testtime = mirrorfiles[5].lastModified();
s.setMillis(testtime);
s.setWhen(after);
s.setGranularity(2);
results = mirrorSelectionString(s);
assertEquals("TFFFFTTTTTTT", results);
s = (DateSelector)getInstance();
testtime = mirrorfiles[6].lastModified();
s.setMillis(testtime);
s.setWhen(before);
s.setGranularity(2);
results = mirrorSelectionString(s);
assertEquals("TTTTTTTFFFFT", results);
}
finally {
cleanupMirror();
}
}
finally {
cleanupBed();
}
}
}
|
/*
* Copyright 2010 Red Hat, Inc. and/or 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.optaplanner.core.config.localsearch;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import org.optaplanner.core.config.heuristic.policy.HeuristicConfigPolicy;
import org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType;
import org.optaplanner.core.config.heuristic.selector.common.SelectionOrder;
import org.optaplanner.core.config.heuristic.selector.move.MoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
import org.optaplanner.core.config.localsearch.decider.acceptor.AcceptorConfig;
import org.optaplanner.core.config.localsearch.decider.acceptor.AcceptorType;
import org.optaplanner.core.config.localsearch.decider.forager.LocalSearchForagerConfig;
import org.optaplanner.core.config.phase.PhaseConfig;
import org.optaplanner.core.config.solver.EnvironmentMode;
import org.optaplanner.core.config.util.ConfigUtils;
import org.optaplanner.core.impl.heuristic.selector.move.MoveSelector;
import org.optaplanner.core.impl.localsearch.DefaultLocalSearchPhase;
import org.optaplanner.core.impl.localsearch.LocalSearchPhase;
import org.optaplanner.core.impl.localsearch.decider.LocalSearchDecider;
import org.optaplanner.core.impl.localsearch.decider.acceptor.Acceptor;
import org.optaplanner.core.impl.localsearch.decider.forager.Forager;
import org.optaplanner.core.impl.solver.recaller.BestSolutionRecaller;
import org.optaplanner.core.impl.solver.termination.Termination;
import static org.apache.commons.lang3.ObjectUtils.*;
@XStreamAlias("localSearch")
public class LocalSearchPhaseConfig extends PhaseConfig<LocalSearchPhaseConfig> {
// Warning: all fields are null (and not defaulted) because they can be inherited
// and also because the input config file should match the output config file
protected LocalSearchType localSearchType = null;
// TODO This is a List due to XStream limitations. With JAXB it could be just a MoveSelectorConfig instead.
@XStreamImplicit()
private List<MoveSelectorConfig> moveSelectorConfigList = null;
@XStreamAlias("acceptor")
private AcceptorConfig acceptorConfig = null;
@XStreamAlias("forager")
private LocalSearchForagerConfig foragerConfig = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public LocalSearchType getLocalSearchType() {
return localSearchType;
}
public void setLocalSearchType(LocalSearchType localSearchType) {
this.localSearchType = localSearchType;
}
public MoveSelectorConfig getMoveSelectorConfig() {
return moveSelectorConfigList == null ? null : moveSelectorConfigList.get(0);
}
public void setMoveSelectorConfig(MoveSelectorConfig moveSelectorConfig) {
this.moveSelectorConfigList = moveSelectorConfig == null ? null : Collections.singletonList(moveSelectorConfig);
}
public AcceptorConfig getAcceptorConfig() {
return acceptorConfig;
}
public void setAcceptorConfig(AcceptorConfig acceptorConfig) {
this.acceptorConfig = acceptorConfig;
}
public LocalSearchForagerConfig getForagerConfig() {
return foragerConfig;
}
public void setForagerConfig(LocalSearchForagerConfig foragerConfig) {
this.foragerConfig = foragerConfig;
}
// ************************************************************************
// Builder methods
// ************************************************************************
@Override
public LocalSearchPhase buildPhase(int phaseIndex, HeuristicConfigPolicy solverConfigPolicy,
BestSolutionRecaller bestSolutionRecaller, Termination solverTermination) {
HeuristicConfigPolicy phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
DefaultLocalSearchPhase phase = new DefaultLocalSearchPhase(
phaseIndex, solverConfigPolicy.getLogIndentation(), bestSolutionRecaller,
buildPhaseTermination(phaseConfigPolicy, solverTermination));
phase.setDecider(buildDecider(phaseConfigPolicy,
phase.getTermination()));
EnvironmentMode environmentMode = phaseConfigPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
phase.setAssertStepScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
phase.setAssertExpectedStepScore(true);
phase.setAssertShadowVariablesAreNotStaleAfterStep(true);
}
return phase;
}
private LocalSearchDecider buildDecider(HeuristicConfigPolicy configPolicy, Termination termination) {
MoveSelector moveSelector = buildMoveSelector(configPolicy);
Acceptor acceptor = buildAcceptor(configPolicy);
Forager forager = buildForager(configPolicy);
LocalSearchDecider decider = new LocalSearchDecider(configPolicy.getLogIndentation(),
termination, moveSelector, acceptor, forager);
if (moveSelector.isNeverEnding() && !forager.supportsNeverEndingMoveSelector()) {
throw new IllegalStateException("The moveSelector (" + moveSelector
+ ") has neverEnding (" + moveSelector.isNeverEnding()
+ "), but the forager (" + forager
+ ") does not support it.\n"
+ "Maybe configure the <forager> with an <acceptedCountLimit>.");
}
EnvironmentMode environmentMode = configPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
decider.setAssertMoveScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
decider.setAssertExpectedUndoMoveScore(true);
}
return decider;
}
protected Acceptor buildAcceptor(HeuristicConfigPolicy configPolicy) {
AcceptorConfig acceptorConfig_;
if (acceptorConfig != null) {
if (localSearchType != null) {
throw new IllegalArgumentException("The localSearchType (" + localSearchType
+ ") must not be configured if the acceptorConfig (" + acceptorConfig
+ ") is explicitly configured.");
}
acceptorConfig_ = acceptorConfig;
} else {
LocalSearchType localSearchType_ = defaultIfNull(localSearchType, LocalSearchType.LATE_ACCEPTANCE);
acceptorConfig_ = new AcceptorConfig();
switch (localSearchType_) {
case HILL_CLIMBING:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.HILL_CLIMBING));
break;
case TABU_SEARCH:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.ENTITY_TABU));
break;
case SIMULATED_ANNEALING:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.SIMULATED_ANNEALING));
break;
case LATE_ACCEPTANCE:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.LATE_ACCEPTANCE));
break;
default:
throw new IllegalStateException("The localSearchType (" + localSearchType_
+ ") is not implemented.");
}
}
return acceptorConfig_.buildAcceptor(configPolicy);
}
protected Forager buildForager(HeuristicConfigPolicy configPolicy) {
LocalSearchForagerConfig foragerConfig_;
if (foragerConfig != null) {
if (localSearchType != null) {
throw new IllegalArgumentException("The localSearchType (" + localSearchType
+ ") must not be configured if the foragerConfig (" + foragerConfig
+ ") is explicitly configured.");
}
foragerConfig_ = foragerConfig;
} else {
LocalSearchType localSearchType_ = defaultIfNull(localSearchType, LocalSearchType.LATE_ACCEPTANCE);
foragerConfig_ = new LocalSearchForagerConfig();
switch (localSearchType_) {
case HILL_CLIMBING:
foragerConfig_.setAcceptedCountLimit(1);
break;
case TABU_SEARCH:
// Slow stepping algorithm
foragerConfig_.setAcceptedCountLimit(1000);
break;
case SIMULATED_ANNEALING:
case LATE_ACCEPTANCE:
// Fast stepping algorithm
foragerConfig_.setAcceptedCountLimit(1);
break;
default:
throw new IllegalStateException("The localSearchType (" + localSearchType_
+ ") is not implemented.");
}
}
return foragerConfig_.buildForager(configPolicy);
}
protected MoveSelector buildMoveSelector(HeuristicConfigPolicy configPolicy) {
MoveSelector moveSelector;
SelectionCacheType defaultCacheType = SelectionCacheType.JUST_IN_TIME;
SelectionOrder defaultSelectionOrder = SelectionOrder.RANDOM;
if (ConfigUtils.isEmptyCollection(moveSelectorConfigList)) {
// Default to changeMoveSelector and swapMoveSelector
UnionMoveSelectorConfig unionMoveSelectorConfig = new UnionMoveSelectorConfig();
unionMoveSelectorConfig.setMoveSelectorConfigList(Arrays.<MoveSelectorConfig>asList(
new ChangeMoveSelectorConfig(), new SwapMoveSelectorConfig()));
moveSelector = unionMoveSelectorConfig.buildMoveSelector(configPolicy,
defaultCacheType, defaultSelectionOrder);
} else if (moveSelectorConfigList.size() == 1) {
moveSelector = moveSelectorConfigList.get(0).buildMoveSelector(
configPolicy, defaultCacheType, defaultSelectionOrder);
} else {
// TODO moveSelectorConfigList is only a List because of XStream limitations.
throw new IllegalArgumentException("The moveSelectorConfigList (" + moveSelectorConfigList
+ ") must be a singleton or empty. Use a single " + UnionMoveSelectorConfig.class
+ " or " + CartesianProductMoveSelectorConfig.class
+ " element to nest multiple MoveSelectors.");
}
return moveSelector;
}
@Override
public void inherit(LocalSearchPhaseConfig inheritedConfig) {
super.inherit(inheritedConfig);
localSearchType = ConfigUtils.inheritOverwritableProperty(localSearchType,
inheritedConfig.getLocalSearchType());
setMoveSelectorConfig(ConfigUtils.inheritOverwritableProperty(
getMoveSelectorConfig(), inheritedConfig.getMoveSelectorConfig()));
acceptorConfig = ConfigUtils.inheritConfig(acceptorConfig, inheritedConfig.getAcceptorConfig());
foragerConfig = ConfigUtils.inheritConfig(foragerConfig, inheritedConfig.getForagerConfig());
}
}
|
/*
* Copyright 2016. SHENQINCI(沈钦赐)<dev@qinc.me>
*
* 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 ren.qinc.markdowneditors.base;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
/**
* Created by 沈钦赐 on 16/21/25.
*/
public interface BaseViewInterface {
/**
* Activitiy的布局,必须重写
*
* @return 布局资源
*/
@LayoutRes
int getLayoutId();
/**
* onCreate之后调用,可以用来初始化view
*/
void onCreateAfter(Bundle savedInstanceState);
/**
* 界面渲染完毕,可在这里进行初始化工作,建议在这里启动线程进行初始化工作
* 数据获取等操作
*/
void initData();
}
|
package org.apache.helix.messaging.handling;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.ArrayList;
import java.util.List;
import org.apache.helix.NotificationContext;
import org.apache.helix.model.Message;
import org.apache.log4j.Logger;
public class HelixBatchMessageTask implements MessageTask {
private static Logger LOG = Logger.getLogger(HelixBatchMessageTask.class);
final NotificationContext _context;
final Message _batchMsg;
final List<Message> _subMsgs;
final List<MessageHandler> _handlers;
public HelixBatchMessageTask(Message batchMsg, List<Message> subMsgs,
List<MessageHandler> handlers, NotificationContext context) {
_batchMsg = batchMsg;
_context = context;
_subMsgs = subMsgs;
_handlers = handlers;
}
@Override
public HelixTaskResult call() throws Exception {
HelixTaskResult taskResult = null;
long start = System.currentTimeMillis();
LOG.info("taskId:" + getTaskId() + " handling task begin, at: " + start);
boolean isSucceed = true;
try {
for (MessageHandler handler : _handlers) {
if (handler != null) {
HelixTaskResult subTaskResult = handler.handleMessage();
// if any fails, return false
if (!subTaskResult.isSuccess()) {
// System.err.println("\t[dbg]error handling message: " + handler._message);
isSucceed = false;
}
}
}
} catch (Exception e) {
String errorMessage = "Exception while executing task: " + getTaskId();
LOG.error(errorMessage, e);
taskResult = new HelixTaskResult();
taskResult.setException(e);
taskResult.setMessage(e.getMessage());
return taskResult;
}
if (isSucceed) {
LOG.info("task: " + getTaskId() + " completed sucessfully");
}
taskResult = new HelixTaskResult();
taskResult.setSuccess(isSucceed);
return taskResult;
}
@Override
public String getTaskId() {
StringBuilder sb = new StringBuilder();
sb.append(_batchMsg.getId());
sb.append("/");
List<String> msgIdList = new ArrayList<String>();
if (_subMsgs != null) {
for (Message msg : _subMsgs) {
msgIdList.add(msg.getId());
}
}
sb.append(msgIdList);
return sb.toString();
}
@Override
public Message getMessage() {
return _batchMsg;
}
@Override
public NotificationContext getNotificationContext() {
return _context;
}
@Override
public void onTimeout() {
for (MessageHandler handler : _handlers) {
if (handler != null) {
handler.onTimeout();
}
}
}
}
|
package hackerrank.datastructures.arrays;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Created by nikoo28 on 9/2/20 12:17 AM
*/
class LeftRotationTest {
LeftRotation leftRotation = new LeftRotation();
@Test
void rotateLeft1() {
int arr[] = {1, 2, 3, 4, 5};
int rotation = 2;
int result[] = {3, 4, 5, 1, 2};
leftRotation.rotateLeftUsingReverse(arr, rotation);
assertArrayEquals(result, arr);
arr = new int[]{1, 2, 3, 4, 5};
leftRotation.rotateLeftUsingBruteForce(arr, rotation);
assertArrayEquals(result, arr);
arr = new int[]{1, 2, 3, 4, 5};
leftRotation.rotateLeft(arr, rotation);
assertArrayEquals(result, arr);
}
@Test
void rotateLeft2() {
int arr[] = {1, 2, 3, 4, 5};
int rotation = 22;
int result[] = {3, 4, 5, 1, 2};
leftRotation.rotateLeftUsingReverse(arr, rotation);
assertArrayEquals(result, arr);
arr = new int[]{1, 2, 3, 4, 5};
leftRotation.rotateLeftUsingBruteForce(arr, rotation);
assertArrayEquals(result, arr);
arr = new int[]{1, 2, 3, 4, 5};
leftRotation.rotateLeft(arr, rotation);
assertArrayEquals(result, arr);
}
@Test
void rotateLeft3() {
int arr[] = {1};
int rotation = 22;
int result[] = {1};
leftRotation.rotateLeftUsingReverse(arr, rotation);
assertArrayEquals(result, arr);
arr = new int[]{1};
leftRotation.rotateLeftUsingBruteForce(arr, rotation);
assertArrayEquals(result, arr);
arr = new int[]{1};
leftRotation.rotateLeft(arr, rotation);
assertArrayEquals(result, arr);
}
@Test
void rotateLeft4() {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int rotation = 2;
int[] result = {3, 4, 5, 6, 7, 1, 2};
leftRotation.rotateLeftUsingReverse(arr, rotation);
assertArrayEquals(result, arr);
arr = new int[]{1, 2, 3, 4, 5, 6, 7};
leftRotation.rotateLeftUsingBruteForce(arr, rotation);
assertArrayEquals(result, arr);
arr = new int[]{1, 2, 3, 4, 5, 6, 7};
leftRotation.rotateLeft(arr, rotation);
assertArrayEquals(result, arr);
}
}
|
package org.osmdroid.util;
/**
* {@link PointAccepter} that simplifies the list of consecutive points with the same X or Y.
* One goal is to have faster Path rendering.
* As we clip the Path with a rectangle, additional segments are created by {@link SegmentClipper}.
* When most of the Polygon is out of the screen, many consecutive segments are on the same side
* of the clip rectangle (e.g. same X or same Y). Do we need to render all those segments? No.
* We can simplify this list of consecutive segments into a tiny list of maximum 3 segments.
* And that makes the Path rendering much faster.
*
* @author Fabrice Fontaine
* @since 6.2.0
*/
public class SideOptimizationPointAccepter implements PointAccepter {
private static final int STATUS_DIFFERENT = 0;
private static final int STATUS_SAME_X = 1;
private static final int STATUS_SAME_Y = 2;
private final PointL mLatestPoint = new PointL();
private final PointL mStartPoint = new PointL();
private final PointAccepter mPointAccepter;
private boolean mFirst;
private long mMin;
private long mMax;
private int mStatus;
/**
* We optimize on top of another {@link PointAccepter}
*/
public SideOptimizationPointAccepter(final PointAccepter pPointAccepter) {
mPointAccepter = pPointAccepter;
}
@Override
public void init() {
mFirst = true;
mStatus = STATUS_DIFFERENT;
mPointAccepter.init();
}
@Override
public void add(final long pX, final long pY) {
if (mFirst) {
mFirst = false;
addToAccepter(pX, pY);
mLatestPoint.set(pX, pY);
return;
}
if (mLatestPoint.x == pX && mLatestPoint.y == pY) {
return;
}
if (mLatestPoint.x == pX) {
if (mStatus == STATUS_SAME_X) {
if (mMin > pY) {
mMin = pY;
}
if (mMax < pY) {
mMax = pY;
}
} else {
flushSides();
mStatus = STATUS_SAME_X;
mStartPoint.set(mLatestPoint);
mMin = Math.min(pY, mLatestPoint.y);
mMax = Math.max(pY, mLatestPoint.y);
}
} else if (mLatestPoint.y == pY) {
if (mStatus == STATUS_SAME_Y) {
if (mMin > pX) {
mMin = pX;
}
if (mMax < pX) {
mMax = pX;
}
} else {
flushSides();
mStatus = STATUS_SAME_Y;
mStartPoint.set(mLatestPoint);
mMin = Math.min(pX, mLatestPoint.x);
mMax = Math.max(pX, mLatestPoint.x);
}
} else {
flushSides();
addToAccepter(pX, pY);
}
mLatestPoint.set(pX, pY);
}
@Override
public void end() {
flushSides();
mPointAccepter.end();
}
/**
* Flushing the side (same X or same Y) computed so far
*/
private void flushSides() {
final long segmentMin;
final long segmentMax;
switch (mStatus) {
case STATUS_DIFFERENT:
break;
case STATUS_SAME_X:
final long x = mStartPoint.x;
if (mStartPoint.y <= mLatestPoint.y) {
segmentMin = mStartPoint.y;
segmentMax = mLatestPoint.y;
} else {
segmentMin = mLatestPoint.y;
segmentMax = mStartPoint.y;
}
if (mMin < segmentMin) {
addToAccepter(x, mMin);
}
if (mMax > segmentMax) {
addToAccepter(x, mMax);
}
addToAccepter(x, mLatestPoint.y);
break;
case STATUS_SAME_Y:
final long y = mStartPoint.y;
if (mStartPoint.x <= mLatestPoint.x) {
segmentMin = mStartPoint.x;
segmentMax = mLatestPoint.x;
} else {
segmentMin = mLatestPoint.x;
segmentMax = mStartPoint.x;
}
if (mMin < segmentMin) {
addToAccepter(mMin, y);
}
if (mMax > segmentMax) {
addToAccepter(mMax, y);
}
addToAccepter(mLatestPoint.x, y);
break;
}
mStatus = STATUS_DIFFERENT;
}
/**
* Actually adding the point to the embedded {@link PointAccepter}
*/
private void addToAccepter(final long pX, final long pY) {
mPointAccepter.add(pX, pY);
}
}
|
/*
*
* Copyright 2002-2004 The Ant-Contrib project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.antcontrib.cpptasks.compiler;
import java.io.File;
/**
* A compiler that can utilize precompilation of header files
*
* @author Curt Arnold
*/
public interface PrecompilingCompiler {
/**
*
* This method may be used to get two distinct compiler configurations, one
* for compiling the specified file and producing a precompiled header
* file, and a second for compiling other files using the precompiled
* header file.
*
* The last (preferrably only) include directive in the prototype file will
* be used to mark the boundary between pre-compiled and normally compiled
* headers.
*
* @param config
* base configuration
* @param prototype
* A source file (for example, stdafx.cpp) that is used to build
* the precompiled header file. @returns null if precompiled
* headers are not supported or a two element array containing
* the precompiled header generation configuration and the
* consuming configuration
*
*/
CompilerConfiguration[] createPrecompileConfigurations(
CompilerConfiguration config, File prototype,
String[] nonPrecompiledFiles);
}
|
// Targeted by JavaCPP version 1.5.6: DO NOT EDIT THIS FILE
package org.bytedeco.leptonica;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.leptonica.global.lept.*;
/** Array of double number arrays */
@Name("L_Dnaa") @Properties(inherit = org.bytedeco.leptonica.presets.lept.class)
public class L_DNAA extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public L_DNAA() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public L_DNAA(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public L_DNAA(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public L_DNAA position(long position) {
return (L_DNAA)super.position(position);
}
@Override public L_DNAA getPointer(long i) {
return new L_DNAA((Pointer)this).offsetAddress(i);
}
/** size of allocated ptr array */
public native @Cast("l_int32") int nalloc(); public native L_DNAA nalloc(int setter);
/** number of L_Dna saved */
public native @Cast("l_int32") int n(); public native L_DNAA n(int setter);
/** array of L_Dna */
public native L_DNA dna(int i); public native L_DNAA dna(int i, L_DNA setter);
public native @Cast("L_Dna**") PointerPointer dna(); public native L_DNAA dna(PointerPointer setter);
}
|
package datawave.common.test.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ProcessUtils {
public static final int SYSTEM_EXIT_MINUS_ONE = 255;
public static final int SYSTEM_EXIT_MINUS_TWO = 254;
public static final int SYSTEM_EXIT_ONE = 1;
public static List<String> buildApplicationCommandLine(String clzName, List<String> systemProperties, boolean setupDebugger) {
List<String> results = new ArrayList<>();
results.add("java");
if (setupDebugger) {
results.add("-Xdebug");
results.add("-Xrunjdwp:transport=dt_socket,address=12345,server=y,suspend=y");
}
results.add("-cp");
results.add(System.getProperty("java.class.path"));
for (String property : systemProperties) {
results.add(property);
}
results.add(clzName);
return results;
}
public static String[] convertCommandLine(List<String> arguments) {
return arguments.toArray(new String[0]);
}
public static Process runInstance(String[] cmdArray, Map<String,String> newEnvironment, List<String> dropFromEnvironment, File workingDirectory)
throws IOException {
ProcessBuilder pb = new ProcessBuilder(cmdArray);
Map<String,String> environment = pb.environment();
for (Map.Entry<String,String> item : newEnvironment.entrySet()) {
environment.put(item.getKey(), item.getValue());
}
for (String drop : dropFromEnvironment) {
environment.remove(drop);
}
pb.directory(workingDirectory);
return pb.start();
}
public static List<String> getStandardOutDumps(Process proc) throws IOException {
return getOutputDumps(new InputStreamReader(proc.getInputStream()));
}
public static List<String> getStandardErrorDumps(Process proc) throws IOException {
return getOutputDumps(new InputStreamReader(proc.getErrorStream()));
}
protected static List<String> getOutputDumps(InputStreamReader isr) throws IOException {
List<String> messages = new ArrayList<>();
BufferedReader br = new BufferedReader(isr);
String line;
while (null != (line = br.readLine())) {
if (!line.startsWith("Cobertura: ")) {
messages.add(line);
}
}
return messages;
}
}
|
package com.aim.app.utils;
public class AuthenticationRequest {
private String username;
private String password;
public AuthenticationRequest(){}
public AuthenticationRequest(String username, String password){
this.username = username;
this.password = password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
|
package com.revature.packageA;
public class SomeClass {
public int x = 10;
protected char c = 'c';
float f = 3.14f;
// only accessible inside of this class declaration
private double d = 2.77;
}
|
package cn.xujiajun.tastjava.service;
import cn.xujiajun.tastjava.dao.UserDAO;
import cn.xujiajun.tastjava.entity.User;
import java.util.List;
public class UserService {
private UserDAO userDAO;
public List<User> GetUsers() {
return this.userDAO.GetUsers();
}
public User GetUser(int id) {
// return this.userDAO.GetUser();
return this.userDAO.GetUser2(id);
}
/**
* @return the userDAO
*/
public UserDAO getUserDAO() {
return userDAO;
}
/**
* @param userDAO the userDAO to set
*/
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
|
package hash;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
// 완주하지 못한 선수
public class Solution42576 {
public String solution(String[] participant, String[] completion) {
String answer = "";
Map<String, Integer> map = new HashMap<>();
for (String p : participant) {
if (!map.containsKey(p)) {
map.put(p, 1);
} else {
int v = map.get(p);
map.put(p, v + 1);
}
}
for (String c : completion) {
int v = map.get(c);
if (v > 1) {
map.put(c, v - 1);
} else {
map.remove(c);
}
}
answer = map.keySet().iterator().next();
return answer;
}
public String solution2(String[] participant, String[] completion) {
String answer = "";
Arrays.sort(participant);
Arrays.sort(completion);
for (int i = 0; i < completion.length; i++) {
if (!completion[i].equals(participant[i])) {
answer = participant[i];
break;
}
}
if ("".equals(answer)) {
answer = participant[participant.length-1];
}
return answer;
}
public static void main(String[] args) {
Solution42576 hashSolution = new Solution42576();
// leo
String[] participant = {"leo", "kiki", "eden"};
String[] completion = {"eden", "kiki"};
System.out.println(hashSolution.solution(participant, completion));
// vinko
String[] participant2 = {"marina", "josipa", "nikola", "vinko", "filipa"};
String[] completion2 = {"josipa", "filipa", "marina", "nikola"};
System.out.println(hashSolution.solution(participant2, completion2));
// mislav
String[] participant3 = {"mislav", "stanko", "mislav", "ana"};
String[] completion3 = {"stanko", "ana", "mislav"};
System.out.println(hashSolution.solution(participant3, completion3));
}
}
==================================================================================================================
import java.util.HashMap;
import java.util.Map;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
HashMap<String, Integer> participantCountMap = getCountPerName(participant);
HashMap<String, Integer> completionCountMap = getCountPerName(completion);
for(Map.Entry<String, Integer> entry : participantCountMap.entrySet()) {
String participantName = entry.getKey();
int participantCount = entry.getValue();
if (completionCountMap.get(participantName) == null || completionCountMap.get(participantName) != participantCount) {
answer = participantName;
break;
}
}
return answer;
}
public HashMap<String, Integer> getCountPerName(String[] names) {
HashMap<String, Integer> nameCount = new HashMap<>(names.length);
for(int i=0; i < names.length; i++) {
String name = names[i];
nameCount.compute(name, (k,v) -> (v == null)? 1 : v + 1);
}
return nameCount;
}
}
|
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* 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.jetbrains.kotlin.idea.refactoring.safeDelete;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Disposer;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.refactoring.HelpID;
import com.intellij.ui.BooleanTableCellRenderer;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.table.JBTable;
import com.intellij.usageView.UsageInfo;
import com.intellij.usages.UsageViewPresentation;
import com.intellij.usages.impl.UsagePreviewPanel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor;
import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import org.jetbrains.kotlin.idea.KotlinBundle;
import org.jetbrains.kotlin.idea.caches.resolve.ResolutionUtils;
import org.jetbrains.kotlin.idea.refactoring.JetRefactoringUtil;
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers;
import org.jetbrains.kotlin.psi.KtElement;
import org.jetbrains.kotlin.psi.KtNamedFunction;
import org.jetbrains.kotlin.psi.KtProperty;
import org.jetbrains.kotlin.psi.KtPsiUtil;
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* Mostly copied from com.intellij.refactoring.safeDelete.OverridingMethodsDialog
* Revision: 14aa2e2
* (replace PsiMethod formatting)
*/
class KotlinOverridingDialog extends DialogWrapper {
private final List<UsageInfo> myOverridingMethods;
private final String[] myMethodText;
private final boolean[] myChecked;
private static final int CHECK_COLUMN = 0;
private JBTable myTable;
private final UsagePreviewPanel myUsagePreviewPanel;
public KotlinOverridingDialog(Project project, List<UsageInfo> overridingMethods) {
super(project, true);
myOverridingMethods = overridingMethods;
myChecked = new boolean[myOverridingMethods.size()];
for (int i = 0; i < myChecked.length; i++) {
myChecked[i] = true;
}
myMethodText = new String[myOverridingMethods.size()];
for (int i = 0; i < myMethodText.length; i++) {
myMethodText[i] = formatElement(((KotlinSafeDeleteOverridingUsageInfo) myOverridingMethods.get(i)).getOverridingElement());
}
myUsagePreviewPanel = new UsagePreviewPanel(project, new UsageViewPresentation());
setTitle(KotlinBundle.message("unused.overriding.methods.title"));
init();
}
private static String formatElement(PsiElement element) {
element = KtPsiUtil.ascendIfPropertyAccessor(element);
if (element instanceof KtNamedFunction || element instanceof KtProperty) {
BindingContext bindingContext = ResolutionUtils.analyze((KtElement) element, BodyResolveMode.FULL);
DeclarationDescriptor declarationDescriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, element);
if (declarationDescriptor instanceof CallableMemberDescriptor) {
DeclarationDescriptor containingDescriptor = declarationDescriptor.getContainingDeclaration();
if (containingDescriptor instanceof ClassDescriptor) {
return KotlinBundle.message(
"x.in.y",
DescriptorRenderer.COMPACT.render(declarationDescriptor),
IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_IN_TYPES.render(containingDescriptor)
);
}
}
}
assert element instanceof PsiMethod
: "Method accepts only kotlin functions/properties and java methods, but '" + element.getText() + "' was found";
return JetRefactoringUtil.formatPsiMethod((PsiMethod) element, true, false);
}
@Override
protected String getDimensionServiceKey() {
return "#org.jetbrains.kotlin.idea.refactoring.safeDelete.KotlinOverridingDialog";
}
@NotNull
public List<UsageInfo> getSelected() {
List<UsageInfo> result = new ArrayList<UsageInfo>();
for (int i = 0; i < myChecked.length; i++) {
if (myChecked[i]) {
result.add(myOverridingMethods.get(i));
}
}
return result;
}
@NotNull
@Override
protected Action[] createActions() {
return new Action[] {getOKAction(), getCancelAction()};
}
@Override
protected void doHelpAction() {
HelpManager.getInstance().invokeHelp(HelpID.SAFE_DELETE_OVERRIDING);
}
@Override
protected JComponent createNorthPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JLabel(KotlinBundle.message("there.are.unused.methods.that.override.methods.you.delete")));
panel.add(new JLabel(KotlinBundle.message("choose.the.ones.you.want.to.be.deleted")));
return panel;
}
@Override
public JComponent getPreferredFocusedComponent() {
return myTable;
}
@Override
protected void dispose() {
Disposer.dispose(myUsagePreviewPanel);
super.dispose();
}
@Override
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(8, 0, 4, 0));
final MyTableModel tableModel = new MyTableModel();
myTable = new JBTable(tableModel);
myTable.setShowGrid(false);
TableColumnModel columnModel = myTable.getColumnModel();
int checkBoxWidth = new JCheckBox().getPreferredSize().width;
columnModel.getColumn(CHECK_COLUMN).setCellRenderer(new BooleanTableCellRenderer());
columnModel.getColumn(CHECK_COLUMN).setMaxWidth(checkBoxWidth);
columnModel.getColumn(CHECK_COLUMN).setMinWidth(checkBoxWidth);
// make SPACE check/uncheck selected rows
InputMap inputMap = myTable.getInputMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "enable_disable");
ActionMap actionMap = myTable.getActionMap();
actionMap.put("enable_disable", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (myTable.isEditing()) return;
int[] rows = myTable.getSelectedRows();
if (rows.length > 0) {
boolean valueToBeSet = false;
for (int row : rows) {
if (!myChecked[row]) {
valueToBeSet = true;
break;
}
}
for (int row : rows) {
myChecked[row] = valueToBeSet;
}
tableModel.updateData();
}
}
});
panel.setLayout(new BorderLayout());
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTable);
panel.add(scrollPane, BorderLayout.CENTER);
ListSelectionListener selectionListener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int index = myTable.getSelectionModel().getLeadSelectionIndex();
if (index != -1) {
UsageInfo usageInfo = myOverridingMethods.get(index);
myUsagePreviewPanel.updateLayout(Collections.singletonList(usageInfo));
}
else {
myUsagePreviewPanel.updateLayout(null);
}
}
};
myTable.getSelectionModel().addListSelectionListener(selectionListener);
final Splitter splitter = new Splitter(true, 0.3f);
splitter.setFirstComponent(panel);
splitter.setSecondComponent(myUsagePreviewPanel);
myUsagePreviewPanel.updateLayout(null);
Disposer.register(myDisposable, new Disposable() {
@Override
public void dispose() {
splitter.dispose();
}
});
if (tableModel.getRowCount() != 0) {
myTable.getSelectionModel().addSelectionInterval(0, 0);
}
return splitter;
}
class MyTableModel extends AbstractTableModel {
@Override
public int getRowCount() {
return myChecked.length;
}
@Override
public String getColumnName(int column) {
switch (column) {
case CHECK_COLUMN:
return " ";
default:
return KotlinBundle.message("method.column");
}
}
@Override
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case CHECK_COLUMN:
return Boolean.class;
default:
return String.class;
}
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == CHECK_COLUMN) {
return Boolean.valueOf(myChecked[rowIndex]);
}
else {
return myMethodText[rowIndex];
}
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == CHECK_COLUMN) {
myChecked[rowIndex] = ((Boolean) aValue).booleanValue();
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == CHECK_COLUMN;
}
void updateData() {
fireTableDataChanged();
}
}
}
|
package datadog.trace.instrumentation.jdbc;
import datadog.trace.api.DDSpanTypes;
import datadog.trace.api.DDTags;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import datadog.trace.bootstrap.instrumentation.api.Tags;
import datadog.trace.bootstrap.instrumentation.decorator.DatabaseClientDecorator;
import datadog.trace.bootstrap.instrumentation.jdbc.DBInfo;
import datadog.trace.bootstrap.instrumentation.jdbc.JDBCConnectionUrlParser;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCDecorator extends DatabaseClientDecorator<DBInfo> {
public static final JDBCDecorator DECORATE = new JDBCDecorator();
private static final String DB_QUERY = "DB Query";
@Override
protected String[] instrumentationNames() {
return new String[] {"jdbc"};
}
@Override
protected String service() {
return "jdbc"; // Overridden by onConnection
}
@Override
protected String component() {
return "java-jdbc"; // Overridden by onStatement and onPreparedStatement
}
@Override
protected String spanType() {
return DDSpanTypes.SQL;
}
@Override
protected String dbType() {
return "jdbc";
}
@Override
protected String dbUser(final DBInfo info) {
return info.getUser();
}
@Override
protected String dbInstance(final DBInfo info) {
if (info.getInstance() != null) {
return info.getInstance();
} else {
return info.getDb();
}
}
public AgentSpan onConnection(final AgentSpan span, final Connection connection) {
DBInfo dbInfo = JDBCMaps.connectionInfo.get(connection);
/**
* Logic to get the DBInfo from a JDBC Connection, if the connection was not created via
* Driver.connect, or it has never seen before, the connectionInfo map will return null and will
* attempt to extract DBInfo from the connection. If the DBInfo can't be extracted, then the
* connection will be stored with the DEFAULT DBInfo as the value in the connectionInfo map to
* avoid retry overhead.
*/
{
if (dbInfo == null) {
try {
final DatabaseMetaData metaData = connection.getMetaData();
final String url = metaData.getURL();
if (url != null) {
try {
dbInfo = JDBCConnectionUrlParser.parse(url, connection.getClientInfo());
} catch (final Throwable ex) {
// getClientInfo is likely not allowed.
dbInfo = JDBCConnectionUrlParser.parse(url, null);
}
} else {
dbInfo = DBInfo.DEFAULT;
}
} catch (final SQLException se) {
dbInfo = DBInfo.DEFAULT;
}
JDBCMaps.connectionInfo.put(connection, dbInfo);
}
}
if (dbInfo != null) {
span.setTag(Tags.DB_TYPE, dbInfo.getType());
span.setTag(DDTags.SERVICE_NAME, dbInfo.getType());
}
return super.onConnection(span, dbInfo);
}
@Override
public AgentSpan onStatement(final AgentSpan span, final String statement) {
final String resourceName = statement == null ? DB_QUERY : statement;
span.setTag(DDTags.RESOURCE_NAME, resourceName);
span.setTag(Tags.COMPONENT, "java-jdbc-statement");
return super.onStatement(span, statement);
}
public AgentSpan onPreparedStatement(final AgentSpan span, final PreparedStatement statement) {
final String sql = JDBCMaps.preparedStatements.get(statement);
final String resourceName = sql == null ? DB_QUERY : sql;
span.setTag(DDTags.RESOURCE_NAME, resourceName);
span.setTag(Tags.COMPONENT, "java-jdbc-prepared_statement");
return super.onStatement(span, sql);
}
}
|
package de.adesso.objectfieldcoverage.core.finder.lombok.generator;
import lombok.AccessLevel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import spoon.reflect.declaration.CtField;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.ModifierKind;
import spoon.reflect.factory.MethodFactory;
import java.util.*;
/**
* {@link LombokGetterMethodGenerator} implementation using Spoon's {@link MethodFactory} to generate
* getter methods. See <a href="https://projectlombok.org/features/GetterSetter">Lombok's Documentation</a>
* for more information. This implementation does not take settings made in Lombok's properties file
* into account, so the standard Java-Beans getter naming convention.
*/
@Slf4j
public class LombokGetterMethodGeneratorImpl implements LombokGetterMethodGenerator {
/**
* @inheritDoc
*
* @implNote The access levels {@link AccessLevel#PACKAGE} and {@link AccessLevel#MODULE} are handled
* equally.
*
* @throws IllegalArgumentException When the givne {@code accessLevel} is neither
* {@link AccessLevel#PUBLIC}, {@link AccessLevel#PROTECTED}, {@link AccessLevel#PRIVATE}
* {@link AccessLevel#PACKAGE} nor {@link AccessLevel#MODULE}.
*/
@Override
public boolean isGetterMethodWithDifferentAccessModifierPresent(CtField<?> field, AccessLevel accessLevel) {
Objects.requireNonNull(field, "field cannot be null!");
Objects.requireNonNull(accessLevel, "accessLevel cannot be null!");
var existingGetterMethodOptional = this.getExistingGetterMethodOnDeclaringType(field);
if(existingGetterMethodOptional.isEmpty()) {
log.debug("No lombok getter method for field '{}' declared on type '{}' present!",
field.getSimpleName(), field.getDeclaringType().getQualifiedName());
return false;
}
log.debug("Lombok getter method for field '{}' declared on type '{}' present!",
field.getSimpleName(), field.getDeclaringType().getQualifiedName());
var existingGetterMethod = existingGetterMethodOptional.get();
var isPublic = existingGetterMethod.isPublic();
var isProtected = existingGetterMethod.isProtected();
var isPrivate = existingGetterMethod.isPrivate();
var isPackagePrivate = !isPublic && !isProtected && !isPrivate;
switch (accessLevel) {
case PUBLIC:
return !isPublic;
case PROTECTED:
return !isProtected;
case PRIVATE:
return !isPrivate;
case PACKAGE: case MODULE:
return !isPackagePrivate;
default:
throw new IllegalArgumentException(String.format("Unknown access level '%s' specified!", accessLevel.name()));
}
}
/**
* @inheritDoc
*
* @implNote Uses Spoons {@link MethodFactory} to generate a getter method. Always generates a
* instance method getter (non-static getter).
*/
@Override
public <T> CtMethod<T> generateGetterMethod(CtField<T> field, AccessLevel accessLevel) {
Objects.requireNonNull(field, "field cannot be null!");
Objects.requireNonNull(field, "accessLevel cannot be null!");
if(AccessLevel.NONE == accessLevel) {
throw new IllegalArgumentException("'NONE' is not a valid access level");
}
var existingGetterMethodOptional = this.getExistingGetterMethodOnDeclaringType(field);
if(existingGetterMethodOptional.isPresent()) {
log.debug("Lombok getter method for field '{}' declared on type '{}' present! No new method will be generated!",
field.getSimpleName(), field.getDeclaringType().getQualifiedName());
return existingGetterMethodOptional.get();
}
log.debug("No lombok getter method for field '{}' declared on type '{}' present! New getter method " +
"with access level '{}' will be generated!", field.getSimpleName(),
field.getDeclaringType().getQualifiedName(), accessLevel);
var methodFactory = new MethodFactory(field.getFactory());
var declaringType = field.getDeclaringType();
var getterMethodName = this.lombokGetterMethodName(field);
var accessModifiers = new HashSet<ModifierKind>(1);
switch (accessLevel) {
case PUBLIC:
accessModifiers.add(ModifierKind.PUBLIC);
break;
case PROTECTED:
accessModifiers.add(ModifierKind.PROTECTED);
break;
case PRIVATE:
accessModifiers.add(ModifierKind.PRIVATE);
break;
}
return methodFactory.create(declaringType, accessModifiers, field.getType(), getterMethodName, List.of(), Set.of());
}
/**
*
* @param field
* The {@link CtField} to get the generated getter method prefix for,
* not {@code null}.
*
* @return
* <i>is</s> in case the given {@code field} is of primitive type {@code boolean}
* or reference type {@link Boolean}. <i>get</i> is returned otherwise.
*/
private String getterMethodPrefix(CtField<?> field) {
var fieldType = field.getType();
var fieldTypeName = fieldType.getQualifiedName();
var isOfBooleanPrimitiveType = (fieldType.isPrimitive() && "boolean".equals(fieldTypeName));
var isOfBooleanReferenceType = "java.lang.Boolean".equals(fieldTypeName);
return (isOfBooleanPrimitiveType || isOfBooleanReferenceType) ? "is" : "get";
}
/**
*
* @param field
* The field to get the getter method name for, not {@code null}.
*
* @return
* The name of the getter method generated by lombok.
*
* @see #getterMethodPrefix(CtField)
*/
private String lombokGetterMethodName(CtField<?> field) {
var fieldPostFix = StringUtils.capitalize(field.getSimpleName());
return String.format("%s%s", getterMethodPrefix(field), fieldPostFix);
}
/**
*
* @param field
* The field to get the getter method with the same name as lombok's generated
* getter method for, not {@code null}.
*
* @param <T>
* The type of the field, not {@code null}.
*
* @return
* An optional containing a method with the same name and return type as
* lombok's generated getter method in case it is present on the given {@code field}s
* declaring type.
*/
private <T> Optional<CtMethod<T>> getExistingGetterMethodOnDeclaringType(CtField<T> field) {
var getterMethodName = lombokGetterMethodName(field);
var existingGetterMethodOnDeclaringType = field.getDeclaringType()
.getMethod(field.getType(), getterMethodName);
return Optional.ofNullable(existingGetterMethodOnDeclaringType);
}
}
|
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.monitor.impl;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.hazelcast.instance.Node;
import com.hazelcast.internal.management.dto.SlowOperationDTO;
import com.hazelcast.monitor.LocalOperationStats;
import com.hazelcast.util.Clock;
import java.util.ArrayList;
import java.util.List;
import static com.hazelcast.spi.properties.GroupProperty.MC_MAX_VISIBLE_SLOW_OPERATION_COUNT;
import static com.hazelcast.util.JsonUtil.getArray;
import static com.hazelcast.util.JsonUtil.getLong;
/**
* Hazelcast statistic implementations for local operations.
*/
public class LocalOperationStatsImpl implements LocalOperationStats {
private long maxVisibleSlowOperationCount;
private List<SlowOperationDTO> slowOperations;
private long creationTime;
public LocalOperationStatsImpl() {
this.maxVisibleSlowOperationCount = Long.MAX_VALUE;
this.slowOperations = new ArrayList<SlowOperationDTO>();
this.creationTime = Clock.currentTimeMillis();
}
public LocalOperationStatsImpl(Node node) {
this.maxVisibleSlowOperationCount = node.getProperties().getInteger(MC_MAX_VISIBLE_SLOW_OPERATION_COUNT);
this.slowOperations = node.nodeEngine.getOperationService().getSlowOperationDTOs();
this.creationTime = Clock.currentTimeMillis();
}
public long getMaxVisibleSlowOperationCount() {
return maxVisibleSlowOperationCount;
}
public List<SlowOperationDTO> getSlowOperations() {
return slowOperations;
}
@Override
public long getCreationTime() {
return creationTime;
}
@Override
public JsonObject toJson() {
JsonObject root = new JsonObject();
root.add("maxVisibleSlowOperationCount", maxVisibleSlowOperationCount);
JsonArray slowOperationArray = new JsonArray();
int logCount = 0;
for (SlowOperationDTO slowOperation : slowOperations) {
if (logCount++ < maxVisibleSlowOperationCount) {
slowOperationArray.add(slowOperation.toJson());
}
}
root.add("slowOperations", slowOperationArray);
root.add("creationTime", creationTime);
return root;
}
@Override
public void fromJson(JsonObject json) {
maxVisibleSlowOperationCount = getLong(json, "maxVisibleSlowOperationCount", Long.MAX_VALUE);
for (JsonValue jsonValue : getArray(json, "slowOperations")) {
SlowOperationDTO slowOperationDTO = new SlowOperationDTO();
slowOperationDTO.fromJson(jsonValue.asObject());
slowOperations.add(slowOperationDTO);
}
creationTime = getLong(json, "creationTime", -1L);
}
@Override
public String toString() {
return "LocalOperationStatsImpl{"
+ "maxVisibleSlowOperationCount=" + maxVisibleSlowOperationCount
+ ", slowOperations=" + slowOperations
+ ", creationTime=" + creationTime
+ '}';
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller.Course;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.Courseaddservice;
/**
*
* @author jahrin
*/
@WebServlet(name = "coursesearch1", urlPatterns = {"/coursesearch1"})
public class coursesearch1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String coursecode = request.getParameter("code");
Courseaddservice ss = new Courseaddservice();
String a = ss.Check(coursecode);
if (a.equalsIgnoreCase("non")) {
String m = "No result found for the course code You have Entered";
request.setAttribute("m", m);
request.getRequestDispatcher("/coursesearch1.jsp").forward(request, response);
}
else{
request.setAttribute("code", a);
request.getRequestDispatcher("/coursesearch1.jsp").forward(request, response);
}
}
}
|
/*
* Copyright 2014 Effektif 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.effektif.mongo;
import com.effektif.workflow.impl.configuration.DefaultConfiguration;
import com.effektif.workflow.impl.util.Lists;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.gridfs.GridFS;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
/**
* @see <a href="https://github.com/effektif/effektif/wiki/Workflow-engine-types#mongodb-workflow-engine">MongoDB workflow engine</a>
*/
public class MongoConfiguration extends DefaultConfiguration {
public static List<ServerAddress> DEFAULT_SERVER_ADDRESSES = Lists.of(createServerAddress("localhost", null));
protected List<ServerAddress> serverAddresses;
protected String databaseName = "effektif";
protected String fileDatabaseName = "effektif-files";
protected List<MongoCredential> credentials;
protected String workflowsCollectionName = "workflows";
protected String workflowInstancesCollectionName = "workflowInstances";
protected String jobsCollectionName = "jobs";
protected String jobsArchivedCollectionName = "jobsArchived";
protected String typeCollectionName = "types";
protected boolean isPretty;
protected MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder();
protected boolean storeWorkflowIdsAsStrings = false;
public MongoConfiguration() {
brewery.ingredient(this);
brewery.supplier(new MongoClientSupplier(), MongoClient.class);
brewery.supplier(new MongoDbSupplier(), DB.class);
brewery.supplier(new MongoGridFSSupplier(), GridFS.class);
brewery.supplier(new MongoObjectMapperSupplier(), MongoObjectMapper.class);
brewery.ingredient(new MongoDb());
brewery.ingredient(new MongoWorkflowStore());
brewery.ingredient(new MongoWorkflowInstanceStore());
brewery.ingredient(new MongoJobStore());
brewery.ingredient(new MongoObjectMappingsBuilder());
}
public MongoConfiguration db(DB db) {
brewery.ingredient(db);
return this;
}
public MongoConfiguration mongoClient(MongoClient mongoClient) {
brewery.ingredient(mongoClient);
return this;
}
public MongoConfiguration server(String host) {
if (serverAddresses==null) {
serverAddresses = new ArrayList<>();
}
serverAddresses.add(createServerAddress(host, null));
return this;
}
public MongoConfiguration server(String host, int port) {
if (serverAddresses==null) {
serverAddresses = new ArrayList<>();
}
serverAddresses.add(createServerAddress(host, port));
return this;
}
protected static ServerAddress createServerAddress(String host, Integer port) {
try {
if (port!=null) {
return new ServerAddress(host, port);
}
return new ServerAddress(host);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public List<ServerAddress> getServerAddresses() {
return serverAddresses!=null ? serverAddresses : DEFAULT_SERVER_ADDRESSES;
}
public MongoConfiguration authentication(String username, String password, String database) {
if (credentials==null) {
credentials = new ArrayList<>();
}
credentials.add(MongoCredential.createMongoCRCredential(username, database, password.toCharArray()));
return this;
}
public MongoConfiguration workflowInstancesCollectionName(String processInstancesCollectionName) {
this.workflowInstancesCollectionName = processInstancesCollectionName;
return this;
}
public MongoConfiguration workflowsCollectionName(String workflowsCollectionName) {
this.workflowsCollectionName = workflowsCollectionName;
return this;
}
public MongoConfiguration jobsCollectionName(String jobsCollectionName) {
this.jobsCollectionName = jobsCollectionName;
return this;
}
public MongoConfiguration prettyPrint() {
this.isPretty = true;
return this;
}
public MongoConfiguration storeWorkflowIdsAsStrings() {
this.storeWorkflowIdsAsStrings = true;
return this;
}
public MongoConfiguration jobsArchivedCollectionName(String jobsArchivedCollectionName) {
this.jobsArchivedCollectionName = jobsArchivedCollectionName;
return this;
}
@Override
public MongoConfiguration synchronous() {
super.synchronous();
return this;
}
public MongoConfiguration databaseName(String databaseName) {
this.databaseName = databaseName;
return this;
}
// getters and setters //////////////////////////////////////////////////
public void setServerAddresses(List<ServerAddress> serverAddresses) {
this.serverAddresses = serverAddresses;
}
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public List<MongoCredential> getCredentials() {
return credentials;
}
public void setCredentials(List<MongoCredential> credentials) {
this.credentials = credentials;
}
public String getWorkflowInstancesCollectionName() {
return workflowInstancesCollectionName;
}
public void setWorkflowInstancesCollectionName(String workflowInstancesCollectionName) {
this.workflowInstancesCollectionName = workflowInstancesCollectionName;
}
public String getWorkflowsCollectionName() {
return workflowsCollectionName;
}
public void setWorkflowsCollectionName(String workflowsCollectionName) {
this.workflowsCollectionName = workflowsCollectionName;
}
public String getJobsCollectionName() {
return jobsCollectionName;
}
public void setJobsCollectionName(String jobsCollectionName) {
this.jobsCollectionName = jobsCollectionName;
}
public String getJobsArchivedCollectionName() {
return this.jobsArchivedCollectionName;
}
public void setJobsArchivedCollectionName(String jobsArchivedCollectionName) {
this.jobsArchivedCollectionName = jobsArchivedCollectionName;
}
public String getTypeCollectionName() {
return typeCollectionName;
}
public void setTypeCollectionName(String typeCollectionName) {
this.typeCollectionName = typeCollectionName;
}
public boolean isPretty() {
return isPretty;
}
public void setPretty(boolean isPretty) {
this.isPretty = isPretty;
}
public boolean getStoreWorkflowIdsAsString() {
return this.storeWorkflowIdsAsStrings;
}
public void setStoreWorkflowIdsAsString(boolean storeWorkflowIdsAsStrings) {
this.storeWorkflowIdsAsStrings = storeWorkflowIdsAsStrings;
}
public void setOptionBuilder(MongoClientOptions.Builder optionBuilder) {
this.optionBuilder = optionBuilder;
}
public String getFileDatabaseName() {
return fileDatabaseName;
}
public void setFileDatabaseName(String fileDatabaseName) {
this.fileDatabaseName = fileDatabaseName;
}
public MongoClientOptions.Builder getOptionBuilder() {
return optionBuilder;
}
@Override
public MongoConfiguration ingredient(Object ingredient) {
super.ingredient(ingredient);
return this;
}
}
|
/**
* Copyright (C) 2019 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.opengamma.financial.security;
/**
*
*/
public class FinancialSecurityVisitorSameMethodAdapterTest extends VisitorTestHelper {
// public void test() {
// final Set<FinancialSecurity> securities = getSecurities();
// final FinancialSecurityVisitorSameMethodAdapter<String> visitor = new
// FinancialSecurityVisitorSameMethodAdapter<>(TestVisitor.INSTANCE);
// for (final FinancialSecurity security : securities) {
// assertEquals(security.accept(visitor),
// security.getClass().getSimpleName());
// }
// }
//
// private static final class TestVisitor implements
// FinancialSecurityVisitorSameMethodAdapter.Visitor<String> {
// public static final TestVisitor INSTANCE = new TestVisitor();
//
// private TestVisitor() {
// }
//
// @Override
// public String visit(final FinancialSecurity security) {
// return security.getClass().getSimpleName();
// }
//
// }
}
|
/*
* 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.lib.profiler.ui.components.table;
import org.netbeans.lib.profiler.ui.components.*;
import java.awt.*;
import javax.swing.*;
/** Custom Table cell renderer that paints a bar based on numerical value within min/max bounds.
*
* @author Ian Formanek
* @author Jiri Sedlacek
*/
public class CustomBarCellRenderer extends EnhancedTableCellRenderer {
//~ Static fields/initializers -----------------------------------------------------------------------------------------------
public static final Color BAR_FOREGROUND_COLOR = new Color(195, 41, 41);
//~ Instance fields ----------------------------------------------------------------------------------------------------------
protected double relValue; // relative part of max - min, <0, 1>
protected long max;
protected long min;
//~ Constructors -------------------------------------------------------------------------------------------------------------
public CustomBarCellRenderer(long min, long max) {
setMinimum(min);
setMaximum(max);
setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
}
//~ Methods ------------------------------------------------------------------------------------------------------------------
public void setMaximum(long n) {
max = n;
}
public void setMinimum(long n) {
min = n;
}
public void setRelValue(double n) {
relValue = n;
}
public Component getTableCellRendererComponentPersistent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
return null;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Insets insets = getInsets();
g.setColor(BAR_FOREGROUND_COLOR);
g.fillRect(insets.left, insets.top, (int) Math.round(relValue * (getWidth() - insets.right - insets.left)),
getHeight() - insets.bottom - insets.top);
}
/**
* Called each time this renderer is to be used to render a specific value on specified row/column.
* Subclasses need to implement this method to render the value.
*
* @param table the table in which the rendering occurs
* @param value the value to be rendered
* @param row the row at which the value is located
* @param column the column at which the value is located
*/
protected void setValue(JTable table, Object value, int row, int column) {
if (value instanceof Long) {
//multiplying by 10 to allow displaying graphs for values < 1
// - same done for maxi and min values of progress bar, should be ok
setRelValue(calculateViewValue(((Long) value).longValue()));
} else if (value instanceof Number) {
//multiplying by 10 to allow displaying graphs for values < 1
// - same done for maxi and min values of progress bar, should be ok
setRelValue(calculateViewValue(((Number) value).doubleValue()));
} else if (value instanceof String) {
//multiplying by 10 to allow displaying graphs for values < 1
// - same done for maxi and min values of progress bar, should be ok
setRelValue(calculateViewValue(Double.parseDouble((String) value)));
} else {
setRelValue(min);
}
}
protected double calculateViewValue(long n) {
return (double) (n - min) / (double) (max - min);
}
protected double calculateViewValue(double n) {
return (double) (n - min) / (double) (max - min);
}
}
|
package com.isheihei.mall.coupon.dao;
import com.isheihei.mall.coupon.entity.UndoLogEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
*
*
* @author YazhouTown
* @email yazhoutown@gmail.com
* @date 2021-07-01 21:43:11
*/
@Mapper
public interface UndoLogDao extends BaseMapper<UndoLogEntity> {
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE129_Improper_Validation_of_Array_Index__Environment_array_size_53c.java
Label Definition File: CWE129_Improper_Validation_of_Array_Index.label.xml
Template File: sources-sinks-53c.tmpl.java
*/
/*
* @description
* CWE: 129 Improper Validation of Array Index
* BadSource: Environment Read data from an environment variable
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: array_size
* GoodSink: data is used to set the size of the array and it must be greater than 0
* BadSink : data is used to set the size of the array, but it could be set to 0
* Flow Variant: 53 Data flow: data passed as an argument from one method through two others to a fourth; all four functions are in different classes in the same package
*
* */
package testcases.CWE129_Improper_Validation_of_Array_Index.s02;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE129_Improper_Validation_of_Array_Index__Environment_array_size_53c
{
public void badSink(int data ) throws Throwable
{
(new CWE129_Improper_Validation_of_Array_Index__Environment_array_size_53d()).badSink(data );
}
/* goodG2B() - use goodsource and badsink */
public void goodG2BSink(int data ) throws Throwable
{
(new CWE129_Improper_Validation_of_Array_Index__Environment_array_size_53d()).goodG2BSink(data );
}
/* goodB2G() - use badsource and goodsink */
public void goodB2GSink(int data ) throws Throwable
{
(new CWE129_Improper_Validation_of_Array_Index__Environment_array_size_53d()).goodB2GSink(data );
}
}
|
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2007, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------------------
* XYShapeAnnotationTests.java
* ---------------------------
* (C) Copyright 2004-2007, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 29-Sep-2004 : Version 1 (DG);
* 07-Jan-2005 : Added hashCode() test (DG);
*
*/
package org.jfree.chart.annotations.junit;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.annotations.XYShapeAnnotation;
/**
* Some tests for the {@link XYShapeAnnotation} class.
*/
public class XYShapeAnnotationTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(XYShapeAnnotationTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public XYShapeAnnotationTests(String name) {
super(name);
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
public void testEquals() {
XYShapeAnnotation a1 = new XYShapeAnnotation(
new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0),
new BasicStroke(1.2f), Color.red, Color.blue);
XYShapeAnnotation a2 = new XYShapeAnnotation(
new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0),
new BasicStroke(1.2f), Color.red, Color.blue);
assertTrue(a1.equals(a2));
assertTrue(a2.equals(a1));
// shape
a1 = new XYShapeAnnotation(
new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0),
new BasicStroke(1.2f), Color.red, Color.blue);
assertFalse(a1.equals(a2));
a2 = new XYShapeAnnotation(
new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0),
new BasicStroke(1.2f), Color.red, Color.blue);
assertTrue(a1.equals(a2));
// stroke
a1 = new XYShapeAnnotation(
new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0),
new BasicStroke(2.3f), Color.red, Color.blue);
assertFalse(a1.equals(a2));
a2 = new XYShapeAnnotation(
new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0),
new BasicStroke(2.3f), Color.red, Color.blue);
assertTrue(a1.equals(a2));
GradientPaint gp1a = new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red);
GradientPaint gp1b = new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red);
GradientPaint gp2a = new GradientPaint(5.0f, 6.0f, Color.pink,
7.0f, 8.0f, Color.white);
GradientPaint gp2b = new GradientPaint(5.0f, 6.0f, Color.pink,
7.0f, 8.0f, Color.white);
// outlinePaint
a1 = new XYShapeAnnotation(
new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0),
new BasicStroke(2.3f), gp1a, Color.blue);
assertFalse(a1.equals(a2));
a2 = new XYShapeAnnotation(
new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0),
new BasicStroke(2.3f), gp1b, Color.blue);
assertTrue(a1.equals(a2));
// fillPaint
a1 = new XYShapeAnnotation(
new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0),
new BasicStroke(2.3f), gp1a, gp2a);
assertFalse(a1.equals(a2));
a2 = new XYShapeAnnotation(
new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0),
new BasicStroke(2.3f), gp1b, gp2b);
assertTrue(a1.equals(a2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
public void testHashCode() {
XYShapeAnnotation a1 = new XYShapeAnnotation(
new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0),
new BasicStroke(1.2f), Color.red, Color.blue);
XYShapeAnnotation a2 = new XYShapeAnnotation(
new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0),
new BasicStroke(1.2f), Color.red, Color.blue);
assertTrue(a1.equals(a2));
int h1 = a1.hashCode();
int h2 = a2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
XYShapeAnnotation a1 = new XYShapeAnnotation(
new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0),
new BasicStroke(1.2f), Color.red, Color.blue);
XYShapeAnnotation a2 = null;
try {
a2 = (XYShapeAnnotation) a1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(a1 != a2);
assertTrue(a1.getClass() == a2.getClass());
assertTrue(a1.equals(a2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
XYShapeAnnotation a1 = new XYShapeAnnotation(
new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0),
new BasicStroke(1.2f), Color.red, Color.blue);
XYShapeAnnotation a2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(a1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
a2 = (XYShapeAnnotation) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(a1, a2);
}
}
|
package net.iutil.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* user vo (test)
* @author Erwin Feng
* @since 2019-03-31 17:19
*/
@Data
@Accessors(chain = true)
/* 过滤掉 null 的字段 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserVO implements Serializable {
private static final long serialVersionUID = -6313489245766176805L;
/* ID */
private String id;
/* name */
private String name;
/* age */
private Integer age;
/* register time */
private Date registerTime;
}
|
package com.chain.modules.sys.controller;
import com.chain.common.annotation.SysLog;
import com.chain.common.utils.Constant;
import com.chain.common.utils.PageUtils;
import com.chain.common.utils.R;
import com.chain.common.validator.Assert;
import com.chain.common.validator.ValidatorUtils;
import com.chain.common.validator.group.AddGroup;
import com.chain.common.validator.group.UpdateGroup;
import com.chain.modules.sys.entity.SysUserEntity;
import com.chain.modules.sys.form.PasswordForm;
import com.chain.modules.sys.service.SysUserRoleService;
import com.chain.modules.sys.service.SysUserService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 系统用户
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年10月31日 上午10:40:10
*/
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
@Autowired
private SysUserService sysUserService;
@Autowired
private SysUserRoleService sysUserRoleService;
/**
* 所有用户列表
*/
@GetMapping("/list")
@RequiresPermissions("sys:user:list")
public R list(@RequestParam Map<String, Object> params){
//只有超级管理员,才能查看所有管理员列表
if(getUserId() != Constant.SUPER_ADMIN){
params.put("createUserId", getUserId());
}
PageUtils page = sysUserService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 获取登录的用户信息
*/
@GetMapping("/info")
public R info(){
return R.ok().put("user", getUser());
}
/**
* 修改登录用户密码
*/
@SysLog("修改密码")
@PostMapping("/password")
public R password(@RequestBody PasswordForm form){
Assert.isBlank(form.getNewPassword(), "新密码不为能空");
//sha256加密
String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
//sha256加密
String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();
//更新密码
boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
if(!flag){
return R.error("原密码不正确");
}
return R.ok();
}
/**
* 用户信息
*/
@GetMapping("/info/{userId}")
@RequiresPermissions("sys:user:info")
public R info(@PathVariable("userId") Long userId){
SysUserEntity user = sysUserService.selectById(userId);
//获取用户所属的角色列表
List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
user.setRoleIdList(roleIdList);
return R.ok().put("user", user);
}
/**
* 保存用户
*/
@SysLog("保存用户")
@PostMapping("/save")
@RequiresPermissions("sys:user:save")
public R save(@RequestBody SysUserEntity user){
ValidatorUtils.validateEntity(user, AddGroup.class);
user.setCreateUserId(getUserId());
sysUserService.save(user);
return R.ok();
}
/**
* 修改用户
*/
@SysLog("修改用户")
@PostMapping("/update")
@RequiresPermissions("sys:user:update")
public R update(@RequestBody SysUserEntity user){
ValidatorUtils.validateEntity(user, UpdateGroup.class);
user.setCreateUserId(getUserId());
sysUserService.update(user);
return R.ok();
}
/**
* 删除用户
*/
@SysLog("删除用户")
@PostMapping("/delete")
@RequiresPermissions("sys:user:delete")
public R delete(@RequestBody Long[] userIds){
if(ArrayUtils.contains(userIds, 1L)){
return R.error("系统管理员不能删除");
}
if(ArrayUtils.contains(userIds, getUserId())){
return R.error("当前用户不能删除");
}
sysUserService.deleteBatch(userIds);
return R.ok();
}
}
|
package org.opencv.android;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import org.opencv.core.Core;
import java.text.DecimalFormat;
public class FpsMeter {
private static final String TAG = "FpsMeter";
private static final int STEP = 20;
private static final DecimalFormat FPS_FORMAT = new DecimalFormat("0.00");
Paint mPaint;
boolean mIsInitialized = false;
int mWidth = 0;
int mHeight = 0;
private int mFramesCouner;
private double mFrequency;
private long mprevFrameTime;
private String mStrfps;
public void init() {
mFramesCouner = 0;
mFrequency = Core.getTickFrequency();
mprevFrameTime = Core.getTickCount();
mStrfps = "";
mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setTextSize(20);
}
public void measure() {
if (!mIsInitialized) {
init();
mIsInitialized = true;
} else {
mFramesCouner++;
if (mFramesCouner % STEP == 0) {
long time = Core.getTickCount();
double fps = STEP * mFrequency / (time - mprevFrameTime);
mprevFrameTime = time;
if (mWidth != 0 && mHeight != 0)
mStrfps = FPS_FORMAT.format(fps) + " FPS@" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
else
mStrfps = FPS_FORMAT.format(fps) + " FPS";
Log.i(TAG, mStrfps);
}
}
}
public void setResolution(int width, int height) {
mWidth = width;
mHeight = height;
}
public void draw(Canvas canvas, float offsetx, float offsety) {
Log.d(TAG, mStrfps);
canvas.drawText(mStrfps, offsetx, offsety, mPaint);
}
}
|
/*
* Copyright 2012-2020 CodeLibs Project and the Others.
*
* 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.codelibs.fess.app.web.api.admin.dict;
import java.util.Date;
import org.codelibs.fess.app.web.admin.dict.ListForm;
public class ListBody extends ListForm {
public String id;
public String type;
public String path;
public Date timestamp;
}
|
/*
* Copyright 2018 Red Hat, Inc. and/or 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.kie.workbench.common.stunner.client.lienzo.canvas.wires;
import com.ait.lienzo.client.core.shape.Layer;
import com.ait.lienzo.client.core.shape.wires.IConnectionAcceptor;
import com.ait.lienzo.client.core.shape.wires.IContainmentAcceptor;
import com.ait.lienzo.client.core.shape.wires.IControlPointsAcceptor;
import com.ait.lienzo.client.core.shape.wires.IDockingAcceptor;
import com.ait.lienzo.client.core.shape.wires.ILocationAcceptor;
import com.ait.lienzo.client.core.shape.wires.WiresManager;
import com.ait.lienzo.test.LienzoMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.client.lienzo.wires.WiresManagerFactory;
import org.kie.workbench.common.stunner.core.client.canvas.CanvasPanel;
import org.kie.workbench.common.stunner.core.client.canvas.CanvasSettings;
import org.kie.workbench.common.stunner.core.client.canvas.event.CanvasClearEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.CanvasDrawnEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.CanvasFocusedEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.registration.CanvasShapeAddedEvent;
import org.kie.workbench.common.stunner.core.client.canvas.event.registration.CanvasShapeRemovedEvent;
import org.kie.workbench.common.stunner.core.client.shape.Shape;
import org.kie.workbench.common.stunner.core.client.shape.view.ShapeView;
import org.mockito.Mock;
import org.uberfire.mocks.EventSourceMock;
import static org.junit.Assert.assertEquals;
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.when;
@RunWith(LienzoMockitoTestRunner.class)
public class WiresCanvasTest {
@Mock
private EventSourceMock<CanvasClearEvent> clearEvent;
@Mock
private EventSourceMock<CanvasShapeAddedEvent> shapeAddedEvent;
@Mock
private EventSourceMock<CanvasShapeRemovedEvent> shapeRemovedEvent;
@Mock
private EventSourceMock<CanvasDrawnEvent> canvasDrawnEvent;
@Mock
private EventSourceMock<CanvasFocusedEvent> canvasFocusEvent;
@Mock
private WiresCanvasView view;
@Mock
private WiresLayer wiresLayer;
@Mock
private Layer layer;
@Mock
private WiresManagerFactory wiresManagerFactory;
@Mock
private WiresManager wiresManager;
private WiresCanvas tested;
@Before
public void setUp() throws Exception {
when(wiresLayer.getLienzoLayer()).thenReturn(layer);
when(layer.getLayer()).thenReturn(layer);
when(view.getLayer()).thenReturn(wiresLayer);
when(wiresManagerFactory.newWiresManager(eq(layer))).thenReturn(wiresManager);
tested = new WiresCanvas(clearEvent,
shapeAddedEvent,
shapeRemovedEvent,
canvasDrawnEvent,
canvasFocusEvent,
wiresManagerFactory,
view);
}
@Test
public void testGetView() {
assertEquals(view, tested.getView());
}
@Test
public void testInitialize() {
CanvasPanel panel = mock(CanvasPanel.class);
CanvasSettings settings = mock(CanvasSettings.class);
assertEquals(tested, tested.initialize(panel,
settings));
verify(wiresManager, times(1)).setSpliceEnabled(eq(false));
verify(wiresManager, times(1)).setLocationAcceptor(eq(ILocationAcceptor.NONE));
verify(wiresManager, times(1)).setContainmentAcceptor(eq(IContainmentAcceptor.NONE));
verify(wiresManager, times(1)).setDockingAcceptor(eq(IDockingAcceptor.NONE));
verify(wiresManager, times(1)).setConnectionAcceptor(eq(IConnectionAcceptor.NONE));
verify(wiresManager, times(1)).setControlPointsAcceptor(eq(IControlPointsAcceptor.NONE));
verify(view, times(1)).use(eq(wiresManager));
verify(view, times(1)).initialize(eq(panel), eq(settings));
assertEquals(wiresManager, tested.getWiresManager());
}
@Test
public void testAddChild() {
Shape shape = mock(Shape.class);
ShapeView shapeView = mock(ShapeView.class);
when(shape.getShapeView()).thenReturn(shapeView);
tested.addChild(shape);
verify(view, times(1)).addRoot(eq(shapeView));
}
@Test
public void testDeleteChild() {
Shape shape = mock(Shape.class);
ShapeView shapeView = mock(ShapeView.class);
when(shape.getShapeView()).thenReturn(shapeView);
tested.deleteChild(shape);
verify(view, times(1)).deleteRoot(eq(shapeView));
}
}
|
/*
* Copyright 2021 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.linkedin.tony.runtime;
import org.apache.hadoop.conf.Configuration;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.linkedin.tony.Framework;
import com.linkedin.tony.TaskExecutor;
import static com.linkedin.tony.TonyConfigurationKeys.TENSORBOARD_LOG_DIR;
public class TestMLGenericRuntime {
private TestRuntime runtime;
static class TestRuntime extends MLGenericRuntime {
@Override
public Framework.TaskExecutorAdapter getTaskAdapter(TaskExecutor taskExecutor) {
return new TestTaskExecutorAdapter(taskExecutor);
}
class TestTaskExecutorAdapter extends Task {
public TestTaskExecutorAdapter(TaskExecutor executor) {
super(executor);
}
@Override
protected void buildTaskEnv(TaskExecutor executor) throws Exception {
// ignore
}
}
}
@BeforeTest
public void before() {
runtime = new TestRuntime();
}
/**
* Test MLGenericRuntime when in task executor.
*/
@Test
public void testNeedReserveTBPort() {
TaskExecutor taskExecutor = new TaskExecutor();
taskExecutor.setJobName("chief");
Framework.TaskExecutorAdapter taskExecutorAdapter = runtime.getTaskAdapter(taskExecutor);
taskExecutor.setChief(true);
Assert.assertTrue(taskExecutorAdapter.needReserveTBPort());
Configuration conf1 = new Configuration();
conf1.set(TENSORBOARD_LOG_DIR, "/tmp");
taskExecutor.setTonyConf(conf1);
Assert.assertFalse(taskExecutorAdapter.needReserveTBPort());
taskExecutor.setChief(false);
Assert.assertFalse(taskExecutorAdapter.needReserveTBPort());
taskExecutor.setJobName("tensorboard");
Assert.assertTrue(taskExecutorAdapter.needReserveTBPort());
}
}
|
package external_module_0553.a;
import java.io.*;
import java.rmi.*;
import java.nio.file.*;
/**
* Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
* labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
* Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
*
* @see java.nio.file.FileStore
* @see java.sql.Array
* @see java.util.logging.Filter
*/
@SuppressWarnings("all")
public interface IFoo0<Y> extends java.util.concurrent.Callable<Y> {
java.util.zip.Deflater f0 = null;
javax.annotation.processing.Completion f1 = null;
javax.lang.model.AnnotatedConstruct f2 = null;
String getName();
void setName(String s);
Y get();
void set(Y e);
}
|
package bankaccountapp;
public class Checking extends Account{
//List properties specific to checking account
private int debitCardNumber;
private int debitCardPIN;
//Constructor to initialize checking account properties
public Checking(String name,String sSN,double initDeposit){
super(name,sSN,initDeposit);
accountNumber= "2" + accountNumber;
setDebitCard();
}
@Override
public void setRate(){
rate = getBaseRate()*0.15;
}
private void setDebitCard(){
debitCardNumber = (int)(Math.random()*Math.pow(10,12));
debitCardPIN = (int)(Math.random()*Math.pow(10,4));
}
//List any methods specific to checking account
public void showInfo(){
super.showInfo();
System.out.println("Your Checking Account Features" +
"\n Debit Card Number: " + debitCardNumber +
"\n Debit Card PIN: " + debitCardPIN);
}
}
|
/*
* Copyright 2016 The Netty Project
*
* The Netty Project 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:
*
* 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 io.netty.resolver.dns;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.dns.DefaultDnsOptEcsRecord;
import io.netty.handler.codec.dns.DnsRecord;
import io.netty.util.internal.SocketUtils;
import io.netty.util.concurrent.Future;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.net.InetAddress;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class DnsNameResolverClientSubnetTest {
// See https://www.gsic.uva.es/~jnisigl/dig-edns-client-subnet.html
// Ignore as this needs to query real DNS servers.
@Disabled
@Test
public void testSubnetQuery() throws Exception {
EventLoopGroup group = new NioEventLoopGroup(1);
DnsNameResolver resolver = newResolver(group).build();
try {
// Same as:
// # /.bind-9.9.3-edns/bin/dig @ns1.google.com www.google.es +client=157.88.0.0/24
Future<List<InetAddress>> future = resolver.resolveAll("www.google.es",
Collections.<DnsRecord>singleton(
// Suggest max payload size of 1024
// 157.88.0.0 / 24
new DefaultDnsOptEcsRecord(1024, 24,
SocketUtils.addressByName("157.88.0.0").getAddress())));
for (InetAddress address: future.syncUninterruptibly().getNow()) {
System.out.println(address);
}
} finally {
resolver.close();
group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
}
}
private static DnsNameResolverBuilder newResolver(EventLoopGroup group) {
return new DnsNameResolverBuilder(group.next())
.channelType(NioDatagramChannel.class)
.nameServerProvider(
new SingletonDnsServerAddressStreamProvider(SocketUtils.socketAddress("8.8.8.8", 53)))
.maxQueriesPerResolve(1)
.optResourceEnabled(false)
.ndots(1);
}
}
|
package com.example.timmy.progarkexercise1;
import android.app.Activity;
import android.os.Handler;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by timmy on 27/01/2019.
*/
public class GameController implements Runnable {
public static GameController instance;
public Handler handler;
public ViewGroup gameView;
private long mspf = 17; //58.8fps
private ArrayList<GameObject> gameObjects = new ArrayList<>();
public GameController(ViewGroup view, Handler handler){
instance = this;
this.handler = handler;
this.gameView = view;
Helicopter h = new Helicopter();
}
private float x = 0f;
@Override
public void run() {
//System.out.println("Main loop");
main(); //Main loop
ImageView img = (ImageView) gameView.findViewById(R.id.imageView2);
img.setX((x++ + x++));
TextView tv = (TextView) MainActivity.rootView.findViewById(R.id.textView);
tv.setText("Cool");
handler.postDelayed(this, mspf);
}
public void main(){ //main loop
//Update every Object
for (GameObject obj : gameObjects){
obj.Update();
}
}
public void addGameObject(GameObject o){
gameObjects.add(o);
}
}
|
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Java API Library
*
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.model.marketpay;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* TransferFundsResponse
*/
public class TransferFundsResponse {
@SerializedName("invalidFields")
private List<ErrorFieldType> invalidFields = null;
@SerializedName("merchantReference")
private String merchantReference = null;
@SerializedName("pspReference")
private String pspReference = null;
@SerializedName("resultCode")
private String resultCode = null;
public TransferFundsResponse invalidFields(List<ErrorFieldType> invalidFields) {
this.invalidFields = invalidFields;
return this;
}
public TransferFundsResponse addInvalidFieldsItem(ErrorFieldType invalidFieldsItem) {
if (this.invalidFields == null) {
this.invalidFields = new ArrayList<ErrorFieldType>();
}
this.invalidFields.add(invalidFieldsItem);
return this;
}
/**
* Contains field validation errors that would prevent requests from being processed.
*
* @return invalidFields
**/
public List<ErrorFieldType> getInvalidFields() {
return invalidFields;
}
public void setInvalidFields(List<ErrorFieldType> invalidFields) {
this.invalidFields = invalidFields;
}
public TransferFundsResponse merchantReference(String merchantReference) {
this.merchantReference = merchantReference;
return this;
}
/**
* The value supplied by the executing user when initiating the transfer; may be used to link multiple transactions.
*
* @return merchantReference
**/
public String getMerchantReference() {
return merchantReference;
}
public void setMerchantReference(String merchantReference) {
this.merchantReference = merchantReference;
}
public TransferFundsResponse pspReference(String pspReference) {
this.pspReference = pspReference;
return this;
}
/**
* The reference of a request. Can be used to uniquely identify the request.
*
* @return pspReference
**/
public String getPspReference() {
return pspReference;
}
public void setPspReference(String pspReference) {
this.pspReference = pspReference;
}
public TransferFundsResponse resultCode(String resultCode) {
this.resultCode = resultCode;
return this;
}
/**
* The result code.
*
* @return resultCode
**/
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TransferFundsResponse transferFundsResponse = (TransferFundsResponse) o;
return Objects.equals(this.invalidFields, transferFundsResponse.invalidFields) &&
Objects.equals(this.merchantReference, transferFundsResponse.merchantReference) &&
Objects.equals(this.pspReference, transferFundsResponse.pspReference) &&
Objects.equals(this.resultCode, transferFundsResponse.resultCode);
}
@Override
public int hashCode() {
return Objects.hash(invalidFields, merchantReference, pspReference, resultCode);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TransferFundsResponse {\n");
sb.append(" invalidFields: ").append(toIndentedString(invalidFields)).append("\n");
sb.append(" merchantReference: ").append(toIndentedString(merchantReference)).append("\n");
sb.append(" pspReference: ").append(toIndentedString(pspReference)).append("\n");
sb.append(" resultCode: ").append(toIndentedString(resultCode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.data.manipulator.mutable;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.ImmutablePotionEffectData;
import org.spongepowered.api.data.manipulator.mutable.PotionEffectData;
import org.spongepowered.api.effect.potion.PotionEffect;
import org.spongepowered.common.data.manipulator.immutable.ImmutableSpongePotionEffectData;
import org.spongepowered.common.data.manipulator.mutable.common.AbstractListData;
import java.util.ArrayList;
import java.util.List;
public class SpongePotionEffectData extends AbstractListData<PotionEffect, PotionEffectData, ImmutablePotionEffectData> implements PotionEffectData {
public SpongePotionEffectData() {
this(new ArrayList<>());
}
public SpongePotionEffectData(List<PotionEffect> effects) {
super(PotionEffectData.class, effects, Keys.POTION_EFFECTS, ImmutableSpongePotionEffectData.class);
}
@Override
public DataContainer toContainer() {
return super.toContainer()
.set(Keys.POTION_EFFECTS.getQuery(), this.getValue());
}
}
|
package net.milanqiu.enceladus.datatype.collectiontype;
import net.milanqiu.enceladus.datatype.DataType;
import net.milanqiu.enceladus.datatype.aggregationtype.AtBundle;
import net.milanqiu.enceladus.datatype.basictype.*;
import net.milanqiu.enceladus.datatype.basictype.specialized.BtString20;
import org.junit.Assert;
import org.junit.Test;
import java.util.LinkedHashMap;
/**
* Creation Date: 2020-02-22
* @author Milan Qiu
*/
public class CollectionTypesBaseTest {
@Test
public void test_equals() throws Exception {
// CtArray
Assert.assertEquals(new CtArray(new BtString(20)), new CtArray(new BtString20()));
Assert.assertNotEquals(new CtArray(new BtString(20)), new CtArray(new BtString(30)));
Assert.assertEquals(new CtArray(new CtArray(new BtString(20))), new CtArray(new CtArray(new BtString20())));
Assert.assertNotEquals(new CtArray(new CtArray(new BtString(20))), new CtArray(new CtArray(new BtString(30))));
// CtList
Assert.assertEquals(new CtList(new BtString(20)), new CtList(new BtString20()));
Assert.assertNotEquals(new CtList(new BtString(20)), new CtList(new BtString(30)));
Assert.assertEquals(new CtList(new CtList(new BtString(20))), new CtList(new CtList(new BtString20())));
Assert.assertNotEquals(new CtList(new CtList(new BtString(20))), new CtList(new CtList(new BtString(30))));
// CtMap
Assert.assertEquals(new CtMap(new BtString(20), new BtInt32()),
new CtMap(new BtString20(), new BtInt32()));
Assert.assertNotEquals(new CtMap(new BtString(20), new BtInt32()),
new CtMap(new BtString(30), new BtInt32()));
Assert.assertNotEquals(new CtMap(new BtString(20), new BtInt32()),
new CtMap(new BtString20(), new BtInt32Id()));
Assert.assertEquals(new CtMap(new CtMap(new BtString(20), new BtInt32()), new BtInt32()),
new CtMap(new CtMap(new BtString20(), new BtInt32()), new BtInt32()));
Assert.assertNotEquals(new CtMap(new CtMap(new BtString(20), new BtInt32()), new BtInt32()),
new CtMap(new CtMap(new BtString(30), new BtInt32()), new BtInt32()));
Assert.assertNotEquals(new CtMap(new CtMap(new BtString(20), new BtInt32()), new BtInt32()),
new CtMap(new CtMap(new BtString20(), new BtInt32Id()), new BtInt32()));
// misc
Assert.assertNotEquals(new CtArray(new BtInt32()), new CtList(new BtInt32()));
Assert.assertNotEquals(new CtList(new BtInt32()), new CtArray(new BtInt32()));
}
@Test
public void test_toString() throws Exception {
// CtArray
Assert.assertEquals("CtArray(BtString(20))", new CtArray(new BtString(20)).toString());
Assert.assertEquals("CtArray(CtArray(BtString(20)))", new CtArray(new CtArray(new BtString(20))).toString());
// CtList
Assert.assertEquals("CtList(BtString(20))", new CtList(new BtString(20)).toString());
Assert.assertEquals("CtList(CtList(BtString(20)))", new CtList(new CtList(new BtString(20))).toString());
// CtMap
Assert.assertEquals("CtMap(BtString(20),BtInt32)", new CtMap(new BtString(20), new BtInt32()).toString());
Assert.assertEquals("CtMap(CtMap(BtString(20),BtInt32),BtInt32)", new CtMap(new CtMap(new BtString(20), new BtInt32()), new BtInt32()).toString());
// misc
LinkedHashMap<String, DataType> properties = new LinkedHashMap<>();
properties.put("p1", new BtInt32());
properties.put("p2", new CtArray(new BtString(20)));
Assert.assertEquals("CtMap(CtMap(BtString(20),CtList(CtMap(BtDateTime,BtPercent(10,2)))),CtMap(BtInt32,AtBundle({\"p1\":BtInt32,\"p2\":CtArray(BtString(20))})))",
new CtMap(new CtMap(new BtString(20), new CtList(new CtMap(new BtDateTime(), new BtPercent(10,2)))),
new CtMap(new BtInt32(), new AtBundle(properties)))
.toString());
}
@Test
public void test_fromString() throws Exception {
// CtArray
Assert.assertEquals(new CtArray(new BtString(20)), DataType.fromString("CtArray(BtString(20))"));
Assert.assertEquals(new CtArray(new CtArray(new BtString(20))), DataType.fromString("CtArray(CtArray(BtString(20)))"));
// CtList
Assert.assertEquals(new CtList(new BtString(20)), DataType.fromString("CtList(BtString(20))"));
Assert.assertEquals(new CtList(new CtList(new BtString(20))), DataType.fromString("CtList(CtList(BtString(20)))"));
// CtMap
Assert.assertEquals(new CtMap(new BtString(20), new BtInt32()), DataType.fromString("CtMap(BtString(20),BtInt32)"));
Assert.assertEquals(new CtMap(new CtMap(new BtString(20), new BtInt32()), new BtInt32()), DataType.fromString("CtMap(CtMap(BtString(20),BtInt32),BtInt32)"));
// misc
LinkedHashMap<String, DataType> properties = new LinkedHashMap<>();
properties.put("p1", new BtInt32());
properties.put("p2", new CtArray(new BtString(20)));
Assert.assertEquals(new CtMap(new CtMap(new BtString(20), new CtList(new CtMap(new BtDateTime(), new BtPercent(10,2)))),
new CtMap(new BtInt32(), new AtBundle(properties))),
DataType.fromString("CtMap(CtMap(BtString(20),CtList(CtMap(BtDateTime,BtPercent(10,2)))),CtMap(BtInt32,AtBundle({\"p1\":BtInt32,\"p2\":CtArray(BtString(20))})))"));
// skip spaces and tabs
Assert.assertEquals(new CtMap(new BtString(20), new BtInt32()), DataType.fromString("CtMap( BtString(20),\tBtInt32)"));
}
}
|
/*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.testrunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.xml.XmlDomParser;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import org.junit.Rule;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class RunWithAnnotationIntegrationTest {
@Rule public TemporaryPaths temporaryFolder = new TemporaryPaths();
@Test
public void testSimpleSuiteRun2TestCases() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "runwith", temporaryFolder);
workspace.setUp();
ProcessResult suiteTestResult = workspace.runBuckCommand("test", "//:SimpleSuiteTest");
suiteTestResult.assertSuccess("Test should pass");
assertThat(suiteTestResult.getStderr(), containsString("2 Passed"));
}
@Test
public void testFailingSuiteRun3TestCasesWith1Failure() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "runwith", temporaryFolder);
workspace.setUp();
ProcessResult suiteTestResult = workspace.runBuckCommand("test", "//:FailingSuiteTest");
suiteTestResult.assertTestFailure("Test should fail because of one of subtests failure");
assertThat(suiteTestResult.getStderr(), containsString("2 Passed"));
assertThat(suiteTestResult.getStderr(), containsString("1 Failed"));
}
@Test
public void testParametrizedTestRun4Cases() throws IOException, SAXException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "runwith", temporaryFolder);
workspace.setUp();
ProcessResult suiteTestResult = workspace.runBuckCommand("test", "//:ParametrizedTest");
suiteTestResult.assertSuccess("Test should pass");
assertThat(suiteTestResult.getStderr(), containsString("4 Passed"));
Reader reader =
Files.newBufferedReader(
workspace.getPath(
"buck-out/gen/__java_test_ParametrizedTest_output__/com.example.ParametrizedTest.xml"),
Charset.defaultCharset());
Document doc = XmlDomParser.parse(new InputSource(reader), false);
NodeList testNodes = doc.getElementsByTagName("test");
assertEquals(4, testNodes.getLength());
for (int i = 0; i < testNodes.getLength(); i++) {
Node testNode = testNodes.item(i);
String expectedName = String.format("parametrizedTest[%d]", i);
assertEquals(expectedName, testNode.getAttributes().getNamedItem("name").getTextContent());
String expectedStdout = String.format("Parameter: %d\n", i);
assertEquals(
expectedStdout,
((Element) testNode).getElementsByTagName("stdout").item(0).getTextContent());
}
}
}
|
/*
* Copyright (C) 2019-2021 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.offlinemaps;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.here.sdk.mapview.MapError;
import com.here.sdk.mapview.MapScene;
import com.here.sdk.mapview.MapScheme;
import com.here.sdk.mapview.MapView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private PermissionsRequestor permissionsRequestor;
private MapView mapView;
private OfflineMapsExample offlineMapsExample;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get a MapView instance from layout
mapView = findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
handleAndroidPermissions();
}
private void handleAndroidPermissions() {
permissionsRequestor = new PermissionsRequestor(this);
permissionsRequestor.request(new PermissionsRequestor.ResultListener(){
@Override
public void permissionsGranted() {
loadMapScene();
}
@Override
public void permissionsDenied() {
Log.e(TAG, "Permissions denied by user.");
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
permissionsRequestor.onRequestPermissionsResult(requestCode, grantResults);
}
private void loadMapScene() {
// Load a scene from the HERE SDK to render the map with a map scheme.
mapView.getMapScene().loadScene(MapScheme.NORMAL_DAY, new MapScene.LoadSceneCallback() {
@Override
public void onLoadScene(@Nullable MapError mapError) {
if (mapError == null) {
offlineMapsExample = new OfflineMapsExample(mapView);
} else {
Log.d(TAG, "onLoadScene failed: " + mapError.toString());
}
}
});
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
public void onDownloadListClicked(View view) {
offlineMapsExample.onDownloadListClicked();
}
public void onDownloadMapClicked(View view) {
offlineMapsExample.onDownloadMapClicked();
}
public void onCancelMapDownloadClicked(View view) {
offlineMapsExample.onCancelMapDownloadClicked();
}
public void onSearchPlaceClicked(View view) {
offlineMapsExample.onSearchPlaceClicked();
}
}
|
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.accessservices.subjectarea.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.odpi.openmetadata.accessservices.subjectarea.outtopic.SubjectAreaPublisher;
import org.odpi.openmetadata.frameworks.connectors.properties.beans.Connection;
import org.odpi.openmetadata.repositoryservices.connectors.omrstopic.OMRSTopicListener;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryHelper;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryValidator;
import org.odpi.openmetadata.repositoryservices.events.*;
import org.odpi.openmetadata.repositoryservices.events.beans.v1.OMRSEventV1;
public class SubjectAreaOMRSTopicListener implements OMRSTopicListener
{
private static final Logger log = LoggerFactory.getLogger(SubjectAreaOMRSTopicListener.class);
private SubjectAreaPublisher publisher;
/**
* The constructor is given the connection to the out topic for Asset Consumer OMAS
* along with classes for testing and manipulating instances.
*
* @param assetConsumerOutTopic - connection to the out topic
* @param repositoryHelper - provides methods for working with metadata instances
* @param repositoryValidator - provides validation of metadata instance
* @param componentName - name of component
*/
public SubjectAreaOMRSTopicListener(Connection assetConsumerOutTopic,
OMRSRepositoryHelper repositoryHelper,
OMRSRepositoryValidator repositoryValidator,
String componentName)
{
publisher = new SubjectAreaPublisher(assetConsumerOutTopic,
repositoryHelper,
repositoryValidator,
componentName);
}
/**
* Method to pass a Registry event received on topic.
*
* @param event inbound event
*/
public void processRegistryEvent(OMRSRegistryEvent event)
{
log.debug("Ignoring registry event: " + event.toString());
}
/**
* Method to pass a Registry event received on topic.
*
* @param event inbound event
*/
public void processTypeDefEvent(OMRSTypeDefEvent event)
{
log.debug("Ignoring type event: " + event.toString());
}
/**
* Unpack and deliver an instance event to the InstanceEventProcessor
*
* @param instanceEvent event to unpack
*/
public void processInstanceEvent(OMRSInstanceEvent instanceEvent)
{
log.debug("Processing instance event: " + instanceEvent);
if (instanceEvent == null)
{
log.debug("Null instance event - ignoring event");
}
else
{
OMRSInstanceEventType instanceEventType = instanceEvent.getInstanceEventType();
OMRSEventOriginator instanceEventOriginator = instanceEvent.getEventOriginator();
if ((instanceEventType != null) && (instanceEventOriginator != null))
{
switch (instanceEventType)
{
case NEW_ENTITY_EVENT:
publisher.processNewEntity(instanceEvent.getEntity());
break;
case UPDATED_ENTITY_EVENT:
publisher.processUpdatedEntity(instanceEvent.getOriginalEntity(),
instanceEvent.getEntity());
break;
case CLASSIFIED_ENTITY_EVENT:
publisher.processUpdatedEntity(instanceEvent.getEntity());
break;
case RECLASSIFIED_ENTITY_EVENT:
publisher.processUpdatedEntity(instanceEvent.getEntity());
break;
case DECLASSIFIED_ENTITY_EVENT:
publisher.processUpdatedEntity(instanceEvent.getEntity());
break;
case DELETED_ENTITY_EVENT:
publisher.processDeletedEntity(instanceEvent.getEntity());
break;
case PURGED_ENTITY_EVENT:
if (log.isDebugEnabled())
{
log.debug("Ignoring entity purge org.odpi.openmetadata.accessservices.subjectarea.common.events");
}
break;
case UNDONE_ENTITY_EVENT:
publisher.processUpdatedEntity(instanceEvent.getEntity());
break;
case RESTORED_ENTITY_EVENT:
publisher.processRestoredEntity(instanceEvent.getEntity());
break;
case REFRESH_ENTITY_REQUEST:
case REFRESHED_ENTITY_EVENT:
case RE_HOMED_ENTITY_EVENT:
case RETYPED_ENTITY_EVENT:
case RE_IDENTIFIED_ENTITY_EVENT:
if (log.isDebugEnabled())
{
log.debug("Ignoring entity repository maintenance org.odpi.openmetadata.accessservices.subjectarea.common.events");
}
break;
case NEW_RELATIONSHIP_EVENT:
publisher.processNewRelationship(instanceEvent.getRelationship());
break;
case UPDATED_RELATIONSHIP_EVENT:
publisher.processUpdatedRelationship(instanceEvent.getOriginalRelationship(),
instanceEvent.getRelationship());
break;
case UNDONE_RELATIONSHIP_EVENT:
publisher.processUpdatedRelationship(instanceEvent.getRelationship());
break;
case DELETED_RELATIONSHIP_EVENT:
publisher.processDeletedRelationship(instanceEvent.getRelationship());
break;
case PURGED_RELATIONSHIP_EVENT:
if (log.isDebugEnabled())
{
log.debug("Ignoring relationship purge org.odpi.openmetadata.accessservices.subjectarea.common.events");
}
break;
case RESTORED_RELATIONSHIP_EVENT:
publisher.processRestoredRelationship(instanceEvent.getRelationship());
break;
case REFRESH_RELATIONSHIP_REQUEST:
case REFRESHED_RELATIONSHIP_EVENT:
case RE_IDENTIFIED_RELATIONSHIP_EVENT:
case RE_HOMED_RELATIONSHIP_EVENT:
case RETYPED_RELATIONSHIP_EVENT:
if (log.isDebugEnabled())
{
log.debug("Ignoring relationship repository maintenance org.odpi.openmetadata.accessservices.subjectarea.common.events");
}
break;
case INSTANCE_ERROR_EVENT:
if (log.isDebugEnabled())
{
log.debug("Ignoring instance error org.odpi.openmetadata.accessservices.subjectarea.common.events");
}
break;
}
}
else
{
log.debug("Ignored instance event - null type");
}
}
}
}
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.web.context.request;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.web.multipart.MultipartRequest;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class ServletWebRequestTests {
private MockHttpServletRequest servletRequest;
private MockHttpServletResponse servletResponse;
private ServletWebRequest request;
@Before
public void setup() {
servletRequest = new MockHttpServletRequest();
servletResponse = new MockHttpServletResponse();
request = new ServletWebRequest(servletRequest, servletResponse);
}
@Test
public void parameters() {
servletRequest.addParameter("param1", "value1");
servletRequest.addParameter("param2", "value2");
servletRequest.addParameter("param2", "value2a");
assertEquals("value1", request.getParameter("param1"));
assertEquals(1, request.getParameterValues("param1").length);
assertEquals("value1", request.getParameterValues("param1")[0]);
assertEquals("value2", request.getParameter("param2"));
assertEquals(2, request.getParameterValues("param2").length);
assertEquals("value2", request.getParameterValues("param2")[0]);
assertEquals("value2a", request.getParameterValues("param2")[1]);
Map<String, String[]> paramMap = request.getParameterMap();
assertEquals(2, paramMap.size());
assertEquals(1, paramMap.get("param1").length);
assertEquals("value1", paramMap.get("param1")[0]);
assertEquals(2, paramMap.get("param2").length);
assertEquals("value2", paramMap.get("param2")[0]);
assertEquals("value2a", paramMap.get("param2")[1]);
}
@Test
public void locale() {
servletRequest.addPreferredLocale(Locale.UK);
assertEquals(Locale.UK, request.getLocale());
}
@Test
public void nativeRequest() {
assertSame(servletRequest, request.getNativeRequest());
assertSame(servletRequest, request.getNativeRequest(ServletRequest.class));
assertSame(servletRequest, request.getNativeRequest(HttpServletRequest.class));
assertSame(servletRequest, request.getNativeRequest(MockHttpServletRequest.class));
assertNull(request.getNativeRequest(MultipartRequest.class));
assertSame(servletResponse, request.getNativeResponse());
assertSame(servletResponse, request.getNativeResponse(ServletResponse.class));
assertSame(servletResponse, request.getNativeResponse(HttpServletResponse.class));
assertSame(servletResponse, request.getNativeResponse(MockHttpServletResponse.class));
assertNull(request.getNativeResponse(MultipartRequest.class));
}
@Test
public void decoratedNativeRequest() {
HttpServletRequest decoratedRequest = new HttpServletRequestWrapper(servletRequest);
HttpServletResponse decoratedResponse = new HttpServletResponseWrapper(servletResponse);
ServletWebRequest request = new ServletWebRequest(decoratedRequest, decoratedResponse);
assertSame(decoratedRequest, request.getNativeRequest());
assertSame(decoratedRequest, request.getNativeRequest(ServletRequest.class));
assertSame(decoratedRequest, request.getNativeRequest(HttpServletRequest.class));
assertSame(servletRequest, request.getNativeRequest(MockHttpServletRequest.class));
assertNull(request.getNativeRequest(MultipartRequest.class));
assertSame(decoratedResponse, request.getNativeResponse());
assertSame(decoratedResponse, request.getNativeResponse(ServletResponse.class));
assertSame(decoratedResponse, request.getNativeResponse(HttpServletResponse.class));
assertSame(servletResponse, request.getNativeResponse(MockHttpServletResponse.class));
assertNull(request.getNativeResponse(MultipartRequest.class));
}
}
|
package com.dangdang.config.service.file.protocol;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Protocol factory
*
* @author <a href="mailto:wangyuxuan@dangdang.com">Yuxuan Wang</a>
*/
public final class Protocols {
private Map<String, Class<Protocol>> protocols;
private static Protocols INSTANCE = new Protocols();
private static final String REGISTER_FILE = "META-INF/toolkit/com.dangdang.config.service.file.protocol.Protocol";
private Protocols() {
try {
Properties props = new Properties();
// Load register file contents
Enumeration<URL> registerFiles = this.getClass().getClassLoader().getResources(REGISTER_FILE);
URL registerFile = null;
while (registerFiles.hasMoreElements()) {
registerFile = registerFiles.nextElement();
try (InputStream in = registerFile.openStream()) {
props.load(in);
}
}
// Initialize protocol beans
protocols = new HashMap<>();
for (Map.Entry<Object, Object> entry : props.entrySet()) {
final String protocolName = ((String) entry.getKey()).toLowerCase();
@SuppressWarnings("unchecked") final Class<Protocol> protocolBeanClazz = (Class<Protocol>) Class.forName((String) entry.getValue());
protocols.put(protocolName, protocolBeanClazz);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Protocols getInstance() {
return INSTANCE;
}
public Class<Protocol> get(String protocolName) {
final Class<Protocol> protocolClass = protocols.get(protocolName);
if (protocolClass == null) {
throw new IllegalArgumentException("Procotol with name " + protocolName + " not registered.");
}
return protocolClass;
}
}
|
package com.avianca.vuelos.vo;
public class Pago {
protected int numVuelo;
protected String mensaje;
public Pago(int numVuelo, String mensaje) {
this.numVuelo = numVuelo;
this.mensaje = mensaje;
}
public int getNumVuelo() {
return numVuelo;
}
public void setNumVuelo(int numVuelo) {
this.numVuelo = numVuelo;
}
public String getMensaje() {
return mensaje;
}
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
}
|
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.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.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007 The JRuby Community
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.runtime.load;
import java.io.IOException;
import org.jruby.Ruby;
import org.jruby.ast.executable.Script;
public class JavaCompiledScript implements Library {
private final LoadServiceResource resource;
public JavaCompiledScript(LoadServiceResource resource) {
this.resource = resource;
}
public void load(Ruby runtime, boolean wrap) {
try {
Script script = CompiledScriptLoader.loadScriptFromFile(runtime, resource.getInputStream(), resource.getName());
if (script == null) {
// we're depending on the side effect of the load, which loads the class but does not turn it into a script
// I don't like it, but until we restructure the code a bit more, we'll need to quietly let it by here.
return;
}
script.setFilename(resource.getName());
runtime.loadScript(script, wrap);
} catch (IOException e) {
throw runtime.newIOErrorFromException(e);
}
}
}
|
package chapter08;
// 특정 기능을 전담하는 코드 덩어리를 Sub Routine이라고 한다. 자바에서는 Method라고 부른다.
// 자바는 모든 메서드를 클래스 내에서 작성하며, 홀로 존재하는 전역 함수를 지원하지 않는다.
// static은 메서드를 독립시키는 기능을 한다.
// 메서드 선언문의 인수를 형식 인수(매개 변수, Parameter)라 하며 호출원이 전달한 값을 대입받아 본체에서 참조할 때 사용.
// 형식 인수는 호출 과정에서 실인수값을 대입받아 본체에서 임시적으로 사용하는 일종의 지역 변수이다.
// 작업 사항이 많다면 얼마든지 많은 인수를 전달할 수 있고,
// 별도의 지시 사항이 없다면 인수가 없어도 무방하다. 인수 없으면 선언문에 빈 괄호만 적는다.
public class Getdays {
// 지정자 리턴타입 메서드명(인수 목록)
static int getMonthDays(int year, int month) {
int[] arDays = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2) {
if ( (year%4==0 && year%100 != 0) || year%400==0 ) {
return 29;
}
else {
return 28;
}
} else {
return arDays[month];
}
}
public static void main(String[] args) {
int year = 2016;
int month = 2;
int days = getMonthDays(year, month);
System.out.printf("%d년 %d월은 %d일까지 있습니다.", year, month, days);
}
}
// 구조적 프로그래밍 기법에서 함수는 프로그램의 작업 단위를 분할하는 부품 역할을 한다.
// 객체 지향 기법에서는 메서드가 클래스의 부품으로 격하되었지만, 클래스의 동작을 논리적으로 분할하는 역할을 한다.
/*
1. 두 번 이상 반복되는 코드는 메서드로 분리한다.
2. 한 번에 하나의 일만 한다.
3. 작업 단위를 가급적 잘게 쪼갠다.
4. 직관적이고 좋은 이름을 붙인다.
*/
|
package ru.job4j.stream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* class ListToMap
* project lesson 4.2.4
*
* @author Volodymyr Martynenko (VolodymyrV.Martynenko@gmail.com)
* project job4j
* @version 1.0
* @since 18.05.2019
*/
public class ListToMap {
/**
* method to convert List of Student to Map key=Student.name, value=object student
* @param students List of Students
* @return Map key=Student.name, value=object student
*/
public Map toMapStudends(List<Student> students) {
return students.stream().distinct().collect(
Collectors.toMap(
Student::getName,
student -> student
));
}
}
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.javaFX.actions;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.JavaCreateFromTemplateHandler;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiDirectory;
import org.jetbrains.annotations.NotNull;
public class JavaFxCreateFromTemplateHandler extends JavaCreateFromTemplateHandler {
@Override
public boolean handlesTemplate(@NotNull FileTemplate template) {
return "JavaFXApplication".equals(template.getName());
}
@Override
public boolean canCreate(PsiDirectory @NotNull [] dirs) {
if (dirs.length > 0) {
Project project = dirs[0].getProject();
if (JavaPsiFacade.getInstance(project).findPackage("javafx") == null) {
return false;
}
}
return super.canCreate(dirs);
}
}
|
/*
* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*@Author: niaoge(Zhengsheng Xia)
*@Email 78493244@qq.com
*@Date: 2015-6-20
*/
package com.helpinput.spring.servlet.mvc;
import org.slf4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextException;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import com.helpinput.core.LoggerBase;
import com.helpinput.holder.ContextHolder;
import com.helpinput.spring.registinerceptor.mvc.UrlInterceptorBeanRegistInterceptor;
@SuppressWarnings("serial")
public class EnhanceDispachServlet extends DispatcherServlet {
static Logger logger = LoggerBase.logger;
@Override
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
ContextHolder.beanRegistIntercpterHolder.register(new UrlInterceptorBeanRegistInterceptor());
Class<?> contextClass = getContextClass();
if (logger.isDebugEnabled()) {
logger.debug("Servlet with name '" + getServletName()
+ "' will try to create custom WebApplicationContext context of class '" + contextClass.getName()
+ "'" + ", using parent context [" + parent + "]");
}
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Fatal initialization error in servlet with name '"
+ getServletName() + "': custom WebApplicationContext class [" + contextClass.getName()
+ "] is not of type ConfigurableWebApplicationContext");
}
ConfigurableWebApplicationContext wac;
if (parent instanceof ConfigurableWebApplicationContext)
wac = (ConfigurableWebApplicationContext) parent;
else {
wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(getEnvironment());
wac.setParent(parent);
wac.setConfigLocation(getContextConfigLocation());
configureAndRefreshWebApplicationContext(wac);
}
return wac;
}
}
|
/*
* Copyright 2013-2019 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 uk.co.real_logic.sbe.xml;
import java.io.PrintStream;
/**
* Class to hold error handling state while parsing an XML message schema.
*/
public class ErrorHandler
{
private final PrintStream out;
private final boolean stopOnError;
private final boolean warningsFatal;
private final boolean suppressOutput;
private int errors = 0;
private int warnings = 0;
/**
* Construct a new {@link ErrorHandler} that outputs to a provided {@link PrintStream}.
*
* @param stream to which output should be sent.
* @param options the parsing options.
*/
public ErrorHandler(final PrintStream stream, final ParserOptions options)
{
out = stream;
stopOnError = options.stopOnError();
warningsFatal = options.warningsFatal();
suppressOutput = options.suppressOutput();
}
/**
* Default {@link ErrorHandler} that outputs to {@link System#err}.
*
* @param options the parsing options.
*/
public ErrorHandler(final ParserOptions options)
{
this(System.err, options);
}
/**
* Record a message signifying an error condition.
*
* @param msg signifying an error.
*/
public void error(final String msg)
{
errors++;
if (!suppressOutput)
{
out.println("ERROR: " + msg);
}
if (stopOnError)
{
throw new IllegalArgumentException(msg);
}
}
/**
* Record a message signifying an warning condition.
*
* @param msg signifying an warning.
*/
public void warning(final String msg)
{
warnings++;
if (!suppressOutput)
{
out.println("WARNING: " + msg);
}
if (warningsFatal && stopOnError)
{
throw new IllegalArgumentException(msg);
}
}
/**
* Check if the parser should exit.
*
* @throws IllegalStateException if there are errors or warnings recorded.
*/
public void checkIfShouldExit()
{
if (errors > 0)
{
throw new IllegalStateException("had " + errors + " errors");
}
else if (warnings > 0 && warningsFatal)
{
throw new IllegalStateException("had " + warnings + " warnings");
}
}
/**
* The count of errors encountered.
*
* @return the count of errors encountered.
*/
public int errorCount()
{
return errors;
}
/**
* The count of warnings encountered.
*
* @return the count of warnings encountered.
*/
public int warningCount()
{
return warnings;
}
public String toString()
{
return "ErrorHandler{" +
"out=" + out +
", stopOnError=" + stopOnError +
", warningsFatal=" + warningsFatal +
", suppressOutput=" + suppressOutput +
", errors=" + errors +
", warnings=" + warnings +
'}';
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.