text
stringlengths 7
1.01M
|
|---|
package org.kyojo.schemaorg.m3n5.gson.core.container;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import org.kyojo.gson.JsonDeserializationContext;
import org.kyojo.gson.JsonDeserializer;
import org.kyojo.gson.JsonElement;
import org.kyojo.gson.JsonParseException;
import org.kyojo.schemaorg.m3n5.core.impl.WEIGHT;
import org.kyojo.schemaorg.m3n5.core.Container.Weight;
import org.kyojo.schemaorg.m3n5.gson.DeserializerTemplate;
public class WeightDeserializer implements JsonDeserializer<Weight> {
public static Map<String, Field> fldMap = new HashMap<>();
@Override
public Weight deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
throws JsonParseException {
if(jsonElement.isJsonPrimitive()) {
return new WEIGHT(jsonElement.getAsString());
}
return DeserializerTemplate.deserializeSub(jsonElement, type, context,
new WEIGHT(), Weight.class, WEIGHT.class, fldMap);
}
}
|
package com.playMidi.player;
import com.playMidi.player.Midi.MidiHelperFunctions;
import com.playMidi.player.soundEvent.MidiTimbreSet;
import java.io.IOException;
import java.io.OutputStream;
import waveFormat.PcmHelpers;
/**
* Created by ra on 3/7/2017.
*/
public class Instrument {
private final String name;
private final int midiNumber;
private final MidiTimbreSet instrument;
private final int frameRate;
public Instrument(String name, int midiNumber, MidiTimbreSet inst, int frameRate){
this.name = name;
this.midiNumber = midiNumber;
this.instrument = inst;
this.frameRate = frameRate;
}
public final String getInstrumentName(){
return name;
}
public final int getInstrumentMidiNumber(){
return midiNumber;
}
/**
*
* @param volume float from 0:1
* @param buffer
*/
public final void fillBuffer(
int midiNoteNumber, int position, int noteLength, float volume, short[] buffer){
int wavelength = (int)MidiHelperFunctions.getWavelength(midiNoteNumber, frameRate);
double[] singleWave = new double[wavelength];
for(int i = 0; i<(wavelength ); i++){
singleWave[i] = Math.sin((2*Math.PI*i)/wavelength)*volume;
}
double[] b = new double[buffer.length];
instrument.setFrameRate(frameRate);
instrument.fillBuffer(midiNoteNumber,position,noteLength,buffer,volume,0);
for(int i = 0; i<buffer.length; i++){
buffer[i] = (short)b[i];
}
}
/**
*
* @param out destination output
* @param noteNumber midi sound number
* @param volume number from 0:{@link Short#MAX_VALUE Short.MAX_VALUE}
* @throws IOException
*/
public void SaveToFile(OutputStream out, int noteNumber, int volume) throws IOException{
int seconds = 0;
short[] buffer = new short[2048];
while(seconds>44100*3){
for(int i = 0; i<buffer.length; i++){ buffer[i] = 0; }
fillBuffer( noteNumber, seconds,buffer.length, volume, buffer);
PcmHelpers.Short.write(buffer, out);
seconds+=buffer.length;
}
}
}
|
/*
* Copyright 2021-2021 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.alfresco.activiti.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.alfresco.activiti.model.AppDefinitionRepresentation;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* AppDefinitionSaveRepresentation
*/
@Validated
public class AppDefinitionSaveRepresentation {
@JsonProperty("appDefinition")
private AppDefinitionRepresentation appDefinition = null;
@JsonProperty("force")
private Boolean force = null;
@JsonProperty("publish")
private Boolean publish = null;
public AppDefinitionSaveRepresentation appDefinition(AppDefinitionRepresentation appDefinition) {
this.appDefinition = appDefinition;
return this;
}
/**
* Get appDefinition
* @return appDefinition
**/
@ApiModelProperty(value = "")
@Valid
public AppDefinitionRepresentation getAppDefinition() {
return appDefinition;
}
public void setAppDefinition(AppDefinitionRepresentation appDefinition) {
this.appDefinition = appDefinition;
}
public AppDefinitionSaveRepresentation force(Boolean force) {
this.force = force;
return this;
}
/**
* Get force
* @return force
**/
@ApiModelProperty(value = "")
public Boolean isForce() {
return force;
}
public void setForce(Boolean force) {
this.force = force;
}
public AppDefinitionSaveRepresentation publish(Boolean publish) {
this.publish = publish;
return this;
}
/**
* Get publish
* @return publish
**/
@ApiModelProperty(value = "")
public Boolean isPublish() {
return publish;
}
public void setPublish(Boolean publish) {
this.publish = publish;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AppDefinitionSaveRepresentation appDefinitionSaveRepresentation = (AppDefinitionSaveRepresentation) o;
return Objects.equals(this.appDefinition, appDefinitionSaveRepresentation.appDefinition) &&
Objects.equals(this.force, appDefinitionSaveRepresentation.force) &&
Objects.equals(this.publish, appDefinitionSaveRepresentation.publish);
}
@Override
public int hashCode() {
return Objects.hash(appDefinition, force, publish);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AppDefinitionSaveRepresentation {\n");
sb.append(" appDefinition: ").append(toIndentedString(appDefinition)).append("\n");
sb.append(" force: ").append(toIndentedString(force)).append("\n");
sb.append(" publish: ").append(toIndentedString(publish)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package com.stylefeng.guns.core.datasource;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
/**
* <p>数据库数据源配置</p>
* <p>说明:这个类中包含了许多默认配置,若这些配置符合您的情况,您可以不用管,若不符合,建议不要修改本类,建议直接在"application.yml"中配置即可</p>
* @author stylefeng
* @date 2017-05-21 11:18
*/
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProperties {
private String url = "jdbc:mysql://120.78.73.3:3306/jifang?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
private String username = "sc";
private String password = "gdsc2016";
private String driverClassName = "com.mysql.jdbc.Driver";
private Integer initialSize = 2;
private Integer minIdle = 1;
private Integer maxActive = 20;
private Integer maxWait = 60000;
private Integer timeBetweenEvictionRunsMillis = 60000;
private Integer minEvictableIdleTimeMillis = 300000;
private String validationQuery = "SELECT 'x'";
private Boolean testWhileIdle = true;
private Boolean testOnBorrow = false;
private Boolean testOnReturn = false;
private Boolean poolPreparedStatements = true;
private Integer maxPoolPreparedStatementPerConnectionSize = 20;
private String filters = "stat";
public void config(DruidDataSource dataSource) {
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setInitialSize(initialSize); //定义初始连接数
dataSource.setMinIdle(minIdle); //最小空闲
dataSource.setMaxActive(maxActive); //定义最大连接数
dataSource.setMaxWait(maxWait); //最长等待时间
// 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
// 配置一个连接在池中最小生存的时间,单位是毫秒
dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
dataSource.setValidationQuery(validationQuery);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTestOnBorrow(testOnBorrow);
dataSource.setTestOnReturn(testOnReturn);
// 打开PSCache,并且指定每个连接上PSCache的大小
dataSource.setPoolPreparedStatements(poolPreparedStatements);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
dataSource.setFilters(filters);
} catch (SQLException e) {
e.printStackTrace();
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public Integer getInitialSize() {
return initialSize;
}
public void setInitialSize(Integer initialSize) {
this.initialSize = initialSize;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxWait() {
return maxWait;
}
public void setMaxWait(Integer maxWait) {
this.maxWait = maxWait;
}
public Integer getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Integer getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public Boolean getTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(Boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Boolean getTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(Boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public Boolean getTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(Boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public Boolean getPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public Integer getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
}
|
package com.drumonii.loltrollbuild.security.login;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
@ExtendWith(MockitoExtension.class)
class JsonAuthenticationSuccessHandlerTest {
@Mock
private ObjectMapper objectMapper;
@InjectMocks
private JsonAuthenticationSuccessHandler successHandler;
@Test
void onAuthenticationSuccess() throws IOException {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
User user = new User("username", "password", AuthorityUtils.createAuthorityList("ROLE_ADMIN"));
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
String json =
"{" +
" \"status\": \"SUCCESS\"," +
" \"message\": \"Authentication success\"," +
" \"userDetails\": {" +
" \"name\": \"username\"," +
" \"authorities\": [" +
" { " +
" \"authority\": \"ROLE_ADMIN\"" +
" }" +
" ]" +
" }" +
"}";
given(objectMapper.writeValueAsString(any(LoginResponse.class))).willReturn(json);
successHandler.onAuthenticationSuccess(request, response, authenticationToken);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.getContentType()).isEqualTo("application/json");
assertThat(response.getContentAsString()).isEqualTo(json);
}
}
|
package com.gc.materialdesign.views;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gc.materialdesign.utils.Utils;
import com.mcal.disassembler.R;
import com.nineoldandroids.view.ViewHelper;
public class Slider extends CustomView {
private int backgroundColor = Color.parseColor("#4CAF50");
private Ball ball;
private Bitmap bitmap;
private int max = 100;
private int min = 0;
private NumberIndicator numberIndicator;
private OnValueChangedListener onValueChangedListener;
private boolean placedBall = false;
private boolean press = false;
private boolean showNumberIndicator = false;
private int value = 0;
public Slider(Context context, AttributeSet attrs) {
super(context, attrs);
setAttributes(attrs);
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public OnValueChangedListener getOnValueChangedListener() {
return onValueChangedListener;
}
public void setOnValueChangedListener(
OnValueChangedListener onValueChangedListener) {
this.onValueChangedListener = onValueChangedListener;
}
// GETERS & SETTERS
public int getValue() {
return value;
}
public void setValue(final int value) {
if (placedBall == false)
post(new Runnable() {
@Override
public void run() {
setValue(value);
}
});
else {
this.value = value;
float division = (ball.xFin - ball.xIni) / max;
ViewHelper.setX(ball,
value * division + getHeight() / 2 - ball.getWidth() / 2);
ball.changeBackground();
}
}
@Override
public void invalidate() {
ball.invalidate();
super.invalidate();
}
public boolean isShowNumberIndicator() {
return showNumberIndicator;
}
public void setShowNumberIndicator(boolean showNumberIndicator) {
this.showNumberIndicator = showNumberIndicator;
numberIndicator = (showNumberIndicator) ? new NumberIndicator(
getContext()) : null;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
isLastTouch = true;
if (isEnabled()) {
if (event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE) {
if (numberIndicator != null
&& numberIndicator.isShowing() == false)
numberIndicator.show();
if ((event.getX() <= getWidth() && event.getX() >= 0)) {
press = true;
// calculate value
int newValue = 0;
float division = (ball.xFin - ball.xIni) / (max - min);
if (event.getX() > ball.xFin) {
newValue = max;
} else if (event.getX() < ball.xIni) {
newValue = min;
} else {
newValue = min + (int) ((event.getX() - ball.xIni) / division);
}
if (value != newValue) {
value = newValue;
if (onValueChangedListener != null)
onValueChangedListener.onValueChanged(newValue);
}
// move ball indicator
float x = event.getX();
x = (x < ball.xIni) ? ball.xIni : x;
x = (x > ball.xFin) ? ball.xFin : x;
ViewHelper.setX(ball, x);
ball.changeBackground();
// If slider has number indicator
if (numberIndicator != null) {
// move number indicator
numberIndicator.indicator.x = x;
numberIndicator.indicator.finalY = Utils
.getRelativeTop(this) - getHeight() / 2;
numberIndicator.indicator.finalSize = getHeight() / 2;
numberIndicator.numberIndicator.setText("");
}
} else {
press = false;
isLastTouch = false;
if (numberIndicator != null)
numberIndicator.dismiss();
}
} else if (event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
if (numberIndicator != null)
numberIndicator.dismiss();
isLastTouch = false;
press = false;
}
}
return true;
}
@Override
public void setBackgroundColor(int color) {
backgroundColor = color;
if (isEnabled())
beforeBackground = backgroundColor;
}
/**
* Make a dark color to press effect
*
* @return
*/
protected int makePressColor() {
int r = (this.backgroundColor >> 16) & 0xFF;
int g = (this.backgroundColor >> 8) & 0xFF;
int b = (this.backgroundColor >> 0) & 0xFF;
r = (r - 30 < 0) ? 0 : r - 30;
g = (g - 30 < 0) ? 0 : g - 30;
b = (b - 30 < 0) ? 0 : b - 30;
return Color.argb(70, r, g, b);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!placedBall) {
placeBall();
}
Paint paint = new Paint();
if (value == min) {
// Crop line to transparent effect
if (bitmap == null) {
bitmap = Bitmap.createBitmap(canvas.getWidth(),
canvas.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas temp = new Canvas(bitmap);
paint.setColor(Color.parseColor("#B0B0B0"));
paint.setStrokeWidth(Utils.dpToPx(2, getResources()));
temp.drawLine(getHeight() / 2, getHeight() / 2, getWidth()
- getHeight() / 2, getHeight() / 2, paint);
Paint transparentPaint = new Paint();
transparentPaint.setColor(getResources().getColor(
android.R.color.transparent));
transparentPaint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
temp.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2,
ViewHelper.getY(ball) + ball.getHeight() / 2,
ball.getWidth() / 2, transparentPaint);
canvas.drawBitmap(bitmap, 0, 0, new Paint());
} else {
paint.setColor(Color.parseColor("#B0B0B0"));
paint.setStrokeWidth(Utils.dpToPx(2, getResources()));
canvas.drawLine(getHeight() / 2, getHeight() / 2, getWidth()
- getHeight() / 2, getHeight() / 2, paint);
paint.setColor(backgroundColor);
float division = (ball.xFin - ball.xIni) / (max - min);
int value = this.value - min;
canvas.drawLine(getHeight() / 2, getHeight() / 2, value * division
+ getHeight() / 2, getHeight() / 2, paint);
}
if (press && !showNumberIndicator) {
paint.setColor(backgroundColor);
paint.setAntiAlias(true);
canvas.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2,
getHeight() / 2, getHeight() / 3, paint);
}
invalidate();
}
// Set atributtes of XML to View
protected void setAttributes(AttributeSet attrs) {
setBackgroundResource(R.drawable.background_transparent);
// Set size of view
setMinimumHeight(Utils.dpToPx(48, getResources()));
setMinimumWidth(Utils.dpToPx(80, getResources()));
// Set background Color
// Color by resource
int bacgroundColor = attrs.getAttributeResourceValue(ANDROIDXML,
"background", -1);
if (bacgroundColor != -1) {
setBackgroundColor(getResources().getColor(bacgroundColor));
} else {
// Color by hexadecimal
int background = attrs.getAttributeIntValue(ANDROIDXML, "background", -1);
if (background != -1)
setBackgroundColor(background);
}
showNumberIndicator = attrs.getAttributeBooleanValue(MATERIALDESIGNXML,
"showNumberIndicator", false);
min = attrs.getAttributeIntValue(MATERIALDESIGNXML, "min", 0);
max = attrs.getAttributeIntValue(MATERIALDESIGNXML, "max", 0);
value = attrs.getAttributeIntValue(MATERIALDESIGNXML, "value", min);
ball = new Ball(getContext());
RelativeLayout.LayoutParams params = new LayoutParams(Utils.dpToPx(20,
getResources()), Utils.dpToPx(20, getResources()));
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
ball.setLayoutParams(params);
addView(ball);
// Set if slider content number indicator
// TODO
if (showNumberIndicator) {
numberIndicator = new NumberIndicator(getContext());
}
}
private void placeBall() {
ViewHelper.setX(ball, getHeight() / 2 - ball.getWidth() / 2);
ball.xIni = ViewHelper.getX(ball);
ball.xFin = getWidth() - getHeight() / 2 - ball.getWidth() / 2;
ball.xCen = getWidth() / 2 - ball.getWidth() / 2;
placedBall = true;
}
// Event when slider change value
public interface OnValueChangedListener {
public void onValueChanged(int value);
}
class Ball extends View {
float xIni, xFin, xCen;
public Ball(Context context) {
super(context);
setBackgroundResource(R.drawable.background_switch_ball_uncheck);
}
public void changeBackground() {
if (value != min) {
setBackgroundResource(R.drawable.background_checkbox);
LayerDrawable layer = (LayerDrawable) getBackground();
GradientDrawable shape = (GradientDrawable) layer
.findDrawableByLayerId(R.id.shape_bacground);
shape.setColor(backgroundColor);
} else {
setBackgroundResource(R.drawable.background_switch_ball_uncheck);
}
}
}
// Slider Number Indicator
class Indicator extends RelativeLayout {
boolean animate = true;
// Final size after animation
float finalSize = 0;
// Final y position after animation
float finalY = 0;
boolean numberIndicatorResize = false;
// Size of number indicator
float size = 0;
// Position of number indicator
float x = 0;
float y = 0;
public Indicator(Context context) {
super(context);
setBackgroundColor(getResources().getColor(
android.R.color.transparent));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (numberIndicatorResize == false) {
LayoutParams params = (LayoutParams) numberIndicator.numberIndicator
.getLayoutParams();
params.height = (int) finalSize * 2;
params.width = (int) finalSize * 2;
numberIndicator.numberIndicator.setLayoutParams(params);
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(backgroundColor);
if (animate) {
if (y == 0)
y = finalY + finalSize * 2;
y -= Utils.dpToPx(6, getResources());
size += Utils.dpToPx(2, getResources());
}
canvas.drawCircle(
ViewHelper.getX(ball)
+ Utils.getRelativeLeft((View) ball.getParent())
+ ball.getWidth() / 2, y, size, paint);
if (animate && size >= finalSize)
animate = false;
if (animate == false) {
ViewHelper
.setX(numberIndicator.numberIndicator,
(ViewHelper.getX(ball)
+ Utils.getRelativeLeft((View) ball
.getParent()) + ball.getWidth() / 2)
- size);
ViewHelper.setY(numberIndicator.numberIndicator, y - size);
numberIndicator.numberIndicator.setText(value + "");
}
invalidate();
}
}
class NumberIndicator extends Dialog {
Indicator indicator;
TextView numberIndicator;
public NumberIndicator(Context context) {
super(context, android.R.style.Theme_Translucent);
}
@Override
public void dismiss() {
super.dismiss();
indicator.y = 0;
indicator.size = 0;
indicator.animate = true;
}
@Override
public void onBackPressed() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.gc_materialdesign_number_indicator_spinner);
setCanceledOnTouchOutside(false);
RelativeLayout content = (RelativeLayout) this
.findViewById(R.id.number_indicator_spinner_content);
indicator = new Indicator(this.getContext());
content.addView(indicator);
numberIndicator = new TextView(getContext());
numberIndicator.setTextColor(Color.WHITE);
numberIndicator.setGravity(Gravity.CENTER);
content.addView(numberIndicator);
indicator.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT));
}
}
}
|
/*
* Copyright (c) 2003, 2006, 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 java.lang;
import java.lang.annotation.*;
/**
* Indicates that a method declaration is intended to override a
* method declaration in a supertype. If a method is annotated with
* this annotation type compilers are required to generate an error
* message unless at least one of the following conditions hold:
*
* <ul><li>
* The method does override or implement a method declared in a
* supertype.
* </li><li>
* The method has a signature that is override-equivalent to that of
* any public method declared in {@linkplain Object}.
* </li></ul>
*
* @author Peter von der Ahé
* @author Joshua Bloch
* @jls 9.6.1.4 Override
* @since 1.5
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
|
package retrofit.http.retrofit;
/**
* @class describe
* @anthor aojiaoqiang
* @time 2018/10/19 17:20
*/
public interface IHttpParamListener {
String getBaseUrl();
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.containerinstance.implementation;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The logs.
*/
public class LogsInner {
/**
* The content of the log.
*/
@JsonProperty(value = "content")
private String content;
/**
* Get the content of the log.
*
* @return the content value
*/
public String content() {
return this.content;
}
/**
* Set the content of the log.
*
* @param content the content value to set
* @return the LogsInner object itself.
*/
public LogsInner withContent(String content) {
this.content = content;
return this;
}
}
|
/*
* //******************************************************************
* //
* // Copyright 2016 Samsung Electronics All Rights Reserved.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
* //
* // Licensed under the Apache License, Version 2.0 (the "License");
* // you may not use this file except in compliance with the License.
* // You may obtain a copy of the License at
* //
* // http://www.apache.org/licenses/LICENSE-2.0
* //
* // Unless required by applicable law or agreed to in writing, software
* // distributed under the License is distributed on an "AS IS" BASIS,
* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* // See the License for the specific language governing permissions and
* // limitations under the License.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
package org.iotivity.cloud.ciserver.resources.proxy.rd;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.iotivity.cloud.base.connector.ConnectorPool;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.device.IResponseEventHandler;
import org.iotivity.cloud.base.exception.ClientException;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.ciserver.Constants;
import org.iotivity.cloud.util.Cbor;
/**
*
* This class provides a set of APIs to send requests about resource presence to
* resource directory
*
*/
public class ResourcePresence extends Resource {
IRequestChannel mASServer = null;
private Cbor<HashMap<String, Object>> mCbor = new Cbor<>();
public ResourcePresence() {
super(Arrays.asList(Constants.PREFIX_OIC, Constants.RES_PRESENCE_URI));
mASServer = ConnectorPool.getConnection("account");
}
class AccountReceiveHandler implements IResponseEventHandler {
IRequestChannel mRDServer = null;
private Device mSrcDevice;
private IRequest mRequest;
public AccountReceiveHandler(IRequest request, Device srcDevice) {
mRDServer = ConnectorPool.getConnection("rd");
mSrcDevice = srcDevice;
mRequest = request;
}
@Override
public void onResponseReceived(IResponse response)
throws ClientException {
switch (response.getStatus()) {
case CONTENT:
HashMap<String, Object> payloadData = mCbor
.parsePayloadFromCbor(response.getPayload(),
HashMap.class);
if (payloadData == null) {
mSrcDevice.sendResponse(MessageBuilder.createResponse(
mRequest, ResponseStatus.BAD_REQUEST));
return;
}
if (mRequest.getUriQuery() != null
&& mRequest.getUriQueryMap()
.containsKey(Constants.REQ_DEVICE_ID)) {
if (!getResponseDeviceList(payloadData)
.containsAll(mRequest.getUriQueryMap()
.get(Constants.REQ_DEVICE_ID))) {
mSrcDevice.sendResponse(
MessageBuilder.createResponse(mRequest,
ResponseStatus.BAD_REQUEST));
}
} else {
String additionalQuery = makeAdditionalQuery(
payloadData, mSrcDevice.getDeviceId());
if (additionalQuery == null) {
mSrcDevice.sendResponse(
MessageBuilder.createResponse(mRequest,
ResponseStatus.BAD_REQUEST));
return;
}
mRequest = MessageBuilder.modifyRequest(mRequest, null,
additionalQuery
+ (mRequest.getUriQuery() != null
? ";" + mRequest.getUriQuery()
: ""),
null, null);
}
mRDServer.sendRequest(mRequest, mSrcDevice);
break;
default:
mSrcDevice.sendResponse(MessageBuilder.createResponse(
mRequest, ResponseStatus.BAD_REQUEST));
}
}
private String makeAdditionalQuery(HashMap<String, Object> payloadData,
String did) {
StringBuilder additionalQuery = new StringBuilder();
List<String> deviceList = getResponseDeviceList(payloadData);
if (deviceList.isEmpty()) {
return null;
}
int index = deviceList.size();
for (String device : deviceList) {
additionalQuery.append(Constants.REQ_DEVICE_ID + "=" + device);
if (--index > 0) {
additionalQuery.append(";");
}
}
return additionalQuery.toString();
}
@SuppressWarnings("unchecked")
private List<String> getResponseDeviceList(
HashMap<String, Object> payloadData) {
List<String> deviceList = (List<String>) payloadData
.get(Constants.REQ_DEVICE_LIST);
return deviceList;
}
}
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
StringBuffer uriQuery = new StringBuffer();
uriQuery.append(Constants.REQ_MEMBER_ID + "=" + srcDevice.getUserId());
StringBuffer uriPath = new StringBuffer();
uriPath.append(Constants.PREFIX_OIC + "/");
uriPath.append(Constants.ACL_URI + "/");
uriPath.append(Constants.GROUP_URI + "/");
uriPath.append(srcDevice.getUserId());
IRequest requestToAS = MessageBuilder.createRequest(RequestMethod.GET,
uriPath.toString(), uriQuery.toString());
mASServer.sendRequest(requestToAS,
new AccountReceiveHandler(request, srcDevice));
}
}
|
package ru.job4j.list;
//import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class SimpleList<E> implements SimpleListInterface<E> {
private Object[] container;
private int size = 0;
private int modCount = 0;
public SimpleList() {
this.container = new Object[5];
}
public SimpleList(int capacity) {
this.container = new Object[capacity];
}
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < this.size; i++) {
if (this.container[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < this.size; i++) {
if (this.container[i].equals(o)) {
return i;
}
}
}
return -1;
}
@Override
public void add(E value) {
if (container.length == size) {
resize(2 * size);
}
container[size++] = value;
modCount++;
}
public int size() {
return size;
}
private void resize(int newsize) {
// container = Arrays.copyOf(container, newsize); //OR
Object[] newData = new Object[newsize];
// System.arraycopy(container, 0, newData,0, container.length); // OR
for (int i = 0; i < container.length; i++) {
newData[i] = container[i];
}
container = newData;
}
@Override
@SuppressWarnings("unchecked")
public E get(int index) {
return (E) container[index];
}
@Override
public Iterator<E> iterator() {
return new SimpleIterator();
}
private class SimpleIterator implements Iterator<E> {
int idx = 0;
int expectedModCount = modCount;
@Override
public boolean hasNext() {
return idx < size;
}
@Override
@SuppressWarnings("unchecked")
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
return (E) container[idx++];
}
}
}
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package edu.nwmissouri.zoo03group;
/**
* This class is about Adult Visitor which visitor
* @author Hari Hara Mummadi
*/
public class AdultVisitor extends Visitor{
/**
* Constructor for Adult Visitor Class
* @param visitorCategory
* @param ticketPrice
* @param name
* @param email
* @param phoneNumber
*/
public AdultVisitor(VisitorCategory visitorCategory, String ticketPrice, String name, String email, int phoneNumber) {
super(visitorCategory, ticketPrice, name, email, phoneNumber);
}
/**
* Over riding the Ticket Price For Adult visitor
*/
@Override
public void ticketPrice() {
System.out.println("Zoo Entry Ticket price for the Adult Visitor is : 8.5$");
}
/**
* Over riding the Visitor Category for Adult Visitor
*/
@Override
public void visitorCategory() {
System.out.println("I am an Adult Visitor");
}
/**
* Method for Visitor Occupation of Adult Visitor
*/
public void visitorOccupation(){
System.out.println("Adult Visitor Occupation is : Sales Manager");
}
}
|
/*
* 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.shardingsphere.shardingjdbc.orchestration.internal.yaml;
import java.util.Map;
import java.util.Properties;
import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.encrypt.yaml.config.YamlRootEncryptRuleConfiguration;
import org.apache.shardingsphere.orchestration.center.yaml.config.YamlCenterRepositoryConfiguration;
/**
* Orchestration encrypt configuration for YAML.
*/
@Getter
@Setter
public final class YamlOrchestrationEncryptRuleConfiguration extends YamlRootEncryptRuleConfiguration {
private Map<String, YamlCenterRepositoryConfiguration> orchestration;
private Properties props = new Properties();
}
|
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Consumer;
public class DLinkedList<E> implements ListInterface<E>, Iterable<E>
{
// The first Node in the list.
private Node<E> first;
// The last Node in the list.
private Node<E> last;
// The amount of Nodes in the list.
private int size;
/**
* Constructs an empty list.
*/
public DLinkedList()
{
first = null;
size = 0;
}
/**
* Adds an item at the end of the list.
*/
@Override
public void add(E e)
{
addLast(e);
}
/**
* Adds an item at the start of the list.
*/
@Override
public void addFirst(E item)
{
add(item, 0);
}
/**
* Adds an item at the end of the list.
*/
@Override
public void addLast(E item)
{
add(item, size());
}
/**
* Adds an item at the specified index.
*/
@Override
public void add(E item, int index)
{
if (index > size() || index < 0) {
throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size());
}
Node<E> shiftNode = null; // The node that will be after the new node in the list.
Node<E> prevNode = null; // The node that comes before the new node in the list.
Node<E> newNode = new Node<E>(item);
if (size() == 0 && index == 0) { // If the list is empty and we are requesting to add at the start, don't assign values to shiftNode and prevNode.
shiftNode = null;
prevNode = null;
}
else if (index == size()) { // If adding to the end of the list, the shiftNode will also be null
shiftNode = null;
prevNode = getNode(index - 1, true);
}
else {
shiftNode = getNode(index, true);
prevNode = shiftNode.getPrev();
}
if (size() != 0) { // If this isn't the first item added, first item passes over and simply get assigned to first and last.
if (shiftNode != null) shiftNode.setPrev(newNode);
prevNode.setNext(newNode);
newNode.setNext(shiftNode);
newNode.setPrev(prevNode);
}
// If inserting at the start of the list
if (index == 0) first = newNode;
// If inserting at the end of the list, note that this isnt an else if because the first item inserted would be both.
if (index == size()) last = newNode;
// Ensure the first and last fields are set correctly, even if they didn't change.
if (first != null) first.setPrev(last);
if (last != null) last.setNext(first);
size++;
}
/**
* Returns the number of items in the list.
*/
@Override
public int size()
{
return size;
}
/**
* Removes the item at the specified index.
* @return The item that was removed.
*/
@Override
public E delete(int index)
{
if (index >= size() || index < 0) {
throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size());
}
Node<E> toDelete = getNode(index, true);
Node<E> prevNode = toDelete.getPrev();
Node<E> nextNode = toDelete.getNext();
E data = toDelete.getData();
if (index == 0) { // If removing the first or last item, make sure to assign first/last to the new first/last Node.
first = nextNode;
}
else if (index == size() - 1) {
last = prevNode;
}
prevNode.setNext(nextNode);
nextNode.setPrev(prevNode);
toDelete.clear();
size--;
return data;
}
/**
* Removes the first item in the list.
* @return The first item.
*/
@Override
public E deleteFirst()
{
return delete(0);
}
/**
* Removes the last item in the list.
* @return The last item in the list.
*/
@Override
public E deleteLast()
{
return delete(size() - 1);
}
/**
* Removes all items from the list.
*/
@Override
public void clear()
{
// I looked at the implementation of LinkedList as I wasn't sure if i
// needed to clear all the nodes. There was a comment saying it's not
// required but is still usefull.
Node<E> currentNode = first;
while (currentNode != null) {
Node<E> nextNode = currentNode.getNext();
currentNode.clear();
currentNode = nextNode;
}
first = null;
size = 0;
}
/**
* Gets the item at a specified index.
* @deprecated Use the {@code getFast(int index)} method instead.
*/
@Override
@Deprecated
public E get(int index)
{
return getNode(index, false).getData();
}
/**
* Gets the item at a specified index.
*/
public E getFast(int index)
{
return getNode(index, true).getData();
}
/**
* Gets the first item in the list.
*/
@Override
public E getFirst() {
return first.getData();
}
/**
* Gets the last item in the list.
*/
@Override
public E getLast() {
return last.getData();
}
/**
* Sets a specified items value.
* @param index The index of the item to set.
* @param value The new value.
*/
@Override
public void set(int index, E value)
{
Node<E> toChange = getNode(index, true);
toChange.setData(value);
}
/**
* Returns true if and only if this list has an item that {@code .equals()} {@code item},
* or if {@code item} is null, returns true if this list contains a null element.
*/
@Override
public boolean contains(E item)
{
if (item == null) { // If item is null, check for a null element.
for (int i = 0; i < size; i++) {
if (get(i) == null) return true;
}
}
else { // If item is not null, check for .equals()
for (int i = 0; i < size; i++) {
if (item.equals(get(i))) return true;
}
}
return false;
}
/**
* Gets the node at a specified index.
*/
private Node<E> getNode(int index, boolean fastMode)
{
if (index >= size() || index < 0) {
throw new IndexOutOfBoundsException("Index " + index + " out of bounds for size " + size());
}
if (fastMode && index > size() / 2.0 ) { // fastMode will go from the back of the list if it would be faster.
Node<E> tmp = last;
int backIndex = size() - 1 - index; // Max index - index = how many from the back needed to go.
for (int i = 0; i < backIndex; i++) {
tmp = tmp.getPrev();
}
return tmp;
}
else {
Node<E> tmp = first;
for (int i = 0; i < index; i++) {
tmp = tmp.getNext();
}
return tmp;
}
}
/**
* Provides a string of each item with a space inbetween.
* @return A string with each items toString seperated by a space.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node<E> tmp = first;
while (tmp != null) {
sb.append(tmp.getData() + " ");
tmp = tmp.getNext();
}
return sb.toString().strip();
}
/**
* Returns an iterator of each element in this list in order.
*/
@Override
public Iterator<E> iterator()
{
return new Iterator<E>(){
private Node<E> next = first;
private boolean usedNext = false;
public boolean hasNext()
{
return next != null && (next != first || !usedNext);
}
public E next()
{
E data = next.getData();
next = next.getNext();
usedNext = true;
return data;
}
};
}
/**
* Preforms the given action on every item in the list in order of index.
*/
public void forEach(Consumer<? super E> action)
{
Objects.requireNonNull(action);
Node<E> current = first;
for (int i = 0; i < size(); i++) {
action.accept(current.getData());
current = current.getNext();
}
}
}
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.amazon.ask.model.interfaces.alexa.presentation.apl;
import java.util.Objects;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
/**
* Alexa.Presentation.APL.ExecuteCommands directive used to send APL commands to a device.
*/
@JsonDeserialize(builder = ExecuteCommandsDirective.Builder.class)
public final class ExecuteCommandsDirective extends com.amazon.ask.model.Directive {
@JsonProperty("commands")
private List<com.amazon.ask.model.interfaces.alexa.presentation.apl.Command> commands = new ArrayList<com.amazon.ask.model.interfaces.alexa.presentation.apl.Command>();
@JsonProperty("token")
private String token = null;
public static Builder builder() {
return new Builder();
}
private ExecuteCommandsDirective(Builder builder) {
String discriminatorValue = "Alexa.Presentation.APL.ExecuteCommands";
this.type = discriminatorValue;
if (builder.commands != null) {
this.commands = builder.commands;
}
if (builder.token != null) {
this.token = builder.token;
}
}
/**
* List of Command instances
* @return commands
**/
@JsonProperty("commands")
public List<com.amazon.ask.model.interfaces.alexa.presentation.apl.Command> getCommands() {
return commands;
}
/**
* A skill defined token, unique for each presentation. Must match the token provided by the skill in the RenderDocument directive used to render the original APL document.
* @return token
**/
@JsonProperty("token")
public String getToken() {
return token;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ExecuteCommandsDirective interfacesAlexaPresentationAplExecuteCommandsDirective = (ExecuteCommandsDirective) o;
return Objects.equals(this.commands, interfacesAlexaPresentationAplExecuteCommandsDirective.commands) &&
Objects.equals(this.token, interfacesAlexaPresentationAplExecuteCommandsDirective.token) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(commands, token, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ExecuteCommandsDirective {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" commands: ").append(toIndentedString(commands)).append("\n");
sb.append(" token: ").append(toIndentedString(token)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static class Builder {
private List<com.amazon.ask.model.interfaces.alexa.presentation.apl.Command> commands;
private String token;
private Builder() {}
@JsonProperty("commands")
public Builder withCommands(List<com.amazon.ask.model.interfaces.alexa.presentation.apl.Command> commands) {
this.commands = commands;
return this;
}
public Builder addCommandsItem(com.amazon.ask.model.interfaces.alexa.presentation.apl.Command commandsItem) {
if (this.commands == null) {
this.commands = new ArrayList<com.amazon.ask.model.interfaces.alexa.presentation.apl.Command>();
}
this.commands.add(commandsItem);
return this;
}
@JsonProperty("token")
public Builder withToken(String token) {
this.token = token;
return this;
}
public ExecuteCommandsDirective build() {
return new ExecuteCommandsDirective(this);
}
}
}
|
/**
*
*/
package com.lq.work.modules.oa.service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import com.hls.ws.modules.mail.dao.MailReceiveDao;
import com.hls.ws.modules.mail.entity.MailReceive;
import com.hls.ws.modules.message.dao.MsgInternalDao;
import com.hls.ws.modules.message.entity.MsgInternal;
import com.lq.work.common.persistence.Page;
import com.lq.work.common.service.CrudService;
import com.lq.work.common.utils.IdGen;
import com.lq.work.common.utils.StringUtils;
import com.lq.work.modules.oa.dao.OaNotifyDao;
import com.lq.work.modules.oa.dao.OaNotifyDepDao;
import com.lq.work.modules.oa.dao.OaNotifyRecordDao;
import com.lq.work.modules.oa.entity.OaNotify;
import com.lq.work.modules.oa.entity.OaNotifyDep;
import com.lq.work.modules.oa.entity.OaNotifyRecord;
import com.lq.work.modules.sys.dao.OfficeDao;
import com.lq.work.modules.sys.entity.Office;
/**
* 通知通告Service
*
* @version 2014-05-16
*/
@Service
@Transactional(readOnly = true)
public class OaNotifyService extends CrudService<OaNotifyDao, OaNotify> {
@Autowired
private OaNotifyRecordDao oaNotifyRecordDao;
@Autowired
private OaNotifyDepDao oaNotifyDepDao;
@Autowired
private MsgInternalDao msgInternalDao;
@Autowired
private MailReceiveDao mailReceiveDao;
@Autowired
private OfficeDao officeDao;
public OaNotify get(String id) {
OaNotify entity = dao.get(id);
return entity;
}
/**
* 获取通知发送记录
* @param oaNotify
* @return
*/
public OaNotify getRecordList(OaNotify oaNotify) {
oaNotify.setOaNotifyRecordList(oaNotifyRecordDao.findList(new OaNotifyRecord(oaNotify)));
oaNotify.setOadep(oaNotifyDepDao.findList(new OaNotifyDep(oaNotify)));
return oaNotify;
}
public Page<OaNotify> find(Page<OaNotify> page, OaNotify oaNotify) {
oaNotify.setPage(page);
//page.setList(dao.findList(oaNotify));
page.setList(dao.findNotifyDep(oaNotify));
return page;
}
/**
* 公告管理列表
* **/
public Page<OaNotify> findNotifyList(Page<OaNotify> page,OaNotify oaNotify){
oaNotify.setPage(page);
page.setList(dao.findNotifyList(oaNotify));
return page;
}
/**
* 获取通知数目
* @param oaNotify
* @return
*/
public Long findCount(OaNotify oaNotify) {
return dao.findCount(oaNotify);
}
/**
* 查询各类通知数量
* **/
public Map<String,String> count(){
Map<String,String> map = new HashMap<String,String>();
/*未读公告数量*/
OaNotify oaNotify = new OaNotify();
oaNotify.setSelf(true);
oaNotify.setReadFlag("0");
map.put("notifyCount", String.valueOf(dao.findCount(oaNotify)));
/*未读消息数量*/
MsgInternal msg = new MsgInternal();
map.put("msgCount", String.valueOf(this.msgInternalDao.msgCount(msg)));
/*未读邮件数量*/
map.put("mailCount", String.valueOf(this.mailReceiveDao.unreadCount(new MailReceive())));
return map;
}
@Transactional(readOnly = false)
public void save(OaNotify oaNotify) {
super.save(oaNotify);
// 更新发送接受人记录
oaNotifyRecordDao.deleteByOaNotifyId(oaNotify.getId());
if (oaNotify.getOaNotifyRecordList().size() > 0){
oaNotifyRecordDao.insertAll(oaNotify.getOaNotifyRecordList());
}
//更新部门
oaNotifyDepDao.deleteByOaNotifyId(oaNotify.getId());
if(StringUtils.equals(oaNotify.getNotifyScope(), "0")){
List<OaNotifyDep> list = Lists.newArrayList();
List<Office> office = this.officeDao.findAllList(new Office());
for (Office o : office){
OaNotifyDep entity = new OaNotifyDep();
entity.setId(IdGen.uuid());
entity.setNotifyId(oaNotify);
entity.setDepId(o);
entity.setReadFlag("0");
list.add(entity);
}
oaNotify.setOadep(list);
}
if(oaNotify.getOadep().size()>0){
oaNotifyDepDao.insertAll(oaNotify.getOadep());
}
}
/**
* 获取详情
* **/
@Transactional(readOnly=false)
public OaNotify detail(OaNotify oaNotify){
oaNotify=super.get(oaNotify.getId());
if(StringUtils.equals(oaNotify.getIsBack(), "0")){
/*查看详情时插入查看记录*/
Long count=this.oaNotifyRecordDao.notifyReadCount(new OaNotifyRecord(oaNotify));
if(count==0){
OaNotifyRecord onr = new OaNotifyRecord(oaNotify,oaNotify.getCurrentUser(),"1",new DateTime().toDate());
onr.setId(IdGen.uuid());
this.oaNotifyRecordDao.insert(onr);
}
return dao.detail(oaNotify);
}else{
return new OaNotify();
}
}
/**
* 更新阅读状态
*/
@Transactional(readOnly = false)
public void updateReadFlag(OaNotify oaNotify) {
OaNotifyRecord oaNotifyRecord = new OaNotifyRecord(oaNotify);
oaNotifyRecord.setUser(oaNotifyRecord.getCurrentUser());
oaNotifyRecord.setReadDate(new Date());
oaNotifyRecord.setReadFlag("1");
oaNotifyRecordDao.update(oaNotifyRecord);
}
/**
* 按照部门分组统计各部门已读与未读人数
* @author JERRY
* **/
public OaNotify notifyReadInfo(OaNotifyRecord onr){
OaNotify oa = new OaNotify();
oa.setOaNotifyRecordList(this.oaNotifyRecordDao.notifyReadInfo(onr));
return oa;
}
/**
* 批量标记已读
* **/
@Transactional(readOnly=false)
public Boolean read_notify(String ids){
if(StringUtils.isNotEmpty(ids)){
try {
for(String nid:StringUtils.split(ids, ",")){
OaNotify oaNotify = this.dao.get(nid);
OaNotifyRecord onr = new OaNotifyRecord(oaNotify,oaNotify.getCurrentUser(),"1",new DateTime().toDate());
onr.setId(IdGen.uuid());
this.oaNotifyRecordDao.insert(onr);
}
} catch (Exception e) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
/**
* 通知回退
* **/
@Transactional(readOnly=false)
public int notifyBack(OaNotify oaNotify){
/*删除通知接收部门*/
int i=this.oaNotifyDepDao.deleteByOaNotifyId(oaNotify.getId());
if(i>0){
/*删除通知阅读者信息*/
this.oaNotifyRecordDao.deleteByOaNotifyId(oaNotify.getId());
return dao.notifyBack(oaNotify);
}else{
return 0;
}
}
/**
* 首页公告信息
* @author JERRY
* **/
public List<OaNotify> mainNotify(OaNotify oaNotify){
return dao.mainNotify(oaNotify);
}
}
|
package com.ydh935.swaggercxf.resources;
import javax.servlet.ServletConfig;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.wordnik.swagger.jaxrs.listing.ApiListingResource;
@Path("/api-docs")
public class ApiListingResourceJSON extends ApiListingResource{
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getApiListingJson(@Context Application app,
@Context ServletConfig sc, @Context HttpHeaders headers,
@Context UriInfo uriInfo) {
return this.getListingJson(app, sc, headers, uriInfo);
}
}
|
package org.campagnelab.staging.intentions;
/*Generated by MPS */
import jetbrains.mps.intentions.IntentionAspectBase;
import jetbrains.mps.intentions.IntentionFactory;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import org.jetbrains.annotations.NotNull;
import jetbrains.mps.smodel.adapter.ids.SConceptId;
import java.util.Arrays;
public final class IntentionsDescriptor extends IntentionAspectBase {
private final long[] myId2Index;
private IntentionFactory[] myIntentions0;
public IntentionsDescriptor() {
myId2Index = new long[1];
myId2Index[0] = 0x10802efe25aL;
}
@Override
@Nullable
public Collection<IntentionFactory> getIntentions(@NotNull SConceptId conceptId) {
final int index = Arrays.binarySearch(myId2Index, conceptId.getIdValue());
switch (index) {
case 0:
// Concept: BaseConcept
if (myIntentions0 == null) {
myIntentions0 = new IntentionFactory[1];
myIntentions0[0] = new AddRemoveStageAnnotation_Intention();
}
return Arrays.asList(myIntentions0);
default:
return null;
}
}
@NotNull
@Override
public Collection<IntentionFactory> getAllIntentions() {
IntentionFactory[] rv = new IntentionFactory[1];
rv[0] = new AddRemoveStageAnnotation_Intention();
return Arrays.asList(rv);
}
}
|
package com.gplibs.magicsurfaceview;
public abstract class MagicSurfaceMatrixUpdater extends MagicMatrixUpdater {
MagicSurface mSurface;
public MagicSurfaceMatrixUpdater() {
}
public MagicSurfaceMatrixUpdater(int group) {
super(group);
}
@Override
float[] getMatrix() {
return mSurface.getModel().getMatrix();
}
@Override
void updateMatrix(float[] matrix) {
ReusableVec offset = VecPool.get(3);
try {
mSurface.getModel().getOffset(offset);
updateMatrix(mSurface, offset, matrix);
} finally {
offset.free();
}
}
@Override
void willStart() {
willStart(mSurface);
}
@Override
void didStart() {
didStart(mSurface);
}
@Override
void didStop() {
didStop(mSurface);
}
/**
* 在绘制第一帧之前调用 (可以在此方法里进行一些初始化操作)
* @param surface 需更新的MagicSurface对象
*/
protected abstract void willStart(MagicSurface surface);
/**
* 在开始绘制后调用(绘制第一帧后调用,一般动画可以在此开始)
* @param surface 需更新的MagicSurface对象
*/
protected abstract void didStart(MagicSurface surface);
/**
* 当调用Updater的stop方法之后,真正停止后会回调此方法
* @param surface 需更新的MagicSurface对象
*/
protected abstract void didStop(MagicSurface surface);
/**
* 矩阵变换
* @param surface 需更新的MagicSurface对象
* @param offset offse为模型相对场景中心的坐标偏移量, 如果不进行 offset 位移, model 就会显示在场景中心;
*
* 当使用 View 构造 MagicSurface 时,
* View中心位置 相对 MagicSurfaceView中心位置的坐标偏移量 在场景坐标系中的表现就是 offset。
*
* @param matrix 矩阵
*/
protected abstract void updateMatrix(MagicSurface surface, Vec offset, float[] matrix);
}
|
package com.lyft.pgv;
/**
* {@code ValidatorIndex} defines the entry point for finding {@link Validator} instances for a given type.
*/
public interface ValidatorIndex {
<T> Validator<T> validatorFor(Class clazz);
ValidatorIndex ALWAYS_VALID = new ValidatorIndex() {
@Override
public <T> Validator<T> validatorFor(Class clazz) {
return new Validator<T>() {
@Override
public void assertValid(T proto) throws ValidationException {
// it's valid
}
};
}
};
}
|
/*
* Copyright (c) 2020 Broadcom.
* The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Broadcom, Inc. - initial API and implementation
*
*/
package org.eclipse.lsp.cobol.usecases;
import org.eclipse.lsp.cobol.usecases.engine.UseCaseEngine;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Test;
/** This test checks that the JNIENVPTR doesn't produce a syntax error */
class TestJniEnvSpecialRegister {
private static final String TEXT =
" Identification Division. \n"
+ " Program-id. ProgramId.\n"
+ " Data Division.\n"
+ " Working-Storage Section.\n"
+ " 01 {$*JNIEnv} PIC 9. \n"
+ " Procedure Division.\n"
+ " {#*000-Main-Logic}.\n"
+ " Set address of {$JNIEnv} to JNIEnvPtr.\n"
+ " End program ProgramId.";
@Test
void test() {
UseCaseEngine.runTest(TEXT, ImmutableList.of(), ImmutableMap.of());
}
}
|
package ru.yandex.bolts.collection.impl;
import ru.yandex.bolts.collection.impl.test.SerializationUtils;
import junit.framework.TestCase;
public abstract class EmptyCollectionTestSupport extends TestCase {
protected abstract Object emptyInstance();
public void testSerialization() {
assertSame(EmptyMap.INSTANCE, SerializationUtils.serializeDeserialize(EmptyMap.INSTANCE));
}
} //~
|
/*
* Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://mindorks.com/license/apache-v2
*
* 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.scrachx.foodfacts.checker.di;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier;
/**
* Created by janisharali on 27/01/17.
*/
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface PreferenceInfo {
}
|
package uk.dangrew.jwags.resources.images.stats;
import javafx.scene.image.Image;
public class StatsImages {
private static final Image SPEED = new Image( StatsImages.class.getResourceAsStream( "speed.png" ) );
private static final Image DAMAGE = new Image( StatsImages.class.getResourceAsStream( "damage.png" ) );
private static final Image HEALTH = new Image( StatsImages.class.getResourceAsStream( "health.png" ) );
private static final Image CRITICAL = new Image( StatsImages.class.getResourceAsStream( "critical.png" ) );
private static final Image ARMOR = new Image( StatsImages.class.getResourceAsStream( "armor.png" ) );
public Image speed(){
return SPEED;
}//End Method
public Image damage(){
return DAMAGE;
}//End Method
public Image health(){
return HEALTH;
}//End Method
public Image critical(){
return CRITICAL;
}//End Method
public Image armor(){
return ARMOR;
}//End Method
}//End Class
|
/**
* InventoryService.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201405;
public interface InventoryService extends javax.xml.rpc.Service {
public java.lang.String getInventoryServiceInterfacePortAddress();
public com.google.api.ads.dfp.axis.v201405.InventoryServiceInterface getInventoryServiceInterfacePort() throws javax.xml.rpc.ServiceException;
public com.google.api.ads.dfp.axis.v201405.InventoryServiceInterface getInventoryServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException;
}
|
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.CRInternalAuditAssessmentGrantOutputModelGrantRequestResponseRecord;
import javax.validation.Valid;
/**
* CRInternalAuditAssessmentGrantOutputModel
*/
public class CRInternalAuditAssessmentGrantOutputModel {
private String internalAuditAssessmentParameterType = null;
private String internalAuditAssessmentSelectedOption = null;
private String internalAuditAssessmentRequest = null;
private String internalAuditAssessmentGrantActionTaskReference = null;
private Object internalAuditAssessmentGrantActionTaskRecord = null;
private String grantRequestRecordReference = null;
private CRInternalAuditAssessmentGrantOutputModelGrantRequestResponseRecord grantRequestResponseRecord = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: A Classification value that distinguishes between Assessments according to type of concern defined within Internal Audit Assessment . Eg Market Analysis, Risk Analysis, Perfomance Analysis, etc.
* @return internalAuditAssessmentParameterType
**/
public String getInternalAuditAssessmentParameterType() {
return internalAuditAssessmentParameterType;
}
public void setInternalAuditAssessmentParameterType(String internalAuditAssessmentParameterType) {
this.internalAuditAssessmentParameterType = internalAuditAssessmentParameterType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: A selected optional business service as subject matter of assessment
* @return internalAuditAssessmentSelectedOption
**/
public String getInternalAuditAssessmentSelectedOption() {
return internalAuditAssessmentSelectedOption;
}
public void setInternalAuditAssessmentSelectedOption(String internalAuditAssessmentSelectedOption) {
this.internalAuditAssessmentSelectedOption = internalAuditAssessmentSelectedOption;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Request to assess InternalAudit
* @return internalAuditAssessmentRequest
**/
public String getInternalAuditAssessmentRequest() {
return internalAuditAssessmentRequest;
}
public void setInternalAuditAssessmentRequest(String internalAuditAssessmentRequest) {
this.internalAuditAssessmentRequest = internalAuditAssessmentRequest;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a Internal Audit Assessment instance grant service call
* @return internalAuditAssessmentGrantActionTaskReference
**/
public String getInternalAuditAssessmentGrantActionTaskReference() {
return internalAuditAssessmentGrantActionTaskReference;
}
public void setInternalAuditAssessmentGrantActionTaskReference(String internalAuditAssessmentGrantActionTaskReference) {
this.internalAuditAssessmentGrantActionTaskReference = internalAuditAssessmentGrantActionTaskReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The grant service call consolidated processing record
* @return internalAuditAssessmentGrantActionTaskRecord
**/
public Object getInternalAuditAssessmentGrantActionTaskRecord() {
return internalAuditAssessmentGrantActionTaskRecord;
}
public void setInternalAuditAssessmentGrantActionTaskRecord(Object internalAuditAssessmentGrantActionTaskRecord) {
this.internalAuditAssessmentGrantActionTaskRecord = internalAuditAssessmentGrantActionTaskRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the grant request record
* @return grantRequestRecordReference
**/
public String getGrantRequestRecordReference() {
return grantRequestRecordReference;
}
public void setGrantRequestRecordReference(String grantRequestRecordReference) {
this.grantRequestRecordReference = grantRequestRecordReference;
}
/**
* Get grantRequestResponseRecord
* @return grantRequestResponseRecord
**/
public CRInternalAuditAssessmentGrantOutputModelGrantRequestResponseRecord getGrantRequestResponseRecord() {
return grantRequestResponseRecord;
}
public void setGrantRequestResponseRecord(CRInternalAuditAssessmentGrantOutputModelGrantRequestResponseRecord grantRequestResponseRecord) {
this.grantRequestResponseRecord = grantRequestResponseRecord;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.lsp.client.bindings.refactoring;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
import org.netbeans.api.queries.FileEncodingQuery;
import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.text.NbDocument;
import org.openide.text.PositionRef;
import org.openide.util.Parameters;
/**Copied from csl.api
* Class that collects changes built during a modification task run.
*
* @author Dusan Balek
*/
public final class ModificationResult implements org.netbeans.modules.refactoring.spi.ModificationResult {
private boolean committed;
private final Map<FileObject, List<Difference>> diffs = new HashMap<FileObject, List<Difference>>();
private static final Comparator<Difference> COMPARATOR = new Comparator<Difference>() {
public int compare(Difference d1, Difference d2) {
return d1.getStartPosition().getOffset() - d2.getStartPosition().getOffset();
}
};
/** Creates a new instance of ModificationResult */
public ModificationResult() {
}
// API of the class --------------------------------------------------------
public void addDifferences(FileObject fo, List<Difference> differences) {
List<Difference> fileDiffs = diffs.get(fo);
if (fileDiffs == null) {
fileDiffs = new ArrayList<Difference>();
diffs.put(fo, fileDiffs);
}
fileDiffs.addAll(differences);
// Sort the diffs, if applicable
if (fileDiffs.size() > 0) {
Collections.sort(fileDiffs, COMPARATOR);
}
}
public Set<? extends FileObject> getModifiedFileObjects() {
return diffs.keySet();
}
public List<? extends Difference> getDifferences(FileObject fo) {
return diffs.get(fo);
}
public Set<File> getNewFiles() {
Set<File> newFiles = new HashSet<File>();
for (List<Difference> ds:diffs.values()) {
for (Difference d: ds) {
if (d.getKind() == Difference.Kind.CREATE) {
newFiles.add(((CreateFileDifference) d).getFile());
}
}
}
return newFiles;
}
/**
* Once all of the changes have been collected, this method can be used
* to commit the changes to the source files
*/
public void commit() throws IOException {
if (this.committed) {
throw new IllegalStateException ("Calling commit on already committed Modificationesult."); //NOI18N
}
try {
for (Map.Entry<FileObject, List<Difference>> me : diffs.entrySet()) {
commit(me.getKey(), me.getValue(), null);
}
} finally {
this.committed = true;
}
}
private void commit (final FileObject fo, final List<Difference> differences, final Writer out) throws IOException {
DataObject dObj = DataObject.find(fo);
EditorCookie ec = dObj != null ? dObj.getCookie(org.openide.cookies.EditorCookie.class) : null;
// if editor cookie was found and user does not provided his own
// writer where he wants to see changes, commit the changes to
// found document.
if (ec != null && out == null) {
final StyledDocument doc = ec.getDocument();
if (doc != null) {
final IOException[] exceptions = new IOException [1];
NbDocument.runAtomic(doc, new Runnable () {
public void run () {
try {
commit2 (doc, differences, out);
} catch (IOException ex) {
exceptions [0] = ex;
}
}
});
if (exceptions [0] != null)
throw exceptions [0];
return;
}
}
InputStream ins = null;
ByteArrayOutputStream baos = null;
Reader in = null;
Writer out2 = out;
try {
Charset encoding = FileEncodingQuery.getEncoding(fo);
ins = fo.getInputStream();
baos = new ByteArrayOutputStream();
FileUtil.copy(ins, baos);
ins.close();
ins = null;
byte[] arr = baos.toByteArray();
int arrLength = convertToLF(arr);
baos.close();
baos = null;
in = new InputStreamReader(new ByteArrayInputStream(arr, 0, arrLength), encoding);
// initialize standard commit output stream, if user
// does not provide his own writer
boolean ownOutput = out != null;
if (out2 == null) {
out2 = new OutputStreamWriter(fo.getOutputStream(), encoding);
}
int offset = 0;
for (Difference diff : differences) {
if (diff.isExcluded())
continue;
if (Difference.Kind.CREATE == diff.getKind()) {
if (!ownOutput) {
createUnit((CreateFileDifference)diff, null);
}
continue;
}
int pos = diff.getStartPosition().getOffset();
int toread = pos - offset;
char[] buff = new char[toread];
int n;
int rc = 0;
while ((n = in.read(buff,0, toread - rc)) > 0 && rc < toread) {
out2.write(buff, 0, n);
rc+=n;
offset += n;
}
switch (diff.getKind()) {
case INSERT:
out2.write(diff.getNewText());
break;
case REMOVE:
int len = diff.getEndPosition().getOffset() - diff.getStartPosition().getOffset();
in.skip(len);
offset += len;
break;
case CHANGE:
len = diff.getEndPosition().getOffset() - diff.getStartPosition().getOffset();
in.skip(len);
offset += len;
out2.write(diff.getNewText());
break;
}
}
char[] buff = new char[1024];
int n;
while ((n = in.read(buff)) > 0)
out2.write(buff, 0, n);
} finally {
if (ins != null)
ins.close();
if (baos != null)
baos.close();
if (in != null)
in.close();
if (out2 != null)
out2.close();
}
}
private void commit2 (final StyledDocument doc, final List<Difference> differences, Writer out) throws IOException {
for (Difference diff : differences) {
if (diff.isExcluded())
continue;
switch (diff.getKind()) {
case INSERT:
case REMOVE:
case CHANGE:
processDocument(doc, diff);
break;
case CREATE:
createUnit((CreateFileDifference)diff, out);
break;
}
}
}
private void processDocument(final StyledDocument doc, final Difference diff) throws IOException {
final BadLocationException[] blex = new BadLocationException[1];
Runnable task = new Runnable() {
public void run() {
try {
processDocumentLocked(doc, diff);
} catch (BadLocationException ex) {
blex[0] = ex;
}
}
};
if (diff.isCommitToGuards()) {
NbDocument.runAtomic(doc, task);
} else {
try {
NbDocument.runAtomicAsUser(doc, task);
} catch (BadLocationException ex) {
blex[0] = ex;
}
}
if (blex[0] != null) {
IOException ioe = new IOException();
ioe.initCause(blex[0]);
throw ioe;
}
}
private void processDocumentLocked(Document doc, Difference diff) throws BadLocationException {
switch (diff.getKind()) {
case INSERT:
doc.insertString(diff.getStartPosition().getOffset(), diff.getNewText(), null);
break;
case REMOVE:
doc.remove(diff.getStartPosition().getOffset(), diff.getEndPosition().getOffset() - diff.getStartPosition().getOffset());
break;
case CHANGE:
doc.remove(diff.getStartPosition().getOffset(), diff.getEndPosition().getOffset() - diff.getStartPosition().getOffset());
doc.insertString(diff.getStartPosition().getOffset(), diff.getNewText(), null);
break;
}
}
private void createUnit(CreateFileDifference diff, Writer out) {
Writer w = out;
try {
if (w == null) {
w = new FileWriter(diff.getFile());
}
w.append(diff.getNewText());
} catch (IOException e) {
Logger.getLogger(ModificationResult.class.getName()).log(Level.SEVERE, e.getMessage(), e);
} finally {
if (w != null) {
try {
w.close();
} catch (IOException e) {
Logger.getLogger(ModificationResult.class.getName()).log(Level.SEVERE, e.getMessage(), e);
}
}
}
}
private int convertToLF(byte[] buff) {
int j = 0;
for (int i = 0; i < buff.length; i++) {
if (buff[i] != '\r') {
buff[j++] = buff[i];
}
}
return j;
}
/**
* Returned string represents preview of resulting source. No difference
* really is applied. Respects {@code isExcluded()} flag of difference.
*
* @param there can be more resulting source, user has to specify
* which wants to preview.
* @return if changes are applied source looks like return string
* @throws IllegalArgumentException if the provided {@link FileObject} is not
* modified in this {@link ModificationResult}
*/
public String getResultingSource(FileObject fileObject) throws IOException, IllegalArgumentException {
Parameters.notNull("fileObject", fileObject);
if (!getModifiedFileObjects().contains(fileObject)) {
throw new IllegalArgumentException("File: " + FileUtil.getFileDisplayName(fileObject) + " is not modified in this ModificationResult");
}
StringWriter writer = new StringWriter();
commit(fileObject, diffs.get(fileObject), writer);
return writer.toString();
}
public static class Difference {
Kind kind;
PositionRef startPos;
PositionRef endPos;
String oldText;
String newText;
String description;
private boolean excluded;
private boolean ignoreGuards = false;
public Difference(Kind kind, PositionRef startPos, PositionRef endPos, String oldText, String newText, String description) {
this.kind = kind;
this.startPos = startPos;
this.endPos = endPos;
this.oldText = oldText;
this.newText = newText;
this.description = description;
this.excluded = false;
}
public Difference(Kind kind, PositionRef startPos, PositionRef endPos, String oldText, String newText) {
this(kind, startPos, endPos, oldText, newText, null);
}
public Kind getKind() {
return kind;
}
public PositionRef getStartPosition() {
return startPos;
}
public PositionRef getEndPosition() {
return endPos;
}
public String getOldText() {
return oldText;
}
public String getNewText() {
return newText;
}
public boolean isExcluded() {
return excluded;
}
public void exclude(boolean b) {
excluded = b;
}
/**
* Gets flag if it is possible to write to guarded sections.
* @return {@code true} in case the difference may be written even into
* guarded sections.
* @see #guards(boolean)
* @since 0.33
*/
public boolean isCommitToGuards() {
return ignoreGuards;
}
/**
* Sets flag if it is possible to write to guarded sections.
* @param b flag if it is possible to write to guarded sections
* @since 0.33
*/
public void setCommitToGuards(boolean b) {
ignoreGuards = b;
}
@Override
public String toString() {
return kind + "<" + startPos.getOffset() + ", " + endPos.getOffset() + ">: " + oldText + " -> " + newText;
}
public String getDescription() {
return description;
}
public static enum Kind {
INSERT,
REMOVE,
CHANGE,
CREATE;
}
} // End of Difference class
public static class CreateFileDifference extends Difference {
private final File file;
public CreateFileDifference(File file, String text) {
super(Kind.CREATE, null, null, null, text, "Create file " + file.getPath());
this.file = file;
}
public final File getFile() {
return file;
}
@Override
public String toString() {
return kind + "Create File: " + file.getName() + "; contents = \"\n" + newText + "\"";
}
} // End of CreateFileDifference class
}
|
package at.tuwien.ict.acona.mq.core.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import at.tuwien.ict.acona.mq.core.agentfunction.AgentFunction;
public class AgentFunctionHandlerImpl implements AgentFunctionHandler {
private static Logger log = LoggerFactory.getLogger(AgentFunctionHandlerImpl.class);
/**
* Map with the name of the cellfunction and the actual instance.
*/
private final Map<String, AgentFunction> cellFunctionsMap = new ConcurrentHashMap<>();
private final List<String> applicationFunctions = new ArrayList<>();
private final List<AgentFunctionHandlerListener> listenerList = new ArrayList<>();
private Cell hostCell;
@Override
public void init(Cell caller) {
this.hostCell = caller;
}
@Override
public synchronized void registerCellFunctionInstance(AgentFunction cellFunctionInstance) throws Exception {
try {
// Get all subscribed addresses
// Add the cellfunction itself
// Check if this name is already registered
if (this.cellFunctionsMap.containsKey(cellFunctionInstance.getFunctionRootAddress())) {
log.warn("Agent {}>Cell function={} is already registered. Cellfunction will be overwritten. Watch for errors.", this.hostCell.getName(), cellFunctionInstance.getFunctionRootAddress());
}
this.cellFunctionsMap.put(cellFunctionInstance.getFunctionRootAddress(), cellFunctionInstance);
// Set init state
if ((this.applicationFunctions.contains(cellFunctionInstance.getFunctionRootAddress()) == false)) {
synchronized (this.applicationFunctions) {
this.applicationFunctions.add(cellFunctionInstance.getFunctionRootAddress());
}
// Notify all listeners that a new function has been registered
synchronized (this.listenerList) {
this.listenerList.forEach(l -> {
if (l.getListenerFunction().equals(cellFunctionInstance.getFunctionRootAddress()) == false) {
l.notifyAddedFunction(cellFunctionInstance.getFunctionRootAddress());
}
});
}
}
} catch (Exception e) {
log.error("Cannot register cell function " + cellFunctionInstance + ".", e);
throw new Exception(e.getMessage());
}
}
@Override
public synchronized void deregisterActivatorInstance(String activatorInstance) throws Exception {
// Deregister activator -> deregister all datapoints in the datastorage
// itself
try {
if (this.cellFunctionsMap.containsKey(activatorInstance) == false) {
log.warn("Agent {}, function {}>WARNING: Function is not present in the function list and cannot be deregistered", this.hostCell.getName(), activatorInstance);
}
// Remove the cellfunction itself
this.cellFunctionsMap.remove(activatorInstance);
// if (cellFunctionInstance.getFunctionConfig().getRegisterState().getAsBoolean()==true) {
if (this.applicationFunctions.contains(activatorInstance)) {
synchronized (this.applicationFunctions) {
this.applicationFunctions.remove(activatorInstance);
}
synchronized (this.listenerList) {
this.listenerList.forEach(l -> {
if (l.getListenerFunction().equals(activatorInstance) == false) {
l.notifyRemovedFunction(activatorInstance);
}
});
}
}
// }
// Notify all listeners that an existing function has been unregistered
} catch (Exception e) {
log.error("Cannot deregister cell function " + activatorInstance, e);
throw new Exception(e.getMessage());
}
}
@Override
public AgentFunction getCellFunction(String functionName) {
return this.cellFunctionsMap.get(functionName);
}
@Override
public List<String> getCellFunctionNames() {
return Collections.unmodifiableList(new ArrayList<>(this.cellFunctionsMap.keySet()));
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Registered functions=");
builder.append(this.cellFunctionsMap.keySet());
return builder.toString();
}
@Override
public List<String> registerLister(AgentFunctionHandlerListener listener) {
synchronized (this.listenerList) {
this.listenerList.add(listener);
}
log.debug("A listener was registered for the cell functions");
return Collections.unmodifiableList(applicationFunctions);
}
@Override
public void unregisterListener(AgentFunctionHandlerListener listener) {
synchronized (this.listenerList) {
this.listenerList.remove(listener);
}
log.debug("A listener was unregistered");
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1p4beta1/text_annotation.proto
package com.google.cloud.vision.v1p4beta1;
/**
*
*
* <pre>
* Logical element on the page.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p4beta1.Block}
*/
public final class Block extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1p4beta1.Block)
BlockOrBuilder {
private static final long serialVersionUID = 0L;
// Use Block.newBuilder() to construct.
private Block(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Block() {
paragraphs_ = java.util.Collections.emptyList();
blockType_ = 0;
confidence_ = 0F;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private Block(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.Builder subBuilder =
null;
if (property_ != null) {
subBuilder = property_.toBuilder();
}
property_ =
input.readMessage(
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.parser(),
extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(property_);
property_ = subBuilder.buildPartial();
}
break;
}
case 18:
{
com.google.cloud.vision.v1p4beta1.BoundingPoly.Builder subBuilder = null;
if (boundingBox_ != null) {
subBuilder = boundingBox_.toBuilder();
}
boundingBox_ =
input.readMessage(
com.google.cloud.vision.v1p4beta1.BoundingPoly.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(boundingBox_);
boundingBox_ = subBuilder.buildPartial();
}
break;
}
case 26:
{
if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
paragraphs_ =
new java.util.ArrayList<com.google.cloud.vision.v1p4beta1.Paragraph>();
mutable_bitField0_ |= 0x00000004;
}
paragraphs_.add(
input.readMessage(
com.google.cloud.vision.v1p4beta1.Paragraph.parser(), extensionRegistry));
break;
}
case 32:
{
int rawValue = input.readEnum();
blockType_ = rawValue;
break;
}
case 45:
{
confidence_ = input.readFloat();
break;
}
default:
{
if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
paragraphs_ = java.util.Collections.unmodifiableList(paragraphs_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p4beta1.TextAnnotationProto
.internal_static_google_cloud_vision_v1p4beta1_Block_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p4beta1.TextAnnotationProto
.internal_static_google_cloud_vision_v1p4beta1_Block_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p4beta1.Block.class,
com.google.cloud.vision.v1p4beta1.Block.Builder.class);
}
/**
*
*
* <pre>
* Type of a block (text, image etc) as identified by OCR.
* </pre>
*
* Protobuf enum {@code google.cloud.vision.v1p4beta1.Block.BlockType}
*/
public enum BlockType implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* Unknown block type.
* </pre>
*
* <code>UNKNOWN = 0;</code>
*/
UNKNOWN(0),
/**
*
*
* <pre>
* Regular text block.
* </pre>
*
* <code>TEXT = 1;</code>
*/
TEXT(1),
/**
*
*
* <pre>
* Table block.
* </pre>
*
* <code>TABLE = 2;</code>
*/
TABLE(2),
/**
*
*
* <pre>
* Image block.
* </pre>
*
* <code>PICTURE = 3;</code>
*/
PICTURE(3),
/**
*
*
* <pre>
* Horizontal/vertical line box.
* </pre>
*
* <code>RULER = 4;</code>
*/
RULER(4),
/**
*
*
* <pre>
* Barcode block.
* </pre>
*
* <code>BARCODE = 5;</code>
*/
BARCODE(5),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* Unknown block type.
* </pre>
*
* <code>UNKNOWN = 0;</code>
*/
public static final int UNKNOWN_VALUE = 0;
/**
*
*
* <pre>
* Regular text block.
* </pre>
*
* <code>TEXT = 1;</code>
*/
public static final int TEXT_VALUE = 1;
/**
*
*
* <pre>
* Table block.
* </pre>
*
* <code>TABLE = 2;</code>
*/
public static final int TABLE_VALUE = 2;
/**
*
*
* <pre>
* Image block.
* </pre>
*
* <code>PICTURE = 3;</code>
*/
public static final int PICTURE_VALUE = 3;
/**
*
*
* <pre>
* Horizontal/vertical line box.
* </pre>
*
* <code>RULER = 4;</code>
*/
public static final int RULER_VALUE = 4;
/**
*
*
* <pre>
* Barcode block.
* </pre>
*
* <code>BARCODE = 5;</code>
*/
public static final int BARCODE_VALUE = 5;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/** @deprecated Use {@link #forNumber(int)} instead. */
@java.lang.Deprecated
public static BlockType valueOf(int value) {
return forNumber(value);
}
public static BlockType forNumber(int value) {
switch (value) {
case 0:
return UNKNOWN;
case 1:
return TEXT;
case 2:
return TABLE;
case 3:
return PICTURE;
case 4:
return RULER;
case 5:
return BARCODE;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<BlockType> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<BlockType> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<BlockType>() {
public BlockType findValueByNumber(int number) {
return BlockType.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.cloud.vision.v1p4beta1.Block.getDescriptor().getEnumTypes().get(0);
}
private static final BlockType[] VALUES = values();
public static BlockType valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private BlockType(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.vision.v1p4beta1.Block.BlockType)
}
private int bitField0_;
public static final int PROPERTY_FIELD_NUMBER = 1;
private com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property_;
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public boolean hasProperty() {
return property_ != null;
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty getProperty() {
return property_ == null
? com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.getDefaultInstance()
: property_;
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.TextAnnotation.TextPropertyOrBuilder
getPropertyOrBuilder() {
return getProperty();
}
public static final int BOUNDING_BOX_FIELD_NUMBER = 2;
private com.google.cloud.vision.v1p4beta1.BoundingPoly boundingBox_;
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public boolean hasBoundingBox() {
return boundingBox_ != null;
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public com.google.cloud.vision.v1p4beta1.BoundingPoly getBoundingBox() {
return boundingBox_ == null
? com.google.cloud.vision.v1p4beta1.BoundingPoly.getDefaultInstance()
: boundingBox_;
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public com.google.cloud.vision.v1p4beta1.BoundingPolyOrBuilder getBoundingBoxOrBuilder() {
return getBoundingBox();
}
public static final int PARAGRAPHS_FIELD_NUMBER = 3;
private java.util.List<com.google.cloud.vision.v1p4beta1.Paragraph> paragraphs_;
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public java.util.List<com.google.cloud.vision.v1p4beta1.Paragraph> getParagraphsList() {
return paragraphs_;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public java.util.List<? extends com.google.cloud.vision.v1p4beta1.ParagraphOrBuilder>
getParagraphsOrBuilderList() {
return paragraphs_;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public int getParagraphsCount() {
return paragraphs_.size();
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public com.google.cloud.vision.v1p4beta1.Paragraph getParagraphs(int index) {
return paragraphs_.get(index);
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public com.google.cloud.vision.v1p4beta1.ParagraphOrBuilder getParagraphsOrBuilder(int index) {
return paragraphs_.get(index);
}
public static final int BLOCK_TYPE_FIELD_NUMBER = 4;
private int blockType_;
/**
*
*
* <pre>
* Detected block type (text, image etc) for this block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.Block.BlockType block_type = 4;</code>
*/
public int getBlockTypeValue() {
return blockType_;
}
/**
*
*
* <pre>
* Detected block type (text, image etc) for this block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.Block.BlockType block_type = 4;</code>
*/
public com.google.cloud.vision.v1p4beta1.Block.BlockType getBlockType() {
@SuppressWarnings("deprecation")
com.google.cloud.vision.v1p4beta1.Block.BlockType result =
com.google.cloud.vision.v1p4beta1.Block.BlockType.valueOf(blockType_);
return result == null ? com.google.cloud.vision.v1p4beta1.Block.BlockType.UNRECOGNIZED : result;
}
public static final int CONFIDENCE_FIELD_NUMBER = 5;
private float confidence_;
/**
*
*
* <pre>
* Confidence of the OCR results on the block. Range [0, 1].
* </pre>
*
* <code>float confidence = 5;</code>
*/
public float getConfidence() {
return confidence_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (property_ != null) {
output.writeMessage(1, getProperty());
}
if (boundingBox_ != null) {
output.writeMessage(2, getBoundingBox());
}
for (int i = 0; i < paragraphs_.size(); i++) {
output.writeMessage(3, paragraphs_.get(i));
}
if (blockType_ != com.google.cloud.vision.v1p4beta1.Block.BlockType.UNKNOWN.getNumber()) {
output.writeEnum(4, blockType_);
}
if (confidence_ != 0F) {
output.writeFloat(5, confidence_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (property_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getProperty());
}
if (boundingBox_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getBoundingBox());
}
for (int i = 0; i < paragraphs_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, paragraphs_.get(i));
}
if (blockType_ != com.google.cloud.vision.v1p4beta1.Block.BlockType.UNKNOWN.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(4, blockType_);
}
if (confidence_ != 0F) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(5, confidence_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.vision.v1p4beta1.Block)) {
return super.equals(obj);
}
com.google.cloud.vision.v1p4beta1.Block other = (com.google.cloud.vision.v1p4beta1.Block) obj;
boolean result = true;
result = result && (hasProperty() == other.hasProperty());
if (hasProperty()) {
result = result && getProperty().equals(other.getProperty());
}
result = result && (hasBoundingBox() == other.hasBoundingBox());
if (hasBoundingBox()) {
result = result && getBoundingBox().equals(other.getBoundingBox());
}
result = result && getParagraphsList().equals(other.getParagraphsList());
result = result && blockType_ == other.blockType_;
result =
result
&& (java.lang.Float.floatToIntBits(getConfidence())
== java.lang.Float.floatToIntBits(other.getConfidence()));
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasProperty()) {
hash = (37 * hash) + PROPERTY_FIELD_NUMBER;
hash = (53 * hash) + getProperty().hashCode();
}
if (hasBoundingBox()) {
hash = (37 * hash) + BOUNDING_BOX_FIELD_NUMBER;
hash = (53 * hash) + getBoundingBox().hashCode();
}
if (getParagraphsCount() > 0) {
hash = (37 * hash) + PARAGRAPHS_FIELD_NUMBER;
hash = (53 * hash) + getParagraphsList().hashCode();
}
hash = (37 * hash) + BLOCK_TYPE_FIELD_NUMBER;
hash = (53 * hash) + blockType_;
hash = (37 * hash) + CONFIDENCE_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getConfidence());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.Block parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.Block parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.Block parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.vision.v1p4beta1.Block prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Logical element on the page.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p4beta1.Block}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p4beta1.Block)
com.google.cloud.vision.v1p4beta1.BlockOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p4beta1.TextAnnotationProto
.internal_static_google_cloud_vision_v1p4beta1_Block_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p4beta1.TextAnnotationProto
.internal_static_google_cloud_vision_v1p4beta1_Block_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p4beta1.Block.class,
com.google.cloud.vision.v1p4beta1.Block.Builder.class);
}
// Construct using com.google.cloud.vision.v1p4beta1.Block.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getParagraphsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (propertyBuilder_ == null) {
property_ = null;
} else {
property_ = null;
propertyBuilder_ = null;
}
if (boundingBoxBuilder_ == null) {
boundingBox_ = null;
} else {
boundingBox_ = null;
boundingBoxBuilder_ = null;
}
if (paragraphsBuilder_ == null) {
paragraphs_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
} else {
paragraphsBuilder_.clear();
}
blockType_ = 0;
confidence_ = 0F;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1p4beta1.TextAnnotationProto
.internal_static_google_cloud_vision_v1p4beta1_Block_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.Block getDefaultInstanceForType() {
return com.google.cloud.vision.v1p4beta1.Block.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.Block build() {
com.google.cloud.vision.v1p4beta1.Block result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.Block buildPartial() {
com.google.cloud.vision.v1p4beta1.Block result =
new com.google.cloud.vision.v1p4beta1.Block(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (propertyBuilder_ == null) {
result.property_ = property_;
} else {
result.property_ = propertyBuilder_.build();
}
if (boundingBoxBuilder_ == null) {
result.boundingBox_ = boundingBox_;
} else {
result.boundingBox_ = boundingBoxBuilder_.build();
}
if (paragraphsBuilder_ == null) {
if (((bitField0_ & 0x00000004) == 0x00000004)) {
paragraphs_ = java.util.Collections.unmodifiableList(paragraphs_);
bitField0_ = (bitField0_ & ~0x00000004);
}
result.paragraphs_ = paragraphs_;
} else {
result.paragraphs_ = paragraphsBuilder_.build();
}
result.blockType_ = blockType_;
result.confidence_ = confidence_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return (Builder) super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.vision.v1p4beta1.Block) {
return mergeFrom((com.google.cloud.vision.v1p4beta1.Block) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1p4beta1.Block other) {
if (other == com.google.cloud.vision.v1p4beta1.Block.getDefaultInstance()) return this;
if (other.hasProperty()) {
mergeProperty(other.getProperty());
}
if (other.hasBoundingBox()) {
mergeBoundingBox(other.getBoundingBox());
}
if (paragraphsBuilder_ == null) {
if (!other.paragraphs_.isEmpty()) {
if (paragraphs_.isEmpty()) {
paragraphs_ = other.paragraphs_;
bitField0_ = (bitField0_ & ~0x00000004);
} else {
ensureParagraphsIsMutable();
paragraphs_.addAll(other.paragraphs_);
}
onChanged();
}
} else {
if (!other.paragraphs_.isEmpty()) {
if (paragraphsBuilder_.isEmpty()) {
paragraphsBuilder_.dispose();
paragraphsBuilder_ = null;
paragraphs_ = other.paragraphs_;
bitField0_ = (bitField0_ & ~0x00000004);
paragraphsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getParagraphsFieldBuilder()
: null;
} else {
paragraphsBuilder_.addAllMessages(other.paragraphs_);
}
}
}
if (other.blockType_ != 0) {
setBlockTypeValue(other.getBlockTypeValue());
}
if (other.getConfidence() != 0F) {
setConfidence(other.getConfidence());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.vision.v1p4beta1.Block parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.vision.v1p4beta1.Block) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty,
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.Builder,
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextPropertyOrBuilder>
propertyBuilder_;
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public boolean hasProperty() {
return propertyBuilder_ != null || property_ != null;
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty getProperty() {
if (propertyBuilder_ == null) {
return property_ == null
? com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.getDefaultInstance()
: property_;
} else {
return propertyBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public Builder setProperty(
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty value) {
if (propertyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
property_ = value;
onChanged();
} else {
propertyBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public Builder setProperty(
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.Builder builderForValue) {
if (propertyBuilder_ == null) {
property_ = builderForValue.build();
onChanged();
} else {
propertyBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public Builder mergeProperty(
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty value) {
if (propertyBuilder_ == null) {
if (property_ != null) {
property_ =
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.newBuilder(property_)
.mergeFrom(value)
.buildPartial();
} else {
property_ = value;
}
onChanged();
} else {
propertyBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public Builder clearProperty() {
if (propertyBuilder_ == null) {
property_ = null;
onChanged();
} else {
property_ = null;
propertyBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.Builder
getPropertyBuilder() {
onChanged();
return getPropertyFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.TextAnnotation.TextPropertyOrBuilder
getPropertyOrBuilder() {
if (propertyBuilder_ != null) {
return propertyBuilder_.getMessageOrBuilder();
} else {
return property_ == null
? com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.getDefaultInstance()
: property_;
}
}
/**
*
*
* <pre>
* Additional information detected for the block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty property = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty,
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.Builder,
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextPropertyOrBuilder>
getPropertyFieldBuilder() {
if (propertyBuilder_ == null) {
propertyBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty,
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.Builder,
com.google.cloud.vision.v1p4beta1.TextAnnotation.TextPropertyOrBuilder>(
getProperty(), getParentForChildren(), isClean());
property_ = null;
}
return propertyBuilder_;
}
private com.google.cloud.vision.v1p4beta1.BoundingPoly boundingBox_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.BoundingPoly,
com.google.cloud.vision.v1p4beta1.BoundingPoly.Builder,
com.google.cloud.vision.v1p4beta1.BoundingPolyOrBuilder>
boundingBoxBuilder_;
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public boolean hasBoundingBox() {
return boundingBoxBuilder_ != null || boundingBox_ != null;
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public com.google.cloud.vision.v1p4beta1.BoundingPoly getBoundingBox() {
if (boundingBoxBuilder_ == null) {
return boundingBox_ == null
? com.google.cloud.vision.v1p4beta1.BoundingPoly.getDefaultInstance()
: boundingBox_;
} else {
return boundingBoxBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public Builder setBoundingBox(com.google.cloud.vision.v1p4beta1.BoundingPoly value) {
if (boundingBoxBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
boundingBox_ = value;
onChanged();
} else {
boundingBoxBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public Builder setBoundingBox(
com.google.cloud.vision.v1p4beta1.BoundingPoly.Builder builderForValue) {
if (boundingBoxBuilder_ == null) {
boundingBox_ = builderForValue.build();
onChanged();
} else {
boundingBoxBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public Builder mergeBoundingBox(com.google.cloud.vision.v1p4beta1.BoundingPoly value) {
if (boundingBoxBuilder_ == null) {
if (boundingBox_ != null) {
boundingBox_ =
com.google.cloud.vision.v1p4beta1.BoundingPoly.newBuilder(boundingBox_)
.mergeFrom(value)
.buildPartial();
} else {
boundingBox_ = value;
}
onChanged();
} else {
boundingBoxBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public Builder clearBoundingBox() {
if (boundingBoxBuilder_ == null) {
boundingBox_ = null;
onChanged();
} else {
boundingBox_ = null;
boundingBoxBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public com.google.cloud.vision.v1p4beta1.BoundingPoly.Builder getBoundingBoxBuilder() {
onChanged();
return getBoundingBoxFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
public com.google.cloud.vision.v1p4beta1.BoundingPolyOrBuilder getBoundingBoxOrBuilder() {
if (boundingBoxBuilder_ != null) {
return boundingBoxBuilder_.getMessageOrBuilder();
} else {
return boundingBox_ == null
? com.google.cloud.vision.v1p4beta1.BoundingPoly.getDefaultInstance()
: boundingBox_;
}
}
/**
*
*
* <pre>
* The bounding box for the block.
* The vertices are in the order of top-left, top-right, bottom-right,
* bottom-left. When a rotation of the bounding box is detected the rotation
* is represented as around the top-left corner as defined when the text is
* read in the 'natural' orientation.
* For example:
* * when the text is horizontal it might look like:
* 0----1
* | |
* 3----2
* * when it's rotated 180 degrees around the top-left corner it becomes:
* 2----3
* | |
* 1----0
* and the vertex order will still be (0, 1, 2, 3).
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.BoundingPoly bounding_box = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.BoundingPoly,
com.google.cloud.vision.v1p4beta1.BoundingPoly.Builder,
com.google.cloud.vision.v1p4beta1.BoundingPolyOrBuilder>
getBoundingBoxFieldBuilder() {
if (boundingBoxBuilder_ == null) {
boundingBoxBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.BoundingPoly,
com.google.cloud.vision.v1p4beta1.BoundingPoly.Builder,
com.google.cloud.vision.v1p4beta1.BoundingPolyOrBuilder>(
getBoundingBox(), getParentForChildren(), isClean());
boundingBox_ = null;
}
return boundingBoxBuilder_;
}
private java.util.List<com.google.cloud.vision.v1p4beta1.Paragraph> paragraphs_ =
java.util.Collections.emptyList();
private void ensureParagraphsIsMutable() {
if (!((bitField0_ & 0x00000004) == 0x00000004)) {
paragraphs_ =
new java.util.ArrayList<com.google.cloud.vision.v1p4beta1.Paragraph>(paragraphs_);
bitField0_ |= 0x00000004;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.Paragraph,
com.google.cloud.vision.v1p4beta1.Paragraph.Builder,
com.google.cloud.vision.v1p4beta1.ParagraphOrBuilder>
paragraphsBuilder_;
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public java.util.List<com.google.cloud.vision.v1p4beta1.Paragraph> getParagraphsList() {
if (paragraphsBuilder_ == null) {
return java.util.Collections.unmodifiableList(paragraphs_);
} else {
return paragraphsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public int getParagraphsCount() {
if (paragraphsBuilder_ == null) {
return paragraphs_.size();
} else {
return paragraphsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public com.google.cloud.vision.v1p4beta1.Paragraph getParagraphs(int index) {
if (paragraphsBuilder_ == null) {
return paragraphs_.get(index);
} else {
return paragraphsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder setParagraphs(int index, com.google.cloud.vision.v1p4beta1.Paragraph value) {
if (paragraphsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureParagraphsIsMutable();
paragraphs_.set(index, value);
onChanged();
} else {
paragraphsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder setParagraphs(
int index, com.google.cloud.vision.v1p4beta1.Paragraph.Builder builderForValue) {
if (paragraphsBuilder_ == null) {
ensureParagraphsIsMutable();
paragraphs_.set(index, builderForValue.build());
onChanged();
} else {
paragraphsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder addParagraphs(com.google.cloud.vision.v1p4beta1.Paragraph value) {
if (paragraphsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureParagraphsIsMutable();
paragraphs_.add(value);
onChanged();
} else {
paragraphsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder addParagraphs(int index, com.google.cloud.vision.v1p4beta1.Paragraph value) {
if (paragraphsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureParagraphsIsMutable();
paragraphs_.add(index, value);
onChanged();
} else {
paragraphsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder addParagraphs(
com.google.cloud.vision.v1p4beta1.Paragraph.Builder builderForValue) {
if (paragraphsBuilder_ == null) {
ensureParagraphsIsMutable();
paragraphs_.add(builderForValue.build());
onChanged();
} else {
paragraphsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder addParagraphs(
int index, com.google.cloud.vision.v1p4beta1.Paragraph.Builder builderForValue) {
if (paragraphsBuilder_ == null) {
ensureParagraphsIsMutable();
paragraphs_.add(index, builderForValue.build());
onChanged();
} else {
paragraphsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder addAllParagraphs(
java.lang.Iterable<? extends com.google.cloud.vision.v1p4beta1.Paragraph> values) {
if (paragraphsBuilder_ == null) {
ensureParagraphsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, paragraphs_);
onChanged();
} else {
paragraphsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder clearParagraphs() {
if (paragraphsBuilder_ == null) {
paragraphs_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
} else {
paragraphsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public Builder removeParagraphs(int index) {
if (paragraphsBuilder_ == null) {
ensureParagraphsIsMutable();
paragraphs_.remove(index);
onChanged();
} else {
paragraphsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public com.google.cloud.vision.v1p4beta1.Paragraph.Builder getParagraphsBuilder(int index) {
return getParagraphsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public com.google.cloud.vision.v1p4beta1.ParagraphOrBuilder getParagraphsOrBuilder(int index) {
if (paragraphsBuilder_ == null) {
return paragraphs_.get(index);
} else {
return paragraphsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public java.util.List<? extends com.google.cloud.vision.v1p4beta1.ParagraphOrBuilder>
getParagraphsOrBuilderList() {
if (paragraphsBuilder_ != null) {
return paragraphsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(paragraphs_);
}
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public com.google.cloud.vision.v1p4beta1.Paragraph.Builder addParagraphsBuilder() {
return getParagraphsFieldBuilder()
.addBuilder(com.google.cloud.vision.v1p4beta1.Paragraph.getDefaultInstance());
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public com.google.cloud.vision.v1p4beta1.Paragraph.Builder addParagraphsBuilder(int index) {
return getParagraphsFieldBuilder()
.addBuilder(index, com.google.cloud.vision.v1p4beta1.Paragraph.getDefaultInstance());
}
/**
*
*
* <pre>
* List of paragraphs in this block (if this blocks is of type text).
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Paragraph paragraphs = 3;</code>
*/
public java.util.List<com.google.cloud.vision.v1p4beta1.Paragraph.Builder>
getParagraphsBuilderList() {
return getParagraphsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.Paragraph,
com.google.cloud.vision.v1p4beta1.Paragraph.Builder,
com.google.cloud.vision.v1p4beta1.ParagraphOrBuilder>
getParagraphsFieldBuilder() {
if (paragraphsBuilder_ == null) {
paragraphsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.Paragraph,
com.google.cloud.vision.v1p4beta1.Paragraph.Builder,
com.google.cloud.vision.v1p4beta1.ParagraphOrBuilder>(
paragraphs_,
((bitField0_ & 0x00000004) == 0x00000004),
getParentForChildren(),
isClean());
paragraphs_ = null;
}
return paragraphsBuilder_;
}
private int blockType_ = 0;
/**
*
*
* <pre>
* Detected block type (text, image etc) for this block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.Block.BlockType block_type = 4;</code>
*/
public int getBlockTypeValue() {
return blockType_;
}
/**
*
*
* <pre>
* Detected block type (text, image etc) for this block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.Block.BlockType block_type = 4;</code>
*/
public Builder setBlockTypeValue(int value) {
blockType_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Detected block type (text, image etc) for this block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.Block.BlockType block_type = 4;</code>
*/
public com.google.cloud.vision.v1p4beta1.Block.BlockType getBlockType() {
@SuppressWarnings("deprecation")
com.google.cloud.vision.v1p4beta1.Block.BlockType result =
com.google.cloud.vision.v1p4beta1.Block.BlockType.valueOf(blockType_);
return result == null
? com.google.cloud.vision.v1p4beta1.Block.BlockType.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Detected block type (text, image etc) for this block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.Block.BlockType block_type = 4;</code>
*/
public Builder setBlockType(com.google.cloud.vision.v1p4beta1.Block.BlockType value) {
if (value == null) {
throw new NullPointerException();
}
blockType_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Detected block type (text, image etc) for this block.
* </pre>
*
* <code>.google.cloud.vision.v1p4beta1.Block.BlockType block_type = 4;</code>
*/
public Builder clearBlockType() {
blockType_ = 0;
onChanged();
return this;
}
private float confidence_;
/**
*
*
* <pre>
* Confidence of the OCR results on the block. Range [0, 1].
* </pre>
*
* <code>float confidence = 5;</code>
*/
public float getConfidence() {
return confidence_;
}
/**
*
*
* <pre>
* Confidence of the OCR results on the block. Range [0, 1].
* </pre>
*
* <code>float confidence = 5;</code>
*/
public Builder setConfidence(float value) {
confidence_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Confidence of the OCR results on the block. Range [0, 1].
* </pre>
*
* <code>float confidence = 5;</code>
*/
public Builder clearConfidence() {
confidence_ = 0F;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.vision.v1p4beta1.Block)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Block)
private static final com.google.cloud.vision.v1p4beta1.Block DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1p4beta1.Block();
}
public static com.google.cloud.vision.v1p4beta1.Block getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Block> PARSER =
new com.google.protobuf.AbstractParser<Block>() {
@java.lang.Override
public Block parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Block(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Block> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Block> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.Block getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
package cc.wangcl.core.entity;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.io.Serializable;
import java.util.List;
/**
* DataTables插件的分页查询结果对象。
*
* @author wangcl
*/
public class DataTablesPagingResult<T> implements Serializable {
private static final long serialVersionUID = 5300175861422550662L;
private Integer draw;
private Long recordsTotal;
private Long recordsFiltered;
private List<T> data;
public Integer getDraw() {
return draw;
}
public void setDraw(Integer draw) {
this.draw = draw;
}
public Long getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(Long recordsTotal) {
this.recordsTotal = recordsTotal;
}
public Long getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(Long recordsFiltered) {
this.recordsFiltered = recordsFiltered;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
package org.snomed.snowstorm.core.data.repositories;
import org.snomed.snowstorm.core.data.domain.review.BranchReview;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
import java.util.Date;
public interface BranchReviewRepository extends ElasticsearchCrudRepository<BranchReview, String> {
@Query("{\"bool\":{\"must\":[ {\"term\":{\"source.path\":\"?0\"}}, {\"term\":{\"source.baseTimestamp\":\"?1\"}}, {\"term\":{\"source.headTimestamp\":\"?2\"}}, " +
"{\"term\":{\"target.path\":\"?3\"}}, {\"term\":{\"target.baseTimestamp\":\"?4\"}}, {\"term\":{\"target.headTimestamp\":\"?5\"}} ]}}")
BranchReview findBySourceAndTargetPathsAndStates(String sourcePath, long sourceBase, long sourceHead, String targetPath, long targetBase, long targetHead);
}
|
/*
* 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 utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javafx.scene.control.Alert;
public class SmsInscri {
public String sendSms(int s) {
try {
// Construct data
String apiKey = "apikey=" + "QadtuUxVEd8-oeF6mEE6u4fUTkN0T2zRos9aN9Uzer";
String message = "&message=" + "Vous êtes inscrit dans l'application souk el medina!";
String sender = "&sender=" + "khouloud";
String numbers = "&numbers=" + "216"+s;
// Send data
HttpURLConnection conn = (HttpURLConnection) new URL("https://api.txtlocal.com/send/?").openConnection();
String data = apiKey + numbers + message + sender;
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
conn.getOutputStream().write(data.getBytes("UTF-8"));
final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
//stringBuffer.append(line);
Alert alert = new InputValidation().getAlert("Succes", "Vous êtes inscrit !");
alert.showAndWait();
}
rd.close();
//return stringBuffer.toString();
} catch (Exception e) {
System.out.println("Error SMS "+e);
}
return null;
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int_getParameter_Servlet_postinc_53c.java
Label Definition File: CWE190_Integer_Overflow__int.label.xml
Template File: sources-sinks-53c.tmpl.java
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: getParameter_Servlet Read data from a querystring using getParameter()
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: increment
* GoodSink: Ensure there will not be an overflow before incrementing data
* BadSink : Increment data, which can cause an overflow
* 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.CWE190_Integer_Overflow.s06;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE190_Integer_Overflow__int_getParameter_Servlet_postinc_53c
{
public void badSink(int data , HttpServletRequest request, HttpServletResponse response) throws Throwable
{
(new CWE190_Integer_Overflow__int_getParameter_Servlet_postinc_53d()).badSink(data , request, response);
}
/* goodG2B() - use goodsource and badsink */
public void goodG2BSink(int data , HttpServletRequest request, HttpServletResponse response) throws Throwable
{
(new CWE190_Integer_Overflow__int_getParameter_Servlet_postinc_53d()).goodG2BSink(data , request, response);
}
/* goodB2G() - use badsource and goodsink */
public void goodB2GSink(int data , HttpServletRequest request, HttpServletResponse response) throws Throwable
{
(new CWE190_Integer_Overflow__int_getParameter_Servlet_postinc_53d()).goodB2GSink(data , request, response);
}
}
|
/*
* Copyright 2021 Ian Jones. 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 api.equinix.javasdk.customerportal.client.implementation;
import api.equinix.javasdk.core.client.Config;
import api.equinix.javasdk.core.client.EquinixClient;
import api.equinix.javasdk.customerportal.client.CustomerPortalConfig;
import api.equinix.javasdk.customerportal.client.internal.implementation.InvoiceDetailClientImpl;
import api.equinix.javasdk.customerportal.client.internal.implementation.InvoiceSummaryClientImpl;
import api.equinix.javasdk.customerportal.client.internal.implementation.ResellerClientImpl;
import api.equinix.javasdk.customerportal.client.internal.implementation.ResellerCustomerClientImpl;
import lombok.Getter;
@Getter
public class CustomerPortalConfigImpl extends Config implements CustomerPortalConfig {
private final InvoiceSummaryClientImpl invoiceSummaryClient;
private final InvoiceDetailClientImpl invoiceDetailClient;
private final ResellerClientImpl resellerClient;
private final ResellerCustomerClientImpl resellerCustomerClient;
public CustomerPortalConfigImpl(EquinixClient equinixClient) {
super(equinixClient);
this.invoiceSummaryClient = new InvoiceSummaryClientImpl(this);
this.invoiceDetailClient = new InvoiceDetailClientImpl(this);
this.resellerClient = new ResellerClientImpl(this);
this.resellerCustomerClient = new ResellerCustomerClientImpl(this);
}
}
|
/*
* 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.bcel.generic;
import org.apache.bcel.Const;
import org.apache.bcel.ExceptionConst;
/**
* Super class for the xRETURN family of instructions.
*
*/
public abstract class ReturnInstruction extends Instruction implements ExceptionThrower,
TypedInstruction, StackConsumer {
/**
* Empty constructor needed for Instruction.readInstruction.
* Not to be used otherwise.
*/
ReturnInstruction() {
}
/**
* @param opcode of instruction
*/
protected ReturnInstruction(final short opcode) {
super(opcode, (short) 1);
}
public Type getType() {
final short _opcode = super.getOpcode();
switch (_opcode) {
case Const.IRETURN:
return Type.INT;
case Const.LRETURN:
return Type.LONG;
case Const.FRETURN:
return Type.FLOAT;
case Const.DRETURN:
return Type.DOUBLE;
case Const.ARETURN:
return Type.OBJECT;
case Const.RETURN:
return Type.VOID;
default: // Never reached
throw new ClassGenException("Unknown type " + _opcode);
}
}
@Override
public Class<?>[] getExceptions() {
return new Class[] {
ExceptionConst.ILLEGAL_MONITOR_STATE
};
}
/** @return type associated with the instruction
*/
@Override
public Type getType( final ConstantPoolGen cp ) {
return getType();
}
}
|
package com.example.thy.linechart.Http;
/**
* Created by thy on 18/5/17.
*/
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
|
/*
* Copyright (c) 2016 lhyz 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 io.lhyz.android.zhihu.daily.util;
/**
* hello,android
* Created by lhyz on 2016/8/18.
*/
public class TagHelper {
public static String from(Class<?> clazz) {
return clazz.getName();
}
}
|
package com.chuongvd.awesomehomepage.common;
import android.app.Activity;
import android.arch.lifecycle.AndroidViewModel;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public abstract class BaseDataBindingActivity<B extends ViewDataBinding, V extends AndroidViewModel>
extends AppCompatActivity {
protected B mBinding;
protected V mViewModel;
protected abstract int getContentViewLayoutId();
protected Context context() {
return this;
}
protected abstract void initListeners();
protected abstract void initData();
protected abstract void subscribeToViewModel();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, getContentViewLayoutId());
initListeners();
initData();
subscribeToViewModel();
}
@Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
// all touch events close the keyboard before they are processed except EditText instances.
// if focus is an EditText we need to check, if the touchevent was inside the focus editTexts
final View currentFocus = getCurrentFocus();
if (!(currentFocus instanceof EditText) || !isTouchInsideView(ev, currentFocus)) {
hideKeyboard(this);
}
return super.dispatchTouchEvent(ev);
}
/**
* determine if the given motionevent is inside the given view.
*
* @param ev the given view
* @param currentFocus the motion event.
* @return if the given motionevent is inside the given view
*/
private boolean isTouchInsideView(final MotionEvent ev, final View currentFocus) {
final int[] loc = new int[2];
currentFocus.getLocationOnScreen(loc);
return ev.getRawX() > loc[0] && ev.getRawY() > loc[1] && ev.getRawX() < (loc[0]
+ currentFocus.getWidth()) && ev.getRawY() < (loc[1] + currentFocus.getHeight());
}
private void hideKeyboard(@NonNull Activity activity) {
View view = activity.getCurrentFocus();
if (view == null) return;
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager == null) return;
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
|
package com.tools.http.server;
import com.tools.core.io.IORuntimeException;
import com.tools.core.lang.Console;
import com.tools.http.server.action.Action;
import com.tools.http.server.action.RootAction;
import com.tools.http.server.handler.ActionHandler;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
/**
* 简易Http服务器,基于{@link HttpServer}
*
* @author looly
* @since 5.2.5
*/
public class SimpleServer {
HttpServer server;
/**
* 构造
*
* @param port 监听端口
*/
public SimpleServer(int port) {
this(new InetSocketAddress(port));
}
/**
* 构造
*
* @param hostname 监听地址
* @param port 监听端口
*/
public SimpleServer(String hostname, int port) {
this(new InetSocketAddress(hostname, port));
}
/**
* 构造
*
* @param address 监听地址
*/
public SimpleServer(InetSocketAddress address) {
try {
this.server = HttpServer.create(address, 0);
} catch (IOException e) {
throw new IORuntimeException(e);
}
}
/**
* 增加请求处理规则
*
* @param path 路径
* @param handler 处理器
* @return this
*/
public SimpleServer addHandler(String path, HttpHandler handler) {
this.server.createContext(path, handler);
return this;
}
/**
* 设置根目录,默认的页面从root目录中读取解析返回
*
* @param root 路径
* @return this
*/
public SimpleServer setRoot(String root) {
return setRoot(new File(root));
}
/**
* 设置根目录,默认的页面从root目录中读取解析返回
*
* @param root 路径
* @return this
*/
public SimpleServer setRoot(File root) {
return addAction("/", new RootAction(root));
}
/**
* 增加请求处理规则
*
* @param path 路径
* @param action 处理器
* @return this
*/
public SimpleServer addAction(String path, Action action) {
return addHandler(path, new ActionHandler(action));
}
/**
* 设置自定义线程池
*
* @param executor {@link Executor}
* @return this
*/
public SimpleServer setExecutor(Executor executor) {
this.server.setExecutor(executor);
return this;
}
/**
* 获得原始HttpServer对象
*
* @return {@link HttpServer}
*/
public HttpServer getRawServer() {
return this.server;
}
/**
* 获取服务器地址信息
*
* @return {@link InetSocketAddress}
*/
public InetSocketAddress getAddress() {
return this.server.getAddress();
}
/**
* 启动Http服务器,启动后会阻塞当前线程
*/
public void start() {
final InetSocketAddress address = getAddress();
Console.log("tools Simple Http Server listen on 【{}:{}】", address.getHostName(), address.getPort());
this.server.start();
}
}
|
/**
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br>
* This file is part of FI-WARE project.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License.
* </p>
* <p>
* You may obtain a copy of the License at:<br>
* <br>
* http://www.apache.org/licenses/LICENSE-2.0
* </p>
* <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.
* </p>
* <p>
* See the License for the specific language governing permissions and limitations under the License.
* </p>
* <p>
* For those usages not covered by the Apache version 2.0 License please contact with opensource@tid.es
* </p>
*/
package com.telefonica.euro_iaas.sdc.util;
public interface Configuration {
public final static String EXECUTE_RECIPES_SCRIPT = "executeRecipesScript";
public final static String UPLOAD_RECIPES_SCRIPT = "/opt/sdc/scripts/uploadRecipes.sh {0}";
public final static String DELETE_RECIPES_SCRIPT = "/opt/sdc/scripts/deleteRecipes.sh {0} {1}t";
public final static String COPY_APP_FILES_FROM_SERVER_TO_NODE = "copyAppFilesFromServerToNode";
final static String DEFAULT_APP_FILES_SOURCE_FOLDER = "defaultAppFilesSourceFolder";
public final static String DEFAULT_APP_FILES_DESTINATION_FOLDER = "defaultAppFilesDestinationFolder";
public final static String DEFAULT_HOST_DOMAIN = "defaultHostDomain";
// //////// RECIPE TEMPLATES ///////////
public final static String INSTALL_PRODUCT_RECIPE_TEMPLATE = "{0}::{1}_install";
public final static String UNINSTALL_PRODUCT_RECIPE_TEMPLATE = "{0}::{1}_uninstall";
public final static String DEPLOYAC_PRODUCT_RECIPE_TEMPLATE = "{0}::{1}_deployAC";
public final static String UNDEPLOYAC_PRODUCT_RECIPE_TEMPLATE = "{0}::{1}_undeployAC";
public final static String BACKUP_PRODUCT_RECIPE_TEMPLATE = "{0}::{1}_backup";
public final static String CONFIGURE_PRODUCT_RECIPE_TEMPLATE = "{0}::{1}_install";
public final static String RESTORE_PRODUCT_RECIPE_TEMPLATE = "{0}::{1}_restore";
public final static String PRODUCT_LIST_TEMPLATE = "{0}-{1}";
public final static String PRODUCT_LIST_SEPARATOR = "_";
public final static String CHEF_SERVER_NODES_PATH = "/nodes{0}";
public final static String CHEF_SERVER_CLIENTS_PATH = "/clients{0}";
public final static String CHEF_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public final static String CHEF_TIME_ZONE = "GMT";
public final static String CHEF_DIRECTORY_COOKBOOK = "/root/chef-repo/cookbooks/";
public final static String CHEF_CLIENT_URL_TEMPLATE = "http://{0}:9990/sdc-client";
// WEBDAV
public final static String WEBDAV_FILE_URL = "{0}/{1}/{2}/{3}/{2}{3}-bin.tar";
public final static String WEBDAV_USERNAME = "root";
public final static String WEBDAV_PASSWD = "temporal";
public final static String WEBDAV_PRODUCT_BASEDIR = "product";
public final static String WEBDAV_APPLICATION_BASEDIR = "application";
public final static String PRODUCT_INSTANCE_BASE_PATH = "/rest/vdc/{4}/productInstance/{0}";
public final static String APPLICATION_INSTANCE_BASE_PATH = "/rest/vdc/{4}/application/{0}";
public final static String TASK_BASE_PATH = "/rest/vdc/{1}/task/{0}";
public final static String CHEF_NODE_BASE_PATH = "/vdc/{1}/node/{0}";
public final static String UNTAR_COMMAND = "tar xvf {0} -C {1}";
long OPENSTACK_SYNCHRONIZATION_POLLING_PERIOD = 84000000;
String VALIDATION_TIME_THRESHOLD = "84000000";
String VERSION_PROPERTY = "v2/";
}
|
/*
* 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.presto.operator;
import com.facebook.presto.common.Page;
import io.airlift.slice.Slices;
import io.airlift.slice.XxHash64;
import org.openjdk.jol.info.ClassLayout;
import java.util.Arrays;
import java.util.List;
import static io.airlift.slice.SizeOf.sizeOf;
import static java.util.Objects.requireNonNull;
public final class ArrayPositionLinks
implements PositionLinks
{
private static final int INSTANCE_SIZE = ClassLayout.parseClass(ArrayPositionLinks.class).instanceSize();
public static class FactoryBuilder
implements PositionLinks.FactoryBuilder
{
private final int[] positionLinks;
private int size;
private FactoryBuilder(int size)
{
positionLinks = new int[size];
Arrays.fill(positionLinks, -1);
}
@Override
public int link(int left, int right)
{
size++;
positionLinks[left] = right;
return left;
}
@Override
public PositionLinks.Factory build()
{
return new PositionLinks.Factory()
{
@Override
public PositionLinks create(List<JoinFilterFunction> searchFunctions)
{
return new ArrayPositionLinks(positionLinks);
}
@Override
public long checksum()
{
return XxHash64.hash(Slices.wrappedIntArray(positionLinks));
}
};
}
@Override
public int size()
{
return size;
}
}
private final int[] positionLinks;
private ArrayPositionLinks(int[] positionLinks)
{
this.positionLinks = requireNonNull(positionLinks, "positionLinks is null");
}
public static FactoryBuilder builder(int size)
{
return new FactoryBuilder(size);
}
@Override
public int start(int position, int probePosition, Page allProbeChannelsPage)
{
return position;
}
@Override
public int next(int position, int probePosition, Page allProbeChannelsPage)
{
return positionLinks[position];
}
@Override
public long getSizeInBytes()
{
return INSTANCE_SIZE + sizeOf(positionLinks);
}
}
|
package com.piggymetrics.auth.service.security;
import com.piggymetrics.auth.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class MongoUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository repository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return repository.findById(username).orElseThrow(()->new UsernameNotFoundException(username));
}
}
|
/*
* Copyright 2020 ConsenSys AG.
*
* 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 tech.pegasys.signers.secp256k1.common;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class PasswordFileUtilTest {
@ParameterizedTest
@ValueSource(strings = {"line1\nline2", "line1\n", "line1"})
void canReadPasswordFromFile(final String content, @TempDir final Path tempDir)
throws IOException {
final Path passwordFile = Files.write(tempDir.resolve("password.txt"), content.getBytes(UTF_8));
assertThat(PasswordFileUtil.readPasswordFromFile(passwordFile)).isEqualTo("line1");
}
@Test
void canReadSpaceOnlyPasswordFromFile(@TempDir final Path tempDir) throws IOException {
final Path passwordFile = Files.write(tempDir.resolve("password.txt"), " \n".getBytes(UTF_8));
assertThat(PasswordFileUtil.readPasswordFromFile(passwordFile)).isEqualTo(" ");
}
@ParameterizedTest
@ValueSource(strings = {"", "\n"})
void canReadPasswordFromEmptyStringFile(final String content, @TempDir final Path tempDir)
throws IOException {
final Path passwordFile = Files.write(tempDir.resolve("password.txt"), content.getBytes(UTF_8));
assertThat(PasswordFileUtil.readPasswordFromFile(passwordFile)).isEqualTo("");
}
}
|
/*
* Copyright 2018 JDCLOUD.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.
*
* Watermark
* 水印管理相关接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.vod.model;
import com.jdcloud.sdk.service.JdcloudResult;
/**
* 查询水印
*/
public class GetWatermarkResult extends JdcloudResult implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* 水印ID
*/
private Long id;
/**
* 水印名称。只支持中英文、数字。长度不超过128个字符。UTF-8编码。
*/
private String name;
/**
* 图片地址
*/
private String imgUrl;
/**
* 水印宽度。
当 sizeUnit = pixel 时,取值范围为 [8, 4096] 整数
当 sizeUnit = percent 时,取值范围为 [0, 100] 小数
*/
private String width;
/**
* 水印高度。
当 sizeUnit = pixel 时,取值范围为 [8, 4096] 整数
当 sizeUnit = percent 时,取值范围为 [0, 100] 小数
*/
private String height;
/**
* 尺寸单位。取值范围:
pixel - 像素
percent - 百分比
默认值为 pixel
*/
private String sizeUnit;
/**
* widthRef
*/
private String widthRef;
/**
* 高度参考,仅当 siteUnit = percent 时生效。
取值说明:
w: 输出水印高度 = height * 水印原图高度
v: 等同于 vh
vw: 输出水印高度 = height * 输出视频宽度
vh: 输出水印高度 = height * 输出视频高度
vls: 输出水印高度 = height * 输出视频长边
vss: 输出水印高度 = height * 输出视频短边
*/
private String heightRef;
/**
* 水印位置。取值范围:
LT - 左上
RT - 右上
LB - 左下
RB - 右下
*/
private String position;
/**
* 水平偏移。
当 offsetUnit = pixel 时,取值范围为 [8, 4088] 整数
当 offsetUnit = percent 时,取值范围为 [0, 100] 小数
*/
private String offsetX;
/**
* 竖直偏移。
当 offsetUnit = pixel 时,取值范围为 [8, 4088] 整数
当 offsetUnit = percent 时,取值范围为 [0, 100] 小数
*/
private String offsetY;
/**
* 偏移单位。取值范围:
pixel - 像素
percent - 百分比
默认值为 pixel
*/
private String offsetUnit;
/**
* 创建时间
*/
private String createTime;
/**
* 修改时间
*/
private String updateTime;
/**
* get 水印ID
*
* @return
*/
public Long getId() {
return id;
}
/**
* set 水印ID
*
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* get 水印名称。只支持中英文、数字。长度不超过128个字符。UTF-8编码。
*
* @return
*/
public String getName() {
return name;
}
/**
* set 水印名称。只支持中英文、数字。长度不超过128个字符。UTF-8编码。
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* get 图片地址
*
* @return
*/
public String getImgUrl() {
return imgUrl;
}
/**
* set 图片地址
*
* @param imgUrl
*/
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
/**
* get 水印宽度。
当 sizeUnit = pixel 时,取值范围为 [8, 4096] 整数
当 sizeUnit = percent 时,取值范围为 [0, 100] 小数
*
* @return
*/
public String getWidth() {
return width;
}
/**
* set 水印宽度。
当 sizeUnit = pixel 时,取值范围为 [8, 4096] 整数
当 sizeUnit = percent 时,取值范围为 [0, 100] 小数
*
* @param width
*/
public void setWidth(String width) {
this.width = width;
}
/**
* get 水印高度。
当 sizeUnit = pixel 时,取值范围为 [8, 4096] 整数
当 sizeUnit = percent 时,取值范围为 [0, 100] 小数
*
* @return
*/
public String getHeight() {
return height;
}
/**
* set 水印高度。
当 sizeUnit = pixel 时,取值范围为 [8, 4096] 整数
当 sizeUnit = percent 时,取值范围为 [0, 100] 小数
*
* @param height
*/
public void setHeight(String height) {
this.height = height;
}
/**
* get 尺寸单位。取值范围:
pixel - 像素
percent - 百分比
默认值为 pixel
*
* @return
*/
public String getSizeUnit() {
return sizeUnit;
}
/**
* set 尺寸单位。取值范围:
pixel - 像素
percent - 百分比
默认值为 pixel
*
* @param sizeUnit
*/
public void setSizeUnit(String sizeUnit) {
this.sizeUnit = sizeUnit;
}
/**
* get widthRef
*
* @return
*/
public String getWidthRef() {
return widthRef;
}
/**
* set widthRef
*
* @param widthRef
*/
public void setWidthRef(String widthRef) {
this.widthRef = widthRef;
}
/**
* get 高度参考,仅当 siteUnit = percent 时生效。
取值说明:
w: 输出水印高度 = height * 水印原图高度
v: 等同于 vh
vw: 输出水印高度 = height * 输出视频宽度
vh: 输出水印高度 = height * 输出视频高度
vls: 输出水印高度 = height * 输出视频长边
vss: 输出水印高度 = height * 输出视频短边
*
* @return
*/
public String getHeightRef() {
return heightRef;
}
/**
* set 高度参考,仅当 siteUnit = percent 时生效。
取值说明:
w: 输出水印高度 = height * 水印原图高度
v: 等同于 vh
vw: 输出水印高度 = height * 输出视频宽度
vh: 输出水印高度 = height * 输出视频高度
vls: 输出水印高度 = height * 输出视频长边
vss: 输出水印高度 = height * 输出视频短边
*
* @param heightRef
*/
public void setHeightRef(String heightRef) {
this.heightRef = heightRef;
}
/**
* get 水印位置。取值范围:
LT - 左上
RT - 右上
LB - 左下
RB - 右下
*
* @return
*/
public String getPosition() {
return position;
}
/**
* set 水印位置。取值范围:
LT - 左上
RT - 右上
LB - 左下
RB - 右下
*
* @param position
*/
public void setPosition(String position) {
this.position = position;
}
/**
* get 水平偏移。
当 offsetUnit = pixel 时,取值范围为 [8, 4088] 整数
当 offsetUnit = percent 时,取值范围为 [0, 100] 小数
*
* @return
*/
public String getOffsetX() {
return offsetX;
}
/**
* set 水平偏移。
当 offsetUnit = pixel 时,取值范围为 [8, 4088] 整数
当 offsetUnit = percent 时,取值范围为 [0, 100] 小数
*
* @param offsetX
*/
public void setOffsetX(String offsetX) {
this.offsetX = offsetX;
}
/**
* get 竖直偏移。
当 offsetUnit = pixel 时,取值范围为 [8, 4088] 整数
当 offsetUnit = percent 时,取值范围为 [0, 100] 小数
*
* @return
*/
public String getOffsetY() {
return offsetY;
}
/**
* set 竖直偏移。
当 offsetUnit = pixel 时,取值范围为 [8, 4088] 整数
当 offsetUnit = percent 时,取值范围为 [0, 100] 小数
*
* @param offsetY
*/
public void setOffsetY(String offsetY) {
this.offsetY = offsetY;
}
/**
* get 偏移单位。取值范围:
pixel - 像素
percent - 百分比
默认值为 pixel
*
* @return
*/
public String getOffsetUnit() {
return offsetUnit;
}
/**
* set 偏移单位。取值范围:
pixel - 像素
percent - 百分比
默认值为 pixel
*
* @param offsetUnit
*/
public void setOffsetUnit(String offsetUnit) {
this.offsetUnit = offsetUnit;
}
/**
* get 创建时间
*
* @return
*/
public String getCreateTime() {
return createTime;
}
/**
* set 创建时间
*
* @param createTime
*/
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
/**
* get 修改时间
*
* @return
*/
public String getUpdateTime() {
return updateTime;
}
/**
* set 修改时间
*
* @param updateTime
*/
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
/**
* set 水印ID
*
* @param id
*/
public GetWatermarkResult id(Long id) {
this.id = id;
return this;
}
/**
* set 水印名称。只支持中英文、数字。长度不超过128个字符。UTF-8编码。
*
* @param name
*/
public GetWatermarkResult name(String name) {
this.name = name;
return this;
}
/**
* set 图片地址
*
* @param imgUrl
*/
public GetWatermarkResult imgUrl(String imgUrl) {
this.imgUrl = imgUrl;
return this;
}
/**
* set 水印宽度。
当 sizeUnit = pixel 时,取值范围为 [8, 4096] 整数
当 sizeUnit = percent 时,取值范围为 [0, 100] 小数
*
* @param width
*/
public GetWatermarkResult width(String width) {
this.width = width;
return this;
}
/**
* set 水印高度。
当 sizeUnit = pixel 时,取值范围为 [8, 4096] 整数
当 sizeUnit = percent 时,取值范围为 [0, 100] 小数
*
* @param height
*/
public GetWatermarkResult height(String height) {
this.height = height;
return this;
}
/**
* set 尺寸单位。取值范围:
pixel - 像素
percent - 百分比
默认值为 pixel
*
* @param sizeUnit
*/
public GetWatermarkResult sizeUnit(String sizeUnit) {
this.sizeUnit = sizeUnit;
return this;
}
/**
* set widthRef
*
* @param widthRef
*/
public GetWatermarkResult widthRef(String widthRef) {
this.widthRef = widthRef;
return this;
}
/**
* set 高度参考,仅当 siteUnit = percent 时生效。
取值说明:
w: 输出水印高度 = height * 水印原图高度
v: 等同于 vh
vw: 输出水印高度 = height * 输出视频宽度
vh: 输出水印高度 = height * 输出视频高度
vls: 输出水印高度 = height * 输出视频长边
vss: 输出水印高度 = height * 输出视频短边
*
* @param heightRef
*/
public GetWatermarkResult heightRef(String heightRef) {
this.heightRef = heightRef;
return this;
}
/**
* set 水印位置。取值范围:
LT - 左上
RT - 右上
LB - 左下
RB - 右下
*
* @param position
*/
public GetWatermarkResult position(String position) {
this.position = position;
return this;
}
/**
* set 水平偏移。
当 offsetUnit = pixel 时,取值范围为 [8, 4088] 整数
当 offsetUnit = percent 时,取值范围为 [0, 100] 小数
*
* @param offsetX
*/
public GetWatermarkResult offsetX(String offsetX) {
this.offsetX = offsetX;
return this;
}
/**
* set 竖直偏移。
当 offsetUnit = pixel 时,取值范围为 [8, 4088] 整数
当 offsetUnit = percent 时,取值范围为 [0, 100] 小数
*
* @param offsetY
*/
public GetWatermarkResult offsetY(String offsetY) {
this.offsetY = offsetY;
return this;
}
/**
* set 偏移单位。取值范围:
pixel - 像素
percent - 百分比
默认值为 pixel
*
* @param offsetUnit
*/
public GetWatermarkResult offsetUnit(String offsetUnit) {
this.offsetUnit = offsetUnit;
return this;
}
/**
* set 创建时间
*
* @param createTime
*/
public GetWatermarkResult createTime(String createTime) {
this.createTime = createTime;
return this;
}
/**
* set 修改时间
*
* @param updateTime
*/
public GetWatermarkResult updateTime(String updateTime) {
this.updateTime = updateTime;
return this;
}
}
|
package com.etiennelawlor.quickreturn.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.etiennelawlor.quickreturn.R;
import com.etiennelawlor.quickreturn.library.enums.QuickReturnViewType;
import com.etiennelawlor.quickreturn.library.listeners.QuickReturnScrollViewOnScrollChangedListener;
import com.etiennelawlor.quickreturn.library.views.NotifyingScrollView;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by etiennelawlor on 6/23/14.
*/
public class QuickReturnFragment extends Fragment {
// region Member Variables
private QuickReturnViewType mQuickReturnViewType;
@Bind(R.id.scroll_view)
NotifyingScrollView mNotifyingScrollView;
@Bind(R.id.quick_return_header_tv)
TextView mQuickReturnHeaderTextView;
@Bind(R.id.quick_return_footer_tv)
TextView mQuickReturnFooterTextView;
// endregion
// region Constructors
public QuickReturnFragment() {
}
// endregion
// region Factory Methods
public static QuickReturnFragment newInstance(Bundle extras) {
QuickReturnFragment fragment = new QuickReturnFragment();
fragment.setRetainInstance(true);
fragment.setArguments(extras);
return fragment;
}
// endregion
// region Lifecycle Methods
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mQuickReturnViewType = QuickReturnViewType.valueOf(getArguments().getString("quick_return_view_type"));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_quick_return, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
int headerHeight = getResources().getDimensionPixelSize(R.dimen.header_height2);
int headerTranslation = -(headerHeight);
int footerTranslation = getResources().getDimensionPixelSize(R.dimen.footer_height);
QuickReturnScrollViewOnScrollChangedListener scrollListener;
switch (mQuickReturnViewType) {
case HEADER:
mQuickReturnHeaderTextView.setVisibility(View.VISIBLE);
scrollListener = new QuickReturnScrollViewOnScrollChangedListener.Builder(QuickReturnViewType.HEADER)
.header(mQuickReturnHeaderTextView)
.minHeaderTranslation(headerTranslation)
.build();
mNotifyingScrollView.setOnScrollChangedListener(scrollListener);
break;
case FOOTER:
mQuickReturnFooterTextView.setVisibility(View.VISIBLE);
scrollListener = new QuickReturnScrollViewOnScrollChangedListener.Builder(QuickReturnViewType.FOOTER)
.footer(mQuickReturnFooterTextView)
.minFooterTranslation(footerTranslation)
.build();
mNotifyingScrollView.setOnScrollChangedListener(scrollListener);
break;
case BOTH:
mQuickReturnHeaderTextView.setVisibility(View.VISIBLE);
mQuickReturnFooterTextView.setVisibility(View.VISIBLE);
scrollListener = new QuickReturnScrollViewOnScrollChangedListener.Builder(QuickReturnViewType.BOTH)
.header(mQuickReturnHeaderTextView)
.minHeaderTranslation(headerTranslation)
.footer(mQuickReturnFooterTextView)
.minFooterTranslation(footerTranslation)
.build();
mNotifyingScrollView.setOnScrollChangedListener(scrollListener);
break;
}
mNotifyingScrollView.setOverScrollEnabled(false);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
// endregion
}
|
/**
* 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.apex.malhar.contrib.misc.algo;
import java.util.HashMap;
import org.apache.apex.malhar.lib.util.BaseMatchOperator;
import com.datatorrent.api.DefaultInputPort;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.annotation.OperatorAnnotation;
/**
* This operator filters the incoming stream of key value pairs by obtaining the values corresponding to a specified key,
* and comparing those values to a specified number. For each window, all key value pairs are emitted by the operator until a value satisfying the comparison is encountered.
* <p>
* All key.val pairs with val sub-classed from Number are emitted till the first match; A compare metric is done based on the property "key",
* "value", and "cmp". Then on no tuple is emitted in that window. The comparison is done by getting double value of the Number.
* </p>
* <p>
* This module is a pass through<br>
* <br>
* <b>StateFull : Yes, </b> tuple are processed in current window. <br>
* <b>Partitions : No, </b>will yield wrong results. <br>
* <br>
* <br>
* <b>Ports</b>:<br>
* <b>data</b>: Input port, expects HashMap<K,V><br>
* <b>first</b>: Output port, emits HashMap<K,V> if compare function returns true<br>
* <br>
* <b>Properties</b>:<br>
* <b>key</b>: The key on which compare is done<br>
* <b>value</b>: The value to compare with<br>
* <b>cmp</b>: The compare function. Supported values are "lte", "lt", "eq", "neq", "gt", "gte". Default is "eq"<br>
* <br>
* <b>Specific compile time checks</b>:<br>
* Key must be non empty<br>
* Value must be able to convert to a "double"<br>
* Compare string, if specified, must be one of "lte", "lt", "eq", "neq", "gt", "gte"<br>
* <br>
* </p>
*
* @displayName Emit Keyval Pairs Until Match (Number)
* @category Rules and Alerts
* @tags filter, key value, numeric
* @deprecated
* @since 0.3.2
*/
@Deprecated
@OperatorAnnotation(partitionable = false)
public class FirstTillMatch<K, V extends Number> extends BaseMatchOperator<K, V>
{
/**
* Tuple emitted flag.
*/
boolean emitted = false;
/**
* The input port on which incoming key value pairs are received.
*/
public final transient DefaultInputPort<HashMap<K, V>> data = new DefaultInputPort<HashMap<K, V>>()
{
/**
* Compares the key,val pair with the match condition. Till a match is found tuples are emitted.
* Once a match is found, state is set to emitted, and no more tuples are compared (no more emits).
*/
@Override
public void process(HashMap<K, V> tuple)
{
if (emitted) {
return;
}
V val = tuple.get(getKey());
if (val == null) { // skip if the key does not exist
return;
}
if (compareValue(val.doubleValue())) {
emitted = true;
}
if (!emitted) {
first.emit(cloneTuple(tuple));
}
}
};
/**
* The output port on which key value pairs are emitted until the first match.
*/
public final transient DefaultOutputPort<HashMap<K, V>> first = new DefaultOutputPort<HashMap<K, V>>();
/**
* Emitted set is reset to false
* @param windowId
*/
@Override
public void beginWindow(long windowId)
{
emitted = false;
}
}
|
/*
* @(#)Procedure.java 1.0 09/12/14
*
* This file has been auto-generated by JNC, the
* Java output format plug-in of pyang.
* Origin: module "hcta-epc", revision: "2014-09-18".
*/
package hctaEpc.fgw.statistics.fgwCm;
import Element;
import Epc;
import JNCException;
import com.tailf.jnc.YangElement;
import com.tailf.jnc.YangString;
/**
* This class represents an element from
* the namespace http://hitachi-cta.com/ns/epc
* generated to "src/hctaEpc/fgw/statistics/fgwCm/procedure"
* <p>
* See line 2462 in
* oamPmServerCli.yang
*
* @version 1.0 2014-12-09
* @author Auto Generated
*/
public class Procedure extends YangElement {
private static final long serialVersionUID = 1L;
/**
* Constructor for an empty Procedure object.
*/
public Procedure() {
super(Epc.NAMESPACE, "procedure");
}
/**
* Clones this object, returning an exact copy.
* @return A clone of the object.
*/
public Procedure clone() {
return (Procedure)cloneContent(new Procedure());
}
/**
* Clones this object, returning a shallow copy.
* @return A clone of the object. Children are not included.
*/
public Procedure cloneShallow() {
return (Procedure)cloneShallowContent(new Procedure());
}
/**
* @return An array with the identifiers of any key children
*/
public String[] keyNames() {
return null;
}
/**
* @return An array with the identifiers of any children, in order.
*/
public String[] childrenNames() {
return new String[] {
"service",
"ref-entity-type",
"ref-entity-tag",
"ref-subentity-info",
"register-name",
"register-value",
};
}
/* Access methods for leaf child: "service". */
/**
* Gets the value for child leaf "service".
* @return The value of the leaf.
*/
public YangString getServiceValue() throws JNCException {
return (YangString)getValue("service");
}
/**
* Sets the value for child leaf "service",
* using instance of generated typedef class.
* @param serviceValue The value to set.
* @param serviceValue used during instantiation.
*/
public void setServiceValue(YangString serviceValue) throws JNCException {
setLeafValue(Epc.NAMESPACE,
"service",
serviceValue,
childrenNames());
}
/**
* Sets the value for child leaf "service",
* using a String value.
* @param serviceValue used during instantiation.
*/
public void setServiceValue(String serviceValue) throws JNCException {
setServiceValue(new YangString(serviceValue));
}
/**
* This method is used for creating a subtree filter.
* The added "service" leaf will not have a value.
*/
public void addService() throws JNCException {
setLeafValue(Epc.NAMESPACE,
"service",
null,
childrenNames());
}
/* Access methods for leaf child: "ref-entity-type". */
/**
* Gets the value for child leaf "ref-entity-type".
* @return The value of the leaf.
*/
public YangString getRefEntityTypeValue() throws JNCException {
return (YangString)getValue("ref-entity-type");
}
/**
* Sets the value for child leaf "ref-entity-type",
* using instance of generated typedef class.
* @param refEntityTypeValue The value to set.
* @param refEntityTypeValue used during instantiation.
*/
public void setRefEntityTypeValue(YangString refEntityTypeValue)
throws JNCException {
setLeafValue(Epc.NAMESPACE,
"ref-entity-type",
refEntityTypeValue,
childrenNames());
}
/**
* Sets the value for child leaf "ref-entity-type",
* using a String value.
* @param refEntityTypeValue used during instantiation.
*/
public void setRefEntityTypeValue(String refEntityTypeValue)
throws JNCException {
setRefEntityTypeValue(new YangString(refEntityTypeValue));
}
/**
* This method is used for creating a subtree filter.
* The added "ref-entity-type" leaf will not have a value.
*/
public void addRefEntityType() throws JNCException {
setLeafValue(Epc.NAMESPACE,
"ref-entity-type",
null,
childrenNames());
}
/* Access methods for leaf child: "ref-entity-tag". */
/**
* Gets the value for child leaf "ref-entity-tag".
* @return The value of the leaf.
*/
public YangString getRefEntityTagValue() throws JNCException {
return (YangString)getValue("ref-entity-tag");
}
/**
* Sets the value for child leaf "ref-entity-tag",
* using instance of generated typedef class.
* @param refEntityTagValue The value to set.
* @param refEntityTagValue used during instantiation.
*/
public void setRefEntityTagValue(YangString refEntityTagValue)
throws JNCException {
setLeafValue(Epc.NAMESPACE,
"ref-entity-tag",
refEntityTagValue,
childrenNames());
}
/**
* Sets the value for child leaf "ref-entity-tag",
* using a String value.
* @param refEntityTagValue used during instantiation.
*/
public void setRefEntityTagValue(String refEntityTagValue)
throws JNCException {
setRefEntityTagValue(new YangString(refEntityTagValue));
}
/**
* This method is used for creating a subtree filter.
* The added "ref-entity-tag" leaf will not have a value.
*/
public void addRefEntityTag() throws JNCException {
setLeafValue(Epc.NAMESPACE,
"ref-entity-tag",
null,
childrenNames());
}
/* Access methods for leaf child: "ref-subentity-info". */
/**
* Gets the value for child leaf "ref-subentity-info".
* @return The value of the leaf.
*/
public YangString getRefSubentityInfoValue() throws JNCException {
return (YangString)getValue("ref-subentity-info");
}
/**
* Sets the value for child leaf "ref-subentity-info",
* using instance of generated typedef class.
* @param refSubentityInfoValue The value to set.
* @param refSubentityInfoValue used during instantiation.
*/
public void setRefSubentityInfoValue(YangString refSubentityInfoValue)
throws JNCException {
setLeafValue(Epc.NAMESPACE,
"ref-subentity-info",
refSubentityInfoValue,
childrenNames());
}
/**
* Sets the value for child leaf "ref-subentity-info",
* using a String value.
* @param refSubentityInfoValue used during instantiation.
*/
public void setRefSubentityInfoValue(String refSubentityInfoValue)
throws JNCException {
setRefSubentityInfoValue(new YangString(refSubentityInfoValue));
}
/**
* This method is used for creating a subtree filter.
* The added "ref-subentity-info" leaf will not have a value.
*/
public void addRefSubentityInfo() throws JNCException {
setLeafValue(Epc.NAMESPACE,
"ref-subentity-info",
null,
childrenNames());
}
/* Access methods for leaf child: "register-name". */
/**
* Gets the value for child leaf "register-name".
* @return The value of the leaf.
*/
public YangString getRegisterNameValue() throws JNCException {
return (YangString)getValue("register-name");
}
/**
* Sets the value for child leaf "register-name",
* using instance of generated typedef class.
* @param registerNameValue The value to set.
* @param registerNameValue used during instantiation.
*/
public void setRegisterNameValue(YangString registerNameValue)
throws JNCException {
setLeafValue(Epc.NAMESPACE,
"register-name",
registerNameValue,
childrenNames());
}
/**
* Sets the value for child leaf "register-name",
* using a String value.
* @param registerNameValue used during instantiation.
*/
public void setRegisterNameValue(String registerNameValue)
throws JNCException {
setRegisterNameValue(new YangString(registerNameValue));
}
/**
* This method is used for creating a subtree filter.
* The added "register-name" leaf will not have a value.
*/
public void addRegisterName() throws JNCException {
setLeafValue(Epc.NAMESPACE,
"register-name",
null,
childrenNames());
}
/* Access methods for optional leaf child: "register-value". */
/**
* Gets the value for child leaf "register-value".
* @return The value of the leaf.
*/
public YangString getRegisterValueValue() throws JNCException {
return (YangString)getValue("register-value");
}
/**
* Sets the value for child leaf "register-value",
* using instance of generated typedef class.
* @param registerValueValue The value to set.
* @param registerValueValue used during instantiation.
*/
public void setRegisterValueValue(YangString registerValueValue)
throws JNCException {
setLeafValue(Epc.NAMESPACE,
"register-value",
registerValueValue,
childrenNames());
}
/**
* Sets the value for child leaf "register-value",
* using a String value.
* @param registerValueValue used during instantiation.
*/
public void setRegisterValueValue(String registerValueValue)
throws JNCException {
setRegisterValueValue(new YangString(registerValueValue));
}
/**
* Unsets the value for child leaf "register-value".
*/
public void unsetRegisterValueValue() throws JNCException {
delete("register-value");
}
/**
* This method is used for creating a subtree filter.
* The added "register-value" leaf will not have a value.
*/
public void addRegisterValue() throws JNCException {
setLeafValue(Epc.NAMESPACE,
"register-value",
null,
childrenNames());
}
/**
* Marks the leaf "register-value" with operation "replace".
*/
public void markRegisterValueReplace() throws JNCException {
markLeafReplace("registerValue");
}
/**
* Marks the leaf "register-value" with operation "merge".
*/
public void markRegisterValueMerge() throws JNCException {
markLeafMerge("registerValue");
}
/**
* Marks the leaf "register-value" with operation "create".
*/
public void markRegisterValueCreate() throws JNCException {
markLeafCreate("registerValue");
}
/**
* Marks the leaf "register-value" with operation "delete".
*/
public void markRegisterValueDelete() throws JNCException {
markLeafDelete("registerValue");
}
/**
* Support method for addChild.
* Adds a child to this object.
*
* @param child The child to add
*/
public void addChild(Element child) {
super.addChild(child);
}
}
|
/*
* Copyright (c) 2020. Yuriy Stul
*/
package com.stulsoft.pvertx.kafka.stream;
import com.stulsoft.pvertx.kafka.Config;
import com.stulsoft.pvertx.kafka.Constants;
import io.vertx.core.AbstractVerticle;
import io.vertx.kafka.client.consumer.KafkaConsumer;
import io.vertx.kafka.client.consumer.KafkaConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import static com.stulsoft.pvertx.kafka.Constants.EB_SERVICE_ADDRESS;
/**
* Usual Vertx Kafka consumer. Does not guarantee sequential processing.
*
* @author Yuriy Stul
*/
public class ConsumerVerticle extends AbstractVerticle {
private static final Logger logger = LoggerFactory.getLogger(ConsumerVerticle.class);
private KafkaConsumer<String, String> consumer;
@Override
public void start() throws Exception {
super.start();
var config = new HashMap<String, String>();
config.put("bootstrap.servers", Config.kafkaUrl());
config.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
config.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
config.put("group.id", "stream_test_group");
config.put("auto.offset.reset", "earliest");
config.put("enable.auto.commit", "true");
consumer = KafkaConsumer.create(vertx, config);
consumer.handler(this::handler);
consumer.subscribe(Constants.TOPIC_NAME);
logger.info("Started");
}
private void handler(KafkaConsumerRecord<String, String> record) {
logger.info("Received {}", record.value());
vertx.eventBus().<String>request(EB_SERVICE_ADDRESS,
record.value(),
result -> {
logger.info("Response for {} is {}", record.value(), result.result().body());
});
}
}
|
package ru.job4j.changetracker.abstractclasses.models;
import java.util.Arrays;
/**
* Created on 08.08.2017.
*
* @author Aleks Sidorenko (alek.sidorenko1979@gmail.com).
* @version $Id$.
* @since 0.1.
*/
public class Item {
/**
* @param id - Ordinal number of the person.
*/
private String id;
/**
* @param name - name of Person.
*/
private String name;
/**
* @param desc - description.
*/
private String desc;
/**
* @param created - data of created.
*/
private long created;
/**
* @param comments - array of comments.
*/
private String[] comments;
/**
* Constructor.
* @param id - number.
* @param name - Name of Person.
* @param desc - description.
* @param created - time of created.
* @param comments - comment of Person.
*/
public Item(String id, String name, String desc, long created, String[] comments) {
this.id = id;
this.name = name;
this.desc = desc;
this.created = created;
this.comments = comments;
}
/**
* Constructor.
* @param id - number.
*/
public Item(String id) {
this.id = id;
}
/**
* Constructor is empty.
*/
public Item() { }
/**
* A method that makes it possible to obtain a parameter.
* @return - The resulting parameter.
*/
public String getId() {
return id;
}
/**
* A method that enables the installation of data.
* @param id - Setting parameter.
*/
public void setId(String id) {
this.id = id;
}
/**
* A method that makes it possible to obtain a parameter.
* @return - The resulting parameter.
*/
public String getName() {
return name;
}
/**
* A method that enables the installation of data.
* @param name - Setting parameter.
*/
public void setName(String name) {
this.name = name;
}
/**
* A method that makes it possible to obtain a parameter.
* @return - The resulting parameter.
*/
public String getDesc() {
return desc;
}
/**
* A method that enables the installation of data.
* @param desc - Setting parameter.
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* A method that makes it possible to obtain a parameter.
* @return - The resulting parameter.
*/
public long getCreated() {
return created;
}
/**
* A method that enables the installation of data.
* @param created - Setting parameter.
*/
public void setCreated(long created) {
this.created = created;
}
/**
* A method that makes it possible to obtain a parameter.
* @return - The resulting parameter.
*/
public String[] getComments() {
return comments;
}
/**
* A method that enables the installation of data.
* @param comments - Setting parameter.
*/
public void setComments(String[] comments) {
this.comments = comments;
}
@Override
public String toString() {
return "Item{" + "id='" + id + '\''
+ ", name='" + name + '\''
+ ", desc='" + desc + '\''
+ ", created=" + created
+ ", comments=" + Arrays.toString(comments) + '}';
}
}
|
package co.kr.pmp.dao.mint;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import co.kr.pmp.domain.mint.Mdto;
@Mapper
public interface MPractice {
public List<Mdto>Mtest();
}
|
package io.github.revxrsal.minigames.menu;
import com.cryptomorin.xseries.SkullUtils;
import com.cryptomorin.xseries.XEnchantment;
import com.cryptomorin.xseries.XMaterial;
import com.google.common.base.Preconditions;
import io.github.revxrsal.minigames.gson.GsonHook;
import io.github.revxrsal.minigames.gson.GsonHook.AfterDeserialization;
import io.github.revxrsal.minigames.util.Chat;
import io.github.revxrsal.minigames.util.Placeholders;
import io.github.revxrsal.minigames.util.Utils;
import lombok.AccessLevel;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
/**
* An immutable, fast, and thread-safe wrapper for {@link ItemStack}s.
*/
@Getter
@GsonHook
public class Item {
private final XMaterial type;
@Nullable private final String displayName;
private final List<String> lore;
private final int count;
private final Map<XEnchantment, Integer> enchantments;
private final ItemFlag[] itemFlags;
@Nullable private final UUID skull;
private final boolean unbreakable;
@Getter(AccessLevel.NONE)
protected transient ItemStack itemStack;
protected Item(XMaterial type,
@Nullable String displayName,
List<String> lore,
int count,
Map<XEnchantment, Integer> enchantments,
ItemFlag[] itemFlags,
@Nullable UUID skull,
boolean unbreakable) {
this.type = type;
this.displayName = colorize(displayName);
this.lore = lore == null ? null : lore.stream().map(Item::colorize).collect(Collectors.toList());
this.count = count;
this.enchantments = enchantments;
this.itemFlags = itemFlags;
this.skull = skull;
this.unbreakable = unbreakable;
createItem0();
}
@Contract("null -> null")
public static String colorize(@Nullable String o) {
if (o == null) return null;
return ChatColor.translateAlternateColorCodes('&', o);
}
public void give(Player... players) {
for (Player player : players)
giveItem(player);
}
public void give(int slot, Player... players) {
for (Player player : players)
player.getInventory().setItem(slot, itemStack);
}
public void give(Iterable<Player> players) {
for (Player player : players)
giveItem(player);
}
protected void giveItem(Player player) {
player.getInventory().addItem(itemStack);
}
public Builder asBuilder() {
return new Builder(this);
}
public static Builder builder() {
return new Builder();
}
@AfterDeserialization
protected void createItem0() {
ItemStack item;
if (skull != null) {
item = SkullUtils.getSkull(skull);
} else
item = type.parseItem();
int amount = Utils.coerce(count, 1, 64);
Objects.requireNonNull(item).setAmount(amount);
ItemMeta m = item.getItemMeta();
if (m == null) return;
if (displayName != null && !displayName.equals("{}")) m.setDisplayName(colorize(displayName));
if (lore != null) m.setLore(lore.stream().map(Chat::colorize).collect(Collectors.toList()));
if (itemFlags != null) m.addItemFlags(itemFlags);
if (unbreakable) {
try {
m.setUnbreakable(true);
} catch (Throwable t) {
try {
m.spigot().setUnbreakable(true);
} catch (Throwable ignored) {
}
}
}
if (enchantments != null)
enchantments.forEach((ench, lvl) -> m.addEnchant(ench.parseEnchantment(), lvl, true));
item.setItemMeta(m);
itemStack = item;
}
public ItemStack withPlaceholders(Object... placeholders) {
return setPlaceholders(new ItemStack(itemStack), placeholders);
}
public ItemStack createItem() {
return new ItemStack(itemStack);
}
public boolean isSimilar(@Nullable ItemStack other) {
return itemStack.isSimilar(other);
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof ItemStack) return isSimilar(((ItemStack) o));
if (!(o instanceof Item)) return false;
Item item = (Item) o;
return itemStack.isSimilar(item.itemStack);
}
@Override public int hashCode() {
return Objects.hash(itemStack);
}
@Getter
public static class SlotItem extends Item {
private final int slot;
protected SlotItem(XMaterial type, @Nullable String displayName, List<String> lore, int count, Map<XEnchantment, Integer> enchantments, ItemFlag[] itemFlags, @Nullable UUID skull, boolean unbreakable, int slot) {
super(type, displayName, lore, count, enchantments, itemFlags, skull, unbreakable);
this.slot = slot;
}
@Override protected void giveItem(Player player) {
player.getInventory().setItem(slot, itemStack);
}
}
public static Builder fromItemStack(@NotNull ItemStack item) {
ItemMeta meta = Objects.requireNonNull(item.getItemMeta());
Builder b = Item.builder().type(item.getType())
.name(meta.getDisplayName())
.lore(meta.getLore())
.itemFlags(meta.getItemFlags())
.enchant(Utils.mapKeys(meta.getEnchants(), XEnchantment::matchXEnchantment));
if (meta instanceof SkullMeta)
try {
b.skull(((SkullMeta) meta).getOwningPlayer().getUniqueId());
} catch (Throwable ignored) {
}
return b;
}
public static ItemStack setPlaceholders(ItemStack item, Object... placeholders) {
ItemMeta meta = Builder.n(item.getItemMeta(), "meta is null!");
if (meta.hasDisplayName())
meta.setDisplayName(Placeholders.on(meta.getDisplayName(), placeholders));
if (meta.hasLore())
meta.setLore(meta.getLore().stream().map(t -> Placeholders.on(t, placeholders)).collect(Collectors.toList()));
item.setItemMeta(meta);
return item;
}
public static class Builder {
private XMaterial type = XMaterial.STONE;
@Nullable private String displayName = null;
private List<String> lore = new ArrayList<>();
private int count = 1;
private int slot = -1;
private Map<XEnchantment, Integer> enchantments = new HashMap<>();
private final Set<ItemFlag> itemFlags = new HashSet<>();
@Nullable private UUID skull;
private boolean unbreakable = false;
public Builder() {
}
public Builder(Item item) {
type = item.type;
displayName = item.displayName;
lore = item.lore;
count = item.count;
enchantments = item.enchantments;
skull = item.skull;
Collections.addAll(itemFlags, item.itemFlags);
unbreakable = item.unbreakable;
}
public Builder type(@NotNull Material material) {
this.type = XMaterial.matchXMaterial(n(material, "material"));
return this;
}
public Builder type(@NotNull XMaterial material) {
this.type = n(material, "material");
return this;
}
public Builder slot(int slot) {
Preconditions.checkArgument(slot >= 0, "slot cannot be less than 0!");
this.slot = slot;
return this;
}
public Builder name(@Nullable String name) {
if (name == null || name.equals("{}")) return this;
displayName = name;
return this;
}
public Builder amount(int amount) {
this.count = amount;
return this;
}
public Builder loreLine(@NotNull String lore) {
this.lore.add(n(lore, "lore"));
return this;
}
public Builder lore(@Nullable Collection<String> lore) {
if (lore == null) return this;
this.lore.addAll(n(lore, "lore"));
return this;
}
public Builder lore(@NotNull String... lore) {
Collections.addAll(this.lore, n(lore, "lore"));
return this;
}
public Builder lore(@NotNull String lore, int index) {
this.lore.set(index, n(lore, "lore"));
return this;
}
public Builder removeLore(@NotNull String lore) {
this.lore.remove(lore);
return this;
}
public Builder skull(@Nullable UUID skull) {
this.skull = skull;
return this;
}
public Builder skull(@Nullable String playerName) {
if (playerName == null) {
this.skull = null;
return this;
}
this.skull = Bukkit.getOfflinePlayer(playerName).getUniqueId();
return this;
}
public Builder itemFlag(@NotNull ItemFlag itemFlag) {
this.itemFlags.add(n(itemFlag, "itemFlag"));
return this;
}
public Builder itemFlags(@NotNull Collection<ItemFlag> itemFlags) {
this.itemFlags.addAll(n(itemFlags, "itemFlags"));
return this;
}
public Builder unbreakable(boolean v) {
unbreakable = v;
return this;
}
public Builder enchant(@NotNull XEnchantment enchantment, int level) {
this.enchantments.put(n(enchantment, "enchantment"), level);
return this;
}
public Builder enchant(@NotNull Map<XEnchantment, Integer> enchantments) {
this.enchantments.putAll(n(enchantments, "enchantments"));
return this;
}
public Item build() {
if (slot == -1)
return new Item(type, displayName, lore, count, enchantments, itemFlags.toArray(new ItemFlag[0]), skull, unbreakable);
else
return new SlotItem(type, displayName, lore, count, enchantments, itemFlags.toArray(new ItemFlag[0]), skull, unbreakable, slot);
}
private static <T> T n(T t, String m) {
return Objects.requireNonNull(t, m);
}
}
}
|
package com.softeq.app.services.commands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.softeq.app.domain.User;
import org.junit.jupiter.api.Test;
class UserCommandMapperTest {
private UserCommandMapper mapper = new UserCommandMapperImpl();
@Test
void testMerge() {
User newUser = new User();
UpdateUserCommand command = new UpdateUserCommand();
command.setFirstName("John");
command.setLastName("Doe");
mapper.merge(newUser, command);
assertEquals("John", newUser.getFirstName());
assertEquals("Doe", newUser.getLastName());
}
}
|
/*
* 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.jackrabbit.core.cluster;
import java.io.File;
import java.io.IOException;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import org.apache.commons.io.FileUtils;
import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.jackrabbit.test.JUnitTest;
/**
* <code>FailUpdateOnJournalExceptionTest</code> checks if
* UpdateEventChannel.updateCreated(Update) throws a ClusterException
* when locking the Journal fails. See JCR-3417
*/
public class FailUpdateOnJournalExceptionTest extends JUnitTest {
private RepositoryImpl repo;
@Override
protected void setUp() throws Exception {
super.setUp();
deleteAll();
FileUtils.copyInputStreamToFile(
getClass().getResourceAsStream("repository-with-test-journal.xml"),
new File(getTestDir(), "repository.xml"));
repo = RepositoryImpl.create(RepositoryConfig.create(getTestDir()));
}
@Override
protected void tearDown() throws Exception {
if (repo != null) {
repo.shutdown();
}
deleteAll();
super.tearDown();
}
public void testUpdate() throws Exception {
Session s = repo.login(new SimpleCredentials("admin", "admin".toCharArray()));
Node root = s.getRootNode();
root.addNode("foo");
s.save();
root.addNode("bar");
TestJournal.refuseLock = true;
try {
s.save();
fail("Session.save() must fail with RepositoryException when Journal cannot be locked.");
} catch (RepositoryException e) {
// expected
} finally {
TestJournal.refuseLock = false;
}
}
private static void deleteAll() throws IOException {
FileUtils.deleteDirectory(getTestDir());
}
private static File getTestDir() throws IOException {
return new File("target",
FailUpdateOnJournalExceptionTest.class.getSimpleName());
}
}
|
package seedu.address;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.stage.Stage;
import seedu.address.commons.core.Config;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.Version;
import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.commons.util.ConfigUtil;
import seedu.address.commons.util.StringUtil;
import seedu.address.logic.Logic;
import seedu.address.logic.LogicManager;
import seedu.address.model.AddressBook;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.ReadOnlyAddressBook;
import seedu.address.model.ReadOnlyUserPrefs;
import seedu.address.model.UserPrefs;
import seedu.address.model.util.SampleDataUtil;
import seedu.address.storage.AddressBookStorage;
import seedu.address.storage.JsonAddressBookStorage;
import seedu.address.storage.JsonUserPrefsStorage;
import seedu.address.storage.Storage;
import seedu.address.storage.StorageManager;
import seedu.address.storage.UserPrefsStorage;
import seedu.address.ui.Ui;
import seedu.address.ui.UiManager;
/**
* Runs the application.
*/
public class MainApp extends Application {
public static final Version VERSION = new Version(0, 2, 0, true);
private static final Logger logger = LogsCenter.getLogger(MainApp.class);
protected Ui ui;
protected Logic logic;
protected Storage storage;
protected Model model;
protected Config config;
@Override
public void init() throws Exception {
logger.info("=============================[ Initializing SoConnect ]===========================");
super.init();
AppParameters appParameters = AppParameters.parse(getParameters());
config = initConfig(appParameters.getConfigPath());
UserPrefsStorage userPrefsStorage = new JsonUserPrefsStorage(config.getUserPrefsFilePath());
UserPrefs userPrefs = initPrefs(userPrefsStorage);
AddressBookStorage addressBookStorage = new JsonAddressBookStorage(userPrefs.getAddressBookFilePath());
storage = new StorageManager(addressBookStorage, userPrefsStorage);
initLogging(config);
model = initModelManager(storage, userPrefs);
logic = new LogicManager(model, storage);
ui = new UiManager(logic);
}
/**
* Returns a {@code ModelManager} with the data from {@code storage}'s address book and {@code userPrefs}. <br>
* The data from the sample address book will be used instead if {@code storage}'s address book is not found,
* or an empty address book will be used instead if errors occur when reading {@code storage}'s address book.
*/
private Model initModelManager(Storage storage, ReadOnlyUserPrefs userPrefs) {
Optional<ReadOnlyAddressBook> addressBookOptional;
ReadOnlyAddressBook initialData;
try {
addressBookOptional = storage.readAddressBook();
if (!addressBookOptional.isPresent()) {
logger.info("Data file not found. Will be starting with a sample AddressBook");
}
initialData = addressBookOptional.orElseGet(SampleDataUtil::getSampleAddressBook);
} catch (DataConversionException e) {
logger.warning("Data file not in the correct format. Will be starting with an empty AddressBook");
initialData = new AddressBook();
} catch (IOException e) {
logger.warning("Problem while reading from the file. Will be starting with an empty AddressBook");
initialData = new AddressBook();
}
return new ModelManager(initialData, userPrefs);
}
private void initLogging(Config config) {
LogsCenter.init(config);
}
/**
* Returns a {@code Config} using the file at {@code configFilePath}. <br>
* The default file path {@code Config#DEFAULT_CONFIG_FILE} will be used instead
* if {@code configFilePath} is null.
*/
protected Config initConfig(Path configFilePath) {
Config initializedConfig;
Path configFilePathUsed;
configFilePathUsed = Config.DEFAULT_CONFIG_FILE;
if (configFilePath != null) {
logger.info("Custom Config file specified " + configFilePath);
configFilePathUsed = configFilePath;
}
logger.info("Using config file : " + configFilePathUsed);
try {
Optional<Config> configOptional = ConfigUtil.readConfig(configFilePathUsed);
initializedConfig = configOptional.orElse(new Config());
} catch (DataConversionException e) {
logger.warning("Config file at " + configFilePathUsed + " is not in the correct format. "
+ "Using default config properties");
initializedConfig = new Config();
}
//Update config file in case it was missing to begin with or there are new/unused fields
try {
ConfigUtil.saveConfig(initializedConfig, configFilePathUsed);
} catch (IOException e) {
logger.warning("Failed to save config file : " + StringUtil.getDetails(e));
}
return initializedConfig;
}
/**
* Returns a {@code UserPrefs} using the file at {@code storage}'s user prefs file path,
* or a new {@code UserPrefs} with default configuration if errors occur when
* reading from the file.
*/
protected UserPrefs initPrefs(UserPrefsStorage storage) {
Path prefsFilePath = storage.getUserPrefsFilePath();
logger.info("Using prefs file : " + prefsFilePath);
UserPrefs initializedPrefs;
try {
Optional<UserPrefs> prefsOptional = storage.readUserPrefs();
initializedPrefs = prefsOptional.orElse(new UserPrefs());
} catch (DataConversionException e) {
logger.warning("UserPrefs file at " + prefsFilePath + " is not in the correct format. "
+ "Using default user prefs");
initializedPrefs = new UserPrefs();
} catch (IOException e) {
logger.warning("Problem while reading from the file. Will be starting with an empty AddressBook");
initializedPrefs = new UserPrefs();
}
//Update prefs file in case it was missing to begin with or there are new/unused fields
try {
storage.saveUserPrefs(initializedPrefs);
} catch (IOException e) {
logger.warning("Failed to save config file : " + StringUtil.getDetails(e));
}
return initializedPrefs;
}
@Override
public void start(Stage primaryStage) {
logger.info("Starting AddressBook " + MainApp.VERSION);
ui.start(primaryStage);
}
@Override
public void stop() {
logger.info("============================ [ Stopping SoConnect ] =============================");
try {
storage.saveUserPrefs(model.getUserPrefs());
storage.saveAddressBook(model.getAddressBook(), true);
} catch (IOException e) {
logger.severe("Failed to save preferences " + StringUtil.getDetails(e));
}
}
}
|
/* Licensed under Apache-2.0 2021. */
package io.jyde.aws.athena.connectors.udf.h3;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import com.uber.h3core.AreaUnit;
import com.uber.h3core.H3Core;
import com.uber.h3core.exceptions.DistanceUndefinedException;
import com.uber.h3core.exceptions.LineUndefinedException;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
public class H3AthenaUDFHandlerTest {
private static final Double lat = 0.;
private static final Double lng = 0.;
private static final Integer res = 11;
private static final Long h3 = 628064021095030783L;
private static final Long secondH3 = 628064007838769151L;
private static final String h3address = "8b754e649929fff";
private static final String secondH3Address = "8b754e333701fff";
private static final Integer k = 3;
private static final String unit = "m2";
private H3AthenaUDFHandler handler;
private H3Core h3Core;
private Long nearbyH3WithDifferentResolution;
private String nearbyH3AddressWithDifferentResolution;
private Long tooFarAwayH3;
private String tooFarAwayH3Address;
@Before
public void setup() throws IOException {
this.handler = new H3AthenaUDFHandler();
this.h3Core = H3Core.newInstance();
this.nearbyH3WithDifferentResolution = h3Core.geoToH3(lat + 0.0001, lng + 0.0001, res - 1);
this.nearbyH3AddressWithDifferentResolution =
h3Core.geoToH3Address(lat + 0.0001, lng + 0.0001, res - 1);
this.tooFarAwayH3 = h3Core.geoToH3(lat + 45., lng + 45., res);
this.tooFarAwayH3Address = h3Core.geoToH3Address(lat + 45., lng + 45., res);
}
@Test
public void h3_is_valid() {
assertEquals(h3Core.h3IsValid(h3), handler.h3_is_valid(h3));
}
@Test
public void h3_address_is_valid() {
assertEquals(h3Core.h3IsValid(h3address), handler.h3_is_valid(h3address));
}
@Test
public void h3_get_base_cell() {
assertEquals(h3Core.h3GetBaseCell(h3), handler.h3_get_base_cell(h3).intValue());
}
@Test
public void h3_address_get_base_cell() {
assertEquals(
h3Core.h3GetBaseCell(h3address), handler.h3_get_base_cell(h3address).intValue());
}
@Test
public void h3_is_pentagon() {
assertEquals(h3Core.h3IsPentagon(h3), handler.h3_is_pentagon(h3));
}
@Test
public void h3_address_is_pentagon() {
assertEquals(h3Core.h3IsPentagon(h3address), handler.h3_is_pentagon(h3address));
}
@Test
public void geo_to_h3() {
assertEquals(h3Core.geoToH3(lat, lng, res), handler.geo_to_h3(lat, lng, res).longValue());
}
@Test
public void geo_to_h3_address() {
assertEquals(
h3Core.geoToH3Address(lat, lng, res), handler.geo_to_h3_address(lat, lng, res));
}
@Test
public void k_ring() {
assertEquals(h3Core.kRing(h3, k), handler.k_ring(h3, k));
}
@Test
public void address_k_ring() {
assertEquals(h3Core.kRing(h3address, k), handler.k_ring(h3address, k));
}
@Test
public void h3_distance() throws DistanceUndefinedException {
assertEquals(h3Core.h3Distance(h3, secondH3), handler.h3_distance(h3, secondH3).intValue());
}
@Test
public void h3_distance_WithNullInput() {
assertNull(handler.h3_distance(h3, null));
}
@Test
public void h3_distance_TooFarApart() {
assertNull(handler.h3_distance(h3, tooFarAwayH3));
}
@Test
public void h3_distance_ResolutionMismatch() {
assertThrows(
RuntimeException.class,
() -> handler.h3_distance(h3, nearbyH3WithDifferentResolution));
}
@Test
public void h3_address_distance() throws DistanceUndefinedException {
assertEquals(
h3Core.h3Distance(h3address, secondH3Address),
handler.h3_distance(h3address, secondH3Address).intValue());
}
@Test
public void h3_address_distance_WithNullInput() {
assertNull(handler.h3_distance(h3address, null));
}
@Test
public void h3_address_distance_TooFarApart() {
assertNull(handler.h3_distance(h3address, tooFarAwayH3Address));
}
@Test
public void h3_address_distance_ResolutionMismatch() {
assertThrows(
RuntimeException.class,
() -> handler.h3_distance(h3address, nearbyH3AddressWithDifferentResolution));
}
@Test
public void h3_line() throws DistanceUndefinedException, LineUndefinedException {
assertArrayEquals(
h3Core.h3Line(h3, secondH3).toArray(), handler.h3_line(h3, secondH3).toArray());
}
@Test
public void h3_address_line() throws DistanceUndefinedException, LineUndefinedException {
assertArrayEquals(
h3Core.h3Line(h3address, secondH3Address).toArray(),
handler.h3_line(h3address, secondH3Address).toArray());
}
@Test
public void h3_get_resolution() {
assertEquals(h3Core.h3GetResolution(h3), handler.h3_get_resolution(h3).intValue());
}
@Test
public void h3_address_get_resolution() {
assertEquals(
h3Core.h3GetResolution(h3address), handler.h3_get_resolution(h3address).intValue());
}
@Test
public void h3_to_parent() {
assertEquals(h3Core.h3ToParent(h3, res), handler.h3_to_parent(h3, res).longValue());
}
@Test
public void h3_to_parent_address() {
assertEquals(
h3Core.h3ToParentAddress(h3address, res),
handler.h3_to_parent_address(h3address, res));
}
@Test
public void h3_to_children() {
assertArrayEquals(
h3Core.h3ToChildren(h3, res).toArray(), handler.h3_to_children(h3, res).toArray());
}
@Test
public void h3_address_to_children() {
assertEquals(h3Core.h3ToChildren(h3address, res), handler.h3_to_children(h3address, res));
}
@Test
public void h3_to_center_child() {
assertEquals(
h3Core.h3ToCenterChild(h3, res), handler.h3_to_center_child(h3, res).longValue());
}
@Test
public void h3_address_to_center_child() {
assertEquals(
h3Core.h3ToCenterChild(h3address, res), handler.h3_to_center_child(h3address, res));
}
@Test
public void h3_is_res_class_iii() {
assertEquals(h3Core.h3IsResClassIII(h3), handler.h3_is_res_class_iii(h3));
}
@Test
public void h3_address_is_res_class_iii() {
assertEquals(h3Core.h3IsResClassIII(h3address), handler.h3_is_res_class_iii(h3address));
}
@Test
public void h3_to_string() {
assertEquals(h3Core.h3ToString(h3), handler.h3_to_string(h3));
}
@Test
public void string_to_h3() {
assertEquals(h3Core.stringToH3(h3address), handler.string_to_h3(h3address).longValue());
}
@Test
public void cell_area() {
assertTrue(
almostEqual(
h3Core.cellArea(h3, AreaUnit.valueOf(unit)),
handler.cell_area(h3, unit).doubleValue(),
1e-8));
}
@Test
public void cell_address_area() {
assertTrue(
almostEqual(
h3Core.cellArea(h3address, AreaUnit.valueOf(unit)),
handler.cell_area(h3address, unit).doubleValue(),
1e-8));
}
private static boolean almostEqual(double a, double b, double eps) {
return Math.abs(a - b) < eps;
}
}
|
package com.resfeber.pool.api.controller;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.resfeber.pool.api.mapper.PoolWSMapper;
import com.resfeber.pool.api.mapper.PoolerWSMapper;
import com.resfeber.pool.api.mapper.UserWSMapper;
import com.resfeber.pool.api.util.UserContext;
import com.resfeber.pool.api.ws.PoolWS;
import com.resfeber.pool.api.ws.PoolerWS;
import com.resfeber.pool.api.ws.ResponseWS;
import com.resfeber.pool.api.ws.UserWS;
import com.resfeber.pool.service.PoolService;
import com.resfeber.pool.service.PoolerService;
import com.resfeber.pool.service.UserService;
import com.resfeber.pool.service.bean.PoolBean;
import com.resfeber.pool.service.bean.PoolerBean;
import com.resfeber.pool.service.bean.UserBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@Slf4j
@Component
@Path("/users")
@Api(value = "UserController", produces = "application/json")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserWSMapper userWSMapper;
@Autowired
private PoolService poolService;
@Autowired
private PoolWSMapper poolWSMapper;
@Autowired
private PoolerService poolerService;
@Autowired
private PoolerWSMapper poolerWSMapper;
@Autowired
private UserContext userContext;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response getLoggedInUserDetail() {
UserBean userBean = userContext.getCurrentUser().orElse(null);
return Response.status(202).entity(ResponseWS.builder().code(202).message("ACCEPTED").data(userWSMapper.fromSource(userBean)).build()).build();
}
@GET
@Path("{userId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response findByUuid(@PathParam("userId") String userId) {
UserBean userBean = userService.findByUuid(userId);
return Response.status(202).entity(ResponseWS.builder().code(202).message("ACCEPTED").data(userWSMapper.fromSource(userBean)).build()).build();
}
@ApiOperation(value = "Update user", response = ResponseWS.class)
@ApiResponses(value = {
@ApiResponse(code = 202, message = "ACCEPTED", response = UserWS.class)
})
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response update(UserWS userWS) {
UserBean userBean = userService.updatePhone(userWSMapper.toSource(userWS));
return Response.status(202).entity(ResponseWS.builder().code(202).message("ACCEPTED").data(userWSMapper.fromSource(userBean))).build();
}
@GET
@Path(("/pools"))
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response findPoolByUser() {
UserBean userBean = userContext.getCurrentUser().orElse(null);
List<PoolBean> pools = poolService.findByUserUuid(userBean.getUuid());
List<PoolWS> poolWSList = pools.stream().filter(p -> Objects.nonNull(p)).map(p -> poolWSMapper.fromSource(p)).collect(Collectors.toList());
return Response.status(200).entity(ResponseWS.builder().code(200).message("OK").data(poolWSList)).build();
}
@GET
@Path(("/trips"))
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response findTripsByUser() {
UserBean userBean = userContext.getCurrentUser().orElse(null);
List<PoolerBean> pools = poolerService.findByUserUuid(userBean.getUuid());
List<PoolerWS> poolerWSList = pools.stream().filter(p -> Objects.nonNull(p)).map(p -> poolerWSMapper.fromSource(p)).collect(Collectors.toList());
return Response.status(200).entity(ResponseWS.builder().code(200).message("OK").data(poolerWSList).build()).build();
}
}
|
package it.loreii.AppSyslogd;
import java.net.InetAddress;
import java.text.ParseException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.time.FastDateFormat;
/**
* Simple match
*/
public final class SyslogMsg {
/**
* Simple regexp for matching the first part of protocol definition RFC3164 This
* version SHALL not be anymore used but still present into the web
* https://tools.ietf.org/html/rfc3164
*
* PRI VERSION TIMESTAMP HOSTNAME MSG
*/
private final static String regex_rfc3164 = "^\\<([0-9]{1,3})\\>([A-Za-z]{3}[\\s]+[0-9]{1,2} \\d{2}:\\d{2}:\\d{2}) ([\\S]+) ([\\S\\s]+)";
private final static FastDateFormat dateFormat_rfc3164 = FastDateFormat.getInstance("MMM dd HH:mm:ss"); //TODO use something smarter and parse directly it
private final static FastDateFormat dateFormat_rfc3164_2 = FastDateFormat.getInstance("MMM d HH:mm:ss");
private final static Pattern pattern_rfc3164 = Pattern.compile(regex_rfc3164);
/**
* Simple matcher for RFC-5424, identify the main parts as groups
* https://tools.ietf.org/html/rfc5424
*
* PRI VERSION TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA [MSG]
*/
private final static String regex_rfc5424 = "^\\<([0-9]{1,3})\\>(\\d{0,2}) (\\-|[\\S]+) (\\-|[\\S]{1,255}) (\\-|[\\S]{1,48}) (\\-|[\\S]{1,128}) (\\-|[\\S]{1,32}) (\\-|\\[[\\S\\s]+\\]) ([\\S\\s]+){0,1}";
private final static FastDateFormat dateFormat_rfc5424 = FastDateFormat.getInstance("yyyy-MM-DD'T'HH:mm:ss.SSS'Z'"); //TODO handle timezone
private final static Pattern pattern_rfc5424 = Pattern.compile(regex_rfc5424);
public static Data match(String input) throws NumberFormatException, ParseException {
try {
Matcher m = pattern_rfc5424.matcher(input);
m.find();
return Data.makeDataRFC5424(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)),
dateFormat_rfc5424.parse(m.group(3)), m.group(4), m.group(5), m.group(6), m.group(7), m.group(8),
m.group(9));
} catch (java.lang.IllegalStateException e) {
Matcher m = pattern_rfc3164.matcher(input);
m.find();
Data data;
try {
data = Data.makeDataRFC3164(Integer.parseInt(m.group(1)), dateFormat_rfc3164.parse(m.group(2)), m.group(3), m.group(4));
}catch (Exception ex) {
data = Data.makeDataRFC3164(Integer.parseInt(m.group(1)), dateFormat_rfc3164_2.parse(m.group(2)), m.group(3), m.group(4));
}
return data;
}
}
/**
* Syslog data container
* */
static class Data {
private InetAddress address;
int port;
Integer pri;
Integer version;
Date timestamp;
Date createdAt;
String hostname;
String appName;
String procId;
String msgId;
String structuredData;
String msg;
public static Data makeDataRFC3164(Integer pri, Date timestamp, String hostname, String msg) {
return new Data(pri, timestamp, hostname, msg);
}
public static Data makeDataRFC5424(Integer pri, Integer version, Date timestamp, String hostname,
String appName, String procId, String msgId, String structuredData, String msg) {
return new Data(pri, version, timestamp, hostname, appName, procId, msgId, structuredData, msg);
}
public Data() {
//for JPA
}
private Data(Integer pri, Integer version, Date timestamp, String hostname, String appName, String procId,
String msgId, String structuredData, String msg) {
super();
this.pri = pri;
this.version = version;
this.timestamp = timestamp;
this.hostname = hostname;
this.appName = appName;
this.procId = procId;
this.msgId = msgId;
this.structuredData = structuredData;
this.msg = msg;
this.createdAt = new Date();
}
private Data(Integer pri, Date timestamp, String hostname, String msg) {
this(pri, null, timestamp, hostname, null, null, null, null, msg);
}
public Integer getPri() {
return pri;
}
public Integer getVersion() {
return version;
}
public Date getTimestamp() {
return timestamp;
}
public String getHostname() {
return hostname;
}
public String getAppName() {
return appName;
}
public String getProcId() {
return procId;
}
public String getMsgId() {
return msgId;
}
public String getStructuredData() {
return structuredData;
}
public String getMsg() {
return msg;
}
public InetAddress getAddress() {
return address;
}
public void setAddress(InetAddress address) {
this.address = address;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public Date getCreatedAt() {
return createdAt;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Data [");
if (address != null)
builder.append("address=").append(address).append(", ");
builder.append("port=").append(port).append(", ");
if (pri != null)
builder.append("pri=").append(pri).append(", ");
if (version != null)
builder.append("version=").append(version).append(", ");
if (timestamp != null)
builder.append("timestamp=").append(timestamp).append(", ");
if (hostname != null)
builder.append("hostname=").append(hostname).append(", ");
if (appName != null)
builder.append("appName=").append(appName).append(", ");
if (procId != null)
builder.append("procId=").append(procId).append(", ");
if (msgId != null)
builder.append("msgId=").append(msgId).append(", ");
if (structuredData != null)
builder.append("structuredData=").append(structuredData).append(", ");
if (msg != null)
builder.append("msg=").append(msg);
builder.append("]");
return builder.toString();
}
}
}
|
package com.mwcc.pedidovenda.controller;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import com.mwcc.pedidovenda.model.Cliente;
import com.mwcc.pedidovenda.model.Endereco;
import com.mwcc.pedidovenda.model.TipoPessoa;
import com.mwcc.pedidovenda.repository.ClienteRepository;
import com.mwcc.pedidovenda.service.CadastroClienteService;
@Named
@ViewScoped
public class CadastroClienteBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Cliente cliente;
private Endereco endereco;
private String mascara;
List<Endereco> enderecos;
// private List<Endereco> enderecos;
@Inject
private CadastroClienteService cadastroClienteService;
@Inject
private ClienteRepository clienteRepository;
public void inicializar() {
if (this.cliente == null) {
limpar();
}
}
public void salvar() {
cliente = cadastroClienteService.salvar(cliente);
limpar();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Salvo com sucesso."));
}
public void incluirEndereco() {
enderecos = new ArrayList<>();
enderecos.add(endereco);
cliente.setEnderecos(enderecos);
}
public void excluir() {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Excluído com sucesso!",
"Excluído com sucesso!");
context.addMessage("msgInfo", msg);
}
public boolean isFisica() {
TipoPessoa tipoPessoa = TipoPessoa.FISICA;
if (cliente.getTipo() != null && cliente.getTipo() != tipoPessoa) {
return false;
} else {
return true;
}
}
public boolean isJuridica() {
TipoPessoa tipoPessoa = TipoPessoa.JURIDICA;
if (cliente.getTipo() != null && cliente.getTipo() == tipoPessoa) {
return true;
} else {
return false;
}
}
public void mudarMascara() {
TipoPessoa tipoPessoa = TipoPessoa.FISICA;
if (cliente == null) {
limpar();
} else {
inicializar();
if (cliente.getTipo() != null && cliente.getTipo().equals(tipoPessoa)) {
mascara = "999.999.999-99";
} else {
if (cliente.getTipo() != null && !cliente.getTipo().equals(tipoPessoa)) {
mascara = "99.999.999/9999-99";
}
}
}
}
public void limpar() {
cliente = new Cliente();
endereco = new Endereco();
mascara = "999.999.999-99";
isFisica();
enderecos = new ArrayList<>();
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
if(this.cliente != null) {
mudarMascara();
}
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
public String getMascara() {
return mascara;
}
public void setMascara(String mascara) {
this.mascara = mascara;
}
public boolean isEditando() {
return cliente.getId() != null;
}
}
|
package com.deenysoft.schoolbox.dashboard.model;
/**
* Created by shamsadam on 23/06/16.
*/
public class ExamBoxItem {
public static final String TAG = "ExamBoxItem";
String ExamID;
String ExamTitle;
String ExamDate;
String ExamVenue;
String ExamTime;
String ExamStatus;
public void setExamID(String ExamID) {
this.ExamID = ExamID;
}
public String getExamID(){
return ExamID;
}
public void setExamTitle(String ExamTitle) {
this.ExamTitle = ExamTitle;
}
public String getExamTitle(){
return ExamTitle;
}
public void setExamDate(String ExamDate) {
this.ExamDate = ExamDate;
}
public String getExamDate(){
return ExamDate;
}
public void setExamVenue(String ExamVenue) {
this.ExamVenue = ExamVenue;
}
public String getExamVenue() {
return ExamVenue;
}
public void setExamTime(String ExamTime) {
this.ExamTime = ExamTime;
}
public String getExamTime() {
return ExamTime;
}
public void setExamStatus(String ExamStatus) {
this.ExamStatus = ExamStatus;
}
public String getExamStatus() {
return ExamStatus;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ExamID: "+ExamID);
builder.append("\n");
builder.append("ExamTitle: "+ExamTitle);
builder.append("\n");
builder.append("ExamDate: "+ExamDate);
builder.append("\n");
builder.append("Venue: "+ExamVenue);
builder.append("\n");
builder.append("Time: "+ExamTime);
builder.append("\n\n");
return builder.toString();
}
}
|
package js.wood;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ForwardFilterTest {
@Mock
private ServletContext servletContext;
@Mock
private HttpServletRequest request;
@Mock
private ServletResponse response;
@Mock
private FilterChain chain;
private File projectRoot;
@Before
public void beforeTest() {
projectRoot = new File("src/test/resources/forward-filter");
}
@Test
public void GivenInitParameter_WhenInit_ThenSetInternalState() throws ServletException {
// given
FilterConfig config = mock(FilterConfig.class);
when(config.getServletContext()).thenReturn(servletContext);
when(servletContext.getContextPath()).thenReturn("/test-preview");
when(servletContext.getInitParameter("PROJECT_DIR")).thenReturn(".");
// when
ForwardFilter filter = new ForwardFilter();
filter.init(config);
// then
assertThat(filter.getServletContext(), equalTo(servletContext));
assertThat(filter.getPreviewContextPath(), equalTo("/test-preview"));
assertThat(filter.getBuildContextName(), equalTo("/test"));
assertThat(filter.getProjectRoot(), notNullValue());
assertThat(filter.getProjectRoot(), equalTo(new File(".")));
assertThat(filter.getRequestPathMatcher(), notNullValue());
}
@Test
public void GivenUrlPatternsInitParameter_WhenInit_ThenRequestPathMatches() throws ServletException {
// given
FilterConfig config = mock(FilterConfig.class);
when(config.getServletContext()).thenReturn(servletContext);
when(config.getInitParameter("URL_PATTERNS")).thenReturn("*.rmi");
when(servletContext.getContextPath()).thenReturn("/test-preview");
when(servletContext.getInitParameter("PROJECT_DIR")).thenReturn(".");
// when
ForwardFilter filter = new ForwardFilter();
filter.init(config);
// then
Matchers requestPathMatcher = filter.getRequestPathMatcher();
assertTrue(requestPathMatcher.match("site/Controller/test.rmi"));
}
@Test
public void GivenRequestUriMatchPattern_WhenDoFilter_ThenForwardToBuildContext() throws IOException, ServletException {
// given
when(request.getRequestURI()).thenReturn("/test-preview/res/compos/dialogs/sixqs/site/controller/MainController/getCategoriesSelect.rmi");
ServletContext buildContext = mock(ServletContext.class);
when(servletContext.getContext(null)).thenReturn(buildContext);
RequestDispatcher dispatcher = mock(RequestDispatcher.class);
when(buildContext.getRequestDispatcher("/sixqs/site/controller/MainController/getCategoriesSelect.rmi")).thenReturn(dispatcher);
ForwardFilter filter = new ForwardFilter(servletContext, "/test-preview", projectRoot);
filter.getRequestPathMatcher().addPattern("*.rmi");
// when
filter.doFilter(request, response, chain);
// then
verify(dispatcher, times(1)).forward(request, response);
}
@Test
public void GivenRequestUriDoNotMatchPattern_WhenDoFilter_ThenChainToPreviewContext() throws IOException, ServletException {
// given
when(request.getRequestURI()).thenReturn("/test-preview/res/compo");
ForwardFilter filter = new ForwardFilter(servletContext, "/test-preview", projectRoot);
filter.getRequestPathMatcher().addPattern("*.rmi");
// when
filter.doFilter(request, response, chain);
// then
verify(chain, times(1)).doFilter(request, response);
}
@Test(expected = WoodException.class)
public void GivenMissingBuildContext_WhenDoFilter_ThenWoodException() throws IOException, ServletException {
// given
when(request.getRequestURI()).thenReturn("/test-preview/res/compos/dialogs/sixqs/site/controller/MainController/getCategoriesSelect.rmi");
ForwardFilter filter = new ForwardFilter(servletContext, "/test-preview", projectRoot);
filter.getRequestPathMatcher().addPattern("*.rmi");
// when
filter.doFilter(request, response, chain);
// then
}
@Test
public void GivenRequestUriForBuildContext_WhenForwardPath_ThenReturnRmiMethodPath() {
// given
String requestURI = "res/compos/dialogs/sixqs/site/controller/MainController/getCategoriesSelect.rmi";
// when
String forwardPath = ForwardFilter.forwardPath(projectRoot, requestURI);
// then
assertThat(forwardPath, equalTo("/sixqs/site/controller/MainController/getCategoriesSelect.rmi"));
}
}
|
/* Generated By:JJTree: Do not edit this line. ASTDefaultValue.java */
package net.sourceforge.pmd.ast;
public class ASTDefaultValue extends SimpleJavaNode {
public ASTDefaultValue(int id) {
super(id);
}
public ASTDefaultValue(JavaParser p, int id) {
super(p, id);
}
/**
* Accept the visitor. *
*/
public Object jjtAccept(JavaParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package tests.unit.com.microsoft.azure.iothub.transport.mqtt;
import com.microsoft.azure.iothub.DeviceClientConfig;
import com.microsoft.azure.iothub.IotHubStatusCode;
import com.microsoft.azure.iothub.Message;
import com.microsoft.azure.iothub.auth.IotHubSasToken;
import com.microsoft.azure.iothub.net.IotHubUri;
import com.microsoft.azure.iothub.transport.TransportUtils;
import com.microsoft.azure.iothub.transport.mqtt.MqttIotHubConnection;
import mockit.Deencapsulation;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import mockit.Verifications;
import org.eclipse.paho.client.mqttv3.*;
import org.junit.Test;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Queue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/** Unit tests for MqttIotHubConnection. */
public class MqttIotHubConnectionTest
{
private static String sslPrefix = "ssl://";
private static String sslPortSuffix = ":8883";
final String iotHubHostName = "test.host.name";
final String hubName = "test.iothub";
final String deviceId = "test-deviceId";
final String deviceKey = "test-devicekey?&test";
final String resourceUri = "test-resource-uri";
final int qos = 1;
final String publishTopic = "devices/test-deviceId/messages/events/";
final String subscribeTopic = "devices/test-deviceId/messages/devicebound/#";
@Mocked
protected DeviceClientConfig mockConfig;
@Mocked
protected MqttAsyncClient mockMqttAsyncClient;
@Mocked
protected IMqttToken mockMqttToken;
@Mocked
protected IMqttDeliveryToken mockMqttDeliveryToken;
@Mocked
protected IotHubSasToken mockToken;
@Mocked
protected MqttMessage mockMqttMessage;
@Mocked
IotHubUri mockIotHubUri;
// Tests_SRS_MQTTIOTHUBCONNECTION_15_001: [The constructor shall save the configuration.]
@Test
public void constructorSavesCorrectConfig() throws IOException {
baseExpectations();
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
DeviceClientConfig actualClientConfig = Deencapsulation.getField(connection, "config");
DeviceClientConfig expectedClientConfig = mockConfig;
assertEquals(expectedClientConfig, actualClientConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_002: [The constructor shall create the publish and subscribe
// topic for the specified device id.]
@Test
public void constructorCreatesPublishAndSubscribeTopics(){
this.baseExpectations();
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
String publishTopic = Deencapsulation.getField(connection, "publishTopic");
String subscribeTopic = Deencapsulation.getField(connection, "subscribeTopic");
assertEquals(this.publishTopic, publishTopic);
assertEquals(this.subscribeTopic, subscribeTopic);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_003: [The constructor shall throw a new IllegalArgumentException
// if any of the parameters of the configuration is null or empty.]
@Test(expected = IllegalArgumentException.class)
public void constructorThrowsIllegalArgumentExceptionIfHostNameIsEmpty(){
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname();
result = "";
mockConfig.getIotHubName();
result = hubName;
mockConfig.getDeviceId();
result = deviceId;
mockConfig.getDeviceKey();
result = deviceKey;
}
};
new MqttIotHubConnection(mockConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_003: [The constructor shall throw a new IllegalArgumentException
// if any of the parameters of the configuration is null or empty.]
@Test(expected = IllegalArgumentException.class)
public void constructorThrowsIllegalArgumentExceptionIfHostNameIsNull(){
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname();
result = null;
mockConfig.getIotHubName();
result = hubName;
mockConfig.getDeviceId();
result = deviceId;
mockConfig.getDeviceKey();
result = deviceKey;
}
};
new MqttIotHubConnection(mockConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_003: [The constructor shall throw a new IllegalArgumentException
// if any of the parameters of the configuration is null or empty.]
@Test(expected = IllegalArgumentException.class)
public void constructorThrowsIllegalArgumentExceptionIfDeviceIDIsEmpty(){
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname();
result = iotHubHostName;
mockConfig.getIotHubName();
result = hubName;
mockConfig.getDeviceId();
result = "";
mockConfig.getDeviceKey();
result = deviceKey;
}
};
new MqttIotHubConnection(mockConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_003: [The constructor shall throw a new IllegalArgumentException
// if any of the parameters of the configuration is null or empty.]
@Test(expected = IllegalArgumentException.class)
public void constructorThrowsIllegalArgumentExceptionIfDeviceIDIsNull(){
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname();
result = iotHubHostName;
mockConfig.getIotHubName();
result = hubName;
mockConfig.getDeviceId();
result = null;
mockConfig.getDeviceKey();
result = deviceKey;
}
};
new MqttIotHubConnection(mockConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_003: [The constructor shall throw a new IllegalArgumentException
// if any of the parameters of the configuration is null or empty.]
@Test(expected = IllegalArgumentException.class)
public void constructorThrowsIllegalArgumentExceptionIfUserNameIsEmpty(){
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname();
result = iotHubHostName;
mockConfig.getIotHubName();
result = hubName;
mockConfig.getDeviceId();
result = deviceId;
mockConfig.getDeviceKey();
result = "";
}
};
new MqttIotHubConnection(mockConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_003: [The constructor shall throw a new IllegalArgumentException
// if any of the parameters of the configuration is null or empty.]
@Test(expected = IllegalArgumentException.class)
public void constructorThrowsIllegalArgumentExceptionIfUserNameIsNull(){
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname();
result = iotHubHostName;
mockConfig.getIotHubName();
result = hubName;
mockConfig.getDeviceId();
result = deviceId;
mockConfig.getDeviceKey();
result = null;
}
};
new MqttIotHubConnection(mockConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_003: [The constructor shall throw a new IllegalArgumentException
// if any of the parameters of the configuration is null or empty.]
@Test(expected = IllegalArgumentException.class)
public void constructorThrowsIllegalArgumentExceptionIfSasTokenIsEmpty(){
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname();
result = iotHubHostName;
mockConfig.getIotHubName();
result = "";
mockConfig.getDeviceId();
result = deviceId;
mockConfig.getDeviceKey();
result = deviceKey;
}
};
new MqttIotHubConnection(mockConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_003: [The constructor shall throw a new IllegalArgumentException
// if any of the parameters of the configuration is null or empty.]
@Test(expected = IllegalArgumentException.class)
public void constructorThrowsIllegalArgumentExceptionIfSasTokenIsNull(){
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname();
result = iotHubHostName;
mockConfig.getIotHubName();
result = null;
mockConfig.getDeviceId();
result = deviceId;
mockConfig.getDeviceKey();
result = deviceKey;
}
};
new MqttIotHubConnection(mockConfig);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_004: [The function shall establish an MQTT connection with an IoT Hub
// using the provided host name, user name, device ID, and sas token.]
@Test
public void openEstablishesConnectionUsingCorrectConfig() throws IOException, MqttException
{
baseExpectations();
openExpectations();
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
MqttConnectOptions actualConnectionOptions = Deencapsulation.getField(connection, "connectionOptions");
String clientIdentifier = "DeviceClientType=" + URLEncoder.encode(TransportUtils.javaDeviceClientIdentifier + TransportUtils.clientVersion, "UTF-8");
assertEquals(iotHubHostName + "/" + deviceId + "/" + clientIdentifier, actualConnectionOptions.getUserName());
String expectedSasToken = mockToken.toString();
String actualUserPassword = new String(actualConnectionOptions.getPassword());
assertEquals(expectedSasToken, actualUserPassword);
MqttIotHubConnection.ConnectionState expectedState = MqttIotHubConnection.ConnectionState.OPEN;
MqttIotHubConnection.ConnectionState actualState = Deencapsulation.getField(connection, "state");
assertEquals(expectedState, actualState);
new Verifications()
{
{
new MqttAsyncClient(sslPrefix + iotHubHostName + sslPortSuffix, deviceId, (MqttClientPersistence) any);
new MqttConnectOptions();
mockMqttAsyncClient.connect(actualConnectionOptions);
mockMqttAsyncClient.subscribe(subscribeTopic, qos);
}
};
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_005: [If an MQTT connection is unable to be established for any reason,
// the function shall throw an IOException.]
@Test(expected = IOException.class)
public void openThrowsIOExceptionIfConnectionFails() throws IOException, MqttException {
baseExpectations();
new NonStrictExpectations()
{
{
IotHubUri.getResourceUri(iotHubHostName, deviceId);
result = resourceUri;
new IotHubSasToken(resourceUri, deviceId, deviceKey, anyLong);
result = mockToken;
new MqttAsyncClient(sslPrefix + iotHubHostName + sslPortSuffix, deviceId, (MqttClientPersistence) any);
result = new MqttException(anyInt);
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_006: [If the MQTT connection is already open, the function shall do nothing.]
@Test
public void openDoesNothingIfAlreadyOpened() throws IOException, MqttException
{
baseExpectations();
openExpectations();
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
connection.open();
new Verifications()
{
{
new MqttAsyncClient(sslPrefix + iotHubHostName + sslPortSuffix, deviceId, (MqttClientPersistence) any); times = 1;
}
};
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_005: [The function shall close the MQTT connection.]
@Test
public void closeClosesMqttConnection() throws Exception
{
baseExpectations();
openExpectations();
new NonStrictExpectations()
{
{
mockMqttAsyncClient.unsubscribe(subscribeTopic);
result = mockMqttToken;
result = null;
mockMqttAsyncClient.disconnect();
result = mockMqttToken;
result = null;
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
connection.close();
MqttIotHubConnection.ConnectionState expectedState = MqttIotHubConnection.ConnectionState.CLOSED;
MqttIotHubConnection.ConnectionState actualState = Deencapsulation.getField(connection, "state");
assertEquals(expectedState, actualState);
MqttAsyncClient actualClient = Deencapsulation.getField(connection, "asyncClient");
assertNull(actualClient);
new Verifications()
{
{
mockMqttAsyncClient.disconnect();
}
};
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_007: [If the MQTT connection is closed, the function shall do nothing.]
@Test
public void closeDoesNothingIfConnectionNotYetOpened() throws Exception
{
baseExpectations();
new NonStrictExpectations()
{
{
mockMqttAsyncClient.unsubscribe(subscribeTopic);
result = mockMqttToken;
result = null;
mockMqttAsyncClient.disconnect();
result = mockMqttToken;
result = null;
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.close();
MqttIotHubConnection.ConnectionState expectedState = MqttIotHubConnection.ConnectionState.CLOSED;
MqttIotHubConnection.ConnectionState actualState = Deencapsulation.getField(connection, "state");
assertEquals(expectedState, actualState);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_007: [If the MQTT connection is closed, the function shall do nothing.]
@Test
public void closeDoesNothingIfConnectionAlreadyClosed() throws Exception
{
baseExpectations();
openExpectations();
new NonStrictExpectations()
{
{
mockMqttAsyncClient.unsubscribe(subscribeTopic);
result = mockMqttToken;
result = null;
mockMqttAsyncClient.disconnect();
result = mockMqttToken;
result = null;
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
connection.close();
connection.close();
new Verifications()
{
{
mockMqttAsyncClient.disconnect(); times = 1;
}
};
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_008: [The function shall send an event message to the IoT Hub
// given in the configuration.]
// Tests_SRS_MQTTIOTHUBCONNECTION_15_009: [The function shall send the message payload.]
// Tests_SRS_MQTTIOTHUBCONNECTION_15_011: [If the message was successfully received by the service,
// the function shall return status code OK_EMPTY.]
@Test
public void sendEventPublishesEventCorrectlyToIotHub(@Mocked final Message mockMsg) throws IOException, MqttException
{
baseExpectations();
openExpectations();
final byte[] msgBody = { 0x61, 0x62, 0x63 };
new NonStrictExpectations()
{
{
mockMsg.getBytes();
result = msgBody;
new MqttMessage(msgBody);
result = mockMqttMessage;
mockMqttAsyncClient.publish(publishTopic, mockMqttMessage);
result = mockMqttDeliveryToken;
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
IotHubStatusCode result = connection.sendEvent(mockMsg);
assertEquals(IotHubStatusCode.OK_EMPTY, result);
new Verifications()
{
{
new MqttMessage(msgBody);
mockMqttMessage.setQos(qos);
mockMqttAsyncClient.publish(publishTopic, (MqttMessage) any);
}
};
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_010: [If the message is null or empty,
// the function shall return status code BAD_FORMAT.]
@Test
public void sendEventReturnsBadFormatIfMessageIsNull() throws IOException, MqttException
{
baseExpectations();
openExpectations();
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
IotHubStatusCode result = connection.sendEvent(null);
assertEquals(IotHubStatusCode.BAD_FORMAT, result);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_010: [If the message is null or empty,
// the function shall return status code BAD_FORMAT.]
@Test
public void sendEventReturnsBadFormatIfMessageHasNullBody(@Mocked final Message mockMsg) throws IOException, MqttException
{
baseExpectations();
openExpectations();
new NonStrictExpectations()
{
{
mockMsg.getBytes();
result = null;
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
IotHubStatusCode result = connection.sendEvent(null);
assertEquals(IotHubStatusCode.BAD_FORMAT, result);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_010: [If the message is null or empty,
// the function shall return status code BAD_FORMAT.]
@Test
public void sendEventReturnsBadFormatIfMessageHasEmptyBody(@Mocked final Message mockMsg) throws IOException, MqttException
{
baseExpectations();
new NonStrictExpectations()
{
{
mockMsg.getBytes();
result = new byte[0];
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
IotHubStatusCode result = connection.sendEvent(mockMsg);
assertEquals(IotHubStatusCode.BAD_FORMAT, result);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_013: [If the MQTT connection is closed,
// the function shall throw an IllegalStateException.]
@Test(expected = IllegalStateException.class)
public void sendEventFailsIfConnectionNotYetOpened(@Mocked final Message mockMsg) throws IOException
{
baseExpectations();
final byte[] msgBody = { 0x61, 0x62, 0x63 };
new NonStrictExpectations()
{
{
mockMsg.getBytes();
result = msgBody;
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.sendEvent(mockMsg);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_013: [If the MQTT connection is closed,
// the function shall throw an IllegalStateException.]
@Test(expected = IllegalStateException.class)
public void sendEventFailsIfConnectionClosed(@Mocked final Message mockMsg) throws IOException
{
baseExpectations();
final byte[] msgBody = { 0x61, 0x62, 0x63 };
new NonStrictExpectations()
{
{
mockMsg.getBytes();
result = msgBody;
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
connection.close();
connection.sendEvent(mockMsg);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_012: [If the message was not successfully received by the service,
// the function shall return status code ERROR.]
@Test
public void sendEventReturnsErrorIfMessageNotReceived(@Mocked final Message mockMsg) throws IOException, MqttException
{
baseExpectations();
final byte[] msgBody = { 0x61, 0x62, 0x63 };
new NonStrictExpectations()
{
{
mockMsg.getBytes();
result = msgBody;
new MqttMessage(msgBody);
result = mockMqttMessage;
mockMqttAsyncClient.publish(publishTopic, mockMqttMessage);
result = new MqttException(anyInt);
}
};
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
IotHubStatusCode actualStatus = connection.sendEvent(mockMsg);
IotHubStatusCode expectedStatus = IotHubStatusCode.ERROR;
assertEquals(expectedStatus, actualStatus);
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_014: [The function shall attempt to consume a message
// from the received messages queue.]
@Test
public void receiveMessageConsumesAMessageFromReceivedQueue() throws IOException, MqttException
{
baseExpectations();
openExpectations();
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
Queue<Message> receivedMessagesQueue = Deencapsulation.getField(connection, "receivedMessagesQueue");
byte[] expectedMessageBody = { 0x61, 0x62, 0x63 };
receivedMessagesQueue.add(new Message(expectedMessageBody));
Message message = connection.receiveMessage();
byte[] actualMessageBody = message.getBytes();
for (int i = 0; i < expectedMessageBody.length; i++)
{
assertEquals(expectedMessageBody[i], actualMessageBody[i]);
}
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_015: [If the MQTT connection is closed,
// the function shall throw an IllegalStateException.]
@Test(expected = IllegalStateException.class)
public void receiveMessageFailsIfConnectionClosed(@Mocked final Message mockMsg) throws IOException
{
baseExpectations();
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.receiveMessage();
}
// Tests_SRS_MQTTIOTHUBCONNECTION_15_015: [If the MQTT connection is closed,
// the function shall throw an IllegalStateException.]
@Test(expected = IllegalStateException.class)
public void receiveMessageFailsIfConnectionAlreadyClosed(@Mocked final Message mockMsg) throws IOException
{
baseExpectations();
MqttIotHubConnection connection = new MqttIotHubConnection(mockConfig);
connection.open();
connection.close();
connection.receiveMessage();
}
private void baseExpectations()
{
new NonStrictExpectations() {
{
mockConfig.getIotHubHostname(); result = iotHubHostName;
mockConfig.getIotHubName(); result = hubName;
mockConfig.getDeviceId(); result = deviceId;
mockConfig.getDeviceKey(); result = deviceKey;
}
};
}
private void openExpectations() throws MqttException
{
new NonStrictExpectations()
{
{
IotHubUri.getResourceUri(iotHubHostName, deviceId);
result = resourceUri;
new IotHubSasToken(resourceUri, deviceId, deviceKey, anyLong);
result = mockToken;
new MqttAsyncClient(sslPrefix + iotHubHostName + sslPortSuffix, deviceId, (MqttClientPersistence) any);
result = mockMqttAsyncClient;
mockMqttAsyncClient.connect();
result = mockMqttToken;
mockMqttAsyncClient.subscribe(anyString, anyInt);
result = mockMqttToken;
}
};
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|filter
operator|.
name|function
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|filter
operator|.
name|FunctionCallExpression
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|activemq
operator|.
name|filter
operator|.
name|MessageEvaluationContext
import|;
end_import
begin_comment
comment|/** * Interface required for objects that will be registered as functions for use in selectors. Handles parse- * time and evaluation-time operations. */
end_comment
begin_interface
specifier|public
interface|interface
name|FilterFunction
block|{
comment|/** * Check whether the function, as it is used, is valid. Checking arguments here will return errors * to clients at the time invalid selectors are initially specified, rather than waiting until the selector is * applied to a message. * * @param FunctionCallExpression expr - the full expression of the function call, as used. * @return true - if the function call is valid; false - otherwise. */
specifier|public
name|boolean
name|isValid
parameter_list|(
name|FunctionCallExpression
name|expr
parameter_list|)
function_decl|;
comment|/** * Determine whether the function, as it will be called, returns a boolean value. Called during * expression parsing after the full expression for the function call, including its arguments, has * been parsed. This allows functions with variable return types to function as boolean expressions in * selectors without sacrificing parse-time checking. * * @param FunctionCallExpression expr - the full expression of the function call, as used. * @return true - if the function returns a boolean value for its use in the given expression; * false - otherwise. */
specifier|public
name|boolean
name|returnsBoolean
parameter_list|(
name|FunctionCallExpression
name|expr
parameter_list|)
function_decl|;
comment|/** * Evaluate the function call in the given context. The arguments must be evaluated, as-needed, by the * function. Note that boolean expressions must return Boolean objects. * * @param FunctionCallExpression expr - the full expression of the function call, as used. * @param MessageEvaluationContext message - the context within which to evaluate the call. */
specifier|public
name|Object
name|evaluate
parameter_list|(
name|FunctionCallExpression
name|expr
parameter_list|,
name|MessageEvaluationContext
name|message
parameter_list|)
throws|throws
name|javax
operator|.
name|jms
operator|.
name|JMSException
function_decl|;
block|}
end_interface
end_unit
|
class Solution {
public int findNumberOfLIS(int[] nums) {
int len = nums.length, max_l = 0, ans = 0;
int[] dp = new int[len], cnt = new int[len];
for(int i = 0;i < len;i ++) {
dp[i] = cnt[i] = 1;
for(int j = 0;j < i;j ++) {
if(nums[i] > nums[j]) {
if(dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
cnt[i] = cnt[j];
}else if(dp[j] + 1 == dp[i]) {
cnt[i] += cnt[j];
}
}
}
max_l = Math.max(max_l, dp[i]);
}
for(int i = 0;i < len;i ++) {
if(dp[i] == max_l) ans += cnt[i];
}
return ans;
}
}
|
package ru.intertrust.cm.core.business.impl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.healthmarketscience.rmiio.RemoteInputStream;
import com.healthmarketscience.rmiio.RemoteInputStreamClient;
import ru.intertrust.cm.core.business.api.AttachmentService;
import ru.intertrust.cm.core.business.api.dto.DomainObject;
import ru.intertrust.cm.core.business.api.dto.IdentifiableObject;
import ru.intertrust.cm.core.business.api.dto.IdentifiableObjectCollection;
import ru.intertrust.cm.core.business.api.dto.impl.RdbmsId;
import ru.intertrust.cm.core.dao.access.AccessControlService;
import ru.intertrust.cm.core.dao.access.AccessToken;
import ru.intertrust.cm.core.dao.api.CollectionsDao;
import ru.intertrust.cm.core.dao.api.CurrentDataSourceContext;
import ru.intertrust.cm.core.dao.api.DomainObjectDao;
import ru.intertrust.cm.core.model.ReportServiceException;
import ru.intertrust.cm.core.service.api.ReportTemplateCache;
public class ReportTemplateCacheImpl implements ReportTemplateCache{
@Value("${report.template.cache}")
private String reportCachePath;
@Autowired
protected CollectionsDao collectionsDao;
@Autowired
protected DomainObjectDao domainObjectDao;
@Autowired
protected AccessControlService accessControlService;
@Autowired
protected AttachmentService attachmentService;
@Autowired
private CurrentDataSourceContext currentDataSourceContext;
@Override
public File getTemplateFolder(DomainObject reportTemplateDo) throws IOException {
//Проверка есть директория для данного отчета в файловой системе, и если есть то проверка даты ее создания
final String originalDatasource = currentDataSourceContext.get();
currentDataSourceContext.setToMaster(); // read reports from MASTER DATASOURCE as slave might be outdated
//Получение директории с шаблонами
File templateFolder = new File(reportCachePath, reportTemplateDo.getString("name"));
boolean dirCreated = false;
if (!templateFolder.exists()) {
templateFolder.mkdirs();
dirCreated = true;
}
//Сравнение даты изменения директории и даты создания доменного объекта шаблонов отчета
if (dirCreated || templateFolder.lastModified() < reportTemplateDo.getModifiedDate().getTime()) {
//Шаблоны требуют перезачитывания
//Удаляем все содержимое папки
File[] files = templateFolder.listFiles();
for (File file : files) {
file.delete();
}
//Получение всех вложений
List<DomainObject> attachments = getAttachments("report_template_attach", reportTemplateDo);
for (DomainObject attachment : attachments) {
byte[] content = getAttachmentContent(attachment);
//Запись файла на диск
writeToFile(content, new File(templateFolder, attachment.getString("Name")));
}
templateFolder.setLastModified(System.currentTimeMillis());
}
currentDataSourceContext.set(originalDatasource);
return templateFolder;
}
private void writeToFile(byte[] content, File file) throws IOException {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
outStream.write(content);
} finally {
if (outStream != null) {
outStream.close();
}
}
}
private byte[] getAttachmentContent(DomainObject attachment) {
InputStream contentStream = null;
RemoteInputStream inputStream = null;
try {
inputStream = attachmentService.loadAttachment(attachment.getId());
contentStream = RemoteInputStreamClient.wrap(inputStream);
ByteArrayOutputStream attachmentBytes = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while ((read = contentStream.read(buffer)) > 0){
attachmentBytes.write(buffer, 0, read);
}
return attachmentBytes.toByteArray();
} catch (Exception ex) {
throw new ReportServiceException("Error on get attachment body", ex);
} finally {
try {
if (contentStream != null) {
contentStream.close();
}
if (inputStream != null) {
inputStream.close(true);
}
} catch (IOException ignoreEx) {
}
}
}
private List<DomainObject> getAttachments(String attachmentType, DomainObject attachmentOwner){
String query = "select t.id from " + attachmentType + " t where t.report_template = " + ((RdbmsId)attachmentOwner.getId()).getId();
AccessToken accessToken = accessControlService.createSystemAccessToken(this.getClass().getName());
List<DomainObject> result = new ArrayList<DomainObject>();
IdentifiableObjectCollection collection = collectionsDao.findCollectionByQuery(query, 0, 1000, accessToken);
for (IdentifiableObject identifiableObject : collection) {
result.add(domainObjectDao.find(identifiableObject.getId(), accessToken));
}
return result;
}
}
|
package mobcom.iacademy.thesis.event.controller;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import mobcom.iacademy.thesis.controller.MainActivity;
import mobcom.iacademy.thesis.R;
import mobcom.iacademy.thesis.event.model.EventBean;
public class NewEventActivity extends AppCompatActivity implements
com.wdullaer.materialdatetimepicker.date.DatePickerDialog.OnDateSetListener,
com.wdullaer.materialdatetimepicker.time.TimePickerDialog.OnTimeSetListener {
private Button btnTimeStart, btnTimeEnd, btnDateStart, btnDateEnd;
private TextView timeStartView, timeEndView, dateStartView, dateEndView;
private EditText eventTitle, eventLocation, eventContent;
private CheckBox checkBox;
private boolean allDay = false;
private Intent intent;
private int dayNow, monthNow, yearNow, dayStart, dayEnd;
private String dateStart, dateEnd, format, timeStart, timeSet, timeEnd, title, location, content;
DecimalFormat df = new DecimalFormat("00");
ArrayList<Integer> dayOfMonth = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_event);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setTitle(R.string.new_event);
setSupportActionBar(toolbar);
initUI();
buttonActions();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_new_event, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
attemptSave();
break;
case R.id.action_cancel:
intent = new Intent(NewEventActivity.this, MainActivity.class);
intent.putExtra("Activity", "NewEvent");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
private void initUI() {
eventTitle = (EditText) findViewById(R.id.eventTitle);
eventContent = (EditText) findViewById(R.id.eventContent);
eventLocation = (EditText) findViewById(R.id.eventLocation);
checkBox = (CheckBox) findViewById(R.id.cbAllDay);
btnTimeStart = (Button) findViewById(R.id.btnTimeStart);
btnDateStart = (Button) findViewById(R.id.btnDateStart);
btnTimeEnd = (Button) findViewById(R.id.btnTimeEnd);
btnDateEnd = (Button) findViewById(R.id.btnDateEnd);
dateStartView = (TextView) findViewById(R.id.dateStartView);
timeStartView = (TextView) findViewById(R.id.timeStartView);
dateEndView = (TextView) findViewById(R.id.dateEndView);
timeEndView = (TextView) findViewById(R.id.timeEndView);
dateStartView.setText(getCurrentDate());
dateEndView.setText(getCurrentDate());
timeStartView.setText(getCurrentTime());
timeEndView.setText(getCurrentTime());
}
private void buttonActions() {
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBox.isChecked()) {
allDay = true;
btnTimeStart.setEnabled(false);
btnTimeStart.setBackgroundColor(Color.GRAY);
btnTimeEnd.setEnabled(false);
btnTimeEnd.setBackgroundColor(Color.GRAY);
timeStartView.setText(R.string.all_day_start);
timeEndView.setText(R.string.all_day_end);
} else {
allDay = false;
btnTimeStart.setEnabled(true);
btnTimeStart.setBackgroundColor(Color.parseColor("#3F51B5"));
btnTimeEnd.setEnabled(true);
btnTimeEnd.setBackgroundColor(Color.parseColor("#3F51B5"));
}
}
});
btnDateStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getDateStart();
}
});
btnDateEnd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getDateEnd();
}
});
btnTimeStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimeStart();
}
});
btnTimeEnd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimeEnd();
}
});
}
private void getDateStart() {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(NewEventActivity.this, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
dpd.vibrate(true);
dpd.setTitle(getString(R.string.event_date_start));
dpd.setThemeDark(true);
dpd.setOnDateSetListener(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
dayStart = dayOfMonth;
monthNow = monthOfYear;
yearNow = year;
dateStart = (getMonth(monthNow) + " " + dayStart + ", " + yearNow);
dateStartView.setText(dateStart);
//insert next function here
getDateEnd();
}
});
dpd.show(getFragmentManager(), "Datepickerdialog");
}
private void getDateEnd() {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(NewEventActivity.this, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
dpd.vibrate(true);
dpd.setTitle(getString(R.string.event_date_end));
dpd.setThemeDark(true);
dpd.setOnDateSetListener(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
dayEnd = dayOfMonth;
monthNow = monthOfYear;
yearNow = year;
dateEnd = (getMonth(monthNow) + " " + dayEnd + ", " + yearNow);
dateEndView.setText(dateEnd);
//insert next function here
getTimeStart();
}
});
dpd.show(getFragmentManager(), "Datepickerdialog");
}
private void getTimeStart() {
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(NewEventActivity.this, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), false);
tpd.vibrate(true);
tpd.enableSeconds(false);
tpd.setTitle(getString(R.string.event_time_start));
tpd.setThemeDark(true);
tpd.setOnTimeSetListener(new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
int hour = hourOfDay;
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
timeSet = String.valueOf(df.format(hour) + ":" + String.valueOf(df.format(minute)));
timeStart = timeSet + " " + format;
timeStartView.setText(timeStart);
//insert next function here
getTimeEnd();
}
});
tpd.setOnCancelListener(null);
tpd.show(getFragmentManager(), "Timepickerdialog1");
}
private void getTimeEnd() {
Calendar now = Calendar.getInstance();
TimePickerDialog tpd = TimePickerDialog.newInstance(NewEventActivity.this, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), false);
tpd.vibrate(true);
tpd.enableSeconds(false);
tpd.setTitle(getString(R.string.event_time_end));
tpd.setThemeDark(true);
tpd.setOnTimeSetListener(new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
int hour = hourOfDay;
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
timeSet = String.valueOf(df.format(hour) + ":" + String.valueOf(df.format(minute)));
timeEnd = timeSet + " " + format;
timeEndView.setText(timeEnd);
//insert next function here
}
});
tpd.setOnCancelListener(null);
tpd.show(getFragmentManager(), "Timepickerdialog1");
}
private void attemptSave() {
// Reset errors.
eventTitle.setError(null);
eventContent.setError(null);
eventLocation.setError(null);
// Store values at the time of the save task attempt.
title = eventTitle.getText().toString();
content = eventContent.getText().toString();
location = eventLocation.getText().toString();
dateStart = dateStartView.getText().toString();
dateEnd = dateEndView.getText().toString();
timeStart = timeStartView.getText().toString();
timeEnd = timeEndView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid content, if the user entered one.
if (TextUtils.isEmpty(content)) {
eventContent.setError(getString(R.string.error_field_required));
focusView = eventContent;
cancel = true;
}
// Check for a valid title
if (TextUtils.isEmpty(title)) {
eventTitle.setError(getString(R.string.error_field_required));
focusView = eventTitle;
cancel = true;
}
//check for a valid location
if (TextUtils.isEmpty(location)) {
eventLocation.setError(getString(R.string.error_field_required));
focusView = eventLocation;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt save and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress dialog, and kick off a background task to
// perform the save task attempt.
for (int i = dayStart; i < dayEnd + 1; i++) {
dayOfMonth.add(i);
}
saveEvent(title, content, location, timeStart, timeEnd, dateStart, dateEnd);
}
}
private void saveEvent(final String title, final String content, final String location, final String timeStart, final String timeEnd, final String dateStart, final String dateEnd) {
final ProgressDialog progressDialog = new ProgressDialog(NewEventActivity.this);
progressDialog.setMessage(getString(R.string.new_event_loading));
progressDialog.setCancelable(false);
progressDialog.show();
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if ((ni != null) && (ni.isConnected())) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Event");
query.whereEqualTo("username", ParseUser.getCurrentUser().getObjectId());
query.whereEqualTo("location", location);
query.whereEqualTo("dateStart", dateStart);
query.whereEqualTo("dateEnd", dateEnd);
query.whereEqualTo("timeStart", timeStart);
query.whereEqualTo("timeEnd", timeEnd);
query.getFirstInBackground(new GetCallback<ParseObject>() {
@Override
public void done(ParseObject userevent, ParseException e) {
if (e == null) {
EventBean eventUser = new EventBean(userevent.getObjectId(),
userevent.getString("event"), userevent.getString("description"),
userevent.getString("timeStart"), userevent.getString("timeEnd"),
userevent.getString("location"), userevent.getString("dateStart"),
userevent.getString("dateEnd"), userevent.getString("username"));
progressDialog.dismiss();
showSameEvent(eventUser.getEvent(), eventUser.getLocation(), eventUser.getDateStart(), eventUser.getTimeStart(), eventUser.getTimeEnd());
} else {
//if object does not exist
if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
ParseObject event = new ParseObject("Event");
event.put("username", ParseUser.getCurrentUser().getObjectId());
event.put("event", title);
event.put("description", content);
event.put("location", location);
event.put("year", yearNow);
event.put("month", monthNow);
event.put("day", dayStart);
event.put("isCompleted", false);
event.put("isSharable", false);
if (allDay == false) {
event.put("isAllDay", false);
event.put("timeStart", timeStart);
event.put("timeEnd", timeEnd);
event.put("dateStart", dateStart);
event.put("dateEnd", dateEnd);
} else if (allDay == true) {
event.put("isAllDay", true);
event.put("timeStart", "11:59PM");
event.put("timeEnd", "12:01AM");
event.put("dateStart", dateStart);
event.put("dateEnd", dateEnd);
}
event.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
progressDialog.dismiss();
intent = new Intent(NewEventActivity.this, MainActivity.class);
intent.putExtra("Activity", "NewEvent");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(NewEventActivity.this, "Event Successfully Created", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
});
} else {
progressDialog.cancel();
Toast.makeText(NewEventActivity.this, "Your device appears to be offline. Unable to save event.", Toast.LENGTH_SHORT).show();
}
}
private void showSameEvent(String event, String location, String dateStart, String timeStart, String timeEnd) {
String eventLine = "Event: " + event;
String locationLine = "Location: " + location;
String dateLine = "Date: " + dateStart;
String time = "Time: " + timeStart + " - " + timeEnd;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.duplicate_event);
alertDialogBuilder.setMessage(eventLine + "\n" + locationLine + "\n" + dateLine + "\n" + time);
alertDialogBuilder.setPositiveButton(R.string.dialogOk, null).show();
}
private String getMonth(int month) {
String currentMonth = "";
switch (month) {
case 0:
currentMonth = "Jan";
break;
case 1:
currentMonth = "Feb";
break;
case 2:
currentMonth = "Mar";
break;
case 3:
currentMonth = "Apr";
break;
case 4:
currentMonth = "May";
break;
case 5:
currentMonth = "Jun";
break;
case 6:
currentMonth = "Jul";
break;
case 7:
currentMonth = "Aug";
break;
case 8:
currentMonth = "Sep";
break;
case 9:
currentMonth = "Oct";
break;
case 10:
currentMonth = "Nov";
break;
case 11:
currentMonth = "Dec";
break;
}
return currentMonth;
}
private String getCurrentDate() {
String currentDate;
Calendar now = Calendar.getInstance();
yearNow = now.get(Calendar.YEAR);
monthNow = now.get(Calendar.MONTH);
dayNow = now.get(Calendar.DAY_OF_MONTH);
currentDate = (getMonth(monthNow) + " " + dayNow + ", " + yearNow);
return currentDate;
}
private String getCurrentTime() {
String currentTime;
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
currentTime = String.valueOf(df.format(hour) + ":" + String.valueOf(df.format(minute)) + " " + format);
return currentTime;
}
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
//null
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
//null
}
}
|
package com.atguigu.gulimall.ums.dao;
import com.atguigu.gulimall.ums.entity.MemberCollectSubjectEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 会员收藏的专题活动
*
* @author changchen
* @email doublechang123@163.com
* @date 2019-08-01 21:24:21
*/
@Mapper
public interface MemberCollectSubjectDao extends BaseMapper<MemberCollectSubjectEntity> {
}
|
package pl.jrostowski.filmwebscraper.repository;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Repository;
import pl.jrostowski.filmwebscraper.entity.Movie;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
@Repository
public class ExcelRepository {
public void exportToExcel(Map<Integer, Movie> map, boolean IsNewExcelFormat) throws IOException {
Workbook workbook = createWorkbookObject(IsNewExcelFormat);
Sheet sheet = workbook.createSheet("Toplist");
setHeaders(sheet);
writeRows(map, sheet);
autoSizeColumns(sheet);
FileOutputStream fileOut = getFileExtension(IsNewExcelFormat);
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
private void writeRows(Map<Integer, Movie> map, Sheet sheet) {
map.forEach((rank, movie) -> {
Row row = sheet.createRow(rank);
for (int i = 0; i <= 10; i++) {
Cell cell = row.createCell(i);
switch (i) {
case 0:
cell.setCellValue(rank + ".");
break;
case 1:
cell.setCellValue(movie.getTitle());
break;
case 2:
cell.setCellValue(movie.getYear());
break;
case 3:
cell.setCellValue(movie.getOriginalTitle());
break;
case 4:
cell.setCellValue(movie.getRate());
break;
case 5:
cell.setCellValue(movie.getCriticsRate());
break;
case 6:
cell.setCellValue(movie.getLength());
break;
case 7:
cell.setCellValue(movie.getDirector());
break;
case 8:
cell.setCellValue(movie.getScreenwriter());
break;
case 9:
cell.setCellValue(movie.getGenre());
break;
case 10:
cell.setCellValue(movie.getCountryOfOrigin());
break;
}
}
});
}
private void autoSizeColumns(Sheet sheet) {
for (int i = 0; i < getHeaders().length; i++) {
sheet.autoSizeColumn(i);
}
}
private Workbook createWorkbookObject(boolean IsNewExcelFormat) {
if (IsNewExcelFormat) {
return new XSSFWorkbook();
} else {
return new HSSFWorkbook();
}
}
private FileOutputStream getFileExtension(boolean IsNewExcelFormat) throws IOException {
if (IsNewExcelFormat) {
return new FileOutputStream("toplist.xlsx");
} else {
return new FileOutputStream("toplist.xls");
}
}
private String[] getHeaders() {
return new String[]{
"Rank", "Title", "Year", "Original title", "Rate", "Critics' rate",
"Length", "Director", "Screenwriter", "Genre", "Country of origin"
};
}
private void setHeaders(Sheet sheet) {
Row rowHeader = sheet.createRow(0);
rowHeader.setHeightInPoints(30);
String[] headers = getHeaders();
for (int i = 0; i < 11; i++) {
rowHeader.createCell(i).setCellValue(headers[i]);
}
}
}
|
/*
* Copyright (c) 2002-2014 Gargoyle Software 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.gargoylesoftware.htmlunit.javascript.host.html;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.HTMLOPTION_UNSELECT_SELECTS_FIRST;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_OPTION_CONSTRUCTOR_IGNORES_LABEL;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_OPTION_USE_TEXT_AS_VALUE_IF_NOT_DEFINED;
import org.xml.sax.helpers.AttributesImpl;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomText;
import com.gargoylesoftware.htmlunit.html.HTMLParser;
import com.gargoylesoftware.htmlunit.html.HtmlOption;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter;
import com.gargoylesoftware.htmlunit.javascript.configuration.JsxSetter;
import com.gargoylesoftware.htmlunit.javascript.host.FormChild;
/**
* The JavaScript object that represents an option.
*
* @version $Revision: 9244 $
* @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
* @author David K. Taylor
* @author Chris Erskine
* @author Marc Guillemot
* @author Ahmed Ashour
* @author Ronald Brill
* @author Frank Danek
*/
@JsxClass(domClass = HtmlOption.class)
public class HTMLOptionElement extends FormChild {
/**
* JavaScript constructor.
* @param newText the text
* @param newValue the value
* @param defaultSelected Whether the option is initially selected
* @param selected the current selection state of the option
*/
@JsxConstructor
public void jsConstructor(final String newText, final String newValue,
final boolean defaultSelected, final boolean selected) {
final HtmlPage page = (HtmlPage) getWindow().getWebWindow().getEnclosedPage();
AttributesImpl attributes = null;
if (defaultSelected) {
attributes = new AttributesImpl();
attributes.addAttribute(null, "selected", "selected", null, "selected");
}
final HtmlOption htmlOption = (HtmlOption) HTMLParser.getFactory(HtmlOption.TAG_NAME).createElement(
page, HtmlOption.TAG_NAME, attributes);
htmlOption.setSelected(selected);
setDomNode(htmlOption);
if (!"undefined".equals(newText)) {
htmlOption.appendChild(new DomText(page, newText));
if (!getBrowserVersion().hasFeature(JS_OPTION_CONSTRUCTOR_IGNORES_LABEL)) {
htmlOption.setLabelAttribute(newText);
}
}
if (!"undefined".equals(newValue)) {
htmlOption.setValueAttribute(newValue);
}
}
/**
* Returns the value of the "value" property.
* @return the value property
*/
@JsxGetter
public String getValue() {
String value = getDomNodeOrNull().getAttribute("value");
if (value == DomElement.ATTRIBUTE_NOT_DEFINED
&& getBrowserVersion().hasFeature(JS_OPTION_USE_TEXT_AS_VALUE_IF_NOT_DEFINED)) {
value = getDomNodeOrNull().getText();
}
return value;
}
/**
* Sets the value of the "value" property.
* @param newValue the value property
*/
@JsxSetter
public void setValue(final String newValue) {
getDomNodeOrNull().setValueAttribute(newValue);
}
/**
* Returns the value of the "text" property.
* @return the text property
*/
@Override
@JsxGetter
public String getText() {
return getDomNodeOrNull().getText();
}
/**
* {@inheritDoc}
*/
@Override
public HtmlOption getDomNodeOrNull() {
return (HtmlOption) super.getDomNodeOrNull();
}
/**
* Sets the value of the "text" property.
* @param newText the text property
*/
@JsxSetter
public void setText(final String newText) {
getDomNodeOrNull().setText(newText);
}
/**
* Returns the value of the "selected" property.
* @return the text property
*/
@JsxGetter
public boolean getSelected() {
return getDomNodeOrNull().isSelected();
}
/**
* Sets the value of the "selected" property.
* @param selected the new selected property
*/
@JsxSetter
public void setSelected(final boolean selected) {
final HtmlOption optionNode = getDomNodeOrNull();
final HtmlSelect enclosingSelect = optionNode.getEnclosingSelect();
if (!selected && optionNode.isSelected()
&& enclosingSelect != null && !enclosingSelect.isMultipleSelectEnabled()) {
// un-selecting selected option has no effect in IE and selects first option in FF
if (getBrowserVersion().hasFeature(HTMLOPTION_UNSELECT_SELECTS_FIRST)) {
enclosingSelect.getOption(0).setSelected(true, false);
}
}
else {
optionNode.setSelected(selected, false);
}
}
/**
* Returns the value of the "defaultSelected" property.
* @return the text property
*/
@JsxGetter
public boolean getDefaultSelected() {
return getDomNodeOrNull().isDefaultSelected();
}
/**
* Returns the value of the "label" property.
* @return the label property
*/
@JsxGetter
public String getLabel() {
return getDomNodeOrNull().getLabelAttribute();
}
/**
* Sets the value of the "label" property.
* @param label the new label property
*/
@JsxSetter
public void setLabel(final String label) {
getDomNodeOrNull().setLabelAttribute(label);
}
/**
* {@inheritDoc} Overridden to modify browser configurations.
*/
@Override
@JsxGetter
public boolean getDisabled() {
return super.getDisabled();
}
/**
* {@inheritDoc} Overridden to modify browser configurations.
*/
@Override
@JsxSetter
public void setDisabled(final boolean disabled) {
super.setDisabled(disabled);
}
}
|
package eu.chargetime.ocpp.feature.profile;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <tv@chargetime.eu>
Copyright (C) 2019 Kevin Raddatz <kevin.raddatz@valtech-mobility.com>
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.
*/
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.feature.GetLocalListVersionFeature;
import eu.chargetime.ocpp.feature.ProfileFeature;
import eu.chargetime.ocpp.feature.SendLocalListFeature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.localauthlist.*;
import java.util.HashSet;
import java.util.UUID;
public class ServerLocalAuthListProfile implements Profile {
private HashSet<Feature> featureList;
public ServerLocalAuthListProfile() {
featureList = new HashSet<>();
featureList.add(new GetLocalListVersionFeature(null));
featureList.add(new SendLocalListFeature(null));
}
@Override
public ProfileFeature[] getFeatureList() {
return featureList.toArray(new ProfileFeature[0]);
}
@Override
public Confirmation handleRequest(UUID sessionIndex, Request request) {
return null;
}
/**
* Create a client {@link SendLocalListRequest} with required values.
*
* @param listVersion required, version number of the list.
* @param updateType required, type of update
* @return an instance of {@link SendLocalListConfirmation}.
* @see SendLocalListRequest
* @see SendLocalListFeature
*/
public SendLocalListRequest createSendLocalListRequest(int listVersion, UpdateType updateType) {
return new SendLocalListRequest(listVersion, updateType);
}
/**
* Create a client {@link GetLocalListVersionRequest} with required values.
*
* @return an instance of {@link GetLocalListVersionConfirmation}.
* @see GetLocalListVersionRequest
* @see GetLocalListVersionFeature
*/
public GetLocalListVersionRequest createGetLocalListVersionRequest() {
return new GetLocalListVersionRequest();
}
}
|
package com.xc.luckysheet.mongo.impl;
import com.alibaba.fastjson.JSONObject;
import com.xc.luckysheet.db.IRecordDataInsertHandle;
import com.xc.luckysheet.entity.GridRecordDataModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
/**
* 添加
*
* @author cr
* @Date: 2021-02-27 14:08
*/
@Slf4j
@Repository(value = "mongoRecordDataInsertHandle")
public class RecordDataInsertHandle extends BaseHandle implements IRecordDataInsertHandle {
/**
* 新增Sheet页,并返回刚刚插入的_id
*
* @param pgModel
* @return
*/
@Override
public String insert(GridRecordDataModel pgModel) {
try {
JSONObject jsonObject = tranToJSONObject(pgModel);
mongoTemplate.insert(jsonObject, COLLECTION_NAME);
if (jsonObject.containsKey("_id")) {
return jsonObject.get("_id").toString();
}
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
/**
* 批量添加 添加jsonb
*
* @param models
* @return
*/
@Override
public String InsertIntoBatch(List<GridRecordDataModel> models) {
List<JSONObject> jsonObjects = new ArrayList<>(5);
for (GridRecordDataModel m : models) {
jsonObjects.add(tranToJSONObject(m));
}
return InsertBatchDb(jsonObjects);
}
/**
* 批量添加 添加jsonb
*
* @param models
* @return
*/
@Override
public String InsertBatchDb(List<JSONObject> models) {
try {
mongoTemplate.insert(models, COLLECTION_NAME);
return "";
} catch (Exception e) {
log.error(e.getMessage());
}
return null;
}
}
|
package uk.co.terminological.bibliography.record;
import java.io.Serializable;
import java.util.Optional;
public class ImmutableCitationReference implements CitationReference, Serializable {
public ImmutableCitationReference(CitationReference ref) {
this.identifier = ref.getIdentifier().map(Builder::recordReference).orElse(null);
this.title = ref.getTitle().orElse(null);
this.print = ref.getBibliographicId().map(Builder::printReference).orElse(null);
}
public ImmutableCitationReference(RecordReference crossRefWork, String title, PrintReference crossRefWork2) {
this.identifier = Builder.recordReference(crossRefWork);
this.title = title;
this.print = Builder.printReference(crossRefWork2);
}
ImmutableRecordReference identifier;
String title;
ImmutablePrintReference print;
@Override
public Optional<RecordReference> getIdentifier() {
return Optional.ofNullable(identifier);
}
@Override
public Optional<String> getTitle() {
return Optional.ofNullable(title);
}
@Override
public Optional<PrintReference> getBibliographicId() {
return Optional.ofNullable(print);
}
}
|
/*
* This file is part of Dependency-Track.
*
* 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.
*
* Copyright (c) Steve Springett. All Rights Reserved.
*/
package org.owasp.dependencytrack.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.Join;
import javax.jdo.annotations.Order;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Unique;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* Model class for tracking Dependency-Check scans.
*
* @author Steve Springett
* @since 3.0.0
*/
@PersistenceCapable
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Scan implements Serializable {
private static final long serialVersionUID = 3950039972008164729L;
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.NATIVE)
@JsonIgnore
private long id;
@Persistent
@Column(name = "EXECUTED", jdbcType = "TIMESTAMP", allowsNull = "false")
@NotNull
private Date executed;
@Persistent
@Column(name = "IMPORTED", jdbcType = "TIMESTAMP", allowsNull = "false")
@NotNull
private Date imported;
@Persistent(defaultFetchGroup = "true")
@Column(name = "PROJECT_ID", allowsNull = "false")
@NotNull
private Project project;
@Persistent(table = "SCANS_COMPONENTS", mappedBy = "scans")
@Join(column = "SCAN_ID")
@Element(column = "COMPONENT_ID", dependent = "true")
@Order(extensions = @Extension(vendorName = "datanucleus", key = "list-ordering", value = "id ASC"))
private List<Component> components;
@Persistent(customValueStrategy = "uuid")
@Unique(name = "SCAN_UUID_IDX")
@Column(name = "UUID", jdbcType = "VARCHAR", length = 36, allowsNull = "false")
@NotNull
private UUID uuid;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getExecuted() {
return executed;
}
public void setExecuted(Date executed) {
this.executed = executed;
}
public Date getImported() {
return imported;
}
public void setImported(Date imported) {
this.imported = imported;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public List<Component> getComponents() {
return components;
}
public void setComponents(List<Component> components) {
this.components = components;
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
}
|
package Exercise.restaurant;
import java.math.BigDecimal;
public class Dessert extends Food {
private double calories;
public Dessert(String name, BigDecimal price, double grams, double calories) {
super(name, price, grams);
this.setCalories(calories);
}
public double getCalories() {
return calories;
}
public void setCalories(double calories) {
this.calories = calories;
}
}
|
/*
* This file was automatically generated by EvoSuite
* Wed Aug 01 08:17:43 GMT 2018
*/
package org.mozilla.javascript;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.shaded.org.mockito.Mockito.*;
import static org.evosuite.runtime.EvoAssertions.*;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.ViolatedAssumptionAnswer;
import org.junit.runner.RunWith;
import org.mozilla.javascript.Node;
import org.mozilla.javascript.Token;
import org.mozilla.javascript.ast.ArrayComprehension;
import org.mozilla.javascript.ast.AstRoot;
import org.mozilla.javascript.ast.Block;
import org.mozilla.javascript.ast.BreakStatement;
import org.mozilla.javascript.ast.CatchClause;
import org.mozilla.javascript.ast.Comment;
import org.mozilla.javascript.ast.EmptyExpression;
import org.mozilla.javascript.ast.ErrorNode;
import org.mozilla.javascript.ast.ExpressionStatement;
import org.mozilla.javascript.ast.ForLoop;
import org.mozilla.javascript.ast.FunctionNode;
import org.mozilla.javascript.ast.InfixExpression;
import org.mozilla.javascript.ast.Jump;
import org.mozilla.javascript.ast.KeywordLiteral;
import org.mozilla.javascript.ast.Label;
import org.mozilla.javascript.ast.LabeledStatement;
import org.mozilla.javascript.ast.Name;
import org.mozilla.javascript.ast.NumberLiteral;
import org.mozilla.javascript.ast.ObjectLiteral;
import org.mozilla.javascript.ast.PropertyGet;
import org.mozilla.javascript.ast.ReturnStatement;
import org.mozilla.javascript.ast.StringLiteral;
import org.mozilla.javascript.ast.SwitchStatement;
import org.mozilla.javascript.ast.ThrowStatement;
import org.mozilla.javascript.ast.TryStatement;
import org.mozilla.javascript.ast.XmlDotQuery;
import org.mozilla.javascript.ast.XmlMemberGet;
import org.mozilla.javascript.ast.XmlPropRef;
import org.mozilla.javascript.ast.Yield;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class Node_ESTest extends Node_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
LabeledStatement labeledStatement0 = new LabeledStatement(2);
Node.NodeIterator node_NodeIterator0 = labeledStatement0.new NodeIterator();
// Undeclared exception!
try {
node_NodeIterator0.remove();
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// next() has not been called
//
verifyException("org.mozilla.javascript.Node$NodeIterator", e);
}
}
@Test(timeout = 4000)
public void test01() throws Throwable {
Node node0 = new Node(98);
node0.addChildrenToBack(node0);
Consumer<Object> consumer0 = (Consumer<Object>) mock(Consumer.class, new ViolatedAssumptionAnswer());
node0.forEach(consumer0);
assertEquals(98, node0.getType());
assertEquals((-1), node0.getLineno());
}
@Test(timeout = 4000)
public void test02() throws Throwable {
XmlPropRef xmlPropRef0 = new XmlPropRef(0);
AstRoot astRoot0 = new AstRoot(0);
xmlPropRef0.toStringTree(astRoot0);
assertEquals((-1), astRoot0.getLineno());
assertEquals((-1), xmlPropRef0.getLineno());
}
@Test(timeout = 4000)
public void test03() throws Throwable {
ErrorNode errorNode0 = new ErrorNode(19, 1);
String string0 = errorNode0.toString();
assertEquals("-1", string0);
assertEquals((-1), errorNode0.getLineno());
}
@Test(timeout = 4000)
public void test04() throws Throwable {
Node node0 = Node.newString((-418), "invalid label name");
node0.setString("9u Qg;]0Ik'68K(");
assertEquals((-1), node0.getLineno());
assertEquals((-418), node0.getType());
}
@Test(timeout = 4000)
public void test05() throws Throwable {
XmlDotQuery xmlDotQuery0 = new XmlDotQuery();
AstRoot astRoot0 = new AstRoot(4);
// Undeclared exception!
try {
xmlDotQuery0.setScope(astRoot0);
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// FAILED ASSERTION
//
verifyException("org.mozilla.javascript.Kit", e);
}
}
@Test(timeout = 4000)
public void test06() throws Throwable {
NumberLiteral numberLiteral0 = new NumberLiteral(122, "5gcP+ka,A3nVNW^", 122);
assertEquals((-1), numberLiteral0.getLineno());
assertEquals(122.0, numberLiteral0.getNumber(), 0.01);
}
@Test(timeout = 4000)
public void test07() throws Throwable {
Node node0 = new Node(126);
EmptyExpression emptyExpression0 = new EmptyExpression();
node0.addChildToBack(emptyExpression0);
node0.resetTargets();
assertTrue(node0.hasChildren());
}
@Test(timeout = 4000)
public void test08() throws Throwable {
Yield yield0 = new Yield();
// Undeclared exception!
try {
yield0.resetTargets();
fail("Expecting exception: IllegalStateException");
} catch(IllegalStateException e) {
//
// FAILED ASSERTION
//
verifyException("org.mozilla.javascript.Kit", e);
}
}
@Test(timeout = 4000)
public void test09() throws Throwable {
Node node0 = new Node(131);
node0.addChildrenToBack(node0);
node0.addChildBefore(node0, node0);
node0.replaceChildAfter(node0, node0);
assertEquals("131", node0.toString());
}
@Test(timeout = 4000)
public void test10() throws Throwable {
Node node0 = new Node(131);
PropertyGet propertyGet0 = new PropertyGet(0, 5);
node0.addChildrenToBack(propertyGet0);
node0.addChildrenToBack(node0);
assertTrue(node0.hasChildren());
node0.replaceChild(node0, node0);
assertEquals("131", node0.toString());
}
@Test(timeout = 4000)
public void test11() throws Throwable {
FunctionNode functionNode0 = new FunctionNode();
functionNode0.putIntProp((-3356), (-3356));
functionNode0.putProp((-3356), (Object) null);
assertEquals((-1), functionNode0.getEncodedSourceStart());
}
@Test(timeout = 4000)
public void test12() throws Throwable {
TryStatement tryStatement0 = new TryStatement();
tryStatement0.putIntProp(605, (-843));
tryStatement0.setJsDocNode((Comment) null);
assertEquals((-1), tryStatement0.getLineno());
}
@Test(timeout = 4000)
public void test13() throws Throwable {
Yield yield0 = new Yield();
yield0.removeChildren();
assertEquals((-1), yield0.getLineno());
}
@Test(timeout = 4000)
public void test14() throws Throwable {
Node node0 = new Node(98);
node0.first = node0;
Node node1 = Node.newString(2, "v.d.R=R@=3");
node0.addChildToFront(node1);
node0.removeChild(node0);
assertTrue(node0.hasChildren());
}
@Test(timeout = 4000)
public void test15() throws Throwable {
Node node0 = Node.newString("f1'}8&jC`Eou/");
Node.NodeIterator node_NodeIterator0 = node0.new NodeIterator();
// Undeclared exception!
try {
node_NodeIterator0.next();
fail("Expecting exception: NoSuchElementException");
} catch(NoSuchElementException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.Node$NodeIterator", e);
}
}
@Test(timeout = 4000)
public void test16() throws Throwable {
Node node0 = Node.newNumber(0.0);
assertEquals((-1), node0.getLineno());
assertEquals(0.0, node0.getDouble(), 0.01);
}
@Test(timeout = 4000)
public void test17() throws Throwable {
TryStatement tryStatement0 = new TryStatement();
tryStatement0.putIntProp(605, (-843));
tryStatement0.putProp(8, "FOR");
assertEquals((-1), tryStatement0.getLineno());
}
@Test(timeout = 4000)
public void test18() throws Throwable {
Node node0 = new Node(90);
node0.first = node0;
ObjectLiteral objectLiteral0 = new ObjectLiteral();
node0.first.addChildrenToBack(objectLiteral0);
boolean boolean0 = node0.hasSideEffects();
assertEquals(90, node0.getType());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test19() throws Throwable {
Node node0 = new Node(90);
boolean boolean0 = node0.hasSideEffects();
assertTrue(boolean0);
assertEquals(90, node0.getType());
assertEquals((-1), node0.getLineno());
}
@Test(timeout = 4000)
public void test20() throws Throwable {
Node node0 = new Node(98);
boolean boolean0 = node0.hasSideEffects();
assertEquals((-1), node0.getLineno());
assertEquals("98", node0.toString());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test21() throws Throwable {
ExpressionStatement expressionStatement0 = new ExpressionStatement(4, 16);
ThrowStatement throwStatement0 = new ThrowStatement(1281, expressionStatement0);
boolean boolean0 = throwStatement0.hasChildren();
assertFalse(boolean0);
assertEquals((-1), throwStatement0.getLineno());
}
@Test(timeout = 4000)
public void test22() throws Throwable {
TryStatement tryStatement0 = new TryStatement();
// Undeclared exception!
try {
tryStatement0.getString();
fail("Expecting exception: ClassCastException");
} catch(ClassCastException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
@Test(timeout = 4000)
public void test23() throws Throwable {
FunctionNode functionNode0 = new FunctionNode();
// Undeclared exception!
try {
functionNode0.getScope();
fail("Expecting exception: ClassCastException");
} catch(ClassCastException e) {
//
// org.mozilla.javascript.ast.FunctionNode cannot be cast to org.mozilla.javascript.ast.Name
//
verifyException("org.mozilla.javascript.Node", e);
}
}
@Test(timeout = 4000)
public void test24() throws Throwable {
Name name0 = new Name(22, 25, "Z");
name0.getNext();
assertEquals((-1), name0.getLineno());
}
@Test(timeout = 4000)
public void test25() throws Throwable {
Node node0 = new Node(94);
int int0 = node0.getLineno();
assertEquals(94, node0.getType());
assertEquals((-1), int0);
}
@Test(timeout = 4000)
public void test26() throws Throwable {
InfixExpression infixExpression0 = new InfixExpression(2016, 2016);
infixExpression0.getLastChild();
assertEquals((-1), infixExpression0.getLineno());
assertEquals("-1", infixExpression0.toString());
}
@Test(timeout = 4000)
public void test27() throws Throwable {
StringLiteral stringLiteral0 = new StringLiteral();
Token.CommentType token_CommentType0 = Token.CommentType.JSDOC;
Comment comment0 = new Comment(163, 1, token_CommentType0, "R(6]A?;0+q!bIi");
stringLiteral0.setJsDocNode(comment0);
String string0 = stringLiteral0.getJsDoc();
assertEquals((-1), stringLiteral0.getLineno());
assertNotNull(string0);
}
@Test(timeout = 4000)
public void test28() throws Throwable {
ThrowStatement throwStatement0 = new ThrowStatement();
throwStatement0.getJsDoc();
assertEquals((-1), throwStatement0.getLineno());
}
@Test(timeout = 4000)
public void test29() throws Throwable {
XmlPropRef xmlPropRef0 = new XmlPropRef();
Yield yield0 = new Yield(151, 24, xmlPropRef0);
yield0.labelId(7);
int int0 = yield0.labelId();
assertEquals(7, int0);
}
@Test(timeout = 4000)
public void test30() throws Throwable {
Node node0 = new Node(94);
node0.getFirstChild();
assertEquals("94", node0.toString());
assertEquals((-1), node0.getLineno());
}
@Test(timeout = 4000)
public void test31() throws Throwable {
Node node0 = Node.newTarget();
assertEquals(132, node0.getType());
node0.labelId(7);
int int0 = node0.getExistingIntProp(15);
assertEquals(7, int0);
}
@Test(timeout = 4000)
public void test32() throws Throwable {
TryStatement tryStatement0 = new TryStatement();
InfixExpression infixExpression0 = new InfixExpression((-2779), tryStatement0, tryStatement0, (-650));
// Undeclared exception!
try {
infixExpression0.getDouble();
fail("Expecting exception: ClassCastException");
} catch(ClassCastException e) {
//
// org.mozilla.javascript.ast.InfixExpression cannot be cast to org.mozilla.javascript.ast.NumberLiteral
//
verifyException("org.mozilla.javascript.Node", e);
}
}
@Test(timeout = 4000)
public void test33() throws Throwable {
ReturnStatement returnStatement0 = new ReturnStatement();
LabeledStatement labeledStatement0 = new LabeledStatement();
returnStatement0.addChildToBack(labeledStatement0);
XmlMemberGet xmlMemberGet0 = new XmlMemberGet(2, 27);
// Undeclared exception!
try {
returnStatement0.replaceChild(xmlMemberGet0, xmlMemberGet0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// node is not a child
//
verifyException("org.mozilla.javascript.Node", e);
}
}
@Test(timeout = 4000)
public void test34() throws Throwable {
Node node0 = new Node(90);
node0.first = node0;
node0.removeChild(node0);
assertFalse(node0.hasChildren());
}
@Test(timeout = 4000)
public void test35() throws Throwable {
Block block0 = new Block();
BreakStatement breakStatement0 = new BreakStatement();
ForLoop forLoop0 = new ForLoop(13);
breakStatement0.setJumpStatement(forLoop0);
block0.addStatement(breakStatement0);
boolean boolean0 = block0.hasConsistentReturnUsage();
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test36() throws Throwable {
Block block0 = new Block();
Jump jump0 = new Jump(8);
block0.addStatement(jump0);
boolean boolean0 = block0.hasConsistentReturnUsage();
assertTrue(block0.hasChildren());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test37() throws Throwable {
Block block0 = new Block();
SwitchStatement switchStatement0 = new SwitchStatement();
block0.addStatement(switchStatement0);
boolean boolean0 = block0.hasConsistentReturnUsage();
assertTrue(block0.hasChildren());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test38() throws Throwable {
Block block0 = new Block();
Label label0 = new Label(26);
block0.addStatement(label0);
// Undeclared exception!
try {
block0.hasConsistentReturnUsage();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.Node", e);
}
}
@Test(timeout = 4000)
public void test39() throws Throwable {
Block block0 = new Block();
boolean boolean0 = block0.hasConsistentReturnUsage();
assertTrue(boolean0);
assertEquals((-1), block0.getLineno());
}
@Test(timeout = 4000)
public void test40() throws Throwable {
ReturnStatement returnStatement0 = new ReturnStatement();
LabeledStatement labeledStatement0 = new LabeledStatement();
returnStatement0.addChildToBack(labeledStatement0);
boolean boolean0 = returnStatement0.hasConsistentReturnUsage();
assertTrue(returnStatement0.hasChildren());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test41() throws Throwable {
ReturnStatement returnStatement0 = new ReturnStatement();
boolean boolean0 = returnStatement0.hasConsistentReturnUsage();
assertTrue(boolean0);
assertEquals((-1), returnStatement0.getLineno());
}
@Test(timeout = 4000)
public void test42() throws Throwable {
ThrowStatement throwStatement0 = new ThrowStatement();
boolean boolean0 = throwStatement0.hasConsistentReturnUsage();
assertEquals((-1), throwStatement0.getLineno());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test43() throws Throwable {
Yield yield0 = new Yield();
boolean boolean0 = yield0.hasConsistentReturnUsage();
assertEquals((-1), yield0.getLineno());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test44() throws Throwable {
LabeledStatement labeledStatement0 = new LabeledStatement(26, 0);
ArrayComprehension arrayComprehension0 = new ArrayComprehension();
labeledStatement0.addChildrenToBack(arrayComprehension0);
boolean boolean0 = labeledStatement0.hasConsistentReturnUsage();
assertTrue(labeledStatement0.hasChildren());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test45() throws Throwable {
LabeledStatement labeledStatement0 = new LabeledStatement(26, 0);
boolean boolean0 = labeledStatement0.hasConsistentReturnUsage();
assertTrue(boolean0);
assertEquals((-1), labeledStatement0.getLineno());
}
@Test(timeout = 4000)
public void test46() throws Throwable {
Node node0 = Node.newTarget();
boolean boolean0 = node0.hasConsistentReturnUsage();
assertTrue(boolean0);
assertEquals(132, node0.getType());
assertEquals((-1), node0.getLineno());
}
@Test(timeout = 4000)
public void test47() throws Throwable {
KeywordLiteral keywordLiteral0 = new KeywordLiteral(1281, (-1419));
ExpressionStatement expressionStatement0 = new ExpressionStatement(4, 16);
ThrowStatement throwStatement0 = new ThrowStatement(1281, expressionStatement0);
throwStatement0.addChildrenToFront(keywordLiteral0);
assertTrue(throwStatement0.hasChildren());
}
@Test(timeout = 4000)
public void test48() throws Throwable {
Node node0 = new Node(98);
node0.addChildrenToBack(node0);
node0.replaceChild(node0, node0);
assertTrue(node0.hasChildren());
}
@Test(timeout = 4000)
public void test49() throws Throwable {
Yield yield0 = new Yield();
Node node0 = new Node(682, yield0);
assertTrue(node0.hasChildren());
node0.addChildToBack(yield0);
assertEquals("682", node0.toString());
assertEquals((-1), yield0.getLineno());
assertEquals((-1), node0.getLineno());
}
@Test(timeout = 4000)
public void test50() throws Throwable {
Node node0 = new Node(98);
node0.first = node0;
Node node1 = Node.newString(2, "v.d.R=R@=3");
node0.addChildToFront(node1);
assertEquals(2, node1.getType());
node0.addChildBefore(node0, node0);
assertEquals(98, node0.getType());
assertEquals((-1), node0.getLineno());
}
@Test(timeout = 4000)
public void test51() throws Throwable {
Node node0 = new Node(131);
node0.first = node0;
Node node1 = Node.newString(2, "v.d.R=R@=3");
node0.addChildBefore(node0, node0);
CatchClause catchClause0 = new CatchClause();
// Undeclared exception!
try {
node1.addChildAfter(node0, catchClause0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// newChild had siblings in addChildAfter
//
verifyException("org.mozilla.javascript.Node", e);
}
}
@Test(timeout = 4000)
public void test52() throws Throwable {
KeywordLiteral keywordLiteral0 = new KeywordLiteral();
ErrorNode errorNode0 = new ErrorNode();
keywordLiteral0.addChildAfter(errorNode0, errorNode0);
// Undeclared exception!
try {
keywordLiteral0.addChildBefore(errorNode0, errorNode0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// newChild had siblings in addChildBefore
//
verifyException("org.mozilla.javascript.Node", e);
}
}
@Test(timeout = 4000)
public void test53() throws Throwable {
Node node0 = Node.newTarget();
Node node1 = new Node(6, node0, node0, node0, 1);
// Undeclared exception!
node1.addChildrenToBack(node0);
}
@Test(timeout = 4000)
public void test54() throws Throwable {
EmptyExpression emptyExpression0 = new EmptyExpression(874, 64);
Node node0 = new Node(874, emptyExpression0, emptyExpression0);
Node.NodeIterator node_NodeIterator0 = node0.new NodeIterator();
assertTrue(node_NodeIterator0.hasNext());
node_NodeIterator0.next();
node_NodeIterator0.remove();
node_NodeIterator0.remove();
node_NodeIterator0.remove();
assertFalse(node0.hasChildren());
assertEquals("874", node0.toString());
}
@Test(timeout = 4000)
public void test55() throws Throwable {
SwitchStatement switchStatement0 = new SwitchStatement(0, 0);
Node node0 = new Node(1910, switchStatement0, 45);
assertEquals(1910, node0.getType());
assertEquals((-1), switchStatement0.getLineno());
assertTrue(node0.hasChildren());
assertEquals(45, node0.getLineno());
}
@Test(timeout = 4000)
public void test56() throws Throwable {
XmlDotQuery xmlDotQuery0 = new XmlDotQuery();
Node node0 = new Node(0, xmlDotQuery0);
boolean boolean0 = node0.hasSideEffects();
assertEquals((-1), node0.getLineno());
assertTrue(node0.hasChildren());
assertEquals("0", node0.toString());
assertEquals((-1), xmlDotQuery0.getLineno());
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test57() throws Throwable {
Node node0 = new Node(3813, 3813);
Node node1 = new Node(3813, node0, node0, 0);
assertEquals(3813, node0.getType());
assertEquals(3813, node0.getLineno());
assertEquals(3813, node1.getType());
assertEquals(0, node1.getLineno());
}
}
|
package online.githuboy.wqxuetang.pdfd.utils;
import java.util.Optional;
import java.util.concurrent.*;
/**
* 线程池工具
*
* @author suchu
* @since 2020年2月3日
*/
public class ThreadPoolUtils {
private static ThreadPoolExecutor executor;
private static ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(2);
public static void init(Integer coreSize) {
int actualSize = Optional.ofNullable(coreSize).orElse(1);
executor = new ThreadPoolExecutor(actualSize,
actualSize,
0,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(), new NameTheadFactory("fetch-image"));
}
private ThreadPoolUtils() {
}
public static ScheduledExecutorService getScheduledExecutorService() {
return scheduledExecutorService;
}
public static ThreadPoolExecutor getExecutor() {
return executor;
}
}
|
/**
* 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.hedwig.server.integration;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.concurrent.SynchronousQueue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.google.protobuf.ByteString;
import org.apache.hedwig.client.api.MessageHandler;
import org.apache.hedwig.client.api.Subscriber;
import org.apache.hedwig.client.conf.ClientConfiguration;
import org.apache.hedwig.client.exceptions.InvalidSubscriberIdException;
import org.apache.hedwig.client.HedwigClient;
import org.apache.hedwig.client.api.Client;
import org.apache.hedwig.client.api.Publisher;
import org.apache.hedwig.client.api.Subscriber;
import org.apache.hedwig.exceptions.PubSubException;
import org.apache.hedwig.exceptions.PubSubException.ClientNotSubscribedException;
import org.apache.hedwig.protocol.PubSubProtocol.Message;
import org.apache.hedwig.protocol.PubSubProtocol.MessageSeqId;
import org.apache.hedwig.protocol.PubSubProtocol.OperationType;
import org.apache.hedwig.protocol.PubSubProtocol.ProtocolVersion;
import org.apache.hedwig.protocol.PubSubProtocol.PubSubRequest;
import org.apache.hedwig.protocol.PubSubProtocol.PubSubResponse;
import org.apache.hedwig.protocol.PubSubProtocol.StartDeliveryRequest;
import org.apache.hedwig.protocol.PubSubProtocol.StatusCode;
import org.apache.hedwig.protocol.PubSubProtocol.SubscribeRequest.CreateOrAttach;
import org.apache.hedwig.protoextensions.SubscriptionStateUtils;
import org.apache.hedwig.server.HedwigHubTestBase;
import org.apache.hedwig.server.netty.WriteRecordingChannel;
import org.apache.hedwig.server.proxy.HedwigProxy;
import org.apache.hedwig.server.proxy.ProxyConfiguration;
import org.apache.hedwig.server.regions.HedwigHubClient;
import org.apache.hedwig.util.Callback;
import org.apache.hedwig.util.ConcurrencyUtils;
@RunWith(Parameterized.class)
public class TestHedwigHub extends HedwigHubTestBase {
// Client side variables
protected HedwigClient client;
protected Publisher publisher;
protected Subscriber subscriber;
// Common ByteStrings used in tests.
private final ByteString localSubscriberId = ByteString.copyFromUtf8("LocalSubscriber");
private final ByteString hubSubscriberId = ByteString.copyFromUtf8(SubscriptionStateUtils.HUB_SUBSCRIBER_PREFIX
+ "HubSubcriber");
enum Mode {
REGULAR, PROXY, SSL
};
@Parameters
public static Collection<Object[]> configs() {
return Arrays.asList(new Object[][] { { Mode.PROXY }, { Mode.REGULAR }, { Mode.SSL }});
}
protected Mode mode;
public TestHedwigHub(Mode mode) {
this.mode = mode;
}
protected HedwigProxy proxy;
protected ProxyConfiguration proxyConf = new ProxyConfiguration();
// SynchronousQueues to verify async calls
private final SynchronousQueue<Boolean> queue = new SynchronousQueue<Boolean>();
private final SynchronousQueue<Boolean> consumeQueue = new SynchronousQueue<Boolean>();
// Test implementation of Callback for async client actions.
static class TestCallback implements Callback<Void> {
private final SynchronousQueue<Boolean> queue;
public TestCallback(SynchronousQueue<Boolean> queue) {
this.queue = queue;
}
@Override
public void operationFinished(Object ctx, Void resultOfOperation) {
new Thread(new Runnable() {
@Override
public void run() {
if (logger.isDebugEnabled())
logger.debug("Operation finished!");
ConcurrencyUtils.put(queue, true);
}
}).start();
}
@Override
public void operationFailed(Object ctx, final PubSubException exception) {
new Thread(new Runnable() {
@Override
public void run() {
logger.error("Operation failed!", exception);
ConcurrencyUtils.put(queue, false);
}
}).start();
}
}
// Test implementation of subscriber's message handler.
static class TestMessageHandler implements MessageHandler {
// For subscribe reconnect testing, the server could send us back
// messages we've already processed and consumed. We need to keep
// track of the ones we've encountered so we only signal back to the
// consumeQueue once.
private HashSet<MessageSeqId> consumedMessages = new HashSet<MessageSeqId>();
private long largestMsgSeqIdConsumed = -1;
private final SynchronousQueue<Boolean> consumeQueue;
public TestMessageHandler(SynchronousQueue<Boolean> consumeQueue) {
this.consumeQueue = consumeQueue;
}
public void deliver(ByteString topic, ByteString subscriberId, final Message msg, Callback<Void> callback,
Object context) {
if (!consumedMessages.contains(msg.getMsgId())) {
// New message to consume. Add it to the Set of consumed
// messages.
consumedMessages.add(msg.getMsgId());
// Check that the msg seq ID is incrementing by 1 compared to
// the last consumed message. Don't do this check if this is the
// initial message being consumed.
if (largestMsgSeqIdConsumed >= 0 && msg.getMsgId().getLocalComponent() != largestMsgSeqIdConsumed + 1) {
new Thread(new Runnable() {
@Override
public void run() {
if (logger.isDebugEnabled())
logger.debug("Consuming message that is out of order for msgId: "
+ msg.getMsgId().getLocalComponent());
ConcurrencyUtils.put(consumeQueue, false);
}
}).start();
} else {
new Thread(new Runnable() {
@Override
public void run() {
if (logger.isDebugEnabled())
logger.debug("Consume operation finished successfully!");
ConcurrencyUtils.put(consumeQueue, true);
}
}).start();
}
// Store the consumed message as the new last msg id consumed.
largestMsgSeqIdConsumed = msg.getMsgId().getLocalComponent();
} else {
if (logger.isDebugEnabled())
logger.debug("Consumed a message that we've processed already: " + msg);
}
callback.operationFinished(context, null);
}
}
class TestClientConfiguration extends ClientConfiguration {
@Override
public InetSocketAddress getDefaultServerHost() {
if (mode == Mode.PROXY) {
return new InetSocketAddress(proxyConf.getProxyPort());
} else {
return super.getDefaultServerHost();
}
}
@Override
public boolean isSSLEnabled() {
if (mode == Mode.SSL)
return true;
else
return false;
}
}
// ClientConfiguration to use for this test.
protected ClientConfiguration getClientConfiguration() {
return new TestClientConfiguration();
}
@Override
@Before
public void setUp() throws Exception {
numServers = 3;
super.setUp();
if (mode == Mode.PROXY) {
proxy = new HedwigProxy(proxyConf);
}
client = new HedwigClient(getClientConfiguration());
publisher = client.getPublisher();
subscriber = client.getSubscriber();
}
@Override
@After
public void tearDown() throws Exception {
client.close();
if (mode == Mode.PROXY) {
proxy.shutdown();
}
super.tearDown();
}
// Helper function to generate Messages
protected Message getMsg(int msgNum) {
return Message.newBuilder().setBody(ByteString.copyFromUtf8("Message" + msgNum)).build();
}
// Helper function to generate Topics
protected ByteString getTopic(int topicNum) {
return ByteString.copyFromUtf8("Topic" + topicNum);
}
protected void startDelivery(ByteString topic, ByteString subscriberId, MessageHandler handler) throws Exception {
startDelivery(subscriber, topic, subscriberId, handler);
}
protected void startDelivery(Subscriber subscriber, ByteString topic, ByteString subscriberId,
MessageHandler handler) throws Exception {
subscriber.startDelivery(topic, subscriberId, handler);
if (mode == Mode.PROXY) {
WriteRecordingChannel channel = new WriteRecordingChannel();
PubSubRequest request = PubSubRequest.newBuilder().setProtocolVersion(ProtocolVersion.VERSION_ONE)
.setTopic(topic).setTxnId(0).setType(OperationType.START_DELIVERY).setStartDeliveryRequest(
StartDeliveryRequest.newBuilder().setSubscriberId(subscriberId)).build();
proxy.getStartDeliveryHandler().handleRequest(request, channel);
assertEquals(StatusCode.SUCCESS, ((PubSubResponse) channel.getMessagesWritten().get(0)).getStatusCode());
}
}
protected void publishFirstBatch(int batchSize, boolean messagesToBeConsumed) throws Exception {
if (logger.isDebugEnabled())
logger.debug("Publishing first batch of messages.");
for (int i = 0; i < batchSize; i++) {
publisher.asyncPublish(getTopic(i), getMsg(i), new TestCallback(queue), null);
assertTrue(queue.take());
if (messagesToBeConsumed)
assertTrue(consumeQueue.take());
}
}
protected void publishSecondBatch(int batchSize, boolean messagesToBeConsumed) throws Exception {
if (logger.isDebugEnabled())
logger.debug("Publishing second batch of messages.");
for (int i = 0; i < batchSize; i++) {
publisher.asyncPublish(getTopic(i), getMsg(i + batchSize), new TestCallback(queue), null);
assertTrue(queue.take());
if (messagesToBeConsumed)
assertTrue(consumeQueue.take());
}
}
protected void subscribeToTopics(int batchSize) throws Exception {
if (logger.isDebugEnabled())
logger.debug("Subscribing to topics and starting delivery.");
for (int i = 0; i < batchSize; i++) {
subscriber.asyncSubscribe(getTopic(i), localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH,
new TestCallback(queue), null);
assertTrue(queue.take());
}
// Start delivery for the subscriber
for (int i = 0; i < batchSize; i++) {
startDelivery(getTopic(i), localSubscriberId, new TestMessageHandler(consumeQueue));
}
}
protected void shutDownLastServer() {
if (logger.isDebugEnabled())
logger.debug("Shutting down the last server in the Hedwig hub cluster.");
serversList.get(serversList.size() - 1).shutdown();
// Due to a possible race condition, after we've shutdown the server,
// the client could still be caching the channel connection to that
// server. It is possible for a publish request to go to the shutdown
// server using the closed/shutdown channel before the channel
// disconnect logic kicks in. What could happen is that the publish
// is done successfully on the channel but the server on the other end
// can't/won't read it. This publish request will time out and the
// Junit test will fail. Since that particular scenario is not what is
// tested here, use a workaround of sleeping in this thread (so the
// channel disconnect logic can complete) before we publish again.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error("Thread was interrupted while sleeping after shutting down last server!", e);
}
}
// This tests out the manual sending of consume messages to the server
// instead of relying on the automatic sending by the client lib for it.
@Test
public void testManualConsumeClient() throws Exception {
HedwigClient myClient = new HedwigClient(new TestClientConfiguration() {
@Override
public boolean isAutoSendConsumeMessageEnabled() {
return false;
}
});
Subscriber mySubscriber = myClient.getSubscriber();
Publisher myPublisher = myClient.getPublisher();
ByteString myTopic = getTopic(0);
// Subscribe to a topic and start delivery on it
mySubscriber.asyncSubscribe(myTopic, localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH,
new TestCallback(queue), null);
assertTrue(queue.take());
startDelivery(mySubscriber, myTopic, localSubscriberId, new TestMessageHandler(consumeQueue));
// Publish some messages
int batchSize = 10;
for (int i = 0; i < batchSize; i++) {
myPublisher.asyncPublish(myTopic, getMsg(i), new TestCallback(queue), null);
assertTrue(queue.take());
assertTrue(consumeQueue.take());
}
// Now manually send a consume message for each message received
for (int i = 0; i < batchSize; i++) {
boolean success = true;
try {
mySubscriber.consume(myTopic, localSubscriberId, MessageSeqId.newBuilder().setLocalComponent(i + 1)
.build());
} catch (ClientNotSubscribedException e) {
success = false;
}
assertTrue(success);
}
// Since the consume call eventually does an async write to the Netty
// channel, the writing of the consume requests may not have completed
// yet before we stop the client. Sleep a little before we stop the
// client just so error messages are not logged.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error("Thread was interrupted while waiting to stop client for manual consume test!!", e);
}
myClient.close();
}
@Test
public void testAttachToSubscriptionSuccess() throws Exception {
ByteString topic = getTopic(0);
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH, new TestCallback(queue),
null);
assertTrue(queue.take());
// Close the subscription asynchronously
subscriber.asyncCloseSubscription(topic, localSubscriberId, new TestCallback(queue), null);
assertTrue(queue.take());
// Now try to attach to the subscription
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.ATTACH, new TestCallback(queue), null);
assertTrue(queue.take());
// Start delivery and publish some messages. Make sure they are consumed
// correctly.
startDelivery(topic, localSubscriberId, new TestMessageHandler(consumeQueue));
int batchSize = 5;
for (int i = 0; i < batchSize; i++) {
publisher.asyncPublish(topic, getMsg(i), new TestCallback(queue), null);
assertTrue(queue.take());
assertTrue(consumeQueue.take());
}
}
@Test
public void testServerRedirect() throws Exception {
int batchSize = 10;
publishFirstBatch(batchSize, false);
}
@Test
public void testSubscribeAndConsume() throws Exception {
int batchSize = 10;
subscribeToTopics(batchSize);
publishFirstBatch(batchSize, true);
}
@Test
public void testServerFailoverPublishOnly() throws Exception {
int batchSize = 10;
publishFirstBatch(batchSize, false);
shutDownLastServer();
publishSecondBatch(batchSize, false);
}
@Test
public void testServerFailover() throws Exception {
int batchSize = 10;
subscribeToTopics(batchSize);
publishFirstBatch(batchSize, true);
shutDownLastServer();
publishSecondBatch(batchSize, true);
}
@Test
public void testUnsubscribe() throws Exception {
ByteString topic = getTopic(0);
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH, new TestCallback(queue),
null);
assertTrue(queue.take());
startDelivery(topic, localSubscriberId, new TestMessageHandler(consumeQueue));
publisher.asyncPublish(topic, getMsg(0), new TestCallback(queue), null);
assertTrue(queue.take());
assertTrue(consumeQueue.take());
// Send an Unsubscribe request
subscriber.asyncUnsubscribe(topic, localSubscriberId, new TestCallback(queue), null);
assertTrue(queue.take());
// Now publish a message and make sure it is not consumed by the client
publisher.asyncPublish(topic, getMsg(1), new TestCallback(queue), null);
assertTrue(queue.take());
// Wait a little bit just in case the message handler is still active,
// consuming the message, and then putting a true value in the
// consumeQueue.
Thread.sleep(1000);
// Put a False value on the consumeQueue so we can verify that it
// is not blocked by a message consume action which already put a True
// value into the queue.
new Thread(new Runnable() {
@Override
public void run() {
ConcurrencyUtils.put(consumeQueue, false);
}
}).start();
assertFalse(consumeQueue.take());
}
@Test
public void testSyncUnsubscribeWithoutSubscription() throws Exception {
boolean unsubscribeSuccess = false;
try {
subscriber.unsubscribe(getTopic(0), localSubscriberId);
} catch (ClientNotSubscribedException e) {
unsubscribeSuccess = true;
} catch (Exception ex) {
unsubscribeSuccess = false;
}
assertTrue(unsubscribeSuccess);
}
@Test
public void testAsyncUnsubscribeWithoutSubscription() throws Exception {
subscriber.asyncUnsubscribe(getTopic(0), localSubscriberId, new TestCallback(queue), null);
assertFalse(queue.take());
}
@Test
public void testCloseSubscription() throws Exception {
ByteString topic = getTopic(0);
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH, new TestCallback(queue),
null);
assertTrue(queue.take());
startDelivery(topic, localSubscriberId, new TestMessageHandler(consumeQueue));
publisher.asyncPublish(topic, getMsg(0), new TestCallback(queue), null);
assertTrue(queue.take());
assertTrue(consumeQueue.take());
// Close the subscription asynchronously
subscriber.asyncCloseSubscription(topic, localSubscriberId, new TestCallback(queue), null);
assertTrue(queue.take());
// Now publish a message and make sure it is not consumed by the client
publisher.asyncPublish(topic, getMsg(1), new TestCallback(queue), null);
assertTrue(queue.take());
// Wait a little bit just in case the message handler is still active,
// consuming the message, and then putting a true value in the
// consumeQueue.
Thread.sleep(1000);
// Put a False value on the consumeQueue so we can verify that it
// is not blocked by a message consume action which already put a True
// value into the queue.
new Thread(new Runnable() {
@Override
public void run() {
ConcurrencyUtils.put(consumeQueue, false);
}
}).start();
assertFalse(consumeQueue.take());
}
@Test
public void testStopDelivery() throws Exception {
ByteString topic = getTopic(0);
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH, new TestCallback(queue),
null);
assertTrue(queue.take());
startDelivery(topic, localSubscriberId, new TestMessageHandler(consumeQueue));
publisher.asyncPublish(topic, getMsg(0), new TestCallback(queue), null);
assertTrue(queue.take());
assertTrue(consumeQueue.take());
// Stop the delivery for this subscription
subscriber.stopDelivery(topic, localSubscriberId);
// Publish some more messages so they are queued up to be delivered to
// the client
int batchSize = 10;
for (int i = 0; i < batchSize; i++) {
publisher.asyncPublish(topic, getMsg(i + 1), new TestCallback(queue), null);
assertTrue(queue.take());
}
// Wait a little bit just in case the message handler is still active,
// consuming the message, and then putting a true value in the
// consumeQueue.
Thread.sleep(1000);
// Put a False value on the consumeQueue so we can verify that it
// is not blocked by a message consume action which already put a True
// value into the queue.
new Thread(new Runnable() {
@Override
public void run() {
ConcurrencyUtils.put(consumeQueue, false);
}
}).start();
assertFalse(consumeQueue.take());
// Now start delivery again and verify that the queued up messages are
// consumed
startDelivery(topic, localSubscriberId, new TestMessageHandler(consumeQueue));
for (int i = 0; i < batchSize; i++) {
assertTrue(consumeQueue.take());
}
}
@Test
public void testConsumedMessagesInOrder() throws Exception {
ByteString topic = getTopic(0);
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH, new TestCallback(queue),
null);
assertTrue(queue.take());
startDelivery(topic, localSubscriberId, new TestMessageHandler(consumeQueue));
// Now publish some messages and verify that they are delivered in order
// to the subscriber
int batchSize = 100;
for (int i = 0; i < batchSize; i++) {
publisher.asyncPublish(topic, getMsg(i), new TestCallback(queue), null);
}
// We've sent out all of the publish messages asynchronously,
// now verify that they are consumed in the correct order.
for (int i = 0; i < batchSize; i++) {
assertTrue(queue.take());
assertTrue(consumeQueue.take());
}
}
@Test
public void testCreateSubscriptionFailure() throws Exception {
ByteString topic = getTopic(0);
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH, new TestCallback(queue),
null);
assertTrue(queue.take());
// Close the subscription asynchronously
subscriber.asyncCloseSubscription(topic, localSubscriberId, new TestCallback(queue), null);
assertTrue(queue.take());
// Now try to create the subscription when it already exists
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.CREATE, new TestCallback(queue), null);
assertFalse(queue.take());
}
@Test
public void testCreateSubscriptionSuccess() throws Exception {
ByteString topic = getTopic(0);
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.CREATE, new TestCallback(queue), null);
assertTrue(queue.take());
startDelivery(topic, localSubscriberId, new TestMessageHandler(consumeQueue));
int batchSize = 5;
for (int i = 0; i < batchSize; i++) {
publisher.asyncPublish(topic, getMsg(i), new TestCallback(queue), null);
assertTrue(queue.take());
assertTrue(consumeQueue.take());
}
}
@Test
public void testAttachToSubscriptionFailure() throws Exception {
ByteString topic = getTopic(0);
subscriber.asyncSubscribe(topic, localSubscriberId, CreateOrAttach.ATTACH, new TestCallback(queue), null);
assertFalse(queue.take());
}
// The following 4 tests are to make sure that the subscriberId validation
// works when it is a local subscriber and we're expecting the subscriberId
// to be in the "local" specific format.
@Test
public void testSyncSubscribeWithInvalidSubscriberId() throws Exception {
boolean subscribeSuccess = false;
try {
subscriber.subscribe(getTopic(0), hubSubscriberId, CreateOrAttach.CREATE_OR_ATTACH);
} catch (InvalidSubscriberIdException e) {
subscribeSuccess = true;
} catch (Exception ex) {
subscribeSuccess = false;
}
assertTrue(subscribeSuccess);
}
@Test
public void testAsyncSubscribeWithInvalidSubscriberId() throws Exception {
subscriber.asyncSubscribe(getTopic(0), hubSubscriberId, CreateOrAttach.CREATE_OR_ATTACH,
new TestCallback(queue), null);
assertFalse(queue.take());
}
@Test
public void testSyncUnsubscribeWithInvalidSubscriberId() throws Exception {
boolean unsubscribeSuccess = false;
try {
subscriber.unsubscribe(getTopic(0), hubSubscriberId);
} catch (InvalidSubscriberIdException e) {
unsubscribeSuccess = true;
} catch (Exception ex) {
unsubscribeSuccess = false;
}
assertTrue(unsubscribeSuccess);
}
@Test
public void testAsyncUnsubscribeWithInvalidSubscriberId() throws Exception {
subscriber.asyncUnsubscribe(getTopic(0), hubSubscriberId, new TestCallback(queue), null);
assertFalse(queue.take());
}
// The following 4 tests are to make sure that the subscriberId validation
// also works when it is a hub subscriber and we're expecting the
// subscriberId to be in the "hub" specific format.
@Test
public void testSyncHubSubscribeWithInvalidSubscriberId() throws Exception {
Client hubClient = new HedwigHubClient(new ClientConfiguration());
Subscriber hubSubscriber = hubClient.getSubscriber();
boolean subscribeSuccess = false;
try {
hubSubscriber.subscribe(getTopic(0), localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH);
} catch (InvalidSubscriberIdException e) {
subscribeSuccess = true;
} catch (Exception ex) {
subscribeSuccess = false;
}
assertTrue(subscribeSuccess);
hubClient.close();
}
@Test
public void testAsyncHubSubscribeWithInvalidSubscriberId() throws Exception {
Client hubClient = new HedwigHubClient(new ClientConfiguration());
Subscriber hubSubscriber = hubClient.getSubscriber();
hubSubscriber.asyncSubscribe(getTopic(0), localSubscriberId, CreateOrAttach.CREATE_OR_ATTACH, new TestCallback(
queue), null);
assertFalse(queue.take());
hubClient.close();
}
@Test
public void testSyncHubUnsubscribeWithInvalidSubscriberId() throws Exception {
Client hubClient = new HedwigHubClient(new ClientConfiguration());
Subscriber hubSubscriber = hubClient.getSubscriber();
boolean unsubscribeSuccess = false;
try {
hubSubscriber.unsubscribe(getTopic(0), localSubscriberId);
} catch (InvalidSubscriberIdException e) {
unsubscribeSuccess = true;
} catch (Exception ex) {
unsubscribeSuccess = false;
}
assertTrue(unsubscribeSuccess);
hubClient.close();
}
@Test
public void testAsyncHubUnsubscribeWithInvalidSubscriberId() throws Exception {
Client hubClient = new HedwigHubClient(new ClientConfiguration());
Subscriber hubSubscriber = hubClient.getSubscriber();
hubSubscriber.asyncUnsubscribe(getTopic(0), localSubscriberId, new TestCallback(queue), null);
assertFalse(queue.take());
hubClient.close();
}
}
|
/*-
* -\-\-
* Helios Client
* --
* Copyright (C) 2016 Spotify AB
* --
* 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.spotify.helios.common.descriptors;
import static java.util.Collections.emptyList;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Lists;
import java.util.List;
import org.jetbrains.annotations.Nullable;
/**
* Represents a Helios deployment group.
*
* <p>An sample expression of it in JSON might be:
* <pre>
* {
* "name":"foo-group",
* "jobId":"foo:0.1.0",
* "hostSelectors":[
* {
* "label":"foo",
* "operator":"EQUALS"
* "operand":"bar",
* },
* {
* "label":"baz",
* "operator":"EQUALS"
* "operand":"qux",
* }
* ],
* "rolloutOptions":{
* "migrate":false,
* "parallelism":2,
* "timeout":1000,
* "overlap":true,
* "token": "insecure-access-token"
* },
* "rollingUpdateReason": "MANUAL"
* }
* </pre>
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DeploymentGroup extends Descriptor {
public enum RollingUpdateReason {
MANUAL,
HOSTS_CHANGED
}
public static final String EMPTY_NAME = "";
public static final JobId EMPTY_JOB_ID = null;
private final String name;
private final List<HostSelector> hostSelectors;
private final JobId jobId;
private final RolloutOptions rolloutOptions;
private final RollingUpdateReason reason;
/**
* Create a Job.
*
* <p>Note that despite annotating jobId as @JsonProperty("job") in practice it's serialised as
* "jobId" because we neglected to annotate the getter to match. The annotation has been left here
* to ensure backwards compatibility.
*
* @param name The docker name to use.
* @param jobId The job ID for the deployment group.
* @param hostSelectors The selectors that determine which agents are part of the deployment
* group.
* @param reason The reason the most recent rolling update (if any) occurred.
*/
public DeploymentGroup(
@JsonProperty("name") final String name,
@JsonProperty("hostSelectors") final List<HostSelector> hostSelectors,
@JsonProperty("job") @Nullable final JobId jobId,
@JsonProperty("rolloutOptions") @Nullable final RolloutOptions rolloutOptions,
@JsonProperty("rollingUpdateReason") @Nullable final RollingUpdateReason reason) {
this.name = name;
this.hostSelectors = hostSelectors;
this.jobId = jobId;
this.rolloutOptions = rolloutOptions;
this.reason = reason;
}
public String getName() {
return name;
}
public JobId getJobId() {
return jobId;
}
public List<HostSelector> getHostSelectors() {
return hostSelectors;
}
public RolloutOptions getRolloutOptions() {
return rolloutOptions;
}
public RollingUpdateReason getRollingUpdateReason() {
return reason;
}
public static Builder newBuilder() {
return new Builder();
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final DeploymentGroup that = (DeploymentGroup) obj;
if (jobId != null ? !jobId.equals(that.jobId) : that.jobId != null) {
return false;
}
if (hostSelectors != null ? !hostSelectors.equals(that.hostSelectors)
: that.hostSelectors != null) {
return false;
}
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
if (rolloutOptions != null ? !rolloutOptions.equals(that.rolloutOptions)
: that.rolloutOptions != null) {
return false;
}
if (reason != null ? !reason.equals(that.reason) : that.reason != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (hostSelectors != null ? hostSelectors.hashCode() : 0);
result = 31 * result + (jobId != null ? jobId.hashCode() : 0);
result = 31 * result + (rolloutOptions != null ? rolloutOptions.hashCode() : 0);
result = 31 * result + (reason != null ? reason.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "DeploymentGroup{"
+ "name='" + name + '\''
+ ", hostSelectors=" + hostSelectors
+ ", job=" + jobId
+ ", rolloutOptions=" + rolloutOptions
+ ", reason=" + reason
+ '}';
}
public Builder toBuilder() {
final Builder builder = newBuilder();
return builder.setName(name)
.setJobId(jobId)
.setHostSelectors(hostSelectors)
.setRolloutOptions(rolloutOptions)
.setRollingUpdateReason(reason);
}
public static class Builder implements Cloneable {
private final Parameters pm;
private Builder() {
this.pm = new Parameters();
}
private static class Parameters implements Cloneable {
public String name;
public JobId jobId;
public List<HostSelector> hostSelectors;
public RolloutOptions rolloutOptions;
public RollingUpdateReason reason;
private Parameters() {
this.name = EMPTY_NAME;
this.jobId = EMPTY_JOB_ID;
this.hostSelectors = emptyList();
this.rolloutOptions = null;
this.reason = null;
}
}
public String getName() {
return pm.name;
}
public Builder setName(final String name) {
pm.name = name;
return this;
}
public JobId getJobId() {
return pm.jobId;
}
public Builder setJobId(final JobId jobId) {
pm.jobId = jobId;
return this;
}
public List<HostSelector> getHostSelectors() {
return pm.hostSelectors;
}
public Builder setHostSelectors(final List<HostSelector> hostSelectors) {
pm.hostSelectors = Lists.newArrayList(hostSelectors);
return this;
}
public RolloutOptions getRolloutOptions() {
return pm.rolloutOptions;
}
public Builder setRolloutOptions(final RolloutOptions rolloutOptions) {
pm.rolloutOptions = rolloutOptions;
return this;
}
public RollingUpdateReason getRollingUpdateReason() {
return pm.reason;
}
public Builder setRollingUpdateReason(final RollingUpdateReason reason) {
pm.reason = reason;
return this;
}
public DeploymentGroup build() {
return new DeploymentGroup(pm.name, pm.hostSelectors, pm.jobId, pm.rolloutOptions, pm.reason);
}
}
}
|
/*
Copyright (C) GridGain Systems. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.grid.dr.cache.receiver;
/**
* Metrics for data center replication receiver cache.
*/
public interface GridDrReceiverCacheMetrics {
/**
* Gets total amount of cache entries received from receiver hub.
*
* @return Total amount of cache entries received from receiver hub.
*/
public long entriesReceived();
/**
* Gets total amount of conflicts resolved by using new value. See
* {@link GridDrReceiverCacheConflictContext#useNew()} for more info.
*
* @return Total amount of conflicts resolved by using new value.
*/
public long conflictNew();
/**
* Gets total amount of conflicts resolved by using old value. See
* {@link GridDrReceiverCacheConflictContext#useOld()} for more info.
*
* @return Total amount of conflicts resolved by using old value.
*/
public long conflictOld();
/**
* Gets total amount of conflicts resolved by merge. See
* {@link GridDrReceiverCacheConflictContext#merge(Object, long)} for more info.
*
* @return Total amount of conflicts resolved by merge.
*/
public long conflictMerge();
}
|
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package io.github.mmm.marshall.json.impl;
import io.github.mmm.marshall.spi.StructuredNodeType;
/**
* State object for reading or writing JSON.
*
* @since 1.0.0
*/
public class JsonState {
final JsonState parent;
final StructuredNodeType type;
int valueCount;
JsonState() {
this(null, null);
}
JsonState(JsonState parent, StructuredNodeType type) {
super();
this.parent = parent;
this.type = type;
}
}
|
package com.design.mode.proxy;
import javax.swing.*;
public class Test
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Proxy test client");
JLabel label = new JLabel("Loading web page ......");
frame.getContentPane().add(label);
PageProxy pageProxy = new PageProxy();
frame.getContentPane().add(pageProxy);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
//frame.pack();
frame.setVisible(true);
pageProxy.label.setText("aaa");
}
}
|
/*-
* #%L
* rapidoid-commons
* %%
* Copyright (C) 2014 - 2018 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.rapidoid.config;
import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.commons.RapidoidInfo;
import org.rapidoid.commons.Str;
import org.rapidoid.u.U;
import org.rapidoid.util.Msc;
import java.util.Arrays;
import java.util.List;
@Authors("Nikolche Mihajlovski")
@Since("5.0.2")
public class ConfigHelp extends RapidoidThing {
public static boolean isHelpRequested(String[] args) {
return Arrays.equals(args, new String[]{"--help"})
|| Arrays.equals(args, new String[]{"help"});
}
public static void processHelp(String[] args) {
if (isHelpRequested(args)) {
showUsage();
System.exit(0);
}
}
private static void showUsage() {
show(RapidoidInfo.nameAndInfo());
show("");
show("Usage:");
if (Msc.dockerized()) {
show(" docker run -it --rm -p <PORT>:8888 [-v <your-app-root>:/app] rapidoid [option1 option2 ...]");
show(" docker run -d -p <PORT>:8888 [-v <your-app-root>:/app] [-u nobody] rapidoid [option1 option2 ...]");
show(" docker run -it rapidoid command [arg1 arg2 ...]");
} else {
show(" java -cp <yourapp>.jar com.example.Main [option1 option2 ...]");
}
show("\nExample:");
if (Msc.dockerized()) {
show(" docker run -it --rm --net=host -v $(pwd):/app rapidoid users.admin.password=my-pass");
show(" docker run -it --rm -p 80:8888 -v $(pwd):/app -u nobody rapidoid users.admin.password=my-pass");
show(" docker run -it --rm rapidoid password");
} else {
show(" java -cp <yourapp>.jar com.example.Main on.port=9090 on.address=127.0.0.1 production users.admin.password=my-pass");
}
show("\nMain configuration options:");
showOpts(ConfigOptions.ALL);
show("\nSupported commands:");
showOpts(ConfigOptions.COMMANDS);
show("\nFor a complete list of options see: https://www.rapidoid.org/docs.html#_the_built_in_configuration");
}
private static void showOpts(List<ConfigOption> opts) {
for (ConfigOption opt : opts) {
Object def = opt.getDefaultValue();
String desc = opt.getDesc();
if (def != null) {
desc = U.frmt("%s (default: %s)", desc, def);
}
opt(opt.getName(), desc);
}
}
private static void opt(String opt, String desc) {
show(" " + opt + Str.mul(" ", 25 - opt.length()) + " - " + desc);
}
private static void show(String msg) {
U.print(msg);
}
}
|
package io.hyperfoil.core.steps;
import io.hyperfoil.api.session.Access;
import io.hyperfoil.api.session.Session;
import io.hyperfoil.api.statistics.Statistics;
public class StopwatchEndStep extends StatisticsStep {
private final Access key;
private final String metrics;
public StopwatchEndStep(Access key, String metrics) {
super(StatisticsStep.nextId());
this.key = key;
this.metrics = metrics;
}
@Override
public boolean invoke(Session session) {
long now = System.nanoTime();
StopwatchBeginStep.StartTime startTime = (StopwatchBeginStep.StartTime) key.getObject(session);
Statistics statistics = session.statistics(id(), metrics);
statistics.incrementRequests(startTime.timestampMillis);
statistics.recordResponse(startTime.timestampMillis, 0, now - startTime.timestampNanos);
// TODO: record any request/response counts?
return true;
}
}
|
/*******************************************************************************
* Copyright © 2019 by California Community Colleges Chancellor's Office
*
* 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.cccnext.tesuto.rules.service;
import static org.cccnext.tesuto.service.multiplemeasures.OperationalDataStoreService.SELF_REPORTED;
import static org.cccnext.tesuto.service.multiplemeasures.OperationalDataStoreService.VERIFIED;
import static org.cccnext.tesuto.service.multiplemeasures.OperationalDataStoreService.CALPAS_SOURCE;
import static org.cccnext.tesuto.service.multiplemeasures.OperationalDataStoreService.APPLY_SOURCE;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.cccnext.tesuto.domain.multiplemeasures.Fact;
import org.cccnext.tesuto.domain.multiplemeasures.Student;
import org.cccnext.tesuto.domain.multiplemeasures.VariableSet;
import org.cccnext.tesuto.service.multiplemeasures.OperationalDataStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import lombok.extern.slf4j.Slf4j;
/**
* @author James Travis Stanley <jstanley@uncion.net>
*/
@Slf4j
public class MultipleMeasureFactProcessingUtils {
@Qualifier("operationalDataStore")
@Autowired
private OperationalDataStoreService ods;
public static String MATH_RANKING_KEY = "math_ranking";
public VariableSet chooseVariableSet(String cccId, String misCode, Boolean selfReportedOptIn) {
log.info(String.format("Fetching variable set for student %s", cccId));
Student student = ods.fetchStudent(cccId);
log.info(String.format("Student fetched with id %s", cccId));
if(student == null || CollectionUtils.isEmpty( student.getVariableSets())){
log.info(String.format("VariableSets were empty for student %s", cccId));
return null;
}
log.info(String.format("Fetching variable set for student with id %s", cccId));
Optional<VariableSet> variableSet = student.getVariableSets().stream().filter(vs -> (selfReportedOptIn || !SELF_REPORTED.equals(vs.getSourceType()))
&& (vs.getMisCode() == null || vs.getMisCode().equals(misCode))).max(variableSetComparator);
if(variableSet.isPresent()) {
log.info(String.format("Variable set found for student with id %s", cccId));
return ods.fetchFacts(cccId, variableSet.get());
}
return null;
}
public static void addMathRanking(Map<String, Fact> facts) {
Map<String, Double> classRankings = mathClassRankings();
Double ranking = -1.0;
Fact rankingFact = null;
if (facts.get("stat_ap") != null && facts.get("stat") != null) {
if (parseDouble(facts.get("stat_ap").getValue()) > parseDouble(facts.get("stat").getValue())) {
facts.put("stat", facts.get("stat_ap"));
}
}
for (String key : classRankings.keySet()) {
if (facts.containsKey(key)) {
rankingFact = facts.get(key);
Double grade = StringUtils.isBlank(rankingFact.getValue()) ? null
: Double.parseDouble(rankingFact.getValue());
if (grade != null) {
if( ranking < classRankings.get(key) + (grade / 10))
ranking = classRankings.get(key) + (grade / 10);
}
}
}
if(ranking >= 0.0) {
Fact rankedFact = new Fact();
rankedFact.setName(MATH_RANKING_KEY);
rankedFact.setValue(Double.toString(ranking));
rankedFact.setSourceDate(new Date());
rankedFact.setSource(rankingFact.getSource());
rankedFact.setSourceType(rankingFact.getSourceType());
facts.put(MATH_RANKING_KEY, rankedFact);
}
}
private static Double parseDouble(String value) {
if (StringUtils.isBlank(value)) {
return 0.0;
}
return Double.parseDouble(value);
}
protected static Map<String, Double> mathClassRankings() {
return Collections.unmodifiableMap(new LinkedHashMap<String, Double>() {
{
put("calc", 6.0);
put("calc_ap", 6.0);
put("pre_calc", 5.0);
put("pre_calc_ap", 5.0);
put("trig", 4.0);
put("trig_ap", 4.0);
put("geo", 3.0);
put("geo_ap", 3.0);
put("stat", 2.0);
put("stat_ap", 2.0);
put("alg_ii", 2.0);
put("alg_ii_ap", 2.0);
put("alg_i", 1.0);
put("alg_i_ap", 1.0);
put("pre_alg", 0.0);
put("pre_alg_ap", 0.0);
}
});
}
private Comparator<VariableSet> variableSetComparator = new Comparator<VariableSet>() {
public int compare(VariableSet vs1, VariableSet vs2) {
if (VERIFIED.equals(vs1.getSourceType()) && SELF_REPORTED.equals(vs2.getSourceType()))
return 1;
else if (SELF_REPORTED.equals(vs1.getSourceType()) && VERIFIED.equals(vs2.getSourceType()))
return -1;
else if (CALPAS_SOURCE.equals(vs1.getSource()) && !CALPAS_SOURCE.equals(vs2.getSource()))
return 1;
else if (!CALPAS_SOURCE.equals(vs1.getSource()) && CALPAS_SOURCE.equals(vs2.getSource()))
return -1;
else if (vs1.getSourceDate() == null && vs2.getSourceDate() == null) {
if (vs1.getCreateDate() == null && vs2.getCreateDate() == null) {
return 0;
}
else if (vs1.getCreateDate() == null && vs2.getCreateDate() != null)
return 1;
else if (vs1.getCreateDate() != null && vs2.getCreateDate() == null)
return -1;
else
return vs1.getCreateDate().compareTo(vs2.getCreateDate());
}
else if (vs1.getSourceDate() == null && vs2.getSourceDate() != null)
return 1;
else if (vs1.getSourceDate() != null && vs2.getSourceDate() == null)
return -1;
else
return vs1.getSourceDate().compareTo(vs2.getSourceDate());
}
};
}
|
package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_BOOK_DISPLAYED_INDEX;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.index.Index;
import seedu.address.logic.commands.UsageCommand;
import seedu.address.logic.parser.exceptions.ParseException;
/**
* Parses input arguments and creates a new UsageCommand object
*/
public class UsageCommandParser implements Parser<UsageCommand> {
/**
* Parses the given {@code String} of arguments in the context of the UsageCommand
* and returns a UsageCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public UsageCommand parse(String args) throws ParseException {
try {
Index index = ParserUtil.parseIndex(args);
return new UsageCommand(index);
} catch (ParseException pe) {
throw new ParseException(
String.format(MESSAGE_INVALID_BOOK_DISPLAYED_INDEX, Messages.MESSAGE_USAGE), pe);
}
}
}
|
package com.github.binarywang.wxpay.bean.request;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* 发送红包请求参数对象
* Created by Binary Wang on 2016/9/24.
*
* @author binarywang (https://github.com/binarywang)
*/
@XStreamAlias("xml")
public class WxPaySendRedpackRequest extends WxPayBaseRequest {
/**
* mch_billno
* 商户订单号(每个订单号必须唯一) 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。 接口根据商户订单号支持重入,如出现超时可再调用。
*/
@XStreamAlias("mch_billno")
private String mchBillNo;
/**
* send_name
* 商户名称
* 红包发送者名称
*/
@XStreamAlias("send_name")
private String sendName;
/**
* re_openid
* 接受红包的用户 用户在wxappid下的openid
*/
@XStreamAlias("re_openid")
private String reOpenid;
/**
* total_amount
* 红包总额
*/
@XStreamAlias("total_amount")
private Integer totalAmount;
/**
* total_num
* 红包发放总人数
*/
@XStreamAlias("total_num")
private Integer totalNum;
/**
* amt_type
* 红包金额设置方式
* ALL_RAND—全部随机,商户指定总金额和红包发放总人数,由微信支付随机计算出各红包金额
* 裂变红包必填
*/
@XStreamAlias("amt_type")
private String amtType;
/**
* wishing
* 红包祝福语
*/
@XStreamAlias("wishing")
private String wishing;
/**
* client_ip
* 服务器Ip地址
* 调用接口的机器Ip地址
*/
@XStreamAlias("client_ip")
private String clientIp;
/**
* act_name
* 活动名称
*/
@XStreamAlias("act_name")
private String actName;
/**
* remark
* 备注
*/
@XStreamAlias("remark")
private String remark;
/**
* wxappid
* 微信分配的公众账号ID(企业号corpid即为此appId)。接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的)
*/
@XStreamAlias("wxappid")
private String wxAppid;
/**
* <pre>
* scene_id
* 场景id
* PRODUCT_1:商品促销
* PRODUCT_2:抽奖
* PRODUCT_3:虚拟物品兑奖
* PRODUCT_4:企业内部福利
* PRODUCT_5:渠道分润
* PRODUCT_6:保险回馈
* PRODUCT_7:彩票派奖
* PRODUCT_8:税务刮奖
* 非必填字段
* </pre>
*/
@XStreamAlias("scene_id")
private String sceneId;
/**
* <pre>
* risk_info
* 活动信息
* posttime:用户操作的时间戳
* mobile:业务系统账号的手机号,国家代码-手机号。不需要+号
* deviceid :mac 地址或者设备唯一标识
* clientversion :用户操作的客户端版本
* 把值为非空的信息用key=value进行拼接,再进行urlencode
* urlencode(posttime=xx&mobile=xx&deviceid=xx)
* 非必填字段
* </pre>
*/
@XStreamAlias("risk_info")
private String riskInfo;
/**
* <pre>
* consume_mch_id
* 资金授权商户号
* 资金授权商户号
* 服务商替特约商户发放时使用
* 非必填字段
* </pre>
*/
@XStreamAlias("consume_mch_id")
private String consumeMchId;
public String getMchBillNo() {
return mchBillNo;
}
public void setMchBillNo(String mchBillNo) {
this.mchBillNo = mchBillNo;
}
public String getSendName() {
return this.sendName;
}
public void setSendName(String sendName) {
this.sendName = sendName;
}
public String getReOpenid() {
return this.reOpenid;
}
public void setReOpenid(String reOpenid) {
this.reOpenid = reOpenid;
}
public Integer getTotalAmount() {
return this.totalAmount;
}
public void setTotalAmount(Integer totalAmount) {
this.totalAmount = totalAmount;
}
public Integer getTotalNum() {
return this.totalNum;
}
public void setTotalNum(Integer totalNum) {
this.totalNum = totalNum;
}
public String getAmtType() {
return this.amtType;
}
public void setAmtType(String amtType) {
this.amtType = amtType;
}
public String getWishing() {
return this.wishing;
}
public void setWishing(String wishing) {
this.wishing = wishing;
}
public String getClientIp() {
return this.clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public String getActName() {
return this.actName;
}
public void setActName(String actName) {
this.actName = actName;
}
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
protected void checkConstraints() {
}
@Override
public String getAppid() {
return this.wxAppid;
}
@Override
public void setAppid(String appid) {
this.wxAppid = appid;
}
public String getSceneId() {
return this.sceneId;
}
public void setSceneId(String sceneId) {
this.sceneId = sceneId;
}
public String getRiskInfo() {
return this.riskInfo;
}
public void setRiskInfo(String riskInfo) {
this.riskInfo = riskInfo;
}
public String getConsumeMchId() {
return this.consumeMchId;
}
public void setConsumeMchId(String consumeMchId) {
this.consumeMchId = consumeMchId;
}
}
|
/***********************************************************************************************
*
* Copyright 2018 Infosys Ltd.
* Use of this source code is governed by MIT license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
***********************************************************************************************/
package org.infy.entities.triggerinputs;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
/**
* TestTest is a test class for Test
*
* @see org.infy.entities.triggerinputs.Test
*
*/
public class TestTest {
/**
* Constructor for test class.
*
*
*/
public TestTest() {
/*
* This constructor should not be modified. Any initialization code
* should be placed in the setUp() method instead.
*/
}
/**
*
* Test for get and set
*
*/
@Test
public void testGetSet() throws Throwable{
org.infy.entities.triggerinputs.Test testObject= new org.infy.entities.triggerinputs.Test();
List<String> testEnv = null;
testObject.setTestEnv(testEnv);
assertEquals(null,testObject.getTestEnv());
}
/**
* Utility main method. Runs the test cases defined in this test class.
*
* Usage: java TestTest
*
* @param args
* command line arguments are not needed
*
*/
public static void main(String[] args) {
org.junit.runner.JUnitCore.main("org.infy.entities.triggerinputs.TestTest");
}
/**
* Get the class object of the class which will be tested.
*
* @return the class which will be tested
*
*/
public Class getTestedClass() {
return Test.class;
}
}
|
package java012;
/**
* created by cicek on 25.12.2018 18:49
*/
public class MyMain {
public static void main(String[] args){
MyClass my1 = new MyClass();
MyClass my2 = new MyClass();
MyClass my3 = new MyClass();
MyClass my4 = new MyClass(2);
my1.sanane(0);
my2.sanane(2);
my3.sanane(4);
my4.sanane(6);
System.out.printf("my1 toString: %s\n", my1.toString());
System.out.printf("my2 toString: %s\n", my2.toString());
System.out.printf("my2 toString: %s\n", my3.toString());
System.out.printf("my2 toString: %s\n", my4.toString());
}
}
|
package com.rmo.fibu.model;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.github.cliftonlabs.json_simple.Jsoner;
import com.rmo.fibu.util.Config;
import com.rmo.fibu.util.Trace;
/**
* Verwaltet das JsonFile, kennt Name und Location wo gespeichert wird.
* @author ruedi
*
*/
public class JsonFile {
/**
* Der FileName des Json-Files
*/
private static String getJsonFileName() {
String lFileName = Config.sDefaultDir + "/" + Config.sFibuDbName + Config.sJsonExtension;
return lFileName;
}
/**
* Check, ob das File exisitert
* @return
*/
public static boolean exist() {
File jsonFile = new File(getJsonFileName());
return jsonFile.exists();
}
/**
* Das File löschen
*/
public static void delete() {
File jsonFile = new File(getJsonFileName());
jsonFile.delete();
}
/**
* Einlesen alle Daten vom Json file, Zeile um Zeile.
*/
public static List<BuchungCsv> readFromFile() {
Trace.println(5,"JsonFile.readFromFile()");
FileReader fileIn = null;
try {
fileIn = new FileReader(getJsonFileName());
} catch (FileNotFoundException ex) {
Trace.println(4, ex.getMessage());
}
List<BuchungCsv> buchungList = new ArrayList<BuchungCsv>();
// hier werden die Daten eingelesen, Zeile um Zeile
BufferedReader br = new BufferedReader(fileIn);
try {
String companyName = br.readLine();
// alle Buchungen in File schreiben
String json = br.readLine();
while (json != null) {
BuchungCsv buchungCsv = new BuchungCsv(json);
buchungCsv.setCompanyName(companyName);
buchungList.add(buchungCsv);
json = br.readLine();
}
fileIn.close();
} catch (IOException ex) {
Trace.println(4, ex.getMessage());
}
Trace.println(5,"JsonFile.readFromFile() => end");
return buchungList;
}
/** Die Buchungen in einer Json-Datei speichern
*/
public static String saveInFile(String companyName, List<BuchungCsv> buchungList) {
StringBuffer antwort = new StringBuffer(100);
// file öffnen
FileWriter fileOut = null;
try {
fileOut = new FileWriter(getJsonFileName());
} catch (FileNotFoundException ex) {
Trace.println(4, ex.getMessage());
antwort.append(ex.getMessage());
} catch (IOException ex) {
Trace.println(4, ex.getMessage());
antwort.append(ex.getMessage());
}
BufferedWriter bw = new BufferedWriter(fileOut);
try {
bw.append(companyName);
bw.newLine();
// alle Buchungen in File schreiben
BuchungCsv buchungCsv = null;
Iterator<BuchungCsv> iter = buchungList.iterator();
while (iter.hasNext()) {
buchungCsv = iter.next();
String json = Jsoner.serialize(buchungCsv);
bw.append(json);
bw.newLine();
}
bw.flush();
antwort.append(getJsonFileName());
fileOut.close();
} catch (IOException ex) {
Trace.println(4, ex.getMessage());
antwort.append(ex.getMessage());
}
return antwort.toString();
}
}
|
/* Copyright 2017 Zutubi Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zutubi.validation.validators;
import com.zutubi.validation.ValidationException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Use the default java.net.URL url validation.
*/
public class URLValidator extends StringFieldValidatorSupport
{
public void validateStringField(String value) throws ValidationException
{
try
{
new URL(value);
}
catch (MalformedURLException e)
{
addError();
}
}
}
|
/*
This file is part of SSID.
SSID 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 3 of the License, or
(at your option) any later version.
SSID 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 SSID. If not, see <http://www.gnu.org/licenses/>.
*/
package dbscan;
import dbscan.util.*;
public final class DBSCAN {
public void buildClusters(SetOfPoints setOfPoints, int minPts) {
int clusterId = nextId(Point.NOISE);
for (Point point : setOfPoints) {
if (point.getClusterId() == Point.UNCLASSIFIED) {
if (expandCluster(setOfPoints, point, clusterId, minPts))
clusterId = nextId(clusterId);
}
}
}
private boolean expandCluster(SetOfPoints setOfPoints, Point point,
int clusterId, int minPts) {
SetOfPoints seeds = setOfPoints.regionQuery(point);
if (seeds.size() < minPts) { // no core point
SetOfPoints.changeClId(point, Point.NOISE);
return false;
}
// All points in seeds are density-reachable from Point
SetOfPoints.changeClIds(seeds, clusterId);
seeds.delete(point);
Point currentP;// , resultP;
SetOfPoints result;
while (seeds.size() > 0) {
currentP = seeds.first();
result = setOfPoints.regionQuery(currentP);
if (result.size() >= minPts) {
for (Point resultP : result) {
int resultPClId = resultP.getClusterId();
if (resultPClId == Point.UNCLASSIFIED
|| resultPClId == Point.NOISE) {
if (resultPClId == Point.UNCLASSIFIED) {
seeds.append(resultP);
}
SetOfPoints.changeClId(resultP, clusterId);
} // UNCLASSIFIED OR NOISE
}
} // result.size >= MinPts
seeds.delete(currentP);
} // seeds != Empty
return true;
}
private int nextId(int id) {
return id + 1;
}
}
|
/*
* Copyright 2015 DuraSpace, 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 org.fcrepo.http.commons.domain;
import javax.ws.rs.HttpMethod;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* MOVE HTTP method
*
* @author cbeer
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("MOVE")
public @interface MOVE {
}
|
package com.xpf.dagger.main.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.xpf.dagger.R;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
/**
* Created by x-sir on 2019/4/28 :)
* Function:
*/
public class MainFragment extends DaggerFragment implements IMainFragmentView {
private static final String TAG = "MainFragment";
@Inject
MainFragmentPresenter mainFragmentPresenter;
private TextView textView;
public static MainFragment newInstance() {
return new MainFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = View.inflate(getContext(), R.layout.fragment_main, null);
textView = view.findViewById(R.id.textView);
mainFragmentPresenter.onMainFragmentLoaded();
return view;
}
@Override
public void onMainFragmentLoaded() {
Log.d(TAG, "onMainFragmentLoaded()");
textView.postDelayed(new Runnable() {
@Override
public void run() {
textView.setText("Hello MainFragment~");
}
}, 2000);
}
}
|
package com.algorand.algosdk.abi;
public class TypeArrayStatic extends ABIType {
public final ABIType elemType;
public final int length;
public TypeArrayStatic(ABIType elemType, int length) {
if (length < 1)
throw new IllegalArgumentException("static-array initialize failure: array length should be at least 1");
this.elemType = elemType;
this.length = length;
}
@Override
public String toString() {
return this.elemType.toString() + "[" + this.length + "]";
}
@Override
public boolean isDynamic() {
return this.elemType.isDynamic();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof TypeArrayStatic)) return false;
return length == ((TypeArrayStatic) o).length && this.elemType.equals(((TypeArrayStatic) o).elemType);
}
@Override
public byte[] encode(Object o) {
Object[] objArray = ABIType.unifyToArrayOfObjects(o);
if (objArray.length != this.length)
throw new IllegalArgumentException("cannot encode abi static array: length of value != length in array type");
return ABIType.castToTupleType(this.length, this.elemType).encode(objArray);
}
@Override
public Object decode(byte[] encoded) {
return ABIType.castToTupleType(this.length, this.elemType).decode(encoded);
}
@Override
public int byteLen() {
if (this.elemType instanceof TypeBool)
return (this.length + 7) / 8;
return this.elemType.byteLen() * this.length;
}
}
|
/*
* 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.
*/
/**
* Index writer plugin for <a href="http://www.elasticsearch.org/">Elasticsearch</a>.
*/
package org.apache.nutch.indexwriter.elastic;
|
/*
* 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
*
* 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.springframework.web.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.util.DefaultUriTemplateHandler;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
/**
* @author Arjen Poutsma
* @author Rossen Stoyanchev
*/
@SuppressWarnings("unchecked")
public class RestTemplateTests {
private RestTemplate template;
private ClientHttpRequestFactory requestFactory;
private ClientHttpRequest request;
private ClientHttpResponse response;
private ResponseErrorHandler errorHandler;
@SuppressWarnings("rawtypes")
private HttpMessageConverter converter;
@Before
public void setup() {
requestFactory = mock(ClientHttpRequestFactory.class);
request = mock(ClientHttpRequest.class);
response = mock(ClientHttpResponse.class);
errorHandler = mock(ResponseErrorHandler.class);
converter = mock(HttpMessageConverter.class);
template = new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
template.setRequestFactory(requestFactory);
template.setErrorHandler(errorHandler);
}
@Test
public void varArgsTemplateVariables() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
.willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.execute("http://example.com/hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42",
"21");
verify(response).close();
}
@Test
public void varArgsNullTemplateVariable() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET))
.willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, null, "foo");
verify(response).close();
}
@Test
public void mapTemplateVariables() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/42"), HttpMethod.GET))
.willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Map<String, String> vars = Collections.singletonMap("hotel", "42");
template.execute("http://example.com/hotels/{hotel}/bookings/{hotel}", HttpMethod.GET, null, null, vars);
verify(response).close();
}
@Test
public void mapNullTemplateVariable() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET))
.willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Map<String, String> vars = new HashMap<>(2);
vars.put("first", null);
vars.put("last", "foo");
template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, vars);
verify(response).close();
}
@Test // SPR-15201
public void uriTemplateWithTrailingSlash() throws Exception {
String url = "http://example.com/spring/";
given(requestFactory.createRequest(new URI(url), HttpMethod.GET)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.execute(url, HttpMethod.GET, null, null);
verify(response).close();
}
@Test
public void errorHandling() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(true);
given(response.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR);
given(response.getStatusText()).willReturn("Internal Server Error");
willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)).given(errorHandler).handleError(response);
try {
template.execute("http://example.com", HttpMethod.GET, null, null);
fail("HttpServerErrorException expected");
}
catch (HttpServerErrorException ex) {
// expected
}
verify(response).close();
}
@Test
public void getForObject() throws Exception {
given(converter.canRead(String.class, null)).willReturn(true);
MediaType textPlain = new MediaType("text", "plain");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
String expected = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
given(converter.canRead(String.class, textPlain)).willReturn(true);
given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expected);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
String result = template.getForObject("http://example.com", String.class);
assertEquals("Invalid GET result", expected, result);
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void getUnsupportedMediaType() throws Exception {
given(converter.canRead(String.class, null)).willReturn(true);
MediaType supportedMediaType = new MediaType("foo", "bar");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(supportedMediaType));
given(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = new MediaType("bar", "baz");
responseHeaders.setContentType(contentType);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream("Foo".getBytes()));
given(converter.canRead(String.class, contentType)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
try {
template.getForObject("http://example.com/{p}", String.class, "resource");
fail("UnsupportedMediaTypeException expected");
}
catch (RestClientException ex) {
// expected
}
verify(response).close();
}
@Test
public void getForEntity() throws Exception {
given(converter.canRead(String.class, null)).willReturn(true);
MediaType textPlain = new MediaType("text", "plain");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
String expected = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
given(converter.canRead(String.class, textPlain)).willReturn(true);
given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expected);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
ResponseEntity<String> result = template.getForEntity("http://example.com", String.class);
assertEquals("Invalid GET result", expected, result.getBody());
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
assertEquals("Invalid Content-Type header", textPlain, result.getHeaders().getContentType());
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void getForObjectWithCustomUriTemplateHandler() throws Exception {
DefaultUriTemplateHandler uriTemplateHandler = new DefaultUriTemplateHandler();
uriTemplateHandler.setParsePath(true);
template.setUriTemplateHandler(uriTemplateHandler);
URI expectedUri = new URI("http://example.com/hotels/1/pic/pics%2Flogo.png/size/150x150");
given(requestFactory.createRequest(expectedUri, HttpMethod.GET)).willReturn(request);
given(request.getHeaders()).willReturn(new HttpHeaders());
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(new HttpHeaders());
given(response.getBody()).willReturn(null);
Map<String, String> uriVariables = new HashMap<>(2);
uriVariables.put("hotel", "1");
uriVariables.put("publicpath", "pics/logo.png");
uriVariables.put("scale", "150x150");
String url = "http://example.com/hotels/{hotel}/pic/{publicpath}/size/{scale}";
template.getForObject(url, String.class, uriVariables);
verify(response).close();
}
@Test
public void headForHeaders() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.HEAD)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders result = template.headForHeaders("http://example.com");
assertSame("Invalid headers returned", responseHeaders, result);
verify(response).close();
}
@Test
public void postForLocation() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
converter.write(helloWorld, null, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
URI result = template.postForLocation("http://example.com", helloWorld);
assertEquals("Invalid POST result", expected, result);
verify(response).close();
}
@Test
public void postForLocationEntityContentType() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
String helloWorld = "Hello World";
MediaType contentType = MediaType.TEXT_PLAIN;
given(converter.canWrite(String.class, contentType)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
converter.write(helloWorld, contentType, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.setContentType(contentType);
HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);
URI result = template.postForLocation("http://example.com", entity);
assertEquals("Invalid POST result", expected, result);
verify(response).close();
}
@Test
public void postForLocationEntityCustomHeader() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
converter.write(helloWorld, null, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.set("MyHeader", "MyValue");
HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);
URI result = template.postForLocation("http://example.com", entity);
assertEquals("Invalid POST result", expected, result);
assertEquals("No custom header set", "MyValue", requestHeaders.getFirst("MyHeader"));
verify(response).close();
}
@Test
public void postForLocationNoLocation() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
String helloWorld = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
converter.write(helloWorld, null, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
URI result = template.postForLocation("http://example.com", helloWorld);
assertNull("Invalid POST result", result);
verify(response).close();
}
@Test
public void postForLocationNull() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.postForLocation("http://example.com", null);
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void postForObject() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
String request = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
converter.write(request, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
Integer expected = 42;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.toString().getBytes()));
given(converter.canRead(Integer.class, textPlain)).willReturn(true);
given(converter.read(eq(Integer.class), any(HttpInputMessage.class))).willReturn(expected);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Integer result = template.postForObject("http://example.com", request, Integer.class);
assertEquals("Invalid POST result", expected, result);
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void postForEntity() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
String request = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
converter.write(request, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
Integer expected = 42;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.toString().getBytes()));
given(converter.canRead(Integer.class, textPlain)).willReturn(true);
given(converter.read(eq(Integer.class), any(HttpInputMessage.class))).willReturn(expected);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
ResponseEntity<Integer> result = template.postForEntity("http://example.com", request, Integer.class);
assertEquals("Invalid POST result", expected, result.getBody());
assertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType());
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void postForObjectNull() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(converter.canRead(Integer.class, textPlain)).willReturn(true);
given(converter.read(Integer.class, response)).willReturn(null);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Integer result = template.postForObject("http://example.com", null, Integer.class);
assertNull("Invalid POST result", result);
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void postForEntityNull() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(converter.canRead(Integer.class, textPlain)).willReturn(true);
given(converter.read(Integer.class, response)).willReturn(null);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
ResponseEntity<Integer> result = template.postForEntity("http://example.com", null, Integer.class);
assertFalse("Invalid POST result", result.hasBody());
assertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType());
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
public void put() throws Exception {
given(converter.canWrite(String.class, null)).willReturn(true);
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).willReturn(request);
String helloWorld = "Hello World";
converter.write(helloWorld, null, request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.put("http://example.com", helloWorld);
verify(response).close();
}
@Test
public void putNull() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.put("http://example.com", null);
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void patchForObject() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PATCH)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
String request = "Hello World";
given(converter.canWrite(String.class, null)).willReturn(true);
converter.write(request, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
Integer expected = 42;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.toString().getBytes()));
given(converter.canRead(Integer.class, textPlain)).willReturn(true);
given(converter.read(eq(Integer.class), any(HttpInputMessage.class))).willReturn(expected);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Integer result = template.patchForObject("http://example.com", request, Integer.class);
assertEquals("Invalid POST result", expected, result);
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
verify(response).close();
}
@Test
public void patchForObjectNull() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PATCH)).willReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
given(request.getHeaders()).willReturn(requestHeaders);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(converter.canRead(Integer.class, textPlain)).willReturn(true);
given(converter.read(Integer.class, response)).willReturn(null);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Integer result = template.patchForObject("http://example.com", null, Integer.class);
assertNull("Invalid POST result", result);
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verify(response).close();
}
@Test
public void delete() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.DELETE)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
template.delete("http://example.com");
verify(response).close();
}
@Test
public void optionsForAllow() throws Exception {
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.OPTIONS)).willReturn(request);
given(request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
EnumSet<HttpMethod> expected = EnumSet.of(HttpMethod.GET, HttpMethod.POST);
responseHeaders.setAllow(expected);
given(response.getHeaders()).willReturn(responseHeaders);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
Set<HttpMethod> result = template.optionsForAllow("http://example.com");
assertEquals("Invalid OPTIONS result", expected, result);
verify(response).close();
}
// Issue: SPR-9325, SPR-13860
@Test
public void ioException() throws Exception {
String url = "http://example.com/resource?access_token=123";
given(converter.canRead(String.class, null)).willReturn(true);
MediaType mediaType = new MediaType("foo", "bar");
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(mediaType));
given(requestFactory.createRequest(new URI(url), HttpMethod.GET)).willReturn(request);
given(request.getHeaders()).willReturn(new HttpHeaders());
given(request.execute()).willThrow(new IOException("Socket failure"));
try {
template.getForObject(url, String.class);
fail("RestClientException expected");
}
catch (ResourceAccessException ex) {
assertEquals("I/O error on GET request for \"http://example.com/resource\": " +
"Socket failure; nested exception is java.io.IOException: Socket failure",
ex.getMessage());
}
}
@Test
public void exchange() throws Exception {
given(converter.canRead(Integer.class, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
given(converter.canWrite(String.class, null)).willReturn(true);
String body = "Hello World";
converter.write(body, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
Integer expected = 42;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.toString().getBytes()));
given(converter.canRead(Integer.class, MediaType.TEXT_PLAIN)).willReturn(true);
given(converter.read(Integer.class, response)).willReturn(expected);
given(converter.read(eq(Integer.class), any(HttpInputMessage.class))).willReturn(expected);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.set("MyHeader", "MyValue");
HttpEntity<String> requestEntity = new HttpEntity<>(body, entityHeaders);
ResponseEntity<Integer> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, Integer.class);
assertEquals("Invalid POST result", expected, result.getBody());
assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
@Test
@SuppressWarnings("rawtypes")
public void exchangeParameterizedType() throws Exception {
GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class);
template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
ParameterizedTypeReference<List<Integer>> intList = new ParameterizedTypeReference<List<Integer>>() {};
given(converter.canRead(intList.getType(), null, null)).willReturn(true);
given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
given(this.request.getHeaders()).willReturn(requestHeaders);
given(converter.canWrite(String.class, String.class, null)).willReturn(true);
String requestBody = "Hello World";
converter.write(requestBody, String.class, null, this.request);
given(this.request.execute()).willReturn(response);
given(errorHandler.hasError(response)).willReturn(false);
List<Integer> expected = Collections.singletonList(42);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.TEXT_PLAIN);
responseHeaders.setContentLength(10);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
HttpStatus status = HttpStatus.OK;
given(response.getStatusCode()).willReturn(status);
given(response.getStatusText()).willReturn(status.getReasonPhrase());
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.set("MyHeader", "MyValue");
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, entityHeaders);
ResponseEntity<List<Integer>> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, intList);
assertEquals("Invalid POST result", expected, result.getBody());
assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verify(response).close();
}
}
|
package io.katharsis.request.path;
import io.katharsis.resource.exception.ResourceException;
import io.katharsis.resource.exception.ResourceFieldNotFoundException;
import io.katharsis.resource.exception.ResourceNotFoundException;
import io.katharsis.resource.field.ResourceField;
import io.katharsis.resource.registry.RegistryEntry;
import io.katharsis.resource.registry.ResourceRegistry;
import io.katharsis.utils.StringUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Builder responsible for parsing URL path.
*/
public class PathBuilder {
public static final String SEPARATOR = "/";
public static final String RELATIONSHIP_MARK = "relationships";
private final ResourceRegistry resourceRegistry;
public PathBuilder(ResourceRegistry resourceRegistry) {
this.resourceRegistry = resourceRegistry;
}
private static PathIds createPathIds(String idsString) {
List<String> pathIds = Arrays.asList(idsString.split(PathIds.ID_SEPERATOR));
return new PathIds(pathIds);
}
private static String[] splitPath(String path) {
if (path.startsWith(SEPARATOR)) {
path = path.substring(1);
}
if (path.endsWith(SEPARATOR)) {
path = path.substring(0, path.length());
}
return path.split(SEPARATOR);
}
/**
* Creates a path using the provided JsonPath structure.
*
* @param jsonPath JsonPath structure to be parsed
* @return String representing structure provided in the input
*/
public static String buildPath(JsonPath jsonPath) {
List<String> urlParts = new LinkedList<>();
JsonPath currentJsonPath = jsonPath;
String pathPart;
do {
if (currentJsonPath instanceof RelationshipsPath) {
pathPart = RELATIONSHIP_MARK + SEPARATOR + currentJsonPath.getElementName();
} else if (currentJsonPath instanceof FieldPath) {
pathPart = currentJsonPath.getElementName();
} else {
pathPart = currentJsonPath.getElementName();
if (currentJsonPath.getIds() != null) {
pathPart += SEPARATOR + mergeIds(currentJsonPath.getIds());
}
}
urlParts.add(pathPart);
currentJsonPath = currentJsonPath.getParentResource();
} while (currentJsonPath != null);
Collections.reverse(urlParts);
return SEPARATOR + StringUtils.join(SEPARATOR, urlParts) + SEPARATOR;
}
private static String mergeIds(PathIds ids) {
return StringUtils.join(PathIds.ID_SEPERATOR, ids.getIds());
}
/**
* Parses path provided by the application. The path provided cannot contain neither hostname nor protocol. It
* can start or end with slash e.g. <i>/tasks/1/</i> or <i>tasks/1</i>.
*
* @param path Path to be parsed
* @return doubly-linked list which represents path given at the input
*/
public JsonPath buildPath(String path) {
String[] strings = splitPath(path);
if (strings.length == 0 || (strings.length == 1 && "".equals(strings[0]))) {
throw new ResourceException("Path is empty");
}
JsonPath previousJsonPath = null, currentJsonPath = null;
PathIds pathIds;
boolean relationshipMark;
String elementName;
for (int currentElementIdx = 0; currentElementIdx < strings.length; ) {
elementName = null;
pathIds = null;
relationshipMark = false;
if (RELATIONSHIP_MARK.equals(strings[currentElementIdx])) {
relationshipMark = true;
currentElementIdx++;
}
if (currentElementIdx < strings.length && !RELATIONSHIP_MARK.equals(strings[currentElementIdx])) {
elementName = strings[currentElementIdx];
currentElementIdx++;
}
if (currentElementIdx < strings.length && !RELATIONSHIP_MARK.equals(strings[currentElementIdx])) {
pathIds = createPathIds(strings[currentElementIdx]);
currentElementIdx++;
}
RegistryEntry entry = resourceRegistry.getEntry(elementName);
if (previousJsonPath != null) {
currentJsonPath = getNonResourcePath(previousJsonPath, elementName, relationshipMark);
if (pathIds != null) {
throw new ResourceException("RelationshipsPath and FieldPath cannot contain ids");
}
} else if (entry != null && !relationshipMark) {
currentJsonPath = new ResourcePath(elementName);
} else {
throw new ResourceNotFoundException(path);
}
if (pathIds != null) {
currentJsonPath.setIds(pathIds);
}
if (previousJsonPath != null) {
previousJsonPath.setChildResource(currentJsonPath);
currentJsonPath.setParentResource(previousJsonPath);
}
previousJsonPath = currentJsonPath;
}
return currentJsonPath;
}
private JsonPath getNonResourcePath(JsonPath previousJsonPath, String elementName, boolean relationshipMark) {
String previousElementName = previousJsonPath.getElementName();
RegistryEntry previousEntry = resourceRegistry.getEntry(previousElementName);
Set<ResourceField> resourceFields = previousEntry.getResourceInformation().getRelationshipFields();
for (ResourceField field : resourceFields) {
if (field.getJsonName().equals(elementName)) {
if (relationshipMark) {
return new RelationshipsPath(elementName);
} else {
return new FieldPath(elementName);
}
}
}
//TODO: Throw different exception? element name can be null..
throw new ResourceFieldNotFoundException(elementName);
}
}
|
/*
* Copyright 2011-2016 Amazon.com, Inc. or its affiliates. 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. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.cognitosync.model;
import java.io.Serializable;
/**
* Returned for a successful ListDatasets request.
*/
public class ListDatasetsResult implements Serializable, Cloneable {
/** A set of datasets. */
private com.amazonaws.internal.SdkInternalList<Dataset> datasets;
/** Number of datasets returned. */
private Integer count;
/** A pagination token for obtaining the next page of results. */
private String nextToken;
/**
* A set of datasets.
*
* @return A set of datasets.
*/
public java.util.List<Dataset> getDatasets() {
if (datasets == null) {
datasets = new com.amazonaws.internal.SdkInternalList<Dataset>();
}
return datasets;
}
/**
* A set of datasets.
*
* @param datasets
* A set of datasets.
*/
public void setDatasets(java.util.Collection<Dataset> datasets) {
if (datasets == null) {
this.datasets = null;
return;
}
this.datasets = new com.amazonaws.internal.SdkInternalList<Dataset>(
datasets);
}
/**
* A set of datasets.
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setDatasets(java.util.Collection)} or
* {@link #withDatasets(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param datasets
* A set of datasets.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ListDatasetsResult withDatasets(Dataset... datasets) {
if (this.datasets == null) {
setDatasets(new com.amazonaws.internal.SdkInternalList<Dataset>(
datasets.length));
}
for (Dataset ele : datasets) {
this.datasets.add(ele);
}
return this;
}
/**
* A set of datasets.
*
* @param datasets
* A set of datasets.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ListDatasetsResult withDatasets(
java.util.Collection<Dataset> datasets) {
setDatasets(datasets);
return this;
}
/**
* Number of datasets returned.
*
* @param count
* Number of datasets returned.
*/
public void setCount(Integer count) {
this.count = count;
}
/**
* Number of datasets returned.
*
* @return Number of datasets returned.
*/
public Integer getCount() {
return this.count;
}
/**
* Number of datasets returned.
*
* @param count
* Number of datasets returned.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ListDatasetsResult withCount(Integer count) {
setCount(count);
return this;
}
/**
* A pagination token for obtaining the next page of results.
*
* @param nextToken
* A pagination token for obtaining the next page of results.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* A pagination token for obtaining the next page of results.
*
* @return A pagination token for obtaining the next page of results.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* A pagination token for obtaining the next page of results.
*
* @param nextToken
* A pagination token for obtaining the next page of results.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ListDatasetsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getDatasets() != null)
sb.append("Datasets: " + getDatasets() + ",");
if (getCount() != null)
sb.append("Count: " + getCount() + ",");
if (getNextToken() != null)
sb.append("NextToken: " + getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListDatasetsResult == false)
return false;
ListDatasetsResult other = (ListDatasetsResult) obj;
if (other.getDatasets() == null ^ this.getDatasets() == null)
return false;
if (other.getDatasets() != null
&& other.getDatasets().equals(this.getDatasets()) == false)
return false;
if (other.getCount() == null ^ this.getCount() == null)
return false;
if (other.getCount() != null
&& other.getCount().equals(this.getCount()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null
&& other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getDatasets() == null) ? 0 : getDatasets().hashCode());
hashCode = prime * hashCode
+ ((getCount() == null) ? 0 : getCount().hashCode());
hashCode = prime * hashCode
+ ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListDatasetsResult clone() {
try {
return (ListDatasetsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
|
package me.adjoined.gulimall.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import me.adjoined.common.utils.PageUtils;
import me.adjoined.gulimall.product.entity.CategoryEntity;
import java.util.Map;
/**
* ÉÌÆ·Èý¼¶·ÖÀà
*
* @author tianbian
* @email adjoined.tb@gmail.com
* @date 2021-03-30 21:05:37
*/
public interface CategoryService extends IService<CategoryEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
/**
* Copyright 2019 Anthony Trinh
*
* 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 ch.qos.logback.core.net;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import ch.qos.logback.core.CoreConstants;
/**
* Factory for {@link ch.qos.logback.core.net.ObjectWriter} instances.
*
* @author Sebastian Gröbler
*/
public class ObjectWriterFactory {
/**
* Creates a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance.
*
* @param outputStream the underlying {@link java.io.OutputStream} to write to
* @return a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance
* @throws IOException if an I/O error occurs while writing stream header
*/
public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException {
return new AutoFlushingObjectWriter(new ObjectOutputStream(outputStream), CoreConstants.OOS_RESET_FREQUENCY);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.