text
stringlengths 7
1.01M
|
|---|
package com.thirdpart.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.thirdpart.tasktrackerpms.R;
public class DisplayMultiLineItemView extends FrameLayout {
public DisplayMultiLineItemView(Context context){
this(context ,null);
}
public DisplayMultiLineItemView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
View view = LayoutInflater.from(context).inflate(
R.layout.common_display_multi_line_item, this, true);
InitView(view, attrs);
}
@Override
public void setBackgroundResource(int resid) {
// TODO Auto-generated method stub
super.setBackgroundResource(resid);
getChildAt(0).setBackgroundResource(resid);
}
@Override
protected void onDetachedFromWindow() {
// TODO Auto-generated method stub
super.onDetachedFromWindow();
}
private TextView nameView, contentView;
private void InitView(View view, AttributeSet attrs) {
// TODO Auto-generated method stub
String name = null;
String content = null;
if (attrs!=null) {
TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.DisplayViewStyle);
name = a.getString(R.styleable.DisplayViewStyle_customName);
content = a
.getString(R.styleable.DisplayViewStyle_customContent);
a.recycle();
}
nameView = (TextView) view.findViewById(R.id.common_display_item_name);
contentView = (TextView) view
.findViewById(R.id.common_display_item_content);
if (name != null) {
nameView.setText(name);
}
if (content != null) {
contentView.setText(content);
}
}
public void setNameAndContent(String name,String content) {
// TODO Auto-generated method stub
nameView.setText(name);
setContent(content);
}
public void setContentOnclickListenr(OnClickListener l){
contentView.setOnClickListener(l);
}
public void setContent(String describe) {
// TODO Auto-generated method stub
contentView.setText(describe);
}
public TextView getContentView() {
return contentView;
}
public String getContent() {
// TODO Auto-generated method stub
return TextUtils.isEmpty(contentView.getText())?null:contentView.getText().toString();
}
public void setNameBgColor(int rgb) {
// TODO Auto-generated method stub
setBackgroundColor(rgb);
}
}
|
/*******************************************************************************
*
* Copyright (C) 2018 Kim Kwon Young
*
* 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.ktoy.exchange.api.entity;
import com.google.common.base.MoreObjects;
import com.ktoy.exchange.api.entity.symbol.GdaxCurrencyPair;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "trades")
public class GdaxTrade implements Trade {
@Id
@GeneratedValue
private long id;
private GdaxCurrencyPair currency;
private long mtsCreate;
private long orderId;
private float execAmount;
private float execPrice;
private String orderType;
private float orderPrice;
/**
* Needed for hibernate
*/
public GdaxTrade() {
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public GdaxCurrencyPair getCurrency() {
return currency;
}
public void setCurrency(final GdaxCurrencyPair currency) {
this.currency = currency;
}
public long getMtsCreate() {
return mtsCreate;
}
public void setMtsCreate(final long mtsCreate) {
this.mtsCreate = mtsCreate;
}
public long getOrderId() {
return orderId;
}
public void setOrderId(final long orderId) {
this.orderId = orderId;
}
public float getExecAmount() {
return execAmount;
}
public void setExecAmount(final float execAmount) {
this.execAmount = execAmount;
}
public float getExecPrice() {
return execPrice;
}
public void setExecPrice(final float execPrice) {
this.execPrice = execPrice;
}
public String getOrderType() {
return orderType;
}
public void setOrderType(final String orderType) {
this.orderType = orderType;
}
public float getOrderPrice() {
return orderPrice;
}
public void setOrderPrice(final float orderPrice) {
this.orderPrice = orderPrice;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", id)
.add("currency", currency)
.add("mtsCreate", mtsCreate)
.add("orderId", orderId)
.add("execAmount", execAmount)
.add("execPrice", execPrice)
.add("orderType", orderType)
.add("orderPrice", orderPrice)
.toString();
}
}
|
package com.shake.app.utils;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import com.shake.app.Define;
public final class ViewUtil {
/**
* 从 dp 转换成 px 。
* @param dp
* @param context
* @return
*/
public static int convertDpToPixel(int dp, Context context) {
float px = dp * Define.DENSITY;
return Float.valueOf(px).intValue();
}
/**
* 从 dp 转换成 px 。
* @param dp
* @return
*/
public static int dp(int dp)
{
float px = dp * Define.DENSITY;
return Float.valueOf(px).intValue();
}
/**
* 从 px 转换成 dp 。
* @param px
* @param context
* @return
*/
public static int convertPixelsToDp(int px, Context context) {
float dp = px / Define.DENSITY;
return Float.valueOf(dp).intValue();
}
/**
* 把 RelativeLayout 内的 View 调整位置。
* @param view
* @param xPosition
* @param yPosition
*/
public static void resetViewToPosition(View view, int xPosition, int yPosition) {
view.clearAnimation();
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)view.getLayoutParams();
params.setMargins(xPosition, yPosition, -xPosition, -yPosition);
view.setLayoutParams(params);
}
/**
* 获得 RelativeLayout 内的 View 左上角的 X 坐标。
* @param view
* @return
*/
public static int getViewXPosition(View view) {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
return params.leftMargin;
}
/**
* 获得 RelativeLayout 内的 View 左上角的 Y 坐标。
* @param view
* @return
*/
public static int getViewYPosition(View view) {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
return params.topMargin;
}
/**
* 通过动画移动 RelativeLayout 内的 View 到新的位置。
* @param view
* @param xPosition
* @param yPosition
* @param duration 动画的时间(毫秒)。
*/
public static void animateViewToPosition(final View view, final int xPosition, final int yPosition, int duration) {
view.clearAnimation();
final int currentX = getViewXPosition(view);
final int currentY = getViewYPosition(view);
TranslateAnimation translateAnimation = new TranslateAnimation(0, xPosition - currentX, 0, yPosition - currentY);
translateAnimation.setInterpolator(new DecelerateInterpolator(1.0f));
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
view.clearAnimation();
resetViewToPosition(view, xPosition, yPosition);
}
});
translateAnimation.setDuration(duration);
translateAnimation.reset();
translateAnimation.setFillAfter(true);
view.startAnimation(translateAnimation);
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/automl/v1beta1/operations.proto
package com.google.cloud.automl.v1beta1;
public interface DeleteOperationMetadataOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.automl.v1beta1.DeleteOperationMetadata)
com.google.protobuf.MessageOrBuilder {
}
|
package com.behzad.enums;
/**
* Created by Behzad Altaf
*/
public enum InputSplitStrategy {
LINEAR,
LINEARREVERSE,
RANDOM,
STRATIFIED
}
|
package com.github.zuihou.area2;
import cn.hutool.log.StaticLog;
import com.github.zuihou.authority.entity.common.Area;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class LocationCityParserDecorator {
public List<Area> parseProvinces(List<Area> list) {
StaticLog.info("查询出经纬度了. . . ");
return list;
}
}
|
/*******************************************************************************
* Copyright (c) 2016 ATOS Spain S.A.
* 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.
*
* Contributors:
* Yosu Gorroñogoitia (ATOS) - main development
*
* Initially developed in the context of SUPERSEDE EU project www.supersede.eu
*******************************************************************************/
package eu.supersede.integration.api.monitoring.proxies.test;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.util.Assert;
import eu.supersede.integration.api.monitoring.manager.types.HttpMonitorConfiguration;
import eu.supersede.integration.api.monitoring.manager.types.Method;
import eu.supersede.integration.api.monitoring.monitors.proxies.HttpMonitorProxy;
public class HttpMonitorProxyTest {
// private static final Logger log =
// LoggerFactory.getLogger(FeedbackOrchestratorProxyTest.class);
private static HttpMonitorProxy<?, ?> proxy;
@BeforeClass
public static void setup() throws Exception {
proxy = new HttpMonitorProxy<Object, Object>();
}
@Test
public void testCreateAndDeleteMonitorConfiguration() throws Exception {
HttpMonitorConfiguration conf = createMonitorConfiguration();
HttpMonitorConfiguration result = proxy.createMonitorConfiguration(conf);
Assert.notNull(result);
Assert.isTrue(result.getId()>0);
proxy.deleteMonitorConfiguration(conf);
}
@Test
public void testCreateAndDeleteMonitorConfigurationMultipart() throws Exception {
HttpMonitorConfiguration conf = createMonitorConfiguration();
Path file = FileSystems.getDefault().getPath("src/test/resources/files", "list1s.txt");
HttpMonitorConfiguration result = proxy.createMonitorConfiguration(conf, file );
Assert.notNull(result);
Assert.isTrue(result.getId()>0);
proxy.deleteMonitorConfiguration(conf);
}
@Test
public void testUpdateMonitorConfiguration() throws Exception {
HttpMonitorConfiguration conf = createMonitorConfiguration();
HttpMonitorConfiguration result = proxy.createMonitorConfiguration(conf);
Assert.notNull(result);
result.setTimeSlot(6000);
result = proxy.updateMonitorConfiguration(result);
Assert.notNull(result);
Assert.isTrue(result.getTimeSlot() == 6000);
}
@Test
public void testUpdateMonitorConfigurationMultipart() throws Exception {
HttpMonitorConfiguration conf = createMonitorConfiguration();
Path file = FileSystems.getDefault().getPath("src/test/resources/files", "list1s.txt");
HttpMonitorConfiguration result = proxy.createMonitorConfiguration(conf, file);
Assert.notNull(result);
result.setTimeSlot(6000);
result = proxy.updateMonitorConfiguration(result);
Assert.notNull(result);
Assert.isTrue(result.getTimeSlot() == 6000);
}
private HttpMonitorConfiguration createMonitorConfiguration() throws MalformedURLException {
HttpMonitorConfiguration conf = new HttpMonitorConfiguration();
conf.setToolName("ApacheHttp");
conf.setTimeSlot(3000);
conf.setKafkaTopic("HttpTopic");
conf.setKafkaEndpoint(new URL("http://localhost:9092"));
conf.setUrl("http://lab-supersede.atos-sports.tv:8000/handshake_test.php");
conf.setMethod(Method.GET);
return conf;
}
}
|
package io.h2cone.network.netty.example.discard;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* https://netty.io/wiki/user-guide-for-4.x.html
*/
public class DiscardServer {
private int port;
public DiscardServer(int port) {
this.port = port;
}
public void run() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync();
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
int port = 8080;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
new DiscardServer(port).run();
}
}
|
/*
* Copyright 2017-2022 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.chime.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.chime.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListAppInstancesRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListAppInstancesRequestProtocolMarshaller implements Marshaller<Request<ListAppInstancesRequest>, ListAppInstancesRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/app-instances")
.httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AmazonChime").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public ListAppInstancesRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<ListAppInstancesRequest> marshall(ListAppInstancesRequest listAppInstancesRequest) {
if (listAppInstancesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<ListAppInstancesRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
listAppInstancesRequest);
protocolMarshaller.startMarshalling();
ListAppInstancesRequestMarshaller.getInstance().marshall(listAppInstancesRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
package org.odk.collect.android.utilities;
public class ArrayUtils {
/**
* An empty immutable {@code Long} array.
*/
private static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];
/**
* An empty immutable {@code long} array.
*/
private static final long[] EMPTY_LONG_ARRAY = new long[0];
private ArrayUtils() {
}
/**
* <p>Converts an array of primitive longs to objects.</p>
*
* @param array a {@code long} array
* @return a {@code Long} array
*/
@SuppressWarnings("PMD.AvoidArrayLoops")
public static Long[] toObject(long[] array) {
if (array == null || array.length == 0) {
return EMPTY_LONG_OBJECT_ARRAY;
}
final Long[] result = new Long[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i];
}
return result;
}
/**
* <p>Converts an array of object Longs to primitives.</p>
*
* @param array a {@code Long} array
* @return a {@code long} array
*/
@SuppressWarnings("PMD.AvoidArrayLoops")
public static long[] toPrimitive(Long[] array) {
if (array == null || array.length == 0) {
return EMPTY_LONG_ARRAY;
}
final long[] result = new long[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i];
}
return result;
}
}
|
package ex;
/*
* Topic: 假設某個停車場的費率是停車2小時以內,每半小時30元,
* 超過2小時,但未滿4小時的部份,每半小時40元,
* 超過4小時以上的部份,每半小時60元,未滿半小時部分不計費。
* 如果您從早上10點23分停到下午3點20分,請撰寫程式計算共需繳交的停車費。
* Date: 2016/09/26
* Author: 102002017 邱泓偉
*/
import java.util.Scanner;
public class ex03_102002017 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Start
System.out.println("幾點幾分進入停車場 ");
Scanner scn = new Scanner(System.in);
int h1 = scn.nextInt();
Scanner scn2 = new Scanner(System.in);
int m1 = scn2.nextInt();
//End
System.out.println("幾點幾分離開停車場 ");
Scanner scn3 = new Scanner(System.in);
int h2 = scn3.nextInt();
Scanner scn4 = new Scanner(System.in);
int m2 = scn4.nextInt();
//停車時間
int h3 = h2 - h1;
int m3 = m2 - m1;
if(m3 < 0)
{
h3-=1;
m3 = 60+m3;
}
int time = (h3*2)+(m3/30);
//停車費
int price = 0;
int p1;
int p2;
int p3;
if(time < 4)
{
p1 = time * 30;
System.out.println("停車費 = " + p1);
}
else if (time > 4 && time < 8)
{
p2 = time - 4;
price = p2 * 40;
System.out.println("停車費 = " + (120 + price));
}
else if (time > 8)
{
p3 = time - 8;
price = p3 * 60;
System.out.println("停車費 = " + (120 + 160 + price));
}
}
}
|
/**
* Copyright (c) 2015, by the Authors: Antonio Sanchez (UBC)
*
* This software is freely available under a 2-clause BSD license. Please see
* the LICENSE file in the ArtiSynth distribution directory for details.
*/
package maspack.fileutil.uri;
import java.util.HashMap;
public class URIxScheme {
public static final int ZIP_TYPE = 1;
private static HashMap<String,URIxScheme> schemeMap = new HashMap<>();
public static final URIxScheme GZ = createScheme("gz", ZIP_TYPE);
public static final URIxScheme BZ2 = createScheme("bz2", ZIP_TYPE);
public static final URIxScheme TAR = createScheme("tar", ZIP_TYPE);
public static final URIxScheme TGZ = createScheme("tgz", ZIP_TYPE);
public static final URIxScheme TBZ2 = createScheme("tbz2", ZIP_TYPE);
public static final URIxScheme ZIP = createScheme("zip", ZIP_TYPE);
public static final URIxScheme JAR = createScheme("jar", ZIP_TYPE);
public static final URIxScheme FILE = createScheme("file", 0);
public static final URIxScheme HTTP = createScheme("http", 0);
public static final URIxScheme HTTPS = createScheme("https", 0);
public static final URIxScheme FTP = createScheme("ftp", 0);
public static final URIxScheme SFTP = createScheme("sftp", 0);
public static final URIxScheme WEBDAV = createScheme("webdav", 0, new String[]{"webdav", "dav"});
public static final URIxScheme WEBDAVS = createScheme("webdavs", 0, new String[]{"webdavs", "davs"});
private String name;
private int type;
private String[] aliases;
private URIxScheme(String name, int type) {
this(name, type, new String[]{name});
}
private URIxScheme(String name, int type, String[] aliases) {
this.name = name;
this.type = type;
if (aliases == null) {
aliases = new String[]{ name };
}
this.aliases = aliases;
}
public boolean isZipType() {
return (type & ZIP_TYPE) > 0;
}
public String toString() {
return name;
}
public static URIxScheme createScheme(String str, int typemask) {
return createScheme(str, typemask, new String[]{str});
}
public static URIxScheme createScheme(String str, int typemask, String[] aliases) {
URIxScheme scheme = new URIxScheme(str, typemask, aliases);
synchronized (schemeMap) {
for (String alias : scheme.aliases) {
schemeMap.put(alias, scheme);
}
}
return scheme;
}
public static URIxScheme findScheme(String str) {
URIxScheme scheme = null;
synchronized(schemeMap) {
scheme = schemeMap.get(str);
// XXX do not create scheme by default
// if (scheme == null) {
// scheme = createScheme(str, 0, new String[]{str});
// }
}
return scheme;
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.network;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.os.UserManager;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class NetworkResetRestrictionCheckerTest {
@Mock
private UserManager mUserManager;
@Mock
private Context mContext;
private NetworkResetRestrictionChecker mRestrictionChecker;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
mRestrictionChecker = spy(new NetworkResetRestrictionChecker(mContext));
}
@Test
public void testHasRestriction_notAdmin_shouldReturnTrue() {
final Context context = mock(Context.class);
when(context.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
when(mUserManager.isAdminUser()).thenReturn(false);
assertThat(mRestrictionChecker.hasRestriction()).isTrue();
}
@Test
public void testHasRestriction_hasUserRestriction_shouldReturnTrue() {
when(mUserManager.isAdminUser()).thenReturn(true);
doReturn(true).when(mRestrictionChecker).hasUserBaseRestriction();
doReturn(false).when(mRestrictionChecker).isRestrictionEnforcedByAdmin();
assertThat(mRestrictionChecker.hasRestriction()).isTrue();
}
@Test
public void testHasRestriction_hasAdminRestriction_shouldReturnTrue() {
when(mUserManager.isAdminUser()).thenReturn(true);
doReturn(false).when(mRestrictionChecker).hasUserBaseRestriction();
doReturn(true).when(mRestrictionChecker).isRestrictionEnforcedByAdmin();
assertThat(mRestrictionChecker.hasRestriction()).isTrue();
}
@Test
public void testHasRestriction_noRestriction_shouldReturnFalse() {
when(mUserManager.isAdminUser()).thenReturn(true);
doReturn(false).when(mRestrictionChecker).hasUserBaseRestriction();
doReturn(false).when(mRestrictionChecker).isRestrictionEnforcedByAdmin();
assertThat(mRestrictionChecker.hasRestriction()).isFalse();
}
}
|
package com.parking;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "Parking";
}
}
|
/*
* @author : Jagepard <jagepard@yandex.ru>
* @license https://mit-license.org/ MIT
*/
package Behavioral.Command;
import java.util.LinkedHashMap;
public class Lamp implements DeviceInterface{
LinkedHashMap<String, CommandInterface> commands = new LinkedHashMap<>();
public String execute(String commandName) {
if (!commands.containsKey(commandName)) {
throw new IllegalArgumentException("Command does not exist in the registry");
}
return commands.get(commandName).execute();
}
public void setCommand(String commandName, CommandInterface command) {
if (commands.containsKey(commandName)) {
throw new IllegalArgumentException("Command already exists");
}
commands.put(commandName, command);
}
}
|
package com.codeborne.selenide.commands;
import com.codeborne.selenide.DriverStub;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.ex.ElementNotFound;
import com.codeborne.selenide.impl.WebElementSource;
import org.assertj.core.api.WithAssertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Quotes;
import static java.util.Collections.singletonList;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class SelectOptionByTextOrIndexCommandTest implements WithAssertions {
private SelenideElement proxy = mock(SelenideElement.class);
private WebElementSource selectField = mock(WebElementSource.class);
private SelectOptionByTextOrIndex selectOptionByTextOrIndexCommand = new SelectOptionByTextOrIndex();
private WebElement mockedElement = mock(WebElement.class);
private String defaultElementText = "This is element text";
private WebElement mockedFoundElement = mock(WebElement.class);
private int defaultIndex = 1;
@BeforeEach
void setup() {
when(selectField.driver()).thenReturn(new DriverStub());
when(selectField.getWebElement()).thenReturn(mockedElement);
when(mockedElement.getText()).thenReturn(defaultElementText);
when(mockedElement.getTagName()).thenReturn("select");
when(mockedFoundElement.isSelected()).thenReturn(true);
}
@Test
void testSelectOptionByText() {
when(mockedElement.findElements(By.xpath(".//option[normalize-space(.) = " + Quotes.escape(defaultElementText) + "]")))
.thenReturn(singletonList(mockedFoundElement));
selectOptionByTextOrIndexCommand.execute(proxy, selectField, new Object[]{new String[]{this.defaultElementText}});
}
@Test
void selectOptionByTextWhenElementIsNotFound() {
try {
selectOptionByTextOrIndexCommand.execute(proxy, selectField, new Object[]{new String[]{this.defaultElementText}});
} catch (ElementNotFound exception) {
assertThat(exception)
.hasMessageStartingWith(String.format("Element not found {null/option[text:%s]}%nExpected: exist", this.defaultElementText));
}
}
@Test
void selectedOptionByTextWhenNoSuchElementIsThrown() {
doThrow(new NoSuchElementException("no element found"))
.when(mockedElement)
.findElements(By.xpath(".//option[normalize-space(.) = " + Quotes.escape(defaultElementText) + "]"));
try {
selectOptionByTextOrIndexCommand.execute(proxy, selectField, new Object[]{new String[]{""}});
} catch (ElementNotFound exception) {
assertThat(exception)
.hasMessage("Element not found {null/option[text:]}\nExpected: exist\n" +
"Screenshot: null\n" +
"Timeout: 0 ms.\n" +
"Caused by: NoSuchElementException: Cannot locate element with text:");
}
}
@Test
void selectOptionByIndex() {
when(mockedElement.findElements(By.tagName("option"))).thenReturn(singletonList(mockedFoundElement));
when(mockedFoundElement.getAttribute("index")).thenReturn(String.valueOf(defaultIndex));
selectOptionByTextOrIndexCommand.execute(proxy, selectField, new Object[]{new int[]{defaultIndex}});
}
@Test
void selectOptionByIndexWhenNoElementFound() {
try {
selectOptionByTextOrIndexCommand.execute(proxy, selectField, new Object[]{new int[]{defaultIndex}});
} catch (ElementNotFound exception) {
assertThat(exception)
.hasMessageStartingWith(String.format("Element not found {null/option[index:%d]}%nExpected: exist", defaultIndex));
}
}
@Test
void executeMethodWhenArgIsNotStringOrInt() {
assertThat(selectOptionByTextOrIndexCommand.execute(proxy, selectField, new Object[]{new Double[]{1.0}}))
.isNull();
}
}
|
package ir.alirezaiyan.stepindicator;
import androidx.appcompat.app.AppCompatActivity;
import ir.alirezaiyan.stepview.StepIndicator;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
int step = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StepIndicator stepIndicator = findViewById(R.id.stepIndicator);
String[] icons = {getResources().getString(R.string.step1),
getResources().getString(R.string.step2),
getResources().getString(R.string.step3),
getResources().getString(R.string.step4), ""};
stepIndicator.setIcons(icons);
stepIndicator.setCurrentStepPosition(0);
findViewById(R.id.button).setOnClickListener(v -> {
step++;
if (step > 4)
step = 0;
stepIndicator.setCurrentStepPosition(step);
});
}
}
|
/*
// * Copyright 1999-2017 Alibaba Group Holding 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.alibaba.druid.bvt.sql.sqlserver;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser;
import com.alibaba.druid.sql.test.TestUtils;
public class SQLServerSelectTest13 extends TestCase {
public void test_simple() throws Exception {
String sql = "SELECT" + //
" a.* " + //
"FROM" + //
" (" + //
" SELECT" + //
" row_number () over (ORDER BY a.time_add DESC) ROW," + //
" a.detail_no AS detailNo," + //
" a.ba_id AS baId," + //
" a.ba_name AS baName," + //
" a.tran_no AS tranNo," + //
" a.tran_name AS tranName, " + //
" a.tran_type AS tranType, " + //
" a.balance_type AS balanceType, " + //
" a.detail_income AS detailIncome, " + //
" a.detail_payout AS detailPayout, " + //
" a.before_balance AS beforeBalance, " + //
" a.after_balance AS afterBalance, " + //
" a.time_add AS timeAdd, " + //
" a.user_add AS userAdd, " + //
" a.remark AS remark, " + //
" ( " + //
" SELECT " + //
" top 1 t.param_name " + //
" FROM " + //
" config.sys_params t " + //
" WHERE " + //
" t.param_type = ? " + //
" AND t.param_value = a.tran_type " + //
" ) AS tranTypeName " + //
" FROM " + //
" bussiness.account_detail a " + //
" WHERE " + //
" 1 = 1 " + //
" AND a.time_add >= ? " + //
" AND a.time_add <= ? " + //
" ) a " + //
"WHERE " + //
" a. ROW NOT BETWEEN (?+ 1) " + //
"AND (?+?)"; //
String expect = "SELECT a.*\n" +
"FROM (\n" +
"\tSELECT ROW_NUMBER() OVER (ORDER BY a.time_add DESC) AS ROW, a.detail_no AS detailNo, a.ba_id AS baId, a.ba_name AS baName, a.tran_no AS tranNo\n" +
"\t\t, a.tran_name AS tranName, a.tran_type AS tranType, a.balance_type AS balanceType, a.detail_income AS detailIncome, a.detail_payout AS detailPayout\n" +
"\t\t, a.before_balance AS beforeBalance, a.after_balance AS afterBalance, a.time_add AS timeAdd, a.user_add AS userAdd, a.remark AS remark\n" +
"\t\t, (\n" +
"\t\t\tSELECT TOP 1 t.param_name\n" +
"\t\t\tFROM config.sys_params t\n" +
"\t\t\tWHERE t.param_type = ?\n" +
"\t\t\t\tAND t.param_value = a.tran_type\n" +
"\t\t) AS tranTypeName\n" +
"\tFROM bussiness.account_detail a\n" +
"\tWHERE 1 = 1\n" +
"\t\tAND a.time_add >= ?\n" +
"\t\tAND a.time_add <= ?\n" +
") a\n" +
"WHERE a.ROW NOT BETWEEN ? + 1 AND ? + ?";
SQLServerStatementParser parser = new SQLServerStatementParser(sql);
SQLStatement stmt = parser.parseStatementList().get(0);
String text = TestUtils.outputSqlServer(stmt);
Assert.assertEquals(expect, text);
// System.out.println(text);
}
}
|
package com.dreamcc.system.service.impl;
import com.dreamcc.common.core.utils.StringUtils;
import com.dreamcc.system.api.model.LoginUser;
import com.dreamcc.system.domain.SysUserOnline;
import com.dreamcc.system.service.ISysUserOnlineService;
import org.springframework.stereotype.Service;
/**
* 在线用户 服务层处理
*
* @author ruoyi
*/
@Service
public class SysUserOnlineServiceImpl implements ISysUserOnlineService
{
/**
* 通过登录地址查询信息
*
* @param ipaddr 登录地址
* @param user 用户信息
* @return 在线用户信息
*/
@Override
public SysUserOnline selectOnlineByIpaddr(String ipaddr, LoginUser user)
{
if (StringUtils.equals(ipaddr, user.getIpaddr()))
{
return loginUserToUserOnline(user);
}
return null;
}
/**
* 通过用户名称查询信息
*
* @param userName 用户名称
* @param user 用户信息
* @return 在线用户信息
*/
@Override
public SysUserOnline selectOnlineByUserName(String userName, LoginUser user)
{
if (StringUtils.equals(userName, user.getUsername()))
{
return loginUserToUserOnline(user);
}
return null;
}
/**
* 通过登录地址/用户名称查询信息
*
* @param ipaddr 登录地址
* @param userName 用户名称
* @param user 用户信息
* @return 在线用户信息
*/
@Override
public SysUserOnline selectOnlineByInfo(String ipaddr, String userName, LoginUser user)
{
if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername()))
{
return loginUserToUserOnline(user);
}
return null;
}
/**
* 设置在线用户信息
*
* @param user 用户信息
* @return 在线用户
*/
@Override
public SysUserOnline loginUserToUserOnline(LoginUser user)
{
if (StringUtils.isNull(user))
{
return null;
}
SysUserOnline sysUserOnline = new SysUserOnline();
sysUserOnline.setTokenId(user.getToken());
sysUserOnline.setUserName(user.getUsername());
sysUserOnline.setIpaddr(user.getIpaddr());
sysUserOnline.setLoginTime(user.getLoginTime());
return sysUserOnline;
}
}
|
package com.mlykotom.valifi.fields;
import com.mlykotom.valifi.ValiFi;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
public class ValiFieldPhone extends ValiFieldText {
public ValiFieldPhone() {
super();
addPhoneValidator(getString(getErrorRes(ValiFi.Builder.ERROR_RES_PHONE)));
}
public ValiFieldPhone(@Nullable String defaultValue) {
super(defaultValue);
addPhoneValidator(getString(getErrorRes(ValiFi.Builder.ERROR_RES_PHONE)));
}
public ValiFieldPhone(@Nullable String defaultValue, boolean markAsChanged) {
super(defaultValue, markAsChanged);
addPhoneValidator(getString(getErrorRes(ValiFi.Builder.ERROR_RES_PHONE)));
}
public ValiFieldPhone(@StringRes int errorResource) {
super();
addPhoneValidator(getString(errorResource));
}
public ValiFieldPhone(@Nullable String defaultValue, @StringRes int errorResource) {
super(defaultValue);
addPhoneValidator(getString(errorResource));
}
public ValiFieldPhone(@Nullable String defaultValue, @StringRes int errorResource, boolean markAsChanged) {
super(defaultValue, markAsChanged);
addPhoneValidator(getString(errorResource));
}
public ValiFieldPhone(@Nullable String defaultValue, String errorMessage) {
super(defaultValue);
addPhoneValidator(errorMessage);
}
public ValiFieldPhone(@Nullable String defaultValue, String errorMessage, boolean markAsChanged) {
super(defaultValue, markAsChanged);
addPhoneValidator(errorMessage);
}
}
|
package okhttp3.internal.http2;
import java.util.List;
import kotlin.Metadata;
import okhttp3.internal.concurrent.Task;
@Metadata(bv = {1, 0, 3}, d1 = {"\u0000\u0011\n\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\t\n\u0000*\u0001\u0000\b\n\u0018\u00002\u00020\u0001J\b\u0010\u0002\u001a\u00020\u0003H\u0016¨\u0006\u0004¸\u0006\u0000"}, d2 = {"okhttp3/internal/concurrent/TaskQueue$execute$1", "Lokhttp3/internal/concurrent/Task;", "runOnce", "", "okhttp"}, k = 1, mv = {1, 1, 16})
/* compiled from: TaskQueue.kt */
public final class Http2Connection$pushHeadersLater$$inlined$execute$1 extends Task {
final /* synthetic */ boolean $cancelable;
final /* synthetic */ boolean $inFinished$inlined;
final /* synthetic */ String $name;
final /* synthetic */ List $requestHeaders$inlined;
final /* synthetic */ int $streamId$inlined;
final /* synthetic */ Http2Connection this$0;
/* JADX INFO: super call moved to the top of the method (can break code semantics) */
public Http2Connection$pushHeadersLater$$inlined$execute$1(String str, boolean z, String str2, boolean z2, Http2Connection http2Connection, int i, List list, boolean z3) {
super(str2, z2);
this.$name = str;
this.$cancelable = z;
this.this$0 = http2Connection;
this.$streamId$inlined = i;
this.$requestHeaders$inlined = list;
this.$inFinished$inlined = z3;
}
/* JADX WARNING: Code restructure failed: missing block: B:18:?, code lost:
return -1;
*/
/* JADX WARNING: Exception block dominator not found, dom blocks: [] */
/* Code decompiled incorrectly, please refer to instructions dump. */
public long runOnce() {
/*
r4 = this;
okhttp3.internal.http2.Http2Connection r0 = r4.this$0
okhttp3.internal.http2.PushObserver r0 = r0.pushObserver
int r1 = r4.$streamId$inlined
java.util.List r2 = r4.$requestHeaders$inlined
boolean r3 = r4.$inFinished$inlined
boolean r0 = r0.onHeaders(r1, r2, r3)
if (r0 == 0) goto L_0x001f
okhttp3.internal.http2.Http2Connection r1 = r4.this$0 // Catch:{ IOException -> 0x003c }
okhttp3.internal.http2.Http2Writer r1 = r1.getWriter() // Catch:{ IOException -> 0x003c }
int r2 = r4.$streamId$inlined // Catch:{ IOException -> 0x003c }
okhttp3.internal.http2.ErrorCode r3 = okhttp3.internal.http2.ErrorCode.CANCEL // Catch:{ IOException -> 0x003c }
r1.rstStream(r2, r3) // Catch:{ IOException -> 0x003c }
L_0x001f:
if (r0 != 0) goto L_0x0025
boolean r0 = r4.$inFinished$inlined // Catch:{ IOException -> 0x003c }
if (r0 == 0) goto L_0x003c
L_0x0025:
okhttp3.internal.http2.Http2Connection r0 = r4.this$0 // Catch:{ IOException -> 0x003c }
monitor-enter(r0) // Catch:{ IOException -> 0x003c }
okhttp3.internal.http2.Http2Connection r1 = r4.this$0 // Catch:{ all -> 0x0039 }
java.util.Set r1 = r1.currentPushRequests // Catch:{ all -> 0x0039 }
int r2 = r4.$streamId$inlined // Catch:{ all -> 0x0039 }
java.lang.Integer r2 = java.lang.Integer.valueOf(r2) // Catch:{ all -> 0x0039 }
r1.remove(r2) // Catch:{ all -> 0x0039 }
monitor-exit(r0) // Catch:{ IOException -> 0x003c }
goto L_0x003c
L_0x0039:
r1 = move-exception
monitor-exit(r0) // Catch:{ IOException -> 0x003c }
throw r1 // Catch:{ IOException -> 0x003c }
L_0x003c:
r0 = -1
return r0
*/
throw new UnsupportedOperationException("Method not decompiled: okhttp3.internal.http2.Http2Connection$pushHeadersLater$$inlined$execute$1.runOnce():long");
}
}
|
// Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.numpy;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import org.bytedeco.cpython.*;
import static org.bytedeco.cpython.global.python.*;
import static org.bytedeco.numpy.global.numpy.*;
/* Function pointers for freeing or cloning auxiliary data */
@Properties(inherit = org.bytedeco.numpy.presets.numpy.class)
public class NpyAuxData_FreeFunc extends FunctionPointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public NpyAuxData_FreeFunc(Pointer p) { super(p); }
protected NpyAuxData_FreeFunc() { allocate(); }
private native void allocate();
public native void call(NpyAuxData arg0);
}
|
package ga.gasoft.smartpolice.Network;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetUtils
{
public static String NO_NETWORK = "oops! it seems like you've lost connectivity..";
public static String SERVER_ERROR = "Seems like our server is not behaving";
public static String NETWORK_TIMEOUT = "Oh damn! there goes the network";
public static String NETWORK_ERROR = "Oh damn! there goes the network";
public static Boolean isOnline(Context c)
{
ConnectivityManager con = null;
if(c != null)
con = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
if(con != null)
{
NetworkInfo ni = con.getActiveNetworkInfo();
if(ni != null && ni.isAvailable() && ni.isConnected())
{
return true;
}
}
return false;
}
}
|
package com.beanframework.core.importlistener;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import com.beanframework.core.CoreImportListenerConstants;
import com.beanframework.imex.registry.ImportListener;
@Component
public class AddressImportListener extends ImportListener {
@PostConstruct
public void importer() {
setType(CoreImportListenerConstants.AddressImport.TYPE);
setName(CoreImportListenerConstants.AddressImport.NAME);
setSort(CoreImportListenerConstants.AddressImport.SORT);
setDescription(CoreImportListenerConstants.AddressImport.DESCRIPTION);
setClassCsv(CoreImportListenerConstants.AddressImport.CLASS_CSV);
setClassEntity(CoreImportListenerConstants.AddressImport.CLASS_ENTITY);
}
}
|
package org.compiere.model;
/** Generated Interface for C_Phonecall_Schema_Version
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public interface I_C_Phonecall_Schema_Version
{
/** TableName=C_Phonecall_Schema_Version */
public static final String Table_Name = "C_Phonecall_Schema_Version";
/** AD_Table_ID=541175 */
// public static final int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name);
// org.compiere.util.KeyNamePair Model = new org.compiere.util.KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 7 - System - Client - Org
*/
// java.math.BigDecimal accessLevel = java.math.BigDecimal.valueOf(7);
/** Load Meta Data */
/**
* Get Mandant.
* Mandant für diese Installation.
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getAD_Client_ID();
public org.compiere.model.I_AD_Client getAD_Client();
/** Column definition for AD_Client_ID */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_AD_Client> COLUMN_AD_Client_ID = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_AD_Client>(I_C_Phonecall_Schema_Version.class, "AD_Client_ID", org.compiere.model.I_AD_Client.class);
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/**
* Set Sektion.
* Organisatorische Einheit des Mandanten
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setAD_Org_ID (int AD_Org_ID);
/**
* Get Sektion.
* Organisatorische Einheit des Mandanten
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getAD_Org_ID();
public org.compiere.model.I_AD_Org getAD_Org();
public void setAD_Org(org.compiere.model.I_AD_Org AD_Org);
/** Column definition for AD_Org_ID */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_AD_Org> COLUMN_AD_Org_ID = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_AD_Org>(I_C_Phonecall_Schema_Version.class, "AD_Org_ID", org.compiere.model.I_AD_Org.class);
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/**
* Set Anrufliste.
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setC_Phonecall_Schema_ID (int C_Phonecall_Schema_ID);
/**
* Get Anrufliste.
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getC_Phonecall_Schema_ID();
public org.compiere.model.I_C_Phonecall_Schema getC_Phonecall_Schema();
public void setC_Phonecall_Schema(org.compiere.model.I_C_Phonecall_Schema C_Phonecall_Schema);
/** Column definition for C_Phonecall_Schema_ID */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_C_Phonecall_Schema> COLUMN_C_Phonecall_Schema_ID = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_C_Phonecall_Schema>(I_C_Phonecall_Schema_Version.class, "C_Phonecall_Schema_ID", org.compiere.model.I_C_Phonecall_Schema.class);
/** Column name C_Phonecall_Schema_ID */
public static final String COLUMNNAME_C_Phonecall_Schema_ID = "C_Phonecall_Schema_ID";
/**
* Set Anruflistenversion.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setC_Phonecall_Schema_Version_ID (int C_Phonecall_Schema_Version_ID);
/**
* Get Anruflistenversion.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getC_Phonecall_Schema_Version_ID();
/** Column definition for C_Phonecall_Schema_Version_ID */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_C_Phonecall_Schema_Version_ID = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "C_Phonecall_Schema_Version_ID", null);
/** Column name C_Phonecall_Schema_Version_ID */
public static final String COLUMNNAME_C_Phonecall_Schema_Version_ID = "C_Phonecall_Schema_Version_ID";
/**
* Get Erstellt.
* Datum, an dem dieser Eintrag erstellt wurde
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public java.sql.Timestamp getCreated();
/** Column definition for Created */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_Created = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "Created", null);
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/**
* Get Erstellt durch.
* Nutzer, der diesen Eintrag erstellt hat
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getCreatedBy();
/** Column definition for CreatedBy */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_AD_User> COLUMN_CreatedBy = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_AD_User>(I_C_Phonecall_Schema_Version.class, "CreatedBy", org.compiere.model.I_AD_User.class);
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/**
* Set Every Month.
* Every x Months
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setEveryMonth (int EveryMonth);
/**
* Get Every Month.
* Every x Months
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getEveryMonth();
/** Column definition for EveryMonth */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_EveryMonth = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "EveryMonth", null);
/** Column name EveryMonth */
public static final String COLUMNNAME_EveryMonth = "EveryMonth";
/**
* Set Every Week.
* Every x weeks
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setEveryWeek (int EveryWeek);
/**
* Get Every Week.
* Every x weeks
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getEveryWeek();
/** Column definition for EveryWeek */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_EveryWeek = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "EveryWeek", null);
/** Column name EveryWeek */
public static final String COLUMNNAME_EveryWeek = "EveryWeek";
/**
* Set Aktiv.
* Der Eintrag ist im System aktiv
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setIsActive (boolean IsActive);
/**
* Get Aktiv.
* Der Eintrag ist im System aktiv
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public boolean isActive();
/** Column definition for IsActive */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_IsActive = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "IsActive", null);
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/**
* Set IsCancelPhonecallDay.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setIsCancelPhonecallDay (boolean IsCancelPhonecallDay);
/**
* Get IsCancelPhonecallDay.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public boolean isCancelPhonecallDay();
/** Column definition for IsCancelPhonecallDay */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_IsCancelPhonecallDay = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "IsCancelPhonecallDay", null);
/** Column name IsCancelPhonecallDay */
public static final String COLUMNNAME_IsCancelPhonecallDay = "IsCancelPhonecallDay";
/**
* Set Monthly.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setIsMonthly (boolean IsMonthly);
/**
* Get Monthly.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public boolean isMonthly();
/** Column definition for IsMonthly */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_IsMonthly = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "IsMonthly", null);
/** Column name IsMonthly */
public static final String COLUMNNAME_IsMonthly = "IsMonthly";
/**
* Set IsMovePhonecallDay.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setIsMovePhonecallDay (boolean IsMovePhonecallDay);
/**
* Get IsMovePhonecallDay.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public boolean isMovePhonecallDay();
/** Column definition for IsMovePhonecallDay */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_IsMovePhonecallDay = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "IsMovePhonecallDay", null);
/** Column name IsMovePhonecallDay */
public static final String COLUMNNAME_IsMovePhonecallDay = "IsMovePhonecallDay";
/**
* Set Weekly.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setIsWeekly (boolean IsWeekly);
/**
* Get Weekly.
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public boolean isWeekly();
/** Column definition for IsWeekly */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_IsWeekly = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "IsWeekly", null);
/** Column name IsWeekly */
public static final String COLUMNNAME_IsWeekly = "IsWeekly";
/**
* Set Day of the Month.
* Day of the month 1 to 28/29/30/31
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setMonthDay (int MonthDay);
/**
* Get Day of the Month.
* Day of the month 1 to 28/29/30/31
*
* <br>Type: Integer
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public int getMonthDay();
/** Column definition for MonthDay */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_MonthDay = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "MonthDay", null);
/** Column name MonthDay */
public static final String COLUMNNAME_MonthDay = "MonthDay";
/**
* Set Name.
* Alphanumeric identifier of the entity
*
* <br>Type: String
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setName (java.lang.String Name);
/**
* Get Name.
* Alphanumeric identifier of the entity
*
* <br>Type: String
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public java.lang.String getName();
/** Column definition for Name */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_Name = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "Name", null);
/** Column name Name */
public static final String COLUMNNAME_Name = "Name";
/**
* Set Freitag.
* Freitags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setOnFriday (boolean OnFriday);
/**
* Get Freitag.
* Freitags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isOnFriday();
/** Column definition for OnFriday */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_OnFriday = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "OnFriday", null);
/** Column name OnFriday */
public static final String COLUMNNAME_OnFriday = "OnFriday";
/**
* Set Montag.
* Montags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setOnMonday (boolean OnMonday);
/**
* Get Montag.
* Montags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isOnMonday();
/** Column definition for OnMonday */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_OnMonday = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "OnMonday", null);
/** Column name OnMonday */
public static final String COLUMNNAME_OnMonday = "OnMonday";
/**
* Set Samstag.
* Samstags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setOnSaturday (boolean OnSaturday);
/**
* Get Samstag.
* Samstags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isOnSaturday();
/** Column definition for OnSaturday */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_OnSaturday = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "OnSaturday", null);
/** Column name OnSaturday */
public static final String COLUMNNAME_OnSaturday = "OnSaturday";
/**
* Set Sonntag.
* Sonntags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setOnSunday (boolean OnSunday);
/**
* Get Sonntag.
* Sonntags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isOnSunday();
/** Column definition for OnSunday */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_OnSunday = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "OnSunday", null);
/** Column name OnSunday */
public static final String COLUMNNAME_OnSunday = "OnSunday";
/**
* Set Donnerstag.
* Donnerstags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setOnThursday (boolean OnThursday);
/**
* Get Donnerstag.
* Donnerstags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isOnThursday();
/** Column definition for OnThursday */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_OnThursday = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "OnThursday", null);
/** Column name OnThursday */
public static final String COLUMNNAME_OnThursday = "OnThursday";
/**
* Set Dienstag.
* Dienstags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setOnTuesday (boolean OnTuesday);
/**
* Get Dienstag.
* Dienstags verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isOnTuesday();
/** Column definition for OnTuesday */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_OnTuesday = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "OnTuesday", null);
/** Column name OnTuesday */
public static final String COLUMNNAME_OnTuesday = "OnTuesday";
/**
* Set Mittwoch.
* Mittwochs verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public void setOnWednesday (boolean OnWednesday);
/**
* Get Mittwoch.
* Mittwochs verfügbar
*
* <br>Type: YesNo
* <br>Mandatory: false
* <br>Virtual Column: false
*/
public boolean isOnWednesday();
/** Column definition for OnWednesday */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_OnWednesday = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "OnWednesday", null);
/** Column name OnWednesday */
public static final String COLUMNNAME_OnWednesday = "OnWednesday";
/**
* Get Aktualisiert.
* Datum, an dem dieser Eintrag aktualisiert wurde
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public java.sql.Timestamp getUpdated();
/** Column definition for Updated */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_Updated = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "Updated", null);
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/**
* Get Aktualisiert durch.
* Nutzer, der diesen Eintrag aktualisiert hat
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public int getUpdatedBy();
/** Column definition for UpdatedBy */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_AD_User> COLUMN_UpdatedBy = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, org.compiere.model.I_AD_User>(I_C_Phonecall_Schema_Version.class, "UpdatedBy", org.compiere.model.I_AD_User.class);
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/**
* Set Gültig ab.
* Gültig ab inklusiv (erster Tag)
*
* <br>Type: Date
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public void setValidFrom (java.sql.Timestamp ValidFrom);
/**
* Get Gültig ab.
* Gültig ab inklusiv (erster Tag)
*
* <br>Type: Date
* <br>Mandatory: true
* <br>Virtual Column: false
*/
public java.sql.Timestamp getValidFrom();
/** Column definition for ValidFrom */
public static final org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object> COLUMN_ValidFrom = new org.adempiere.model.ModelColumn<I_C_Phonecall_Schema_Version, Object>(I_C_Phonecall_Schema_Version.class, "ValidFrom", null);
/** Column name ValidFrom */
public static final String COLUMNNAME_ValidFrom = "ValidFrom";
}
|
package code.ui.render;
import java.util.List;
import java.util.ArrayList;
import code.engine.Resources;
import code.graphics.buffer.MasterBuffer;
import code.graphics.buffer.RenderJob;
import code.graphics.buffer.RenderLayer;
import code.graphics.texture.Renderable;
import code.math.VectorD;
import code.ui.styles.Style;
/**
* Provides methods for rendering text
*/
public final class TextRenderer {
private static final String SPACE = " ";
private static final String NEWLINE = "\\\\";
private static final String L_BRACKET = "{";
private static final String R_BRACKET = "}";
private static final int SPACING = 10;
private static final int TWO = 2;
private static final int NEWLINE_OFFSET = 16;
private TextRenderer() {
}
/**
* Render the text according to the given style
*
* @param position the position of the text
* @param style the style of the text
* @param buffer the master buffer of the game
*/
public static void renderText(VectorD position, Style style, MasterBuffer buffer) {
String text = style.getProperty("text");
double scale = Double.parseDouble(style.getProperty("text-scale"));
boolean alignLeft = "left".equals(style.getProperty("align"));
String[] lines = text.split(NEWLINE);
VectorD offset = new VectorD(0, 0);
for (String line : lines) {
List<Character> characters = getCharacters(line);
if (!alignLeft) {
offset.setValue(0, calculateOffset(characters) * scale);
}
for (Character character : characters) {
VectorD charOffset = offset.sum(new VectorD(character.getWidth() * scale / TWO, 0));
character.render(position.sum(charOffset), scale, buffer);
offset.setValue(0, offset.getValue(0) + character.getWidth() * scale);
}
offset.setValue(1, offset.getValue(1) - NEWLINE_OFFSET * scale);
}
}
private static List<Character> getCharacters(String line) {
List<Character> characters = new ArrayList<>();
int i = 0;
while (i < line.length()) {
String c = line.substring(i, i + 1);
if (c.equals(L_BRACKET)) {
int start = i + 1;
while (!c.equals(R_BRACKET)) {
i++;
c = line.substring(i, i + 1);
}
characters.add(new Character(
Resources.get().getRenderables().get(line.substring(start, i))));
} else if (c.equals(SPACE)) {
characters.add(new Character(SPACING));
} else {
characters.add(new Character(Resources.get().getRenderables().get(c)));
}
i++;
}
return characters;
}
private static double calculateOffset(List<Character> line) {
return -calculateLineWidth(line) / TWO;
}
private static double calculateLineWidth(List<Character> line) {
return line.stream().map(Character::getWidth).reduce(0.,
(Double accWidth, Double width) -> accWidth += width);
}
private static class Character {
private double width;
private Renderable sprite;
public Character(Renderable sprite) {
this.sprite = sprite;
this.width = sprite.getDim().getValue(0);
}
public Character(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
/**
* Renders this character at the specified position with the specified scale
*
* @param position the position of the character
* @param scale the scale of the character
* @param buffer the master buffer of the game
*/
public void render(VectorD position, double scale, MasterBuffer buffer) {
if (sprite != null) {
RenderJob data = new RenderJob();
data.applyTranslation(position);
data.applyRot(0);
data.applyScale(scale);
data.setRenderable(sprite);
buffer.addNewRenderJob(RenderLayer.UI, data);
}
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// package org.apache.commons.codec.binary;
package com.d2lvalence.idkeyauth.codec.binary;
import java.util.Arrays;
// import org.apache.commons.codec.BinaryDecoder;
// import org.apache.commons.codec.BinaryEncoder;
// import org.apache.commons.codec.DecoderException;
// import org.apache.commons.codec.EncoderException;
/**
* Abstract superclass for Base-N encoders and decoders.
*
* <p>
* This class is thread-safe.
* </p>
*
* @version $Id: BaseNCodec.java 1465182 2013-04-06 04:03:12Z ggregory $
*/
public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
/**
* Holds thread context so classes can be thread-safe.
*
* This class is not itself thread-safe; each thread must allocate its own copy.
*
* @since 1.7
*/
static class Context {
/**
* Place holder for the bytes we're dealing with for our based logic.
* Bitwise operations store and extract the encoding or decoding from this variable.
*/
int ibitWorkArea;
/**
* Place holder for the bytes we're dealing with for our based logic.
* Bitwise operations store and extract the encoding or decoding from this variable.
*/
long lbitWorkArea;
/**
* Buffer for streaming.
*/
byte[] buffer;
/**
* Position where next character should be written in the buffer.
*/
int pos;
/**
* Position where next character should be read from the buffer.
*/
int readPos;
/**
* Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless,
* and must be thrown away.
*/
boolean eof;
/**
* Variable tracks how many characters have been written to the current line. Only used when encoding. We use
* it to make sure each encoded line never goes beyond lineLength (if lineLength > 0).
*/
int currentLinePos;
/**
* Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This
* variable helps track that.
*/
int modulus;
Context() {
}
/**
* Returns a String useful for debugging (especially within a debugger.)
*
* @return a String useful for debugging.
*/
@SuppressWarnings("boxing") // OK to ignore boxing here
@Override
public String toString() {
return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " +
"modulus=%s, pos=%s, readPos=%s]", this.getClass().getSimpleName(), Arrays.toString(buffer),
currentLinePos, eof, ibitWorkArea, lbitWorkArea, modulus, pos, readPos);
}
}
/**
* EOF
*
* @since 1.7
*/
static final int EOF = -1;
/**
* MIME chunk size per RFC 2045 section 6.8.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
public static final int MIME_CHUNK_SIZE = 76;
/**
* PEM chunk size per RFC 1421 section 4.3.2.4.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
*
* @see <a href="http://tools.ietf.org/html/rfc1421">RFC 1421 section 4.3.2.4</a>
*/
public static final int PEM_CHUNK_SIZE = 64;
private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
/**
* Defines the default buffer size - currently {@value}
* - must be large enough for at least one encoded block+separator
*/
private static final int DEFAULT_BUFFER_SIZE = 8192;
/** Mask used to extract 8 bits, used in decoding bytes */
protected static final int MASK_8BITS = 0xff;
/**
* Byte used to pad output.
*/
protected static final byte PAD_DEFAULT = '='; // Allow static access to default
protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later
/** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
private final int unencodedBlockSize;
/** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
private final int encodedBlockSize;
/**
* Chunksize for encoding. Not used when decoding.
* A value of zero or less implies no chunking of the encoded data.
* Rounded down to nearest multiple of encodedBlockSize.
*/
protected final int lineLength;
/**
* Size of chunk separator. Not used unless {@link #lineLength} > 0.
*/
private final int chunkSeparatorLength;
/**
* Note <code>lineLength</code> is rounded down to the nearest multiple of {@link #encodedBlockSize}
* If <code>chunkSeparatorLength</code> is zero, then chunking is disabled.
* @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
* @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
* @param lineLength if > 0, use chunking with a length <code>lineLength</code>
* @param chunkSeparatorLength the chunk separator length, if relevant
*/
protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize,
final int lineLength, final int chunkSeparatorLength) {
this.unencodedBlockSize = unencodedBlockSize;
this.encodedBlockSize = encodedBlockSize;
final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0;
this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
this.chunkSeparatorLength = chunkSeparatorLength;
}
/**
* Returns true if this object has buffered data for reading.
*
* @param context the context to be used
* @return true if there is data still available for reading.
*/
boolean hasData(final Context context) { // package protected for access from I/O streams
return context.buffer != null;
}
/**
* Returns the amount of buffered data available for reading.
*
* @param context the context to be used
* @return The amount of buffered data available for reading.
*/
int available(final Context context) { // package protected for access from I/O streams
return context.buffer != null ? context.pos - context.readPos : 0;
}
/**
* Get the default buffer size. Can be overridden.
*
* @return {@link #DEFAULT_BUFFER_SIZE}
*/
protected int getDefaultBufferSize() {
return DEFAULT_BUFFER_SIZE;
}
/**
* Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
* @param context the context to be used
*/
private byte[] resizeBuffer(final Context context) {
if (context.buffer == null) {
context.buffer = new byte[getDefaultBufferSize()];
context.pos = 0;
context.readPos = 0;
} else {
final byte[] b = new byte[context.buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR];
System.arraycopy(context.buffer, 0, b, 0, context.buffer.length);
context.buffer = b;
}
return context.buffer;
}
/**
* Ensure that the buffer has room for <code>size</code> bytes
*
* @param size minimum spare space required
* @param context the context to be used
*/
protected byte[] ensureBufferSize(final int size, final Context context){
if ((context.buffer == null) || (context.buffer.length < context.pos + size)){
return resizeBuffer(context);
}
return context.buffer;
}
/**
* Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail
* bytes. Returns how many bytes were actually extracted.
* <p>
* Package protected for access from I/O streams.
*
* @param b
* byte[] array to extract the buffered data into.
* @param bPos
* position in byte[] array to start extraction at.
* @param bAvail
* amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
* @param context
* the context to be used
* @return The number of bytes successfully extracted into the provided byte[] array.
*/
int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) {
if (context.buffer != null) {
final int len = Math.min(available(context), bAvail);
System.arraycopy(context.buffer, context.readPos, b, bPos, len);
context.readPos += len;
if (context.readPos >= context.pos) {
context.buffer = null; // so hasData() will return false, and this method can return -1
}
return len;
}
return context.eof ? EOF : 0;
}
/**
* Checks if a byte value is whitespace or not.
* Whitespace is taken to mean: space, tab, CR, LF
* @param byteToCheck
* the byte to check
* @return true if byte is whitespace, false otherwise
*/
protected static boolean isWhiteSpace(final byte byteToCheck) {
switch (byteToCheck) {
case ' ' :
case '\n' :
case '\r' :
case '\t' :
return true;
default :
return false;
}
}
/**
* Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
* the Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].
*
* @param obj
* Object to encode
* @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
* @throws EncoderException
* if the parameter supplied is not of type byte[]
*/
public Object encode(final Object obj) throws EncoderException {
if (!(obj instanceof byte[])) {
throw new EncoderException("Parameter supplied to Base-N encode is not a byte[]");
}
return encode((byte[]) obj);
}
/**
* Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.
* Uses UTF8 encoding.
*
* @param pArray
* a byte array containing binary data
* @return A String containing only Base-N character data
*/
public String encodeToString(final byte[] pArray) {
return StringUtils.newStringUtf8(encode(pArray));
}
/**
* Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet.
* Uses UTF8 encoding.
*
* @param pArray a byte array containing binary data
* @return String containing only character data in the appropriate alphabet.
*/
public String encodeAsString(final byte[] pArray){
return StringUtils.newStringUtf8(encode(pArray));
}
/**
* Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
* the Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.
*
* @param obj
* Object to decode
* @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String
* supplied.
* @throws DecoderException
* if the parameter supplied is not of type byte[]
*/
public Object decode(final Object obj) throws DecoderException {
if (obj instanceof byte[]) {
return decode((byte[]) obj);
} else if (obj instanceof String) {
return decode((String) obj);
} else {
throw new DecoderException("Parameter supplied to Base-N decode is not a byte[] or a String");
}
}
/**
* Decodes a String containing characters in the Base-N alphabet.
*
* @param pArray
* A String containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(final String pArray) {
return decode(StringUtils.getBytesUtf8(pArray));
}
/**
* Decodes a byte[] containing characters in the Base-N alphabet.
*
* @param pArray
* A byte array containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(final byte[] pArray) {
if (pArray == null || pArray.length == 0) {
return pArray;
}
final Context context = new Context();
decode(pArray, 0, pArray.length, context);
decode(pArray, 0, EOF, context); // Notify decoder of EOF.
final byte[] result = new byte[context.pos];
readResults(result, 0, result.length, context);
return result;
}
/**
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
*
* @param pArray
* a byte array containing binary data
* @return A byte array containing only the basen alphabetic character data
*/
public byte[] encode(final byte[] pArray) {
if (pArray == null || pArray.length == 0) {
return pArray;
}
final Context context = new Context();
encode(pArray, 0, pArray.length, context);
encode(pArray, 0, EOF, context); // Notify encoder of EOF.
final byte[] buf = new byte[context.pos - context.readPos];
readResults(buf, 0, buf.length, context);
return buf;
}
// package protected for access from I/O streams
abstract void encode(byte[] pArray, int i, int length, Context context);
// package protected for access from I/O streams
abstract void decode(byte[] pArray, int i, int length, Context context);
/**
* Returns whether or not the <code>octet</code> is in the current alphabet.
* Does not allow whitespace or pad.
*
* @param value The value to test
*
* @return {@code true} if the value is defined in the current alphabet, {@code false} otherwise.
*/
protected abstract boolean isInAlphabet(byte value);
/**
* Tests a given byte array to see if it contains only valid characters within the alphabet.
* The method optionally treats whitespace and pad as valid.
*
* @param arrayOctet byte array to test
* @param allowWSPad if {@code true}, then whitespace and PAD are also allowed
*
* @return {@code true} if all bytes are valid characters in the alphabet or if the byte array is empty;
* {@code false}, otherwise
*/
public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) {
for (int i = 0; i < arrayOctet.length; i++) {
if (!isInAlphabet(arrayOctet[i]) &&
(!allowWSPad || (arrayOctet[i] != PAD) && !isWhiteSpace(arrayOctet[i]))) {
return false;
}
}
return true;
}
/**
* Tests a given String to see if it contains only valid characters within the alphabet.
* The method treats whitespace and PAD as valid.
*
* @param basen String to test
* @return {@code true} if all characters in the String are valid characters in the alphabet or if
* the String is empty; {@code false}, otherwise
* @see #isInAlphabet(byte[], boolean)
*/
public boolean isInAlphabet(final String basen) {
return isInAlphabet(StringUtils.getBytesUtf8(basen), true);
}
/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
*
* Intended for use in checking line-ending arrays
*
* @param arrayOctet
* byte array to test
* @return {@code true} if any byte is a valid character in the alphabet or PAD; {@code false} otherwise
*/
protected boolean containsAlphabetOrPad(final byte[] arrayOctet) {
if (arrayOctet == null) {
return false;
}
for (final byte element : arrayOctet) {
if (PAD == element || isInAlphabet(element)) {
return true;
}
}
return false;
}
/**
* Calculates the amount of space needed to encode the supplied array.
*
* @param pArray byte[] array which will later be encoded
*
* @return amount of space needed to encoded the supplied array.
* Returns a long since a max-len array will require > Integer.MAX_VALUE
*/
public long getEncodedLength(final byte[] pArray) {
// Calculate non-chunked size - rounded up to allow for padding
// cast to long is needed to avoid possibility of overflow
long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
if (lineLength > 0) { // We're using chunking
// Round up to nearest multiple
len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
}
return len;
}
}
|
package app.fachinformatiker.threads;
public class Blubb {
boolean flag = false;
public synchronized void first() {
if(flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("ich bin der erste");
flag = true;
notify();
}
public synchronized void second() {
if(!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("ich bin der zweite");
flag = false;
notify();
}
}
|
/*
* Copyright 2019. The Scouter2 Authors.
*
* @https://github.com/scouter-project/scouter2
*
* 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 scouter2.collector.sandbox;
import org.apache.commons.io.FileUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.mapdb.Atomic;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;
import org.springframework.util.StopWatch;
import scouter2.collector.domain.obj.Obj;
import scouter2.fixture.ObjFixture;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Gun Lee (gunlee01@gmail.com) on 2019-08-15
*/
@Ignore
public class MapDbPersistTest {
@Test
@Ignore
public void test() {
String dir = System.getProperty("java.io.tmpdir") + "/persist-test";
new File(dir).mkdir();
DB db = DBMaker.fileDB(dir + "/persist.db")
.fileChannelEnable()
.fileMmapEnableIfSupported()
.closeOnJvmShutdown()
.transactionEnable()
.make()
;
HTreeMap<String, Long> objNameId = db.hashMap("objNameId")
.keySerializer(Serializer.STRING)
.valueSerializer(Serializer.LONG)
.createOrOpen();
System.out.println("get1 : " + objNameId.get("test1"));
objNameId.put("test1", 100L);
System.out.println("get1 : " + objNameId.get("test1"));
db.commit();
}
@Test
@Ignore
public void perf_test() throws IOException {
String dir = System.getProperty("java.io.tmpdir") + "/persist-test2";
FileUtils.deleteDirectory(new File(dir));
CommonDb4Test commonDb = new CommonDb4Test(dir);
HTreeMap<Long, Obj> map = commonDb.getObjMap();
Atomic.Long objIdGenerator = commonDb.getObjIdGenerator();
StopWatch stopWatch = new StopWatch("MapDB HashMap Perf Stop Watch");
int checkCount = 10000;
stopWatch.start("atomicLong increase time");
List<Obj> objList = IntStream.range(0, checkCount)
.mapToObj(no -> ObjFixture.getOne(objIdGenerator.incrementAndGet()))
.collect(Collectors.toList());
stopWatch.stop();
stopWatch.start("obj insertion time");
objList.forEach(obj -> map.put(obj.getObjId(), obj));
stopWatch.stop();
stopWatch.start("obj insertion time2");
objList.forEach(obj -> map.put(obj.getObjId(), obj));
stopWatch.stop();
List<Obj> collect;
stopWatch.start("get all values time");
collect = map.values().stream().collect(Collectors.toList());
stopWatch.stop();
stopWatch.start("get all values time2");
collect = map.values().stream().collect(Collectors.toList());
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
System.out.println(collect.size());
}
@Test
@Ignore
public void perf_test_with_scheduled_commit() throws IOException {
String dir = System.getProperty("java.io.tmpdir") + "/persist-test-with-scheduled-commit";
FileUtils.deleteDirectory(new File(dir));
CommonDb4Test commonDb = new CommonDb4Test(dir);
HTreeMap<Long, Obj> map = commonDb.getObjMap();
Atomic.Long objIdGenerator = commonDb.getObjIdGenerator();
StopWatch stopWatch = new StopWatch("MapDB HashMap Perf Stop Watch");
int checkCount = 10000;
scheduleCommit(commonDb, 100);
stopWatch.start("atomicLong increase time");
List<Obj> objList = IntStream.range(0, checkCount)
.mapToObj(no -> ObjFixture.getOne(objIdGenerator.incrementAndGet()))
.collect(Collectors.toList());
stopWatch.stop();
stopWatch.start("obj insertion time");
objList.forEach(obj -> map.put(obj.getObjId(), obj));
stopWatch.stop();
stopWatch.start("obj insertion time2");
objList.forEach(obj -> map.put(obj.getObjId(), obj));
stopWatch.stop();
List<Obj> collect;
stopWatch.start("get all values time");
collect = map.values().stream().collect(Collectors.toList());
stopWatch.stop();
stopWatch.start("get all values time2");
collect = map.values().stream().collect(Collectors.toList());
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
System.out.println(collect.size());
}
@Test
@Ignore
public void check_persistency_with_scheduled_commit() throws IOException, InterruptedException {
String dir = System.getProperty("java.io.tmpdir") + "/persistency-in-concurrency";
FileUtils.deleteDirectory(new File(dir));
CommonDb4Test commonDb = new CommonDb4Test(dir);
HTreeMap<Long, Obj> map = commonDb.getObjMap();
Atomic.Long objIdGenerator = commonDb.getObjIdGenerator();
StopWatch stopWatch = new StopWatch("MapDB HashMap Perf Stop Watch");
int checkCount = 10000;
List<Obj> objList = IntStream.range(0, checkCount).mapToObj(no -> ObjFixture.getOne(no)).collect(Collectors.toList());
scheduleCommit(commonDb, 10);
CountDownLatch latch = new CountDownLatch(4);
long start = System.currentTimeMillis();
new Thread(() -> {
System.out.println("start inc 1.");
IntStream.range(0, checkCount).filter(this::even)
.forEach(n -> ObjFixture.getOne(objIdGenerator.incrementAndGet()));
latch.countDown();
System.out.println("end inc 1 : " + (System.currentTimeMillis() - start));
}).start();
new Thread(() -> {
System.out.println("start inc 2.");
IntStream.range(0, checkCount).filter(this::odd)
.forEach(n -> ObjFixture.getOne(objIdGenerator.incrementAndGet()));
latch.countDown();
System.out.println("end inc 2 : " + (System.currentTimeMillis() - start));
}).start();
new Thread(() -> {
System.out.println("start add 1.");
IntStream.range(0, checkCount).filter(this::even)
.forEach(n -> map.put(objList.get(n).getObjId(), objList.get(n)));
latch.countDown();
System.out.println("end add 1 : " + (System.currentTimeMillis() - start));
}).start();
new Thread(() -> {
System.out.println("start add 2.");
IntStream.range(0, checkCount).filter(this::odd)
.forEach(n -> map.put(objList.get(n).getObjId(), objList.get(n)));
latch.countDown();
System.out.println("end add 2 : " + (System.currentTimeMillis() - start));
}).start();
latch.await();
System.out.println("end. all elapsed: " + (System.currentTimeMillis() - start));
assertThat(objIdGenerator.get()).isEqualTo(10000L);
assertThat(map.size()).isEqualTo(10000);
commonDb.getDb().commit();
commonDb.getDb().close();
CommonDb4Test commonDbReopen = new CommonDb4Test(dir);
assertThat(commonDbReopen.getObjIdGenerator().get()).isEqualTo(10000L);
assertThat(commonDbReopen.getObjMap().size()).isEqualTo(10000);
commonDbReopen.getDb().close();
FileUtils.deleteDirectory(new File(dir));
}
private boolean odd(int n) {
return n%2 == 1;
}
private boolean even(int n) {
return n%2 == 0;
}
private void scheduleCommit(CommonDb4Test commonDb, long millis) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(millis);
if (!commonDb.getDb().isClosed()) {
commonDb.getDb().commit();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
|
/*
* 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.carbondata.core.carbon.metadata.schema.table;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.carbondata.core.constants.CarbonCommonConstants;
/**
* Store the information about the table.
* it stores the fact table as well as aggregate table present in the schema
*/
public class TableInfo implements Serializable {
/**
* serialization version
*/
private static final long serialVersionUID = -5034287968314105193L;
/**
* name of the database;
*/
private String databaseName;
/**
* table name to group fact table and aggregate table
*/
private String tableUniqueName;
/**
* fact table information
*/
private TableSchema factTable;
/**
* list of aggregate table
*/
private List<TableSchema> aggregateTableList;
/**
* last updated time to update the cube if any changes
*/
private long lastUpdatedTime;
/**
* metadata file path (check if it is really required )
*/
private String metaDataFilepath;
public TableInfo() {
aggregateTableList = new ArrayList<TableSchema>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);
}
/**
* @return the factTable
*/
public TableSchema getFactTable() {
return factTable;
}
/**
* @param factTable the factTable to set
*/
public void setFactTable(TableSchema factTable) {
this.factTable = factTable;
}
/**
* @return the aggregateTableList
*/
public List<TableSchema> getAggregateTableList() {
return aggregateTableList;
}
/**
* @param aggregateTableList the aggregateTableList to set
*/
public void setAggregateTableList(List<TableSchema> aggregateTableList) {
this.aggregateTableList = aggregateTableList;
}
/**
* @return the databaseName
*/
public String getDatabaseName() {
return databaseName;
}
/**
* @param databaseName the databaseName to set
*/
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public TableSchema getTableSchemaByName(String tableName) {
if (factTable.getTableName().equalsIgnoreCase(tableName)) {
return factTable;
}
for (TableSchema aggregatTableSchema : aggregateTableList) {
if (aggregatTableSchema.getTableName().equals(tableName)) {
return aggregatTableSchema;
}
}
return null;
}
public TableSchema getTableSchemaByTableId(int tableId) {
if (factTable.getTableId() == tableId) {
return factTable;
}
for (TableSchema aggregatTableSchema : aggregateTableList) {
if (aggregatTableSchema.getTableId() == tableId) {
return aggregatTableSchema;
}
}
return null;
}
public int getNumberOfAggregateTables() {
return aggregateTableList.size();
}
/**
* @return the tableUniqueName
*/
public String getTableUniqueName() {
return tableUniqueName;
}
/**
* @param tableUniqueName the tableUniqueName to set
*/
public void setTableUniqueName(String tableUniqueName) {
this.tableUniqueName = tableUniqueName;
}
/**
* @return the lastUpdatedTime
*/
public long getLastUpdatedTime() {
return lastUpdatedTime;
}
/**
* @param lastUpdatedTime the lastUpdatedTime to set
*/
public void setLastUpdatedTime(long lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
/**
* @return
*/
public String getMetaDataFilepath() {
return metaDataFilepath;
}
/**
* @param metaDataFilepath
*/
public void setMetaDataFilepath(String metaDataFilepath) {
this.metaDataFilepath = metaDataFilepath;
}
/**
* to generate the hash code
*/
@Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((databaseName == null) ? 0 : databaseName.hashCode());
result = prime * result + ((tableUniqueName == null) ? 0 : tableUniqueName.hashCode());
return result;
}
/**
* Overridden equals method
*/
@Override public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof TableInfo) {
return false;
}
TableInfo other = (TableInfo) obj;
if (databaseName == null) {
if (other.databaseName != null) {
return false;
}
} else if (!tableUniqueName.equals(other.tableUniqueName)) {
return false;
}
if (tableUniqueName == null) {
if (other.tableUniqueName != null) {
return false;
}
} else if (!tableUniqueName.equals(other.tableUniqueName)) {
return false;
}
return true;
}
}
|
/*
* Copyright (C) 2019 - 2020 Rabobank Nederland
*
* 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.rabobank.argos.domain;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Builder
@Setter
@Getter
@EqualsAndHashCode(exclude={"signature"})
@ToString
public class Signature {
private String keyId;
private String signature;
}
|
package org.ga4gh.cts.api.reads;
import junitparams.JUnitParamsRunner;
import org.apache.avro.AvroRemoteException;
import org.ga4gh.ctk.CtkLogs;
import org.ga4gh.ctk.transport.GAWrapperException;
import org.ga4gh.ctk.transport.URLMAPPING;
import org.ga4gh.ctk.transport.protocols.Client;
import org.ga4gh.cts.api.TestData;
import org.ga4gh.cts.api.Utils;
import org.ga4gh.methods.GAException;
import org.ga4gh.methods.SearchReadGroupSetsRequest;
import org.ga4gh.methods.SearchReadGroupSetsResponse;
import org.ga4gh.models.ReadGroup;
import org.ga4gh.models.ReadGroupSet;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.ga4gh.cts.api.Utils.catchGAWrapperException;
/**
* <p>Validates the data returned by /readgroupsets/search.</p>
*/
@Category(ReadsTests.class)
@RunWith(JUnitParamsRunner.class)
public class ReadGroupSetsSearchIT implements CtkLogs {
private static Client client = new Client(URLMAPPING.getInstance());
/**
* <p>When we supply a name to {@link SearchReadGroupSetsRequest}, the
* returned objects must all have names that match.</p>
* <p>The Schemas documentation says
* that a {@link SearchReadGroupSetsRequest} always matches names exactly.</p>
*
* @throws AvroRemoteException the exception thrown
*/
@Test
public void readGroupSetsNameShouldRetrieveOnlyMatchingReadGroupSets() throws
AvroRemoteException {
for (String readGroupSetName : TestData.EXPECTED_READGROUPSETS_NAMES) {
final SearchReadGroupSetsRequest req =
SearchReadGroupSetsRequest.newBuilder().
setDatasetId(TestData.getDatasetId()).setName(readGroupSetName).build();
SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
final List<ReadGroupSet> rgSets = resp.getReadGroupSets();
assertThat(rgSets).hasSize(1);
assertThat(rgSets.get(0).getName()).isEqualTo(readGroupSetName);
}
}
/**
* <p>Calling {@link SearchReadGroupSetsRequest} with a nonexistent dataset ID should throw an
* exception with status code <tt>NOT_FOUND</tt>.</p>
*
* <p>Pass in a well-formed but non-matching dataset ID to a SearchReadGroupSetsRequest
* expect a valid SearchReadGroupSetsResponse with no ReadGroupSets in it.</p>
*
* @throws AvroRemoteException the exception thrown
*/
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
public void readgroupSetResponseForNonexistentDatasetIdShouldThrowException() throws AvroRemoteException {
SearchReadGroupSetsRequest reqb =
SearchReadGroupSetsRequest.newBuilder()
.setDatasetId(Utils.randomId())
.build();
final GAWrapperException t = catchGAWrapperException(() -> client.reads
.searchReadGroupSets(reqb));
assertThat(t.getHttpStatusCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND);
}
/**
* Retrieve all {@link ReadGroupSet}s and make sure they all have the right dataset ID.
* (Adapted from one of the JavaScript compliance tests.)
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void allReadGroupSetsShouldHaveCorrectDatasetId() throws AvroRemoteException {
final SearchReadGroupSetsRequest req =
SearchReadGroupSetsRequest.newBuilder()
.setDatasetId(TestData.getDatasetId())
.build();
final SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
final List<ReadGroupSet> readGroupSets = resp.getReadGroupSets();
readGroupSets.stream().forEach(rgs -> assertThat(rgs.getDatasetId()).isEqualTo(TestData.getDatasetId()));
}
/**
* Retrieve all {@link ReadGroupSet}s and make sure they all contain an ID.
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void allReadGroupSetsShouldContainId() throws AvroRemoteException {
final SearchReadGroupSetsRequest req =
SearchReadGroupSetsRequest.newBuilder()
.setDatasetId(TestData.getDatasetId())
.build();
final SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
final List<ReadGroupSet> readGroupSets = resp.getReadGroupSets();
readGroupSets.stream().forEach(rgs -> assertThat(rgs.getId()).isNotNull());
}
/**
* Retrieve all {@link ReadGroup}s and make sure they all have the right dataset ID.
* (Adapted from one of the JavaScript compliance tests.)
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void allReadGroupsShouldHaveCorrectDatasetId() throws AvroRemoteException {
final SearchReadGroupSetsRequest req =
SearchReadGroupSetsRequest.newBuilder()
.setDatasetId(TestData.getDatasetId())
.build();
final SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
final List<ReadGroupSet> readGroupSets = resp.getReadGroupSets();
for (ReadGroupSet readGroupSet : readGroupSets) {
for (ReadGroup readGroup : readGroupSet.getReadGroups()) {
assertThat(readGroup).isNotNull();
assertThat(readGroup.getDatasetId()).isEqualTo(TestData.getDatasetId());
}
}
}
/**
* Retrieve all {@link ReadGroup}s and make sure they all contain <tt>Program</tt> information.
* (Adapted from one of the JavaScript compliance tests.)
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void allReadGroupsShouldContainPrograms() throws AvroRemoteException {
final SearchReadGroupSetsRequest req =
SearchReadGroupSetsRequest.newBuilder()
.setDatasetId(TestData.getDatasetId())
.build();
final SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
final List<ReadGroupSet> readGroupSets = resp.getReadGroupSets();
for (ReadGroupSet readGroupSet : readGroupSets) {
for (ReadGroup readGroup : readGroupSet.getReadGroups()) {
assertThat(readGroup.getPrograms()).isNotEmpty();
assertThat(readGroup.getPrograms()).doesNotContain(Utils.nullProgram);
}
}
}
/**
* Retrieve all {@link ReadGroup}s and make sure they all contain a non-null <tt>{@link ReadGroup#info}</tt>
* field. If it's non-null, it must perforce be a {@link Map}. The contents of the {@link Map} don't concern
* us.
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void allReadGroupsShouldContainInfoMap() throws AvroRemoteException {
final SearchReadGroupSetsRequest req =
SearchReadGroupSetsRequest.newBuilder()
.setDatasetId(TestData.getDatasetId())
.build();
final SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
final List<ReadGroupSet> readGroupSets = resp.getReadGroupSets();
for (ReadGroupSet readGroupSet : readGroupSets) {
for (ReadGroup readGroup : readGroupSet.getReadGroups()) {
assertThat(readGroup.getInfo()).isNotNull();
}
}
}
/**
* Retrieve all {@link ReadGroup}s and make sure they all contain a non-null <tt>{@link ReadGroup#id}</tt>
* field. If it's non-null, it must perforce be a {@link String}. The contents of the {@link String} don't concern
* us.
*
* @throws AvroRemoteException if there's a communication problem or server exception ({@link GAException})
*/
@Test
public void allReadGroupsShouldContainId() throws AvroRemoteException {
final SearchReadGroupSetsRequest req =
SearchReadGroupSetsRequest.newBuilder()
.setDatasetId(TestData.getDatasetId())
.build();
final SearchReadGroupSetsResponse resp = client.reads.searchReadGroupSets(req);
final List<ReadGroupSet> readGroupSets = resp.getReadGroupSets();
for (ReadGroupSet readGroupSet : readGroupSets) {
for (ReadGroup readGroup : readGroupSet.getReadGroups()) {
assertThat(readGroup.getId()).isNotNull();
}
}
}
}
|
package me.EmiliaMMO.skill;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.Sound;
public class SkillOrder {
static HashMap<UUID, String[]> skillOrderMap = new HashMap<UUID, String[]>();
public static boolean isMapContainsPlayer(Player player) {
return skillOrderMap.containsKey(player.getUniqueId());
}
public static String[] getMapPlayerSkillOrder(Player player) {
return skillOrderMap.get(player.getUniqueId());
}
public static void initMap(Player player) {
skillOrderMap.put(player.getUniqueId(), new String[] { "-", "-", "-", "-", "-" });
}
public static boolean isSkillReady(Player player) {
if (getMapPlayerSkillOrder(player)[1].equals("-"))
return false;
return true;
}
public static boolean noAutoAttackStart(Player player) {
if (getMapPlayerSkillOrder(player)[0].equals("-"))
return false;
return true;
}
public static void setLatestSkillOrder(Player player, String key) {
String[] tempOrder = getMapPlayerSkillOrder(player);
for (int i = 0; i < tempOrder.length; i++) {
if (tempOrder[i].equals("-")) {
tempOrder[i] = key;
skillOrderMap.put(player.getUniqueId(), tempOrder);
return;
}
}
}
public static void skillOrderReminder(Player player, String[] skillOrder) {
String message = ChatColor.GOLD + skillOrder[0] + " " + skillOrder[1] + " " + skillOrder[2];
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message));
}
public static void skillReleasedReminder(Player player, String[] skillOrder) {
player.getLocation().getWorld().playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 1.0F, 1.0F);
String message = ChatColor.GOLD + skillOrder[0] + " " + skillOrder[1] + " " + skillOrder[2]
+ " Has been released!";
player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message));
}
}
|
/*
* Copyright 2017 Apereo
*
* 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.tle.web.connectors.migration;
import com.tle.common.connectors.ConnectorConstants;
import com.tle.common.security.SecurityConstants;
import com.tle.core.guice.Bind;
import com.tle.core.hibernate.impl.HibernateMigrationHelper;
import com.tle.core.migration.AbstractHibernateDataMigration;
import com.tle.core.migration.MigrationInfo;
import com.tle.core.migration.MigrationResult;
import com.tle.core.plugins.impl.PluginServiceImpl;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.Index;
import org.hibernate.classic.Session;
@Bind
@SuppressWarnings("nls")
public class AddPushToLMSACLMigration extends AbstractHibernateDataMigration {
private static final String KEY_PREFIX =
PluginServiceImpl.getMyPluginId(AddPushToLMSACLMigration.class) + ".";
@Override
public MigrationInfo createMigrationInfo() {
return new MigrationInfo(KEY_PREFIX + "migration.acl.exporttolms");
}
private FakeAccessExpression createEveryoneExpression(Session session) {
FakeAccessExpression everyone = new FakeAccessExpression();
everyone = new FakeAccessExpression();
everyone.dynamic = false;
everyone.expression = "*";
session.save(everyone);
return everyone;
}
@Override
protected void executeDataMigration(
HibernateMigrationHelper helper, MigrationResult result, Session session) throws Exception {
@SuppressWarnings("unchecked")
List<FakeAccessExpression> qr =
session.createQuery("from AccessExpression where expression = '*'").list();
FakeAccessExpression everyone = qr.isEmpty() ? createEveryoneExpression(session) : qr.get(0);
@SuppressWarnings("unchecked")
List<FakeInstitution> institutions = session.createQuery("FROM Institution").list();
for (FakeInstitution inst : institutions) {
FakeAccessEntry aclEntry = new FakeAccessEntry();
aclEntry.grantRevoke = SecurityConstants.GRANT;
aclEntry.privilege = ConnectorConstants.PRIV_EXPORT_TO_LMS_ITEM;
aclEntry.targetObject = SecurityConstants.TARGET_EVERYTHING;
aclEntry.aclPriority = -SecurityConstants.PRIORITY_ALL_COLLECTIONS;
aclEntry.aclOrder = 0;
aclEntry.expression = everyone;
aclEntry.institution = inst;
String aggregateOrdering =
String.format(
"%04d %04d %c",
(aclEntry.aclPriority + SecurityConstants.PRIORITY_MAX),
aclEntry.aclOrder,
aclEntry.grantRevoke);
aclEntry.aggregateOrdering = aggregateOrdering;
session.save(aclEntry);
result.incrementStatus();
}
session.flush();
session.clear();
}
@Override
protected int countDataMigrations(HibernateMigrationHelper helper, Session session) {
return count(session, "FROM Institution");
}
@Override
protected Class<?>[] getDomainClasses() {
return new Class<?>[] {
FakeAccessEntry.class, FakeAccessExpression.class, FakeInstitution.class
};
}
@Entity(name = "ItemDefinition")
@AccessType("field")
public class FakeItemDefinition {
@Id long id;
}
@Entity(name = "AccessEntry")
@AccessType("field")
public static class FakeAccessEntry {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
long id;
@JoinColumn(nullable = false)
@ManyToOne(fetch = FetchType.LAZY)
@Index(name = "accessEntryExpression")
FakeAccessExpression expression;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false)
@Index(name = "accessEntryInstitution")
FakeInstitution institution;
@Column(length = 80)
@Index(name = "targetObjectIndex")
String targetObject;
@Column(length = 30)
@Index(name = "privilegeIndex")
String privilege;
@Column(length = 12, nullable = false)
@Index(name = "aggregateOrderingIndex")
String aggregateOrdering;
char grantRevoke;
int aclOrder;
int aclPriority;
}
@Entity(name = "Institution")
@AccessType("field")
public static class FakeInstitution {
@Id long id;
}
@AccessType("field")
@Entity(name = "AccessExpression")
public static class FakeAccessExpression {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
long id;
boolean dynamic;
@Column(length = 1024)
String expression;
}
}
|
package org.fantasizer.domain;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.envers.Audited;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
/**
* Base abstract class for entities which will hold definitions for created, last modified by and created,
* last modified by date.
*/
@MappedSuperclass
@Audited
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;
@CreatedDate
@Column(name = "created_date", nullable = false, updatable = false)
@JsonIgnore
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
@JsonIgnore
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
@JsonIgnore
private Instant lastModifiedDate = Instant.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
|
package com.shortcuts.example.giftcard.Models.Response;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class AuthenticateResponse extends BaseResponse {
@JsonProperty("access_token")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String accessToken;
}
|
/*
* Copyright 2002-2010 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.core.serializer;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
/**
* Serializer that writes an object to an output stream using Java Serialization.
*
* @author Gary Russell
* @author Mark Fisher
* @since 3.0.5
*/
public class DefaultSerializer implements Serializer<Object> {
/**
* Writes the source object to an output stream using Java Serialization.
* The source object must implement {@link Serializable}.
*/
public void serialize(Object object, OutputStream outputStream) throws IOException {
if (!(object instanceof Serializable)) {
throw new IllegalArgumentException(getClass().getSimpleName() + " requires a Serializable payload " +
"but received an object of type [" + object.getClass().getName() + "]");
}
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(object);
objectOutputStream.flush();
}
}
|
/*
* Copyright (c) 2018 American Express Travel Related Services Company, 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 io.aexp.nodes.graphql;
import io.aexp.nodes.graphql.exceptions.GraphQLException;
public class GraphQLTemplate {
private Fetch fetch = new Fetch();
public enum GraphQLMethod {
QUERY("query"),
MUTATE("mutation");
private String value;
GraphQLMethod(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
/**
* Execute a GraphQL query request.
* @param requestEntity request entity to be executed upon
* @param responseClass response from the execution
* @return GraphQLResponseEntity\<T>
*/
public <T> GraphQLResponseEntity<T> query(GraphQLRequestEntity requestEntity, Class<T> responseClass) throws GraphQLException {
return execute(GraphQLMethod.QUERY, requestEntity, responseClass);
}
/**
* Execute a GraphQL mutation request.
* @param requestEntity request entity to be executed upon
* @param responseClass response from the execution
* @return GraphQLResponseEntity\<T>
*/
public <T> GraphQLResponseEntity<T> mutate(GraphQLRequestEntity requestEntity, Class<T> responseClass) throws GraphQLException {
return execute(GraphQLMethod.MUTATE, requestEntity, responseClass);
}
/**
* Execute any static GraphQL request.
* <p>
* This method is intended for making requests using plain text input instead of dynamically building the request
* from a class.
*
* @param requestEntity request entity to be executed upon
* @param responseClass response from the execution
* @return GraphQLResponseEntity\<T>
*/
public <T> GraphQLResponseEntity<T> execute(GraphQLRequestEntity requestEntity, Class<T> responseClass) throws GraphQLException {
return execute(null, requestEntity, responseClass);
}
/**
* Execute any GraphQL request.
*
* @param method sets the request execution verb, optionally null when sending a fully built static request query
* @param requestEntity request entity to be executed upon
* @param responseClass response from the execution
* @return GraphQLResponseEntity\<T>
*/
public <T> GraphQLResponseEntity<T> execute(GraphQLMethod method, GraphQLRequestEntity requestEntity, Class<T> responseClass)
throws GraphQLException {
if (null == requestEntity) {
throw new GraphQLException("requestEntity must not be null");
}
if (null != method) requestEntity.setRequestMethod(method);
return fetch.send(requestEntity, responseClass);
}
}
|
package com.br.gabryel.livraria;
public class LivrariaMain {
public static void main(String[] args) {
PilhaTest teste = new PilhaTest();
// System.out.println("Retira Ultimo Livro : " + teste.testRetiraUltimoLivro());
//
// System.out.println("\n" + "tNao Adiciona Por Padrao livros com Letra Inicial diferente de 'A' ou 'O' : " + teste.testNaoAdicionaPorPadraoLetraInicial());
System.out.println("\n" + "Nao Adicionar Livro Alem do Limite : " + teste.testNaoAdicionarLivroAlemLimite());
}
}
|
package br.com.dio.pilgriman.beerapirest.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import br.com.dio.pilgriman.beerapirest.dto.BeerDTO;
import br.com.dio.pilgriman.beerapirest.dto.QuantityDTO;
import br.com.dio.pilgriman.beerapirest.exceptions.BeerAlreadyRegisteredException;
import br.com.dio.pilgriman.beerapirest.exceptions.BeerNotFoundException;
import br.com.dio.pilgriman.beerapirest.exceptions.BeerStockExceededException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import javax.validation.Valid;
import java.util.List;
@Api("Manages beer stock")
public interface BeerControllerDocs {
@ApiOperation(value = "Beer creation operation")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Success beer creation"),
@ApiResponse(code = 400, message = "Missing required fields or wrong field range value.")
})
BeerDTO createBeer(BeerDTO beerDTO) throws BeerAlreadyRegisteredException;
@ApiOperation(value = "Returns beer found by a given name")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success beer found in the system"),
@ApiResponse(code = 404, message = "Beer with given name not found.")
})
BeerDTO findByName(@PathVariable String name) throws BeerNotFoundException;
@ApiOperation(value = "Returns a list of all beers registered in the system")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "List of all beers registered in the system"),
})
List<BeerDTO> listBeers();
@ApiOperation(value = "Delete a beer found by a given valid Id")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Success beer deleted in the system"),
@ApiResponse(code = 404, message = "Beer with given id not found.")
})
void deleteById(@PathVariable Long id) throws BeerNotFoundException;
}
|
package dev.gigafyde.apollo.commands.basic;
/*
Created by GigaFyde
https://github.com/GigaFyde
*/
import dev.gigafyde.apollo.core.command.Command;
import dev.gigafyde.apollo.core.command.CommandEvent;
import dev.gigafyde.apollo.utils.Emoji;
import net.dv8tion.jda.api.EmbedBuilder;
public class Ping extends Command {
public Ping() {
this.name = "ping";
this.triggers = new String[]{"ping"};
}
public void execute(CommandEvent event) {
switch (event.getCommandType()) {
case REGULAR -> {
long currentTime = System.currentTimeMillis();
event.getMessage().reply("Pinging...").mentionRepliedUser(false).queue(message -> message.editMessageEmbeds(new EmbedBuilder().setDescription(Emoji.HEARTBEAT + " " + event.getJDA().getGatewayPing() + " ms\n\n" + Emoji.PINGPONG + " " + (System.currentTimeMillis() - currentTime) + " ms").build()).override(true).queue());
}
case SLASH -> {
long currentTime = System.currentTimeMillis();
event.deferReply().complete();
String embed = Emoji.HEARTBEAT + " %s ms" + "\n" + Emoji.PINGPONG + " %s ms";
event.getHook().editOriginal(String.format(embed, event.getJDA().getGatewayPing(), (System.currentTimeMillis() - currentTime))).queue();
}
}
}
}
|
/*
* Copyright (c) 2009-2019, b3log.org & hacpai.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.
*/
package org.b3log.latke.repository.mysql;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.repository.jdbc.AbstractJdbcDatabaseSolution;
import org.b3log.latke.repository.jdbc.mapping.*;
import org.b3log.latke.repository.jdbc.util.FieldDefinition;
import org.b3log.latke.repository.jdbc.util.RepositoryDefinition;
import java.util.ArrayList;
import java.util.List;
/**
* MysqlJdbcDatabaseSolution, for extend.
*
* @author <a href="mailto:wmainlove@gmail.com">Love Yao</a>
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 2.0.0.1, Nov 14, 2018
*/
public class MysqlJdbcDatabaseSolution extends AbstractJdbcDatabaseSolution {
/**
* Public constructor.
*/
public MysqlJdbcDatabaseSolution() {
registerType("int", new IntMapping());
registerType("boolean", new BooleanMapping());
registerType("long", new LongMapping());
registerType("double", new NumberMapping());
registerType("String", new StringMapping());
registerType("Date", new DateMapping());
}
@Override
public String queryPage(final int start, final int end, final String selectSql,
final String filterSql, final String orderBySql,
final String tableName) {
final StringBuilder sql = new StringBuilder();
sql.append(selectSql).append(" FROM ").append(tableName);
if (StringUtils.isNotBlank(filterSql)) {
sql.append(" WHERE ").append(filterSql);
}
sql.append(orderBySql);
sql.append(" LIMIT ").append(start).append(",").append(end - start);
return sql.toString();
}
@Override
public String getRandomlySql(final String tableName, final int fetchSize) {
final StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM ").append(tableName).append(" ORDER BY RAND() LIMIT ").append(fetchSize);
return sql.toString();
}
@Override
protected void createDropTableSql(final StringBuilder dropTableSql, final String tableName) {
dropTableSql.append("DROP TABLE IF EXISTS ").append(tableName).append(";");
}
@Override
protected void createTableHead(final StringBuilder createTableSql, final RepositoryDefinition repositoryDefinition) {
createTableSql.append("CREATE TABLE IF NOT EXISTS ").append(repositoryDefinition.getName()).append("(");
}
@Override
protected void createTableBody(final StringBuilder createTableSql, final RepositoryDefinition repositoryDefinition) {
final List<FieldDefinition> keyDefinitionList = new ArrayList<>();
final List<FieldDefinition> fieldDefinitions = repositoryDefinition.getKeys();
for (FieldDefinition fieldDefinition : fieldDefinitions) {
final String type = fieldDefinition.getType();
if (type == null) {
throw new RuntimeException("the type of fieldDefinitions should not be null");
}
final Mapping mapping = getJdbcTypeMapping().get(type);
if (null != mapping) {
createTableSql.append(mapping.toDataBaseSting(fieldDefinition));
final String description = fieldDefinition.getDescription();
if (StringUtils.isNotBlank(description)) {
createTableSql.append(" COMMENT '" + description + "'");
}
createTableSql.append(", ");
if (fieldDefinition.getIsKey()) {
keyDefinitionList.add(fieldDefinition);
}
} else {
throw new RuntimeException("The type [" + fieldDefinition.getType() + "] is not register for mapping");
}
}
if (keyDefinitionList.size() < 0) {
throw new RuntimeException("Table must have a primary key");
} else {
createTableSql.append(createKeyDefinition(keyDefinitionList));
}
}
/**
* the keyDefinitionList tableSql.
*
* @param keyDefinitionList keyDefinitionList
* @return createKeyDefinitionsql
*/
private String createKeyDefinition(final List<FieldDefinition> keyDefinitionList) {
final StringBuilder sql = new StringBuilder();
sql.append(" PRIMARY KEY");
boolean isFirst = true;
for (FieldDefinition fieldDefinition : keyDefinitionList) {
if (isFirst) {
sql.append("(");
isFirst = false;
} else {
sql.append(",");
}
sql.append(fieldDefinition.getName());
}
sql.append(")");
return sql.toString();
}
@Override
protected void createTableEnd(final StringBuilder createTableSql, final RepositoryDefinition repositoryDefinition) {
createTableSql.append(") ENGINE=InnoDB");
final String description = repositoryDefinition.getDescription();
if (StringUtils.isNotBlank(description)) {
createTableSql.append(" COMMENT='" + description + "'");
}
}
@Override
public void clearTableSql(final StringBuilder clearTableSq, final String tableName, final boolean ifdrop) {
if (ifdrop) {
clearTableSq.append("DROP TABLE IF EXISTS ").append(tableName);
} else {
clearTableSq.append("TRUNCATE TABLE ").append(tableName);
}
}
}
|
package image.exporter;
import com.google.inject.Guice;
import com.google.inject.Injector;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import mil.army.usace.hec.vortex.GdalRegister;
public class ImageExporterWizard extends Application {
static {
GdalRegister.getInstance();
}
@Override
public void start(Stage primaryStage) throws Exception {
final Injector injector = Guice.createInjector( new WizardModule() );
final Parent p = FXMLLoader.load( ImageExporterWizard.class.getResource("/fxml/Wizard.fxml"),
null,
new JavaFXBuilderFactory(),
injector::getInstance
);
final Scene scene = new Scene(p);
primaryStage.setScene( scene );
primaryStage.setWidth( 600 );
primaryStage.setHeight( 400 );
primaryStage.setTitle("Image Exporter Wizard");
primaryStage.getIcons().add(new Image("/vortex_black.png"));
primaryStage.initStyle(StageStyle.DECORATED);
ViewSwitcher switcher = new ViewSwitcher();
switcher.switchView(primaryStage);
}
public static void main(String[] args) { launch(args); }
}
|
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
/**
* Java code contributors.
*/
package io.spring.initializr.generator.spring.code.java;
|
/**
* Copyright (c) 2014, by the Authors: John E Lloyd (UBC)
*
* This software is freely available under a 2-clause BSD license. Please see
* the LICENSE file in the ArtiSynth distribution directory for details.
*/
package maspack.matrix;
import maspack.matrix.*;
import maspack.matrix.Matrix.Partition;
import maspack.util.InternalErrorException;
/**
* Implements a 3 x 4 matrix
*/
public class Matrix3x4 extends DenseMatrixBase {
public double m00;
public double m01;
public double m02;
public double m03;
public double m10;
public double m11;
public double m12;
public double m13;
public double m20;
public double m21;
public double m22;
public double m23;
/**
* Global zero matrix. Should not be modified.
*/
public static final Matrix3x4 ZERO = new Matrix3x4();
/**
* Creates a new Matrix3x4.
*/
public Matrix3x4() {
super();
}
/**
* {@inheritDoc}
*/
public int rowSize() {
return 3;
}
/**
* {@inheritDoc}
*/
public int colSize() {
return 4;
}
/**
* {@inheritDoc}
*/
public double get (int i, int j) {
switch (i) {
case 0: {
switch (j) {
case 0:
return m00;
case 1:
return m01;
case 2:
return m02;
case 3:
return m03;
default:
throw new ArrayIndexOutOfBoundsException ("" + i + "," + j);
}
}
case 1: {
switch (j) {
case 0:
return m10;
case 1:
return m11;
case 2:
return m12;
case 3:
return m13;
default:
throw new ArrayIndexOutOfBoundsException ("" + i + "," + j);
}
}
case 2: {
switch (j) {
case 0:
return m20;
case 1:
return m21;
case 2:
return m22;
case 3:
return m23;
default:
throw new ArrayIndexOutOfBoundsException ("" + i + "," + j);
}
}
default:
throw new ArrayIndexOutOfBoundsException ("" + i + "," + j);
}
}
/**
* {@inheritDoc}
*/
public void getColumn (int j, double[] values) {
getColumn (j, values, 0);
}
/**
* {@inheritDoc}
*/
public void getColumn (int j, double[] values, int off) {
switch (j) {
case 0: {
values[0 + off] = m00;
values[1 + off] = m10;
values[2 + off] = m20;
break;
}
case 1: {
values[0 + off] = m01;
values[1 + off] = m11;
values[2 + off] = m21;
break;
}
case 2: {
values[0 + off] = m02;
values[1 + off] = m12;
values[2 + off] = m22;
break;
}
case 3: {
values[0 + off] = m03;
values[1 + off] = m13;
values[2 + off] = m23;
break;
}
default: {
throw new ArrayIndexOutOfBoundsException ("j=" + j);
}
}
}
/**
* Copies a column of this matrix into a 3-vector.
*
* @param j
* column index
* @param col
* 3-vector into which the column is copied
*/
public void getColumn (int j, Vector3d col) {
switch (j) {
case 0: {
col.x = m00;
col.y = m10;
col.z = m20;
break;
}
case 1: {
col.x = m01;
col.y = m11;
col.z = m21;
break;
}
case 2: {
col.x = m02;
col.y = m12;
col.z = m22;
break;
}
case 3: {
col.x = m03;
col.y = m13;
col.z = m23;
break;
}
default: {
throw new ArrayIndexOutOfBoundsException ("j=" + j);
}
}
}
/**
* {@inheritDoc}
*/
public void getRow (int i, double[] values) {
getRow (i, values, 0);
}
/**
* {@inheritDoc}
*/
public void getRow (int i, double[] values, int off) {
switch (i) {
case 0: {
values[0 + off] = m00;
values[1 + off] = m01;
values[2 + off] = m02;
values[3 + off] = m03;
break;
}
case 1: {
values[0 + off] = m10;
values[1 + off] = m11;
values[2 + off] = m12;
values[3 + off] = m13;
break;
}
case 2: {
values[0 + off] = m20;
values[1 + off] = m21;
values[2 + off] = m22;
values[3 + off] = m23;
break;
}
default: {
throw new ArrayIndexOutOfBoundsException ("i=" + i);
}
}
}
/**
* {@inheritDoc}
*/
public void set (int i, int j, double value) {
switch (i) {
case 0: {
switch (j) {
case 0:
m00 = value;
return;
case 1:
m01 = value;
return;
case 2:
m02 = value;
return;
case 3:
m03 = value;
return;
default:
throw new ArrayIndexOutOfBoundsException ("" + i + "," + j);
}
}
case 1: {
switch (j) {
case 0:
m10 = value;
return;
case 1:
m11 = value;
return;
case 2:
m12 = value;
return;
case 3:
m13 = value;
return;
default:
throw new ArrayIndexOutOfBoundsException ("" + i + "," + j);
}
}
case 2: {
switch (j) {
case 0:
m20 = value;
return;
case 1:
m21 = value;
return;
case 2:
m22 = value;
return;
case 3:
m23 = value;
return;
default:
throw new ArrayIndexOutOfBoundsException ("" + i + "," + j);
}
}
default:
throw new ArrayIndexOutOfBoundsException ("" + i + "," + j);
}
}
/**
* {@inheritDoc}
*/
public void setRow (int i, double[] values) {
switch (i) {
case 0: {
m00 = values[0];
m01 = values[1];
m02 = values[2];
m03 = values[3];
break;
}
case 1: {
m10 = values[0];
m11 = values[1];
m12 = values[2];
m13 = values[3];
break;
}
case 2: {
m20 = values[0];
m21 = values[1];
m22 = values[2];
m23 = values[3];
break;
}
default: {
throw new ArrayIndexOutOfBoundsException ("i=" + i);
}
}
}
/**
* {@inheritDoc}
*/
public void setColumn (int j, double[] values) {
switch (j) {
case 0: {
m00 = values[0];
m10 = values[1];
m20 = values[2];
break;
}
case 1: {
m01 = values[0];
m11 = values[1];
m21 = values[2];
break;
}
case 2: {
m02 = values[0];
m12 = values[1];
m22 = values[2];
break;
}
case 3: {
m03 = values[0];
m13 = values[1];
m23 = values[2];
break;
}
default: {
throw new ArrayIndexOutOfBoundsException ("j=" + j);
}
}
}
/**
* Sets a column of this matrix to the specified 3-vector.
*
* @param j
* column index
* @param col
* 3-vector from which the column is copied
*/
public void setColumn (int j, Vector3d col) {
switch (j) {
case 0: {
m00 = col.x;
m10 = col.y;
m20 = col.z;
break;
}
case 1: {
m01 = col.x;
m11 = col.y;
m21 = col.z;
break;
}
case 2: {
m02 = col.x;
m12 = col.y;
m22 = col.z;
break;
}
case 3: {
m03 = col.x;
m13 = col.y;
m23 = col.z;
break;
}
default: {
throw new ArrayIndexOutOfBoundsException ("j=" + j);
}
}
}
/**
* Sets the elements of this matrix to zero.
*/
public void setZero() {
m00 = 0;
m01 = 0;
m02 = 0;
m03 = 0;
m10 = 0;
m11 = 0;
m12 = 0;
m13 = 0;
m20 = 0;
m21 = 0;
m22 = 0;
m23 = 0;
}
public void set (Matrix M) {
if (M instanceof Matrix3x4) {
set ((Matrix3x4)M);
}
else {
if (M.rowSize() != 3 || M.colSize() != 4) {
throw new ImproperSizeException ("matrix sizes do not conform");
}
m00 = M.get (0, 0);
m01 = M.get (0, 1);
m02 = M.get (0, 2);
m03 = M.get (0, 3);
m10 = M.get (1, 0);
m11 = M.get (1, 1);
m12 = M.get (1, 2);
m13 = M.get (1, 3);
m20 = M.get (2, 0);
m21 = M.get (2, 1);
m22 = M.get (2, 2);
m23 = M.get (2, 3);
}
}
/**
* Sets the contents of this Matrix3x4 to those of a specified block.
*
* @param M
* matrix block providing new values
*/
public void set (Matrix3x4 M) {
m00 = M.m00;
m01 = M.m01;
m02 = M.m02;
m03 = M.m03;
m10 = M.m10;
m11 = M.m11;
m12 = M.m12;
m13 = M.m13;
m20 = M.m20;
m21 = M.m21;
m22 = M.m22;
m23 = M.m23;
}
/**
* Scales the elements of this matrix by <code>s</code>.
*
* @param s
* scaling factor
*/
public void scale (double s) {
m00 *= s;
m01 *= s;
m02 *= s;
m03 *= s;
m10 *= s;
m11 *= s;
m12 *= s;
m13 *= s;
m20 *= s;
m21 *= s;
m22 *= s;
m23 *= s;
}
/**
* Computes s M and places the result in this matrix.
*
* @param s
* scaling factor
* @param M
* matrix to scale
*/
public void scale (double s, Matrix3x4 M) {
m00 = s * M.m00;
m01 = s * M.m01;
m02 = s * M.m02;
m03 = s * M.m03;
m10 = s * M.m10;
m11 = s * M.m11;
m12 = s * M.m12;
m13 = s * M.m13;
m20 = s * M.m20;
m21 = s * M.m21;
m22 = s * M.m22;
m23 = s * M.m23;
}
/**
* Adds this matrix to M and places the result in this matrix.
*
* @param M
* right-hand matrix
* @throws ImproperSizeException
* if this matrix and M have different sizes
*/
public void add (Matrix M) {
if (M instanceof Matrix3x4) {
add ((Matrix3x4)M);
}
else {
if (M.rowSize() != 3 || M.colSize() != 4) {
throw new ImproperSizeException ("matrix sizes do not conform");
}
m00 += M.get (0, 0);
m01 += M.get (0, 1);
m02 += M.get (0, 2);
m03 += M.get (0, 3);
m10 += M.get (1, 0);
m11 += M.get (1, 1);
m12 += M.get (1, 2);
m13 += M.get (1, 3);
m20 += M.get (2, 0);
m21 += M.get (2, 1);
m22 += M.get (2, 2);
m23 += M.get (2, 3);
}
}
/**
* Scales the matrix M and add the result to this matrix.
*
* @param s
* scaling factor
* @param M
* matrix to be scaled and added
* @throws ImproperSizeException
* if this matrix and M have different sizes
*/
public void scaledAdd (double s, Matrix M) {
if (M instanceof Matrix3x4) {
scaledAdd (s, (Matrix3x4)M);
}
else {
if (M.rowSize() != 3 || M.colSize() != 4) {
throw new ImproperSizeException ("matrix sizes do not conform");
}
m00 += s * M.get (0, 0);
m01 += s * M.get (0, 1);
m02 += s * M.get (0, 2);
m03 += s * M.get (0, 3);
m10 += s * M.get (1, 0);
m11 += s * M.get (1, 1);
m12 += s * M.get (1, 2);
m13 += s * M.get (1, 3);
m20 += s * M.get (2, 0);
m21 += s * M.get (2, 1);
m22 += s * M.get (2, 2);
m23 += s * M.get (2, 3);
}
}
/**
* Adds the contents of a Matrix3x4 to this matrix block.
*
* @param M
* matrix block to add
*/
public void add (Matrix3x4 M) {
m00 += M.m00;
m01 += M.m01;
m02 += M.m02;
m03 += M.m03;
m10 += M.m10;
m11 += M.m11;
m12 += M.m12;
m13 += M.m13;
m20 += M.m20;
m21 += M.m21;
m22 += M.m22;
m23 += M.m23;
}
/**
* Computes M1 + M2 and places the result in this matrix.
*
* @param M1
* first matrix to add
* @param M2
* second matrix to add
*/
public void add (Matrix3x4 M1, Matrix3x4 M2) {
m00 = M1.m00 + M2.m00;
m01 = M1.m01 + M2.m01;
m02 = M1.m02 + M2.m02;
m03 = M1.m03 + M2.m03;
m10 = M1.m10 + M2.m10;
m11 = M1.m11 + M2.m11;
m12 = M1.m12 + M2.m12;
m13 = M1.m13 + M2.m13;
m20 = M1.m20 + M2.m20;
m21 = M1.m21 + M2.m21;
m22 = M1.m22 + M2.m22;
m23 = M1.m23 + M2.m23;
}
/**
* Computes s M and adds the result to this matrix.
*
* @param s
* scaling factor
* @param M
* matrix to be scaled and added
*/
public void scaledAdd (double s, Matrix3x4 M) {
m00 += s * M.m00;
m01 += s * M.m01;
m02 += s * M.m02;
m03 += s * M.m03;
m10 += s * M.m10;
m11 += s * M.m11;
m12 += s * M.m12;
m13 += s * M.m13;
m20 += s * M.m20;
m21 += s * M.m21;
m22 += s * M.m22;
m23 += s * M.m23;
}
/**
* Computes s M1 + M2 and places the result in this matrix.
*
* @param s
* scaling factor
* @param M1
* matrix to be scaled
* @param M2
* matrix to be added
*/
public void scaledAdd (double s, Matrix3x4 M1, Matrix3x4 M2) {
m00 = s * M1.m00 + M2.m00;
m01 = s * M1.m01 + M2.m01;
m02 = s * M1.m02 + M2.m02;
m03 = s * M1.m03 + M2.m03;
m10 = s * M1.m10 + M2.m10;
m11 = s * M1.m11 + M2.m11;
m12 = s * M1.m12 + M2.m12;
m13 = s * M1.m13 + M2.m13;
m20 = s * M1.m20 + M2.m20;
m21 = s * M1.m21 + M2.m21;
m22 = s * M1.m22 + M2.m22;
m23 = s * M1.m23 + M2.m23;
}
/**
* Subtracts this matrix from M and places the result in this matrix.
*
* @param M
* right-hand matrix
* @throws ImproperSizeException
* if this matrix and M have different sizes
*/
public void sub (Matrix M) {
if (M instanceof Matrix3x4) {
sub ((Matrix3x4)M);
}
else {
if (M.rowSize() != 3 || M.colSize() != 4) {
throw new ImproperSizeException ("matrix sizes do not conform");
}
m00 -= M.get (0, 0);
m01 -= M.get (0, 1);
m02 -= M.get (0, 2);
m03 -= M.get (0, 3);
m10 -= M.get (1, 0);
m11 -= M.get (1, 1);
m12 -= M.get (1, 2);
m13 -= M.get (1, 3);
m20 -= M.get (2, 0);
m21 -= M.get (2, 1);
m22 -= M.get (2, 2);
m23 -= M.get (2, 3);
}
}
/**
* Subtracts the contents of a Matrix3x4 from this matrix block.
*
* @param M
* matrix block to subtract
*/
public void sub (Matrix3x4 M) {
m00 -= M.m00;
m01 -= M.m01;
m02 -= M.m02;
m03 -= M.m03;
m10 -= M.m10;
m11 -= M.m11;
m12 -= M.m12;
m13 -= M.m13;
m20 -= M.m20;
m21 -= M.m21;
m22 -= M.m22;
m23 -= M.m23;
}
/**
* Computes M1 - M2 places the result in this matrix.
*
* @param M1
* first matrix
* @param M2
* matrix to subtract
*/
public void sub (Matrix3x4 M1, Matrix3x4 M2) {
m00 = M1.m00 - M2.m00;
m01 = M1.m01 - M2.m01;
m02 = M1.m02 - M2.m02;
m03 = M1.m03 - M2.m03;
m10 = M1.m10 - M2.m10;
m11 = M1.m11 - M2.m11;
m12 = M1.m12 - M2.m12;
m13 = M1.m13 - M2.m13;
m20 = M1.m20 - M2.m20;
m21 = M1.m21 - M2.m21;
m22 = M1.m22 - M2.m22;
m23 = M1.m23 - M2.m23;
}
/**
* Multiplies M1 by M2 and places the result in this matrix.
*
* @param M1 left matrix term
* @param M2 right matrix term
*/
public void mulAdd (Matrix M1, Matrix M2) {
MatrixMulAdd.mulAdd3x4 (this, M1, M2);
}
/**
* Computes
* <p>
* M1 D M2^T
* <p>
* where D is a diagonal matrix, and adds the result to matrix MR.
*
* @param MR matrix to add result to
* @param M1 left matrix
* @param D diagonal matrix values
* @param M2 right matrix transpose
*/
public static void mulScaledTransposeRightAdd (
Matrix3d MR, Matrix3x4 M1, double[] D, Matrix3x4 M2) {
double d0 = D[0];
double d1 = D[1];
double d2 = D[2];
double d3 = D[3];
double T00 = d0*M2.m00;
double T01 = d0*M2.m10;
double T02 = d0*M2.m20;
double T10 = d1*M2.m01;
double T11 = d1*M2.m11;
double T12 = d1*M2.m21;
double T20 = d2*M2.m02;
double T21 = d2*M2.m12;
double T22 = d2*M2.m22;
double T30 = d3*M2.m03;
double T31 = d3*M2.m13;
double T32 = d3*M2.m23;
MR.m00 += M1.m00*T00 + M1.m01*T10 + M1.m02*T20 + M1.m03*T30;
MR.m01 += M1.m00*T01 + M1.m01*T11 + M1.m02*T21 + M1.m03*T31;
MR.m02 += M1.m00*T02 + M1.m01*T12 + M1.m02*T22 + M1.m03*T32;
MR.m10 += M1.m10*T00 + M1.m11*T10 + M1.m12*T20 + M1.m13*T30;
MR.m11 += M1.m10*T01 + M1.m11*T11 + M1.m12*T21 + M1.m13*T31;
MR.m12 += M1.m10*T02 + M1.m11*T12 + M1.m12*T22 + M1.m13*T32;
MR.m20 += M1.m20*T00 + M1.m21*T10 + M1.m22*T20 + M1.m23*T30;
MR.m21 += M1.m20*T01 + M1.m21*T11 + M1.m22*T21 + M1.m23*T31;
MR.m22 += M1.m20*T02 + M1.m21*T12 + M1.m22*T22 + M1.m23*T32;
}
/**
* Sets this matrix to the transpose of M
*
* @param M
* matrix to take the transpose of
*/
public void transpose (Matrix4x3 M) {
m00 = M.m00;
m10 = M.m01;
m20 = M.m02;
m01 = M.m10;
m11 = M.m11;
m21 = M.m12;
m02 = M.m20;
m12 = M.m21;
m22 = M.m22;
m03 = M.m30;
m13 = M.m31;
m23 = M.m32;
}
/**
* Creates a clone of this matrix.
*/
public Matrix3x4 clone() {
try {
return (Matrix3x4)super.clone();
}
catch (CloneNotSupportedException e) { // shouldn't happen
throw new InternalErrorException ("clone failed for " + getClass());
}
}
}
|
/*
Copyright (c) 2012 LinkedIn Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* $Id: $
*/
package com.linkedin.restli.client.base;
import com.linkedin.data.template.RecordTemplate;
import com.linkedin.restli.client.BatchUpdateRequestBuilder;
import com.linkedin.restli.client.RestliRequestOptions;
import com.linkedin.restli.common.ResourceSpec;
import com.linkedin.restli.common.attachments.RestLiAttachmentDataSourceWriter;
import com.linkedin.restli.common.attachments.RestLiDataSourceIterator;
import java.util.Map;
/**
* @author Josh Walker
* @version $Revision: $
*/
public class BatchUpdateRequestBuilderBase<
K,
V extends RecordTemplate,
RB extends BatchUpdateRequestBuilderBase<K, V, RB>>
extends BatchUpdateRequestBuilder<K, V>
{
public BatchUpdateRequestBuilderBase(String baseUriTemplate,
Class<V> valueClass,
ResourceSpec resourceSpec,
RestliRequestOptions requestOptions)
{
super(baseUriTemplate, valueClass, resourceSpec, requestOptions);
}
@SuppressWarnings({"unchecked"})
@Override
public RB input(K id, V entity)
{
return (RB) super.input(id, entity);
}
@SuppressWarnings({"unchecked"})
@Override
public RB inputs(Map<K, V> entities)
{
return (RB) super.inputs(entities);
}
@SuppressWarnings({"unchecked"})
@Override
public RB appendSingleAttachment(final RestLiAttachmentDataSourceWriter streamingAttachment)
{
return (RB) super.appendSingleAttachment(streamingAttachment);
}
@SuppressWarnings({"unchecked"})
@Override
public RB appendMultipleAttachments(final RestLiDataSourceIterator dataSourceIterator)
{
return (RB) super.appendMultipleAttachments(dataSourceIterator);
}
@SuppressWarnings({"unchecked"})
@Override
public RB setHeader(String key, String value)
{
return (RB) super.setHeader(key, value);
}
@SuppressWarnings({"unchecked"})
@Override
public RB setParam(String key, Object value)
{
return (RB) super.setParam(key, value);
}
@SuppressWarnings({"unchecked"})
@Override
public RB setReqParam(String key, Object value)
{
return (RB) super.setReqParam(key, value);
}
@SuppressWarnings({"unchecked"})
@Override
public RB addParam(String key, Object value)
{
return (RB) super.addParam(key, value);
}
@SuppressWarnings({"unchecked"})
@Override
public RB addReqParam(String key, Object value)
{
return (RB) super.addReqParam(key, value);
}
@SuppressWarnings({"unchecked"})
@Override
public RB pathKey(String name, Object value)
{
return (RB) super.pathKey(name, value);
}
}
|
/**
* Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.persistence;
import static akka.pattern.PatternsCS.ask;
import java.util.HashSet;
import java.util.Set;
import akka.NotUsed;
import akka.persistence.query.Sequence;
import akka.persistence.query.Offset;
import com.typesafe.config.Config;
import akka.actor.*;
import akka.persistence.query.*;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import akka.util.Timeout;
import com.typesafe.config.ConfigFactory;
import docs.persistence.query.MyEventsByTagPublisher;
import org.reactivestreams.Subscriber;
import scala.concurrent.duration.FiniteDuration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
public class PersistenceQueryDocTest {
final ActorSystem system = ActorSystem.create();
final ActorMaterializer mat = ActorMaterializer.create(system);
static
//#advanced-journal-query-types
public class RichEvent {
public final Set<String >tags;
public final Object payload;
public RichEvent(Set<String> tags, Object payload) {
this.tags = tags;
this.payload = payload;
}
}
//#advanced-journal-query-types
static
//#advanced-journal-query-types
// a plugin can provide:
public final class QueryMetadata{
public final boolean deterministicOrder;
public final boolean infinite;
public QueryMetadata(boolean deterministicOrder, boolean infinite) {
this.deterministicOrder = deterministicOrder;
this.infinite = infinite;
}
}
//#advanced-journal-query-types
static
//#my-read-journal
public class MyReadJournalProvider implements ReadJournalProvider {
private final MyJavadslReadJournal javadslReadJournal;
public MyReadJournalProvider(ExtendedActorSystem system, Config config) {
this.javadslReadJournal = new MyJavadslReadJournal(system, config);
}
@Override
public MyScaladslReadJournal scaladslReadJournal() {
return new MyScaladslReadJournal(javadslReadJournal);
}
@Override
public MyJavadslReadJournal javadslReadJournal() {
return this.javadslReadJournal;
}
}
//#my-read-journal
static
//#my-read-journal
public class MyJavadslReadJournal implements
akka.persistence.query.javadsl.ReadJournal,
akka.persistence.query.javadsl.EventsByTagQuery,
akka.persistence.query.javadsl.EventsByPersistenceIdQuery,
akka.persistence.query.javadsl.PersistenceIdsQuery,
akka.persistence.query.javadsl.CurrentPersistenceIdsQuery {
private final FiniteDuration refreshInterval;
public MyJavadslReadJournal(ExtendedActorSystem system, Config config) {
refreshInterval =
FiniteDuration.create(config.getDuration("refresh-interval",
TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
}
/**
* You can use `NoOffset` to retrieve all events with a given tag or retrieve a subset of all
* events by specifying a `Sequence` `offset`. The `offset` corresponds to an ordered sequence number for
* the specific tag. Note that the corresponding offset of each event is provided in the
* [[akka.persistence.query.EventEnvelope]], which makes it possible to resume the
* stream at a later point from a given offset.
*
* The `offset` is exclusive, i.e. the event with the exact same sequence number will not be included
* in the returned stream. This means that you can use the offset that is returned in `EventEnvelope`
* as the `offset` parameter in a subsequent query.
*/
@Override
public Source<EventEnvelope, NotUsed> eventsByTag(String tag, Offset offset) {
if(offset instanceof Sequence){
Sequence sequenceOffset = (Sequence) offset;
final Props props = MyEventsByTagPublisher.props(tag, sequenceOffset.value(), refreshInterval);
return Source.<EventEnvelope>actorPublisher(props).
mapMaterializedValue(m -> NotUsed.getInstance());
} else if (offset == NoOffset.getInstance())
return eventsByTag(tag, Offset.sequence(0L)); //recursive
else
throw new IllegalArgumentException("MyJavadslReadJournal does not support " + offset.getClass().getName() + " offsets");
}
@Override
public Source<EventEnvelope, NotUsed> eventsByPersistenceId(String persistenceId,
long fromSequenceNr, long toSequenceNr) {
// implement in a similar way as eventsByTag
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public Source<String, NotUsed> persistenceIds() {
// implement in a similar way as eventsByTag
throw new UnsupportedOperationException("Not implemented yet");
}
@Override
public Source<String, NotUsed> currentPersistenceIds() {
// implement in a similar way as eventsByTag
throw new UnsupportedOperationException("Not implemented yet");
}
// possibility to add more plugin specific queries
//#advanced-journal-query-definition
public Source<RichEvent, QueryMetadata> byTagsWithMeta(Set<String> tags) {
//#advanced-journal-query-definition
// implement in a similar way as eventsByTag
throw new UnsupportedOperationException("Not implemented yet");
}
}
//#my-read-journal
static
//#my-read-journal
public class MyScaladslReadJournal implements
akka.persistence.query.scaladsl.ReadJournal,
akka.persistence.query.scaladsl.EventsByTagQuery,
akka.persistence.query.scaladsl.EventsByPersistenceIdQuery,
akka.persistence.query.scaladsl.PersistenceIdsQuery,
akka.persistence.query.scaladsl.CurrentPersistenceIdsQuery {
private final MyJavadslReadJournal javadslReadJournal;
public MyScaladslReadJournal(MyJavadslReadJournal javadslReadJournal) {
this.javadslReadJournal = javadslReadJournal;
}
@Override
public akka.stream.scaladsl.Source<EventEnvelope, NotUsed> eventsByTag(
String tag, akka.persistence.query.Offset offset) {
return javadslReadJournal.eventsByTag(tag, offset).asScala();
}
@Override
public akka.stream.scaladsl.Source<EventEnvelope, NotUsed> eventsByPersistenceId(
String persistenceId, long fromSequenceNr, long toSequenceNr) {
return javadslReadJournal.eventsByPersistenceId(persistenceId, fromSequenceNr,
toSequenceNr).asScala();
}
@Override
public akka.stream.scaladsl.Source<String, NotUsed> persistenceIds() {
return javadslReadJournal.persistenceIds().asScala();
}
@Override
public akka.stream.scaladsl.Source<String, NotUsed> currentPersistenceIds() {
return javadslReadJournal.currentPersistenceIds().asScala();
}
// possibility to add more plugin specific queries
public akka.stream.scaladsl.Source<RichEvent, QueryMetadata> byTagsWithMeta(
scala.collection.Set<String> tags) {
Set<String> jTags = scala.collection.JavaConversions.setAsJavaSet(tags);
return javadslReadJournal.byTagsWithMeta(jTags).asScala();
}
}
//#my-read-journal
void demonstrateBasicUsage() {
final ActorSystem system = ActorSystem.create();
//#basic-usage
// obtain read journal by plugin id
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
// issue query to journal
Source<EventEnvelope, NotUsed> source =
readJournal.eventsByPersistenceId("user-1337", 0, Long.MAX_VALUE);
// materialize stream, consuming events
ActorMaterializer mat = ActorMaterializer.create(system);
source.runForeach(event -> System.out.println("Event: " + event), mat);
//#basic-usage
}
void demonstrateAllPersistenceIdsLive() {
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
//#all-persistence-ids-live
readJournal.persistenceIds();
//#all-persistence-ids-live
}
void demonstrateNoRefresh() {
final ActorSystem system = ActorSystem.create();
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
//#all-persistence-ids-snap
readJournal.currentPersistenceIds();
//#all-persistence-ids-snap
}
void demonstrateRefresh() {
final ActorSystem system = ActorSystem.create();
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
//#events-by-persistent-id
readJournal.eventsByPersistenceId("user-us-1337", 0L, Long.MAX_VALUE);
//#events-by-persistent-id
}
void demonstrateEventsByTag() {
final ActorSystem system = ActorSystem.create();
final ActorMaterializer mat = ActorMaterializer.create(system);
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
//#events-by-tag
// assuming journal is able to work with numeric offsets we can:
final Source<EventEnvelope, NotUsed> blueThings =
readJournal.eventsByTag("blue", new Sequence(0L));
// find top 10 blue things:
final CompletionStage<List<Object>> top10BlueThings =
blueThings
.map(EventEnvelope::event)
.take(10) // cancels the query stream after pulling 10 elements
.runFold(new ArrayList<>(10), (acc, e) -> {
acc.add(e);
return acc;
}, mat);
// start another query, from the known offset
Source<EventEnvelope, NotUsed> blue = readJournal.eventsByTag("blue", new Sequence(10));
//#events-by-tag
}
void demonstrateMaterializedQueryValues() {
final ActorSystem system = ActorSystem.create();
final ActorMaterializer mat = ActorMaterializer.create(system);
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
//#advanced-journal-query-usage
Set<String> tags = new HashSet<String>();
tags.add("red");
tags.add("blue");
final Source<RichEvent, QueryMetadata> events = readJournal.byTagsWithMeta(tags)
.mapMaterializedValue(meta -> {
System.out.println("The query is: " +
"ordered deterministically: " + meta.deterministicOrder + " " +
"infinite: " + meta.infinite);
return meta;
});
events.map(event -> {
System.out.println("Event payload: " + event.payload);
return event.payload;
}).runWith(Sink.ignore(), mat);
//#advanced-journal-query-usage
}
class ReactiveStreamsCompatibleDBDriver {
Subscriber<List<Object>> batchWriter() {
return null;
}
}
void demonstrateWritingIntoDifferentStore() {
final ActorSystem system = ActorSystem.create();
final ActorMaterializer mat = ActorMaterializer.create(system);
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
//#projection-into-different-store-rs
final ReactiveStreamsCompatibleDBDriver driver = new ReactiveStreamsCompatibleDBDriver();
final Subscriber<List<Object>> dbBatchWriter = driver.batchWriter();
// Using an example (Reactive Streams) Database driver
readJournal
.eventsByPersistenceId("user-1337", 0L, Long.MAX_VALUE)
.map(envelope -> envelope.event())
.grouped(20) // batch inserts into groups of 20
.runWith(Sink.fromSubscriber(dbBatchWriter), mat); // write batches to read-side database
//#projection-into-different-store-rs
}
//#projection-into-different-store-simple-classes
class ExampleStore {
CompletionStage<Void> save(Object any) {
// ...
//#projection-into-different-store-simple-classes
return null;
//#projection-into-different-store-simple-classes
}
}
//#projection-into-different-store-simple-classes
void demonstrateWritingIntoDifferentStoreWithMapAsync() {
final ActorSystem system = ActorSystem.create();
final ActorMaterializer mat = ActorMaterializer.create(system);
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
//#projection-into-different-store-simple
final ExampleStore store = new ExampleStore();
readJournal
.eventsByTag("bid", new Sequence(0L))
.mapAsync(1, store::save)
.runWith(Sink.ignore(), mat);
//#projection-into-different-store-simple
}
//#projection-into-different-store
class MyResumableProjection {
private final String name;
public MyResumableProjection(String name) {
this.name = name;
}
public CompletionStage<Long> saveProgress(Offset offset) {
// ...
//#projection-into-different-store
return null;
//#projection-into-different-store
}
public CompletionStage<Long> latestOffset() {
// ...
//#projection-into-different-store
return null;
//#projection-into-different-store
}
}
//#projection-into-different-store
void demonstrateWritingIntoDifferentStoreWithResumableProjections() throws Exception {
final ActorSystem system = ActorSystem.create();
final ActorMaterializer mat = ActorMaterializer.create(system);
final MyJavadslReadJournal readJournal =
PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class,
"akka.persistence.query.my-read-journal");
//#projection-into-different-store-actor-run
final Timeout timeout = Timeout.apply(3, TimeUnit.SECONDS);
final MyResumableProjection bidProjection = new MyResumableProjection("bid");
final Props writerProps = Props.create(TheOneWhoWritesToQueryJournal.class, "bid");
final ActorRef writer = system.actorOf(writerProps, "bid-projection-writer");
long startFromOffset = bidProjection.latestOffset().toCompletableFuture().get(3, TimeUnit.SECONDS);
readJournal
.eventsByTag("bid", new Sequence(startFromOffset))
.mapAsync(8, envelope -> {
final CompletionStage<Object> f = ask(writer, envelope.event(), timeout);
return f.thenApplyAsync(in -> envelope.offset(), system.dispatcher());
})
.mapAsync(1, offset -> bidProjection.saveProgress(offset))
.runWith(Sink.ignore(), mat);
}
//#projection-into-different-store-actor-run
class ComplexState {
boolean readyToSave() {
return false;
}
}
static class Record {
static Record of(Object any) {
return new Record();
}
}
//#projection-into-different-store-actor
final class TheOneWhoWritesToQueryJournal extends AbstractActor {
private final ExampleStore store;
private ComplexState state = new ComplexState();
public TheOneWhoWritesToQueryJournal() {
store = new ExampleStore();
}
@Override
public Receive createReceive() {
return receiveBuilder()
.matchAny(message -> {
state = updateState(state, message);
// example saving logic that requires state to become ready:
if (state.readyToSave())
store.save(Record.of(state));
})
.build();
}
ComplexState updateState(ComplexState state, Object msg) {
// some complicated aggregation logic here ...
return state;
}
}
//#projection-into-different-store-actor
}
|
package com.generation.energym;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class EnergymApplicationTests {
@Test
void contextLoads() {
}
}
|
package oo.Game;
/**
* Interface for Phase
* Not useful, mainly useless and confusing, but asked
*/
public interface Phase {
/**
* Select 4 random players
* Could be moved to the Game class
*/
void selectPlayers();
/**
* Get the current phase
*
* @return Current phase
*/
PhaseEnum getCurrentPhase();
}
|
package io.basc.start.app.web;
import io.basc.framework.http.HttpMethod;
import io.basc.framework.io.IOUtils;
import io.basc.framework.net.message.multipart.MultipartMessage;
import io.basc.framework.security.session.UserSession;
import io.basc.framework.upload.kind.KindDirType;
import io.basc.framework.upload.kind.KindEditor;
import io.basc.framework.upload.kind.KindOrderType;
import io.basc.framework.web.MultiPartServerHttpRequest;
import io.basc.framework.web.pattern.annotation.RequestMapping;
import java.util.HashMap;
import java.util.Map;
@RequestMapping(value = "kind")
public class KindController {
private KindEditor kindEditor;
public KindController(KindEditor kindEditor) {
this.kindEditor = kindEditor;
}
public String getRequestGroup(UserSession<Long> requestUser) {
return requestUser != null? (requestUser.getUid() + "") : null;
}
@RequestMapping(value = "upload", methods = { HttpMethod.POST, HttpMethod.PUT })
public Object upload(UserSession<Long> requestUser, MultiPartServerHttpRequest request, KindDirType dir) {
MultipartMessage fileItem = request.getFirstFile();
if (fileItem == null) {
return error("请选择文件");
}
try {
String url = kindEditor.upload(getRequestGroup(requestUser), dir, fileItem);
return success(url);
} catch (Exception e) {
return error(e.getMessage());
} finally {
IOUtils.closeQuietly(fileItem);
}
}
@RequestMapping(value = "manager", methods = { HttpMethod.GET })
public Object manager(UserSession<Long> requestUser, KindDirType dir, String path, KindOrderType order) {
return kindEditor.manager(getRequestGroup(requestUser), dir, path, order);
}
private Object success(String url) {
Map<String, Object> map = new HashMap<String, Object>(4);
map.put("code", 0);
map.put("url", url);
return map;
}
private Object error(String msg) {
Map<String, Object> map = new HashMap<String, Object>(4);
map.put("code", 1);
map.put("msg", msg);
return map;
}
}
|
/**
* (C) Copyright 2016-2019 teecube
* (https://teecu.be) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package t3.xml;
/**
*
* @author Mathieu Debove <mad@teecu.be>
*
*/
public interface XMLFromPropertiesMapping {
public Object addParameter(String key, String value);
}
|
/*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010 France Telecom S.A.
*
* 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.orangelabs.rcs.core.ipcall;
import android.os.RemoteException;
import com.orangelabs.rcs.protocol.sdp.SdpUtils;
import com.orangelabs.rcs.protocol.sip.SipRequest;
import com.orangelabs.rcs.protocol.sip.SipUtils;
public class IPCall_RemoteHoldInactive extends CallHoldManager {
public IPCall_RemoteHoldInactive(IPCallSession session){
super(session);
}
@Override
public void setCallHold(boolean callHoldAction, SipRequest reInvite) {
// build sdp response
String sdp = buildCallHoldSdpResponse(callHoldAction);
// set sdp response as local content
session.getDialogPath().setLocalContent(sdp);
//get feature tags
String[] featureTags = null;
if (session.isTagPresent(reInvite.getContent(), "m=video")) { // audio+ video
featureTags = IPCallService.FEATURE_TAGS_IP_VIDEO_CALL;
} else { // audio only
featureTags = IPCallService.FEATURE_TAGS_IP_VOICE_CALL;
}
int requestType = (callHoldAction)? IPCallSession.SET_ON_HOLD : IPCallSession.SET_ON_RESUME ;
// process user Answer and SIP response
session.getUpdateSessionManager().send200OkReInviteResp(reInvite,
featureTags,
sdp,
requestType);
}
private String buildCallHoldSdpResponse(boolean action){
try {
// Build SDP part
String ntpTime = SipUtils.constructNTPtime(System.currentTimeMillis());
String ipAddress = session.getDialogPath().getSipStack().getLocalIpAddress();
String aVar = (action)? "a=inactive" : "a=sendrcv" ;
String audioSdp = AudioSdpBuilder.buildSdpOffer(session.getPlayer().getSupportedAudioCodecs(),
session.getPlayer().getLocalAudioRtpPort())+ aVar + SipUtils.CRLF;
String videoSdp = "";
if ((session.getVideoContent()!= null)&&(session.getPlayer()!= null)&&(session.getRenderer()!= null)) {
videoSdp = VideoSdpBuilder.buildSdpOfferWithOrientation(
session.getPlayer().getSupportedVideoCodecs(),
session.getRenderer().getLocalVideoRtpPort())+ aVar + SipUtils.CRLF;
}
String sdp =
"v=0" + SipUtils.CRLF +
"o=- " + ntpTime + " " + ntpTime + " " + SdpUtils.formatAddressType(ipAddress) + SipUtils.CRLF +
"s=-" + SipUtils.CRLF +
"c=" + SdpUtils.formatAddressType(ipAddress) + SipUtils.CRLF +
"t=0 0" + SipUtils.CRLF +
audioSdp +
videoSdp ;
return sdp;
} catch (RemoteException e) {
if (logger.isActivated()) {
logger.error("Add video has failed", e);
}
// Unexpected error
session.handleError(new IPCallError(IPCallError.UNEXPECTED_EXCEPTION, e.getMessage()));
return null;
}
}
@Override
public void prepareSession() {
// TODO Auto-generated method stub
}
@Override
public void setCallHold(boolean callHoldAction) {
// not used in IPCall-RemoteHoldInactive class
}
}
|
/*
* Copyright (c) 2020. Red Hat, Inc. and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.drools.modelcompiler.constraints;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.drools.core.WorkingMemory;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.reteoo.AccumulateNode.AccumulateContextEntry;
import org.drools.core.reteoo.AccumulateNode.GroupByContext;
import org.drools.core.reteoo.LeftTuple;
import org.drools.core.reteoo.RightTuple;
import org.drools.core.rule.Accumulate;
import org.drools.core.rule.Declaration;
import org.drools.core.spi.Accumulator;
import org.drools.core.spi.Tuple;
import org.drools.core.util.index.TupleList;
import org.drools.model.functions.Function1;
import org.drools.model.functions.FunctionN;
public class LambdaGroupByAccumulate extends Accumulate {
private Accumulate innerAccumulate;
private Declaration[] groupingDeclarations;
private FunctionN groupingFunction;
private Function1 groupingFunction1;
public LambdaGroupByAccumulate() { }
public LambdaGroupByAccumulate( Accumulate innerAccumulate, Declaration[] groupingDeclarations, FunctionN groupingFunction ) {
super(innerAccumulate.getSource(), innerAccumulate.getRequiredDeclarations());
this.innerAccumulate = innerAccumulate;
this.groupingDeclarations = groupingDeclarations;
this.groupingFunction = groupingFunction;
this.groupingFunction1 = groupingDeclarations.length == 1 ? groupingFunction.asFunction1() : null;
}
private Object getKey( Tuple tuple, InternalFactHandle handle, WorkingMemory workingMemory ) {
if (groupingFunction1 != null) {
return groupingFunction1.apply( getValue( tuple, handle, workingMemory, groupingDeclarations[0] ) );
}
Object[] args = new Object[groupingDeclarations.length];
for (int i = 0; i < groupingDeclarations.length; i++) {
args[i] = getValue( tuple, handle, workingMemory, groupingDeclarations[i] );
}
return groupingFunction.apply( args );
}
private Object getValue( Tuple tuple, InternalFactHandle handle, WorkingMemory workingMemory, Declaration declaration ) {
// we already have the handle, so avoid tuple iteration if not needed.
// (is this really saving time, as get(int index) has pretty much the same check, at best saves some method call) (mdp)
return declaration.getValue( ( InternalWorkingMemory )workingMemory, declaration.getTupleIndex() < tuple.size() ? tuple.get( declaration ).getObject() : handle.getObject() );
}
@Override
public void readExternal( ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal(in);
this.innerAccumulate = (Accumulate) in.readObject();
this.groupingDeclarations = (Declaration[]) in.readObject();
this.groupingFunction = (FunctionN) in.readObject();
this.groupingFunction1 = groupingDeclarations.length == 1 ? groupingFunction.asFunction1() : null;
}
@Override
public void writeExternal( ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeObject(innerAccumulate);
out.writeObject(groupingDeclarations);
out.writeObject(groupingFunction);
}
@Override
public Accumulator[] getAccumulators() {
return innerAccumulate.getAccumulators();
}
@Override
public Object createFunctionContext() {
return innerAccumulate.createFunctionContext();
}
@Override
public Object init(Object workingMemoryContext, Object accContext,
Object funcContext, Tuple leftTuple, WorkingMemory workingMemory) {
// do nothing here, it's done when the group is first created
return funcContext;
}
@Override
public Object accumulate( Object workingMemoryContext, Object context,
Tuple match, InternalFactHandle handle, WorkingMemory wm ) {
GroupByContext groupByContext = ( GroupByContext ) context;
TupleList<AccumulateContextEntry> tupleList = groupByContext.getGroup(workingMemoryContext, innerAccumulate,
match, getKey(match, handle, wm), wm);
return accumulate(workingMemoryContext, match, handle, groupByContext, tupleList, wm);
}
@Override
public Object accumulate(Object workingMemoryContext, Tuple match, InternalFactHandle handle,
GroupByContext groupByContext, TupleList<AccumulateContextEntry> tupleList, WorkingMemory wm) {
groupByContext.moveToPropagateTupleList(tupleList);
return innerAccumulate.accumulate(workingMemoryContext, tupleList.getContext(), match, handle, wm);
}
@Override
public boolean tryReverse(Object workingMemoryContext, Object context, Tuple leftTuple, InternalFactHandle handle,
RightTuple rightParent, LeftTuple match, WorkingMemory workingMemory) {
TupleList<AccumulateContextEntry> memory = match.getMemory();
AccumulateContextEntry entry = memory.getContext();
boolean reversed = innerAccumulate.tryReverse(workingMemoryContext, entry, leftTuple, handle, rightParent, match, workingMemory);
if (reversed) {
GroupByContext groupByContext = ( GroupByContext ) context;
groupByContext.moveToPropagateTupleList( match.getMemory() );
memory.remove( match );
if ( memory.isEmpty() ) {
groupByContext.removeGroup( entry.getKey() );
memory.getContext().setEmpty( true );
}
}
return reversed;
}
@Override
public Object getResult( Object workingMemoryContext, Object context, Tuple leftTuple, WorkingMemory workingMemory ) {
AccumulateContextEntry entry = (AccumulateContextEntry) context;
return entry.isEmpty() ? null : innerAccumulate.getResult(workingMemoryContext, context, leftTuple, workingMemory);
}
@Override
public boolean supportsReverse() {
return innerAccumulate.supportsReverse();
}
@Override
public Accumulate clone() {
return new LambdaGroupByAccumulate( innerAccumulate.clone(), groupingDeclarations, groupingFunction );
}
@Override
public Object createWorkingMemoryContext() {
return innerAccumulate.createWorkingMemoryContext();
}
@Override
public boolean isMultiFunction() {
return innerAccumulate.isMultiFunction();
}
@Override
public void replaceAccumulatorDeclaration( Declaration declaration, Declaration resolved ) {
innerAccumulate.replaceAccumulatorDeclaration(declaration, resolved);
}
@Override
public boolean isGroupBy() {
return true;
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.companyreg.model.v20201022;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.companyreg.Endpoint;
/**
* @author auto create
* @version
*/
public class GetEnterprisesInfoRequest extends RpcAcsRequest<GetEnterprisesInfoResponse> {
private String creditCode;
private String enterpriseName;
public GetEnterprisesInfoRequest() {
super("companyreg", "2020-10-22", "GetEnterprisesInfo");
setMethod(MethodType.GET);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getCreditCode() {
return this.creditCode;
}
public void setCreditCode(String creditCode) {
this.creditCode = creditCode;
if(creditCode != null){
putQueryParameter("CreditCode", creditCode);
}
}
public String getEnterpriseName() {
return this.enterpriseName;
}
public void setEnterpriseName(String enterpriseName) {
this.enterpriseName = enterpriseName;
if(enterpriseName != null){
putQueryParameter("EnterpriseName", enterpriseName);
}
}
@Override
public Class<GetEnterprisesInfoResponse> getResponseClass() {
return GetEnterprisesInfoResponse.class;
}
}
|
/*
* DatabaseConfiguration.java
*
* Copyright (c) 2019 Rafael Corchuelo.
*
* In keeping with the traditional purpose of furthering education and research, it is
* the policy of the copyright owner to permit non-commercial use and redistribution of
* this software. It has been tested carefully, but it is not guaranteed for any particular
* purposes. The copyright owner does not offer any warranties or representations, nor do
* they accept any liabilities with respect to them.
*/
package acme.framework.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
public class DatabaseConfiguration {
}
|
package peacefulotter.engine.rendering.graphics;
public class RawModel
{
private final int vaoId;
private final int vertexCount;
public RawModel( int vaoId, int vertexCount )
{
this.vaoId = vaoId;
this.vertexCount = vertexCount;
}
public int getVaoId()
{
return vaoId;
}
public int getVertexCount()
{
return vertexCount;
}
}
|
package com.github.sandor_balazs.nosql_java.web.rest.dto;
import java.io.Serializable;
import java.util.Objects;
/**
* A DTO for the Funding entity.
*/
public class FundingDTO implements Serializable {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FundingDTO fundingDTO = (FundingDTO) o;
if ( ! Objects.equals(id, fundingDTO.id)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "FundingDTO{" +
"id=" + id +
", name='" + name + "'" +
'}';
}
}
|
/*******************************************************************************
* Copyright 2021 Nail Sharipov (sharipovn@gmail.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.
******************************************************************************/
package com.hammergenics.core.stages.ui.physics.bullet.dynamics;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.dynamics.btDynamicsWorld;
import com.badlogic.gdx.physics.bullet.dynamics.btMLCPSolver;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.hammergenics.HGGame;
import com.hammergenics.core.ModelEditScreen;
import com.hammergenics.core.stages.ModelEditStage;
import com.hammergenics.core.stages.ui.ContextAwareVisWindow;
import com.hammergenics.physics.bullet.dynamics.btConstraintSolversEnum;
import com.hammergenics.physics.bullet.dynamics.btDynamicsWorldTypesEnum;
import com.hammergenics.physics.bullet.dynamics.btMLCPSolversEnum;
import com.kotcrab.vis.ui.widget.VisCheckBox;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisSelectBox;
import com.kotcrab.vis.ui.widget.VisTable;
import com.kotcrab.vis.ui.widget.VisTextField;
import static com.hammergenics.physics.bullet.dynamics.btConstraintSolversEnum.BT_MLCP_SOLVER;
import static com.hammergenics.HGUtils.btDbgModes;
/**
* Add description here
*
* @author nrsharip
*/
public class btDynamicsWorldVisWindow extends ContextAwareVisWindow {
public btDynamicsWorld dw;
public VisLabel dwTypeLabel;
public VisCheckBox dynamicsCheckBox;
public VisCheckBox rbCheckBox;
public VisCheckBox groundCheckBox;
public VisSelectBox<String> btDebugModeSelectBox;
public VisSelectBox<btConstraintSolversEnum> constraintSolverSelectBox;
public VisSelectBox<btMLCPSolversEnum> mlcpAlgorithmSelectBox;
public VisTextField dwGravityXTF; // dw gravity
public VisTextField dwGravityYTF; // dw gravity
public VisTextField dwGravityZTF; // dw gravity
public Vector3 dwGravity = new Vector3();
public btDynamicsWorldVisWindow(ModelEditScreen modelES, ModelEditStage stage) {
super("Dynamics World", modelES, stage);
this.dw = btDynamicsWorldTypesEnum.selected.dynamicsWorld;
init();
btDebugModeSelectBox.getSelection().setProgrammaticChangeEvents(false);
btDebugModeSelectBox.setSelectedIndex(btDbgModes.indexOfValue(dw.getDebugDrawer().getDebugMode(), false));
btDebugModeSelectBox.getSelection().setProgrammaticChangeEvents(true);
constraintSolverSelectBox.getSelection().setProgrammaticChangeEvents(false);
constraintSolverSelectBox.setSelected(btConstraintSolversEnum.findByType(dw.getConstraintSolver().getSolverType()));
constraintSolverSelectBox.getSelection().setProgrammaticChangeEvents(true);
add(dwTypeLabel).colspan(2).center().expandX();
row();
VisTable row01 = new VisTable();
row01.add(dynamicsCheckBox).expandX();
row01.add(rbCheckBox).expandX();
row01.add(groundCheckBox).expandX();
add(row01).colspan(2).center().expandX().fillX();
row();
add(new VisLabel("bullet debug mode:")).padRight(5f).right();
add(btDebugModeSelectBox).expandX().fillX().center();
row();
add(new VisLabel("constraint solver:")).padRight(5f).right();
add(constraintSolverSelectBox).expandX().fillX().center();
row();
add(new VisLabel("algorithm (for MLCP only):")).padRight(5f).right();
add(mlcpAlgorithmSelectBox).expandX().fillX().center();
row();
VisTable lblTable1 = new VisTable();
lblTable1.add(new VisLabel("x")).expandX().center();
lblTable1.add(new VisLabel("y")).expandX().center();
lblTable1.add(new VisLabel("z")).expandX().center();
add().right();
add(lblTable1).expandX().fillX();
row();
VisTable dwGravityTable = new VisTable();
dwGravityTable.add(dwGravityXTF).width(120).maxWidth(120).left();
dwGravityTable.add(dwGravityYTF).width(120).maxWidth(120).left();
dwGravityTable.add(dwGravityZTF).width(120).maxWidth(120).left();
add(new VisLabel("gravity:")).padRight(5f).right();
add(dwGravityTable).left();
row();
}
public void init() {
dwTypeLabel = new VisLabel("");
dynamicsCheckBox = new VisCheckBox("enable dynamics");
dynamicsCheckBox.setChecked(false);
dynamicsCheckBox.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
if (!dynamicsCheckBox.isChecked()) modelES.eng.arrangeInSpiral(stage.origScaleCheckBox.isChecked());
}
});
rbCheckBox = new VisCheckBox("rigid body");
rbCheckBox.setChecked(false);
groundCheckBox = new VisCheckBox("ground");
groundCheckBox.setChecked(false);
btDebugModeSelectBox = new VisSelectBox<>();
btDebugModeSelectBox.clearItems();
btDebugModeSelectBox.setItems(btDbgModes.keys().toArray());
btDebugModeSelectBox.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
// btIDebugDraw.h
// enum DebugDrawModes
// {
// DBG_NoDebug=0,
// DBG_DrawWireframe = 1,
// DBG_DrawAabb=2,
// DBG_DrawFeaturesText=4,
// DBG_DrawContactPoints=8,
// DBG_NoDeactivation=16,
// DBG_NoHelpText = 32,
// DBG_DrawText=64,
// DBG_ProfileTimings = 128,
// DBG_EnableSatComparison = 256,
// DBG_DisableBulletLCP = 512,
// DBG_EnableCCD = 1024,
// DBG_DrawConstraints = (1 << 11),
// DBG_DrawConstraintLimits = (1 << 12),
// DBG_FastWireframe = (1<<13),
// DBG_DrawNormals = (1<<14),
// DBG_DrawFrames = (1<<15),
// DBG_MAX_DEBUG_DRAW_MODE
// };
dw.getDebugDrawer().setDebugMode(btDbgModes.get(btDebugModeSelectBox.getSelected()));
}
});
constraintSolverSelectBox = new VisSelectBox<>();
constraintSolverSelectBox.clearItems();
constraintSolverSelectBox.setItems(btConstraintSolversEnum.values());
constraintSolverSelectBox.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
// see getConstraintSolver():
// long cPtr = DynamicsJNI.btDynamicsWorld_getConstraintSolver(swigCPtr, this);
// return (cPtr == 0) ? null : new btConstraintSolver(cPtr, false);
// Gdx.app.debug("test", dw.getConstraintSolver().className);
dw.setConstraintSolver(constraintSolverSelectBox.getSelected().getInstance());
}
});
mlcpAlgorithmSelectBox = new VisSelectBox<>();
mlcpAlgorithmSelectBox.clearItems();
mlcpAlgorithmSelectBox.setItems(btMLCPSolversEnum.values());
mlcpAlgorithmSelectBox.setSelected(btMLCPSolversEnum.current());
mlcpAlgorithmSelectBox.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
((btMLCPSolver)BT_MLCP_SOLVER.getInstance()).setMLCPSolver(mlcpAlgorithmSelectBox.getSelected().apply());
}
});
dwGravityXTF = new VisTextField(""); // dw gravity
dwGravityYTF = new VisTextField(""); // dw gravity
dwGravityZTF = new VisTextField(""); // dw gravity
}
@Override
public void update(float delta) {
super.update(delta);
String dwTypeName = btDynamicsWorldTypesEnum.findByType(dw.getWorldType()).toString();
dwTypeLabel.setText("Dynamics World Type: " + dwTypeName);
dwGravity = dw.getGravity();
dwGravityXTF.setText(Float.toString(dwGravity.x));
dwGravityYTF.setText(Float.toString(dwGravity.y));
dwGravityZTF.setText(Float.toString(dwGravity.z));
}
@Override
public void applyLocale(HGGame.I18NBundlesEnum language) { }
}
|
/**
* 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 com.alibaba.jstorm.common.metric;
import com.alibaba.jstorm.metric.KVSerializable;
import com.alibaba.jstorm.metric.MetricUtils;
import com.alibaba.jstorm.utils.JStormUtils;
import java.util.Date;
/**
* @author wange
* @since 15/7/16
*/
public class TopologyHistory implements KVSerializable {
private long id;
private String clusterName;
private String topologyName;
private String topologyId;
private double sampleRate;
private Date start;
private Date end;
public TopologyHistory() {
}
public TopologyHistory(String clusterName, String topologyId) {
this.clusterName = clusterName;
this.topologyId = topologyId;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getTopologyName() {
return topologyName;
}
public void setTopologyName(String topologyName) {
this.topologyName = topologyName;
}
public String getTopologyId() {
return topologyId;
}
public void setTopologyId(String topologyId) {
this.topologyId = topologyId;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public Date getTime() {
return start != null ? start : end;
}
public String getTag() {
return start != null ? KVSerializable.START : KVSerializable.END;
}
public double getSampleRate() {
return sampleRate;
}
public void setSampleRate(Double sampleRate) {
if (sampleRate == null) {
this.sampleRate = 1.0d;
} else {
this.sampleRate = sampleRate;
}
}
/**
* key: clusterName + topologyName + time
*/
@Override
public byte[] getKey() {
return MetricUtils.concat2(clusterName, topologyName, getTime().getTime()).getBytes();
}
/**
* value: topologyId + type: S/E
*/
@Override
public byte[] getValue() {
return MetricUtils.concat2(topologyId, getTag(), sampleRate).getBytes();
}
@Override
public Object fromKV(byte[] key, byte[] value) {
String[] keyParts = new String(key).split(MetricUtils.DELIM);
long time = 0;
if (keyParts.length >= 3) {
this.clusterName = keyParts[0];
this.topologyName = keyParts[1];
time = Long.valueOf(keyParts[2]);
}
String[] valueParts = new String(value).split(MetricUtils.DELIM);
if (valueParts.length >= 3) {
this.topologyId = valueParts[0];
String tag = valueParts[1];
if (tag.equals(KVSerializable.START)) {
this.start = new Date(time);
} else {
this.end = new Date(time);
}
this.sampleRate = JStormUtils.parseDouble(valueParts[2], 0.1d);
}
return this;
}
public String getIdentity(){
return MetricUtils.concat2(clusterName, topologyId);
}
public void merge(TopologyHistory history){
if (history.start != null && this.start == null){
this.start = history.start;
}
if (history.end != null && this.end == null){
this.end = history.end;
}
}
}
|
/*
* 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.synapse.transport.certificatevalidation;
public class CertificateVerificationException extends Exception {
public CertificateVerificationException(String message) {
super(message);
}
public CertificateVerificationException(Throwable throwable) {
super(throwable);
}
public CertificateVerificationException(String message, Throwable throwable) {
super(message, throwable);
}
}
|
package com.yuhs.shiro;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
* 自定义FormAuthenticationFilter,完成认证前进行验证码校验
* Created by yuhaisheng on 2019/4/29.
*/
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
/**
* 原FormAuthenticationFilter的认证方法
* @param request
* @param response
* @return
* @throws Exception
*/
@Override
protected boolean onAccessDenied(
ServletRequest request, ServletResponse response) throws Exception {
//在这里进行验证码校验
//从session中获取验证码
HttpServletRequest httpServletRequest =(HttpServletRequest)request;
String validateCode = (String)httpServletRequest.getSession().getAttribute("validateCode");
//取出页面输入的验证码
String randomcode = httpServletRequest.getParameter("randomcode");
if (randomcode != null && validateCode != null && !validateCode.equals(randomcode)) {
//如果校验失败,将验证码错误信息,通过shiroLoginFailure设置到request中
httpServletRequest.setAttribute("shiroLoginFailure", "randomcodeError");
//拒绝访问,不在校验账号和密码
return true;
}
//如果失败,将验证码失败信息,通过shiroLoginFailure设置到request中
return super.onAccessDenied(request, response);
}
}
|
package com.boyarsky.dapos.core.repository.account;
import com.boyarsky.dapos.core.model.account.Account;
import com.boyarsky.dapos.core.model.account.AccountId;
import com.boyarsky.dapos.core.repository.XodusRepoContext;
import com.boyarsky.dapos.core.repository.aop.Transactional;
import com.boyarsky.dapos.utils.CollectionUtils;
import com.boyarsky.dapos.utils.Convert;
import jetbrains.exodus.entitystore.Entity;
import jetbrains.exodus.entitystore.EntityIterable;
import jetbrains.exodus.entitystore.StoreTransaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@Slf4j
public class XodusAccountRepository implements AccountRepository {
private static final String entityType = "account";
private final XodusRepoContext context;
@Autowired
public XodusAccountRepository(XodusRepoContext context) {
this.context = context;
}
@Override
@Transactional(readonly = true)
public Account find(AccountId accountId) {
StoreTransaction tx = context.getTx();
Entity entity = find(accountId, tx);
if (entity == null) {
return null;
}
return map(entity);
}
private Entity find(AccountId accountId, StoreTransaction txn) {
EntityIterable id = txn.find(entityType, "id", Convert.toHexString(accountId.getAddressBytes()));
return CollectionUtils.requireAtMostOne(id);
}
@Override
@Transactional(requiredExisting = true)
public void save(Account account) {
StoreTransaction tx = context.getTx();
Entity entity;
if (account.getDbId() == null) {
entity = tx.newEntity(entityType);
entity.setProperty("id", Convert.toHexString(account.getCryptoId().getAddressBytes()));
} else {
entity = tx.getEntity(account.getDbId());
}
entity.setProperty("balance", account.getBalance());
if (account.getPublicKey() != null) {
entity.setProperty("publicKey", Convert.toHexString(account.getPublicKey()));
}
entity.setProperty("type", account.getType().getCode());
entity.setProperty("height", account.getHeight());
}
private Account map(Entity entity) {
Account acc = new Account();
acc.setDbId(entity.getId());
acc.setBalance((Long) entity.getProperty("balance"));
acc.setCryptoId(AccountId.fromBytes(Convert.parseHexString((String) entity.getProperty("id"))));
acc.setPublicKey(Convert.parseHexString((String) entity.getProperty("publicKey")));
acc.setType(Account.Type.fromCode((Byte) entity.getProperty("type")));
acc.setHeight((Long) entity.getProperty("height"));
return acc;
}
@Override
@Transactional(readonly = true)
public List<Account> getAll() {
StoreTransaction tx = context.getTx();
List<Account> accounts = new ArrayList<>();
EntityIterable all = tx.getAll(entityType);
for (Entity entity : all) {
accounts.add(map(entity));
}
return accounts;
}
@Override
@Transactional(requiredExisting = true)
public void delete(Account account) {
throw new UnsupportedOperationException("Account deletion is not supported yet");
}
}
|
package io.basc.framework.lucene;
public class LuceneException extends RuntimeException{
private static final long serialVersionUID = 1L;
public LuceneException(Throwable e) {
super(e);
}
public LuceneException(String message) {
super(message);
}
public LuceneException(String message, Throwable cause) {
super(message, cause);
}
}
|
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import static com.facebook.buck.cxx.toolchain.CxxFlavorSanitizer.sanitize;
import static java.io.File.pathSeparator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.oneOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeThat;
import static org.junit.Assume.assumeTrue;
import com.facebook.buck.android.AssumeAndroidPlatform;
import com.facebook.buck.apple.AppleNativeIntegrationTestUtils;
import com.facebook.buck.apple.toolchain.ApplePlatform;
import com.facebook.buck.core.build.engine.BuildRuleStatus;
import com.facebook.buck.core.build.engine.BuildRuleSuccessType;
import com.facebook.buck.core.config.FakeBuckConfig;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.cxx.toolchain.CxxBuckConfig;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.CxxPlatformUtils;
import com.facebook.buck.cxx.toolchain.HeaderVisibility;
import com.facebook.buck.cxx.toolchain.LinkerMapMode;
import com.facebook.buck.cxx.toolchain.PicType;
import com.facebook.buck.cxx.toolchain.StripStyle;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.io.file.MostFiles;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.testutil.ProcessResult;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.BuckBuildLog;
import com.facebook.buck.testutil.integration.InferHelper;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class CxxBinaryIntegrationTest {
@Rule public TemporaryPaths tmp = new TemporaryPaths();
@Before
public void setUp() {
assumeTrue(Platform.detect() != Platform.WINDOWS);
}
@Test
public void testInferCxxBinaryDepsCaching() throws IOException, InterruptedException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
workspace.enableDirCache();
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig());
CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig);
BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_deps");
String inputBuildTargetName =
inputBuildTarget
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor())
.getFullyQualifiedName();
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
/*
* Check that building after clean will use the cache
*/
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
for (BuildTarget buildTarget : buildLog.getAllTargets()) {
buildLog.assertTargetWasFetchedFromCache(buildTarget.toString());
}
/*
* Check that if the file in the binary target changes, then all the deps will be fetched
* from the cache
*/
String sourceName = "src_with_deps.c";
workspace.replaceFileContents("foo/" + sourceName, "10", "30");
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
buildLog = workspace.getBuildLog();
CxxSourceRuleFactory cxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig);
BuildTarget captureBuildTarget = cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName);
// this is flavored, and denotes the analysis step (generates a local report)
BuildTarget inferAnalysisTarget =
inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor());
// this is the flavored version of the top level target (the one give in input to buck)
BuildTarget inferReportTarget =
inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
BuildTarget aggregatedDepsTarget =
cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
String bt;
for (BuildTarget buildTarget : buildLog.getAllTargets()) {
bt = buildTarget.toString();
if (buildTarget
.getFlavors()
.contains(CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR)
|| buildTarget.getFlavors().contains(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR)
|| bt.equals(inferAnalysisTarget.toString())
|| bt.equals(captureBuildTarget.toString())
|| bt.equals(inferReportTarget.toString())
|| bt.equals(aggregatedDepsTarget.toString())) {
buildLog.assertTargetBuiltLocally(bt);
} else {
buildLog.assertTargetWasFetchedFromCache(buildTarget.toString());
}
}
}
@Test
public void testInferCxxBinaryDepsInvalidateCacheWhenVersionChanges()
throws IOException, InterruptedException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
workspace.enableDirCache();
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig());
CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig);
BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_deps");
String inputBuildTargetName =
inputBuildTarget
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor())
.getFullyQualifiedName();
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
/*
* Check that building after clean will use the cache
*/
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
for (BuildTarget buildTarget : buildLog.getAllTargets()) {
buildLog.assertTargetWasFetchedFromCache(buildTarget.toString());
}
/*
* Check that if the version of infer changes, then all the infer-related targets are
* recomputed
*/
workspace.resetBuildLogFile();
workspace.replaceFileContents("fake-infer/fake-bin/infer", "0.12345", "9.9999");
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
buildLog = workspace.getBuildLog();
String sourceName = "src_with_deps.c";
CxxSourceRuleFactory cxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig);
BuildTarget topCaptureBuildTarget =
cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName);
BuildTarget topInferAnalysisTarget =
inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor());
BuildTarget topInferReportTarget =
inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
BuildTarget depOneBuildTarget =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:dep_one");
String depOneSourceName = "dep_one.c";
CxxSourceRuleFactory depOneSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), depOneBuildTarget, cxxPlatform, cxxBuckConfig);
BuildTarget depOneCaptureBuildTarget =
depOneSourceRuleFactory.createInferCaptureBuildTarget(depOneSourceName);
BuildTarget depOneInferAnalysisTarget =
depOneCaptureBuildTarget.withFlavors(
cxxPlatform.getFlavor(), CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor());
BuildTarget depTwoBuildTarget =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:dep_two");
CxxSourceRuleFactory depTwoSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), depTwoBuildTarget, cxxPlatform, cxxBuckConfig);
BuildTarget depTwoCaptureBuildTarget =
depTwoSourceRuleFactory.createInferCaptureBuildTarget("dep_two.c");
BuildTarget depTwoInferAnalysisTarget =
depTwoCaptureBuildTarget.withFlavors(
cxxPlatform.getFlavor(), CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor());
ImmutableSet<String> locallyBuiltTargets =
ImmutableSet.of(
cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget().toString(),
topCaptureBuildTarget.toString(),
topInferAnalysisTarget.toString(),
topInferReportTarget.toString(),
depOneSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget().toString(),
depOneCaptureBuildTarget.toString(),
depOneInferAnalysisTarget.toString(),
depTwoSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget().toString(),
depTwoCaptureBuildTarget.toString(),
depTwoInferAnalysisTarget.toString());
// check that infer-related targets are getting rebuilt
for (String t : locallyBuiltTargets) {
buildLog.assertTargetBuiltLocally(t);
}
Set<String> builtFromCacheTargets =
FluentIterable.from(buildLog.getAllTargets())
// Filter out header symlink tree rules, as they are always built locally.
.filter(
target ->
(!target
.getFlavors()
.contains(CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR)
&& !target
.getFlavors()
.contains(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR)))
.transform(Object::toString)
// Filter out any rules that are explicitly built locally.
.filter(Predicates.not(locallyBuiltTargets::contains))
.toSet();
// check that all the other targets are fetched from the cache
for (String t : builtFromCacheTargets) {
buildLog.assertTargetWasFetchedFromCache(t);
}
}
@Test
public void testInferCxxBinaryWithoutDeps() throws IOException, InterruptedException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig());
CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig);
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:simple");
String inputBuildTargetName =
inputBuildTarget
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor())
.getFullyQualifiedName();
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
/*
* Check that all the required build targets have been generated.
*/
String sourceName = "simple.cpp";
String sourceFull = "foo/" + sourceName;
CxxSourceRuleFactory cxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig);
// this is unflavored, but bounded to the InferCapture build rule
BuildTarget captureBuildTarget = cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName);
// this is unflavored, but necessary to run the compiler successfully
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
inputBuildTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor());
// this is flavored, and denotes the analysis step (generates a local report)
BuildTarget inferAnalysisTarget =
inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor());
// this is flavored and corresponds to the top level target (the one give in input to buck)
BuildTarget inferReportTarget =
inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
BuildTarget aggregatedDepsTarget =
cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
ImmutableSortedSet.Builder<BuildTarget> targetsBuilder =
ImmutableSortedSet.<BuildTarget>naturalOrder()
.add(
aggregatedDepsTarget,
headerSymlinkTreeTarget,
captureBuildTarget,
inferAnalysisTarget,
inferReportTarget);
BuckBuildLog buildLog = workspace.getBuildLog();
assertThat(buildLog.getAllTargets(), containsInAnyOrder(targetsBuilder.build().toArray()));
buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString());
buildLog.assertTargetBuiltLocally(headerSymlinkTreeTarget.toString());
buildLog.assertTargetBuiltLocally(captureBuildTarget.toString());
buildLog.assertTargetBuiltLocally(inferAnalysisTarget.toString());
buildLog.assertTargetBuiltLocally(inferReportTarget.toString());
/*
* Check that running a build again results in no builds since nothing has changed.
*/
workspace.resetBuildLogFile(); // clear for new build
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
buildLog = workspace.getBuildLog();
assertEquals(ImmutableSet.of(inferReportTarget), buildLog.getAllTargets());
buildLog.assertTargetHadMatchingRuleKey(inferReportTarget.toString());
/*
* Check that changing the source file results in running the capture/analysis rules again.
*/
workspace.resetBuildLogFile();
workspace.replaceFileContents(sourceFull, "*s = 42;", "");
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
buildLog = workspace.getBuildLog();
targetsBuilder =
ImmutableSortedSet.<BuildTarget>naturalOrder()
.add(aggregatedDepsTarget, captureBuildTarget, inferAnalysisTarget, inferReportTarget);
assertEquals(buildLog.getAllTargets(), targetsBuilder.build());
buildLog.assertTargetBuiltLocally(captureBuildTarget.toString());
buildLog.assertTargetBuiltLocally(inferAnalysisTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(aggregatedDepsTarget.toString());
}
@Test
public void testInferCxxBinaryWithDeps() throws IOException, InterruptedException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig());
CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig);
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:binary_with_deps");
String inputBuildTargetName =
inputBuildTarget
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor())
.getFullyQualifiedName();
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
/*
* Check that all the required build targets have been generated.
*/
String sourceName = "src_with_deps.c";
CxxSourceRuleFactory cxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig);
// 1. create the targets of binary_with_deps
// this is unflavored, but bounded to the InferCapture build rule
BuildTarget topCaptureBuildTarget =
cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName);
// this is unflavored, but necessary to run the compiler successfully
BuildTarget topHeaderSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
inputBuildTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor());
// this is flavored, and denotes the analysis step (generates a local report)
BuildTarget topInferAnalysisTarget =
inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor());
// this is flavored and corresponds to the top level target (the one give in input to buck)
BuildTarget topInferReportTarget =
inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
BuildTarget topAggregatedDepsTarget =
cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
// 2. create the targets of dep_one
BuildTarget depOneBuildTarget =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:dep_one");
String depOneSourceName = "dep_one.c";
String depOneSourceFull = "foo/" + depOneSourceName;
CxxSourceRuleFactory depOneSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), depOneBuildTarget, cxxPlatform, cxxBuckConfig);
BuildTarget depOneCaptureBuildTarget =
depOneSourceRuleFactory.createInferCaptureBuildTarget(depOneSourceName);
BuildTarget depOneHeaderSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
depOneBuildTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor());
BuildTarget depOneExportedHeaderSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
depOneBuildTarget,
HeaderVisibility.PUBLIC,
CxxPlatformUtils.getHeaderModeForDefaultPlatform(tmp.getRoot()).getFlavor());
BuildTarget depOneInferAnalysisTarget =
depOneCaptureBuildTarget.withFlavors(
cxxPlatform.getFlavor(), CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor());
BuildTarget depOneAggregatedDepsTarget =
depOneSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
// 3. create the targets of dep_two
BuildTarget depTwoBuildTarget =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:dep_two");
CxxSourceRuleFactory depTwoSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), depTwoBuildTarget, cxxPlatform, cxxBuckConfig);
BuildTarget depTwoCaptureBuildTarget =
depTwoSourceRuleFactory.createInferCaptureBuildTarget("dep_two.c");
BuildTarget depTwoHeaderSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
depTwoBuildTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor());
BuildTarget depTwoExportedHeaderSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
depTwoBuildTarget,
HeaderVisibility.PUBLIC,
CxxPlatformUtils.getHeaderModeForDefaultPlatform(tmp.getRoot()).getFlavor());
BuildTarget depTwoInferAnalysisTarget =
depTwoCaptureBuildTarget.withFlavors(
cxxPlatform.getFlavor(), CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor());
BuildTarget depTwoAggregatedDepsTarget =
depTwoSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
ImmutableSet.Builder<BuildTarget> buildTargets =
ImmutableSortedSet.<BuildTarget>naturalOrder()
.add(
topAggregatedDepsTarget,
topCaptureBuildTarget,
topHeaderSymlinkTreeTarget,
topInferAnalysisTarget,
topInferReportTarget,
depOneAggregatedDepsTarget,
depOneCaptureBuildTarget,
depOneHeaderSymlinkTreeTarget,
depOneExportedHeaderSymlinkTreeTarget,
depOneInferAnalysisTarget,
depTwoAggregatedDepsTarget,
depTwoCaptureBuildTarget,
depTwoHeaderSymlinkTreeTarget,
depTwoExportedHeaderSymlinkTreeTarget,
depTwoInferAnalysisTarget);
// Check all the targets are in the buildLog
assertEquals(
buildTargets.build(), ImmutableSet.copyOf(workspace.getBuildLog().getAllTargets()));
/*
* Check that running a build again results in no builds since nothing has changed.
*/
workspace.resetBuildLogFile(); // clear for new build
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
assertEquals(ImmutableSet.of(topInferReportTarget), buildLog.getAllTargets());
buildLog.assertTargetHadMatchingRuleKey(topInferReportTarget.toString());
/*
* Check that if a library source file changes then the capture/analysis rules run again on
* the main target and on dep_one only.
*/
workspace.resetBuildLogFile();
workspace.replaceFileContents(depOneSourceFull, "flag > 0", "flag < 0");
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
buildLog = workspace.getBuildLog();
buildTargets =
ImmutableSortedSet.<BuildTarget>naturalOrder()
.add(
topInferAnalysisTarget, // analysis runs again
topInferReportTarget, // report runs again
topCaptureBuildTarget, // cached
depTwoInferAnalysisTarget, // cached
depOneAggregatedDepsTarget,
depOneCaptureBuildTarget, // capture of the changed file runs again
depOneInferAnalysisTarget // analysis of the library runs again
);
assertEquals(buildTargets.build(), buildLog.getAllTargets());
buildLog.assertTargetBuiltLocally(topInferAnalysisTarget.toString());
buildLog.assertTargetBuiltLocally(topInferReportTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(topCaptureBuildTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(depTwoInferAnalysisTarget.toString());
buildLog.assertTargetBuiltLocally(depOneCaptureBuildTarget.toString());
buildLog.assertTargetBuiltLocally(depOneInferAnalysisTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(depOneAggregatedDepsTarget.toString());
}
@Test
public void testInferCxxBinaryWithDepsEmitsAllTheDependenciesResultsDirs() throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//foo:binary_with_chain_deps")
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
// Build the given target and check that it succeeds.
workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess();
assertTrue(
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem, inputBuildTarget, "infer-%s/infer-deps.txt"))));
Set<String> loggedDeps =
getUniqueLines(
workspace.getFileContents(
BuildTargetPaths.getGenPath(
filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")));
String sanitizedChainDepOne = sanitize("chain_dep_one.c.o");
String sanitizedTopChain = sanitize("top_chain.c.o");
String sanitizedChainDepTwo = sanitize("chain_dep_two.c.o");
BuildTarget analyzeTopChainTarget =
BuildTargetFactory.newInstance("//foo:binary_with_chain_deps#infer-analyze");
BuildTarget captureTopChainTarget =
BuildTargetFactory.newInstance(
"//foo:binary_with_chain_deps#default,infer-capture-" + sanitizedTopChain);
BuildTarget analyzeChainDepOneTarget =
BuildTargetFactory.newInstance("//foo:chain_dep_one#default,infer-analyze");
BuildTarget captureChainDepOneTarget =
BuildTargetFactory.newInstance(
"//foo:chain_dep_one#default,infer-capture-" + sanitizedChainDepOne);
BuildTarget analyzeChainDepTwoTarget =
BuildTargetFactory.newInstance("//foo:chain_dep_two#default,infer-analyze");
BuildTarget captureChainDepTwoTarget =
BuildTargetFactory.newInstance(
"//foo:chain_dep_two#default,infer-capture-" + sanitizedChainDepTwo);
Path basePath = filesystem.getRootPath().toRealPath();
Set<String> expectedOutput =
ImmutableSet.of(
analyzeTopChainTarget.getFullyQualifiedName()
+ "\t"
+ "[infer-analyze]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, analyzeTopChainTarget, "infer-analysis-%s")),
captureTopChainTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-capture-"
+ sanitizedTopChain
+ "]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, captureTopChainTarget, "infer-out-%s")),
analyzeChainDepOneTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-analyze]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, analyzeChainDepOneTarget, "infer-analysis-%s")),
captureChainDepOneTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-capture-"
+ sanitizedChainDepOne
+ "]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, captureChainDepOneTarget, "infer-out-%s")),
analyzeChainDepTwoTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-analyze]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, analyzeChainDepTwoTarget, "infer-analysis-%s")),
captureChainDepTwoTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-capture-"
+ sanitizedChainDepTwo
+ "]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, captureChainDepTwoTarget, "infer-out-%s")));
assertEquals(expectedOutput, loggedDeps);
}
private static void registerCell(
ProjectWorkspace cellToModifyConfigOf,
String cellName,
ProjectWorkspace cellToRegisterAsCellName)
throws IOException {
TestDataHelper.overrideBuckconfig(
cellToModifyConfigOf,
ImmutableMap.of(
"repositories",
ImmutableMap.of(
cellName, cellToRegisterAsCellName.getPath(".").normalize().toString())));
}
@Test
public void inferShouldBeAbleToUseMultipleXCell() throws IOException {
Path rootWorkspacePath = tmp.getRoot();
// create infertest workspace
InferHelper.setupWorkspace(this, rootWorkspacePath, "infertest");
// create infertest/inter-cell/multi-cell/primary sub-workspace as infer-configured one
Path primaryRootPath = tmp.newFolder().toRealPath().normalize();
ProjectWorkspace primary =
InferHelper.setupCxxInferWorkspace(
this,
primaryRootPath,
Optional.empty(),
"infertest/inter-cell/multi-cell/primary",
Optional.of(rootWorkspacePath.resolve("fake-infer")));
// create infertest/inter-cell/multi-cell/secondary sub-workspace
Path secondaryRootPath = tmp.newFolder().toRealPath().normalize();
ProjectWorkspace secondary =
InferHelper.setupWorkspace(
this, secondaryRootPath, "infertest/inter-cell/multi-cell/secondary");
// register cells
registerCell(primary, "secondary", secondary);
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//:cxxbinary")
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
// run from primary workspace
ProcessResult result =
primary.runBuckBuild(
InferHelper.getCxxCLIConfigurationArgs(
rootWorkspacePath.resolve("fake-infer"), Optional.empty(), inputBuildTarget));
result.assertSuccess();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(primary.getDestPath());
String reportPath =
BuildTargetPaths.getGenPath(filesystem, inputBuildTarget, "infer-%s/report.json")
.toString();
List<Object> bugs = InferHelper.loadInferReport(primary, reportPath);
Assert.assertThat(
"2 bugs expected in " + reportPath + " not found", bugs.size(), Matchers.equalTo(2));
}
@Test
public void testInferCxxBinaryWithDiamondDepsEmitsAllBuildRulesInvolvedWhenCacheHit()
throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
workspace.enableDirCache();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//foo:binary_with_diamond_deps")
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
String buildTargetName = inputBuildTarget.getFullyQualifiedName();
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", buildTargetName).assertSuccess();
/*
* Check that building after clean will use the cache
*/
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", buildTargetName).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
ImmutableSet<BuildTarget> allInvolvedTargets = buildLog.getAllTargets();
assertEquals(1, allInvolvedTargets.size()); // Only main target should be fetched from cache
for (BuildTarget bt : allInvolvedTargets) {
buildLog.assertTargetWasFetchedFromCache(bt.toString());
}
assertTrue(
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem, inputBuildTarget, "infer-%s/infer-deps.txt"))));
Set<String> loggedDeps =
getUniqueLines(
workspace.getFileContents(
BuildTargetPaths.getGenPath(
filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")));
BuildTarget analyzeMainTarget =
BuildTargetFactory.newInstance("//foo:binary_with_diamond_deps#infer-analyze");
BuildTarget analyzeDepOneTarget =
BuildTargetFactory.newInstance("//foo:diamond_dep_one#default,infer-analyze");
BuildTarget analyzeDepTwoTarget =
BuildTargetFactory.newInstance("//foo:diamond_dep_two#default,infer-analyze");
BuildTarget analyzeSimpleLibTarget =
BuildTargetFactory.newInstance("//foo:simple_lib#default,infer-analyze");
String sanitizedSimpleCpp = sanitize("simple.cpp.o");
String sanitizedDepOne = sanitize("dep_one.c.o");
String sanitizedDepTwo = sanitize("dep_two.c.o");
String sanitizedSrcWithDeps = sanitize("src_with_deps.c.o");
BuildTarget simpleCppTarget =
BuildTargetFactory.newInstance(
"//foo:simple_lib#default,infer-capture-" + sanitizedSimpleCpp);
BuildTarget depOneTarget =
BuildTargetFactory.newInstance(
"//foo:diamond_dep_one#default,infer-capture-" + sanitizedDepOne);
BuildTarget depTwoTarget =
BuildTargetFactory.newInstance(
"//foo:diamond_dep_two#default,infer-capture-" + sanitizedDepTwo);
BuildTarget srcWithDepsTarget =
BuildTargetFactory.newInstance(
"//foo:binary_with_diamond_deps#default,infer-capture-" + sanitizedSrcWithDeps);
Path basePath = filesystem.getRootPath().toRealPath();
Set<String> expectedOutput =
ImmutableSet.of(
InferLogLine.fromBuildTarget(
analyzeMainTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, analyzeMainTarget, "infer-analysis-%s")))
.toString(),
InferLogLine.fromBuildTarget(
srcWithDepsTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, srcWithDepsTarget, "infer-out-%s")))
.toString(),
InferLogLine.fromBuildTarget(
analyzeDepOneTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, analyzeDepOneTarget, "infer-analysis-%s")))
.toString(),
InferLogLine.fromBuildTarget(
depOneTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, depOneTarget, "infer-out-%s")))
.toString(),
InferLogLine.fromBuildTarget(
analyzeDepTwoTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, analyzeDepTwoTarget, "infer-analysis-%s")))
.toString(),
InferLogLine.fromBuildTarget(
depTwoTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, depTwoTarget, "infer-out-%s")))
.toString(),
InferLogLine.fromBuildTarget(
analyzeSimpleLibTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(
filesystem, analyzeSimpleLibTarget, "infer-analysis-%s")))
.toString(),
InferLogLine.fromBuildTarget(
simpleCppTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, simpleCppTarget, "infer-out-%s")))
.toString());
assertEquals(expectedOutput, loggedDeps);
}
@Test
public void testInferCaptureAllCxxBinaryWithDiamondDepsEmitsAllBuildRulesInvolvedWhenCacheHit()
throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
workspace.enableDirCache();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//foo:binary_with_diamond_deps")
.withFlavors(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.getFlavor());
String buildTargetName = inputBuildTarget.getFullyQualifiedName();
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", buildTargetName).assertSuccess();
/*
* Check that building after clean will use the cache
*/
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", buildTargetName).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
ImmutableSet<BuildTarget> allInvolvedTargets = buildLog.getAllTargets();
for (BuildTarget bt : allInvolvedTargets) {
buildLog.assertTargetWasFetchedFromCache(bt.toString());
}
assertTrue(
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem, inputBuildTarget, "infer-%s/infer-deps.txt"))));
Set<String> loggedDeps =
getUniqueLines(
workspace.getFileContents(
BuildTargetPaths.getGenPath(
filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")));
String sanitizedSimpleCpp = sanitize("simple.cpp.o");
String sanitizedDepOne = sanitize("dep_one.c.o");
String sanitizedDepTwo = sanitize("dep_two.c.o");
String sanitizedSrcWithDeps = sanitize("src_with_deps.c.o");
BuildTarget simpleCppTarget =
BuildTargetFactory.newInstance(
"//foo:simple_lib#default,infer-capture-" + sanitizedSimpleCpp);
BuildTarget depOneTarget =
BuildTargetFactory.newInstance(
"//foo:diamond_dep_one#default,infer-capture-" + sanitizedDepOne);
BuildTarget depTwoTarget =
BuildTargetFactory.newInstance(
"//foo:diamond_dep_two#default,infer-capture-" + sanitizedDepTwo);
BuildTarget srcWithDepsTarget =
BuildTargetFactory.newInstance(
"//foo:binary_with_diamond_deps#default,infer-capture-" + sanitizedSrcWithDeps);
Path basePath = filesystem.getRootPath().toRealPath();
Set<String> expectedOutput =
ImmutableSet.of(
InferLogLine.fromBuildTarget(
srcWithDepsTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, srcWithDepsTarget, "infer-out-%s")))
.toString(),
InferLogLine.fromBuildTarget(
depOneTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, depOneTarget, "infer-out-%s")))
.toString(),
InferLogLine.fromBuildTarget(
depTwoTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, depTwoTarget, "infer-out-%s")))
.toString(),
InferLogLine.fromBuildTarget(
simpleCppTarget,
basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, simpleCppTarget, "infer-out-%s")))
.toString());
assertEquals(expectedOutput, loggedDeps);
}
@Test
public void testInferCxxBinaryWithDiamondDepsHasRuntimeDepsOfAllCaptureRulesWhenCacheHits()
throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
workspace.enableDirCache();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_diamond_deps");
String inputBuildTargetName =
inputBuildTarget
.withFlavors(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.getFlavor())
.getFullyQualifiedName();
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
/*
* Check that building after clean will use the cache
*/
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
for (BuildTarget buildTarget : buildLog.getAllTargets()) {
buildLog.assertTargetWasFetchedFromCache(buildTarget.toString());
}
/*
* Check that runtime deps have been fetched from cache as well
*/
assertTrue(
"This file was expected to exist because it's declared as runtime dep",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:simple_lib#default,infer-capture-" + sanitize("simple.cpp.o")),
"infer-out-%s")
.resolve("captured/simple.cpp_captured/simple.cpp.cfg"))));
assertTrue(
"This file was expected to exist because it's declared as runtime dep",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:diamond_dep_one#default,infer-capture-"
+ sanitize("dep_one.c.o")),
"infer-out-%s")
.resolve("captured/dep_one.c_captured/dep_one.c.cfg"))));
assertTrue(
"This file was expected to exist because it's declared as runtime dep",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:diamond_dep_two#default,infer-capture-"
+ sanitize("dep_two.c.o")),
"infer-out-%s")
.resolve("captured/dep_two.c_captured/dep_two.c.cfg"))));
assertTrue(
"This file was expected to exist because it's declared as runtime dep",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:binary_with_diamond_deps#default,infer-capture-"
+ sanitize("src_with_deps.c.o")),
"infer-out-%s")
.resolve("captured/src_with_deps.c_captured/src_with_deps.c.cfg"))));
}
@Test
public void testInferCxxBinaryWithUnusedDepsDoesNotRebuildWhenUnusedHeaderChanges()
throws IOException, InterruptedException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
workspace.enableDirCache();
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//foo:binary_with_unused_header");
String inputBuildTargetName =
inputBuildTarget
.withFlavors(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.getFlavor())
.getFullyQualifiedName();
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig());
CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig);
CxxSourceRuleFactory cxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig);
BuildTarget simpleOneCppCaptureTarget =
cxxSourceRuleFactory.createInferCaptureBuildTarget("simple_one.cpp");
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
/*
* Check that when the unused-header is changed, no builds are triggered
*/
workspace.resetBuildLogFile();
workspace.replaceFileContents("foo/unused_header.h", "int* input", "int* input, int* input2");
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
BuckBuildLog.BuildLogEntry simpleOnceCppCaptureTargetEntry =
buildLog.getLogEntry(simpleOneCppCaptureTarget);
assertThat(
simpleOnceCppCaptureTargetEntry.getSuccessType(),
Matchers.equalTo(Optional.of(BuildRuleSuccessType.FETCHED_FROM_CACHE_MANIFEST_BASED)));
/*
* Check that when the used-header is changed, then a build is triggered
*/
workspace.resetBuildLogFile();
workspace.replaceFileContents("foo/used_header.h", "int* input", "int* input, int* input2");
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
buildLog = workspace.getBuildLog();
buildLog.assertTargetBuiltLocally(simpleOneCppCaptureTarget.toString());
}
@Test
public void testInferCxxBinaryWithDiamondDepsEmitsAllTransitiveCaptureRulesOnce()
throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//foo:binary_with_diamond_deps")
.withFlavors(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.getFlavor());
// Build the given target and check that it succeeds.
workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess();
assertTrue(
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem, inputBuildTarget, "infer-%s/infer-deps.txt"))));
Set<String> loggedDeps =
getUniqueLines(
workspace.getFileContents(
BuildTargetPaths.getGenPath(
filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")));
String sanitizedSimpleCpp = sanitize("simple.cpp.o");
String sanitizedDepOne = sanitize("dep_one.c.o");
String sanitizedDepTwo = sanitize("dep_two.c.o");
String sanitizedSrcWithDeps = sanitize("src_with_deps.c.o");
BuildTarget simpleCppTarget =
BuildTargetFactory.newInstance(
"//foo:simple_lib#default,infer-capture-" + sanitizedSimpleCpp);
BuildTarget depOneTarget =
BuildTargetFactory.newInstance(
"//foo:diamond_dep_one#default,infer-capture-" + sanitizedDepOne);
BuildTarget depTwoTarget =
BuildTargetFactory.newInstance(
"//foo:diamond_dep_two#default,infer-capture-" + sanitizedDepTwo);
BuildTarget srcWithDepsTarget =
BuildTargetFactory.newInstance(
"//foo:binary_with_diamond_deps#default,infer-capture-" + sanitizedSrcWithDeps);
Path basePath = filesystem.getRootPath().toRealPath();
Set<String> expectedOutput =
ImmutableSet.of(
srcWithDepsTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-capture-"
+ sanitizedSrcWithDeps
+ "]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, srcWithDepsTarget, "infer-out-%s")),
depOneTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-capture-"
+ sanitizedDepOne
+ "]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, depOneTarget, "infer-out-%s")),
depTwoTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-capture-"
+ sanitizedDepTwo
+ "]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, depTwoTarget, "infer-out-%s")),
simpleCppTarget.getFullyQualifiedName()
+ "\t"
+ "[default, infer-capture-"
+ sanitizedSimpleCpp
+ "]\t"
+ basePath.resolve(
BuildTargetPaths.getGenPath(filesystem, simpleCppTarget, "infer-out-%s")));
assertEquals(expectedOutput, loggedDeps);
}
@Test
public void testInferCxxBinarySkipsBlacklistedFiles() throws IOException {
ProjectWorkspace workspace =
InferHelper.setupCxxInferWorkspace(this, tmp, Optional.of(".*one\\.c"));
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_chain_deps");
String inputBuildTargetName =
inputBuildTarget
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor())
.getFullyQualifiedName();
// Build the given target and check that it succeeds.
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
// Check that the cfg associated with chain_dep_one.c does not exist
assertFalse(
"Cfg file for chain_dep_one.c should not exist",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:chain_dep_one#default,infer-capture-"
+ sanitize("chain_dep_one.c.o")),
"infer-out-%s")
.resolve("captured/chain_dep_one.c_captured/chain_dep_one.c.cfg"))));
// Check that the remaining files still have their cfgs
assertTrue(
"Expected cfg for chain_dep_two.c not found",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:chain_dep_two#default,infer-capture-"
+ sanitize("chain_dep_two.c.o")),
"infer-out-%s")
.resolve("captured/chain_dep_two.c_captured/chain_dep_two.c.cfg"))));
assertTrue(
"Expected cfg for top_chain.c not found",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:binary_with_chain_deps#infer-analyze"),
"infer-analysis-%s")
.resolve("captured/top_chain.c_captured/top_chain.c.cfg"))));
}
@Test
public void testInferCxxBinaryRunsOnAllFilesWhenBlacklistIsNotSpecified() throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_chain_deps");
String inputBuildTargetName =
inputBuildTarget
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor())
.getFullyQualifiedName();
// Build the given target and check that it succeeds.
workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
// Check that all cfgs have been created
assertTrue(
"Expected cfg for chain_dep_one.c not found",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:chain_dep_one#default,infer-capture-"
+ sanitize("chain_dep_one.c.o")),
"infer-out-%s")
.resolve("captured/chain_dep_one.c_captured/chain_dep_one.c.cfg"))));
assertTrue(
"Expected cfg for chain_dep_two.c not found",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
"//foo:chain_dep_two#default,infer-capture-"
+ sanitize("chain_dep_two.c.o")),
"infer-out-%s")
.resolve("captured/chain_dep_two.c_captured/chain_dep_two.c.cfg"))));
assertTrue(
"Expected cfg for top_chain.c not found",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance(
filesystem.getRootPath(), "//foo:binary_with_chain_deps#infer-analyze"),
"infer-analysis-%s")
.resolve("captured/top_chain.c_captured/top_chain.c.cfg"))));
}
@Test
public void testInferCxxBinaryWithCachedDepsGetsAllItsTransitiveDeps() throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
workspace.enableDirCache();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//foo:binary_with_chain_deps")
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess();
/*
* Check that building after clean will use the cache
*/
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
for (BuildTarget buildTarget : buildLog.getAllTargets()) {
buildLog.assertTargetWasFetchedFromCache(buildTarget.toString());
}
/*
* Check that if the file in the top target changes, then all the transitive deps will be
* fetched from the cache (even those that are not direct dependencies).
* Make sure there's the specs file of the dependency that has distance 2 from
* the binary target.
*/
String sourceName = "top_chain.c";
workspace.replaceFileContents("foo/" + sourceName, "*p += 1", "*p += 10");
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess();
// Check all the buildrules were fetched from the cache (and there's the specs file)
assertTrue(
"Expected specs file for func_ret_null() in chain_dep_two.c not found",
Files.exists(
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem,
BuildTargetFactory.newInstance("//foo:chain_dep_two#default,infer-analyze"),
"infer-analysis-%s/specs/mockedSpec.specs"))));
}
@Test
public void testInferCxxBinaryMergesAllReportsOfDependencies() throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//foo:binary_with_chain_deps")
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
/*
* Build the given target and check that it succeeds.
*/
workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess();
String reportPath =
BuildTargetPaths.getGenPath(filesystem, inputBuildTarget, "infer-%s/report.json")
.toString();
List<Object> bugs = InferHelper.loadInferReport(workspace, reportPath);
// check that the merge step has merged a total of 3 bugs, one for each target
// (chain_dep_two, chain_dep_one, binary_with_chain_deps)
Assert.assertThat(
"3 bugs expected in " + reportPath + " not found", bugs.size(), Matchers.equalTo(3));
}
@Test
public void testInferCxxBinaryWritesSpecsListFilesOfTransitiveDependencies() throws IOException {
ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp, Optional.empty());
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget inputBuildTarget =
BuildTargetFactory.newInstance("//foo:binary_with_chain_deps")
.withFlavors(CxxInferEnhancer.InferFlavors.INFER.getFlavor());
// Build the given target and check that it succeeds.
workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess();
String specsPathList =
BuildTargetPaths.getGenPath(
filesystem,
inputBuildTarget.withFlavors(
CxxInferEnhancer.InferFlavors.INFER_ANALYZE.getFlavor()),
"infer-analysis-%s/specs_path_list.txt")
.toString();
String out = workspace.getFileContents(specsPathList);
ImmutableList<Path> paths =
FluentIterable.from(out.split("\n")).transform(input -> new File(input).toPath()).toList();
assertSame("There must be 2 paths in total", paths.size(), 2);
for (Path path : paths) {
assertTrue("Path must be absolute", path.isAbsolute());
assertTrue("Path must exist", Files.exists(path));
}
}
@Test
public void testChangingCompilerPathForcesRebuild() throws Exception {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
workspace.enableDirCache();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget target = BuildTargetFactory.newInstance("//foo:simple");
BuildTarget linkTarget = CxxDescriptionEnhancer.createCxxLinkTarget(target, Optional.empty());
// Get the real location of the compiler executable.
String executable = Platform.detect() == Platform.MACOS ? "clang++" : "g++";
Path executableLocation =
new ExecutableFinder()
.getOptionalExecutable(Paths.get(executable), ImmutableMap.copyOf(System.getenv()))
.orElse(Paths.get("/usr/bin", executable));
// Write script as faux clang++/g++ binary
Path firstCompilerPath = tmp.newFolder("path1");
Path firstCompiler = firstCompilerPath.resolve(executable);
filesystem.writeContentsToPath(
"#!/bin/sh\n" + "exec " + executableLocation + " \"$@\"\n", firstCompiler);
// Write script as slightly different faux clang++/g++ binary
Path secondCompilerPath = tmp.newFolder("path2");
Path secondCompiler = secondCompilerPath.resolve(executable);
filesystem.writeContentsToPath(
"#!/bin/sh\n"
+ "exec "
+ executableLocation
+ " \"$@\"\n"
+ "# Comment to make hash different.\n",
secondCompiler);
// Make the second faux clang++/g++ binary executable
MostFiles.makeExecutable(secondCompiler);
// Run two builds, each with different compiler "binaries". In the first
// instance, both binaries are in the PATH but the first binary is not
// marked executable so is not picked up.
workspace
.runBuckCommandWithEnvironmentOverridesAndContext(
workspace.getDestPath(),
Optional.empty(),
ImmutableMap.of(
"PATH",
firstCompilerPath
+ pathSeparator
+ secondCompilerPath
+ pathSeparator
+ System.getenv("PATH")),
"build",
target.getFullyQualifiedName())
.assertSuccess();
workspace.resetBuildLogFile();
// Now, make the first faux clang++/g++ binary executable. In this second
// instance, both binaries are still in the PATH but the first binary is
// now marked executable and so is picked up; causing a rebuild.
MostFiles.makeExecutable(firstCompiler);
workspace
.runBuckCommandWithEnvironmentOverridesAndContext(
workspace.getDestPath(),
Optional.empty(),
ImmutableMap.of(
"PATH",
firstCompilerPath
+ pathSeparator
+ secondCompilerPath
+ pathSeparator
+ System.getenv("PATH")),
"build",
target.getFullyQualifiedName())
.assertSuccess();
// Make sure the binary change caused a rebuild.
workspace.getBuildLog().assertTargetBuiltLocally(linkTarget.toString());
}
@Test
public void testLinkMapIsNotCached() throws Exception {
// Currently we only support Apple platforms for generating link maps.
assumeTrue(Platform.detect() == Platform.MACOS);
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
workspace.enableDirCache();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget target = BuildTargetFactory.newInstance("//foo:simple");
workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess();
Path outputPath = workspace.getPath(BuildTargetPaths.getGenPath(filesystem, target, "%s"));
/*
* Check that building after clean will use the cache
*/
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace.runBuckCommand("build", target.toString()).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
buildLog.assertTargetBuiltLocally(target.toString());
assertThat(Files.exists(Paths.get(outputPath + "-LinkMap.txt")), is(true));
}
@Test
public void testLinkMapIsCached() throws Exception {
// Currently we only support Apple platforms for generating link maps.
assumeTrue(Platform.detect() == Platform.MACOS);
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
workspace.enableDirCache();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
BuildTarget target = BuildTargetFactory.newInstance("//foo:simple");
workspace
.runBuckCommand("build", "-c", "cxx.cache_binaries=true", target.getFullyQualifiedName())
.assertSuccess();
Path outputPath = workspace.getPath(BuildTargetPaths.getGenPath(filesystem, target, "%s"));
/*
* Check that building after clean will use the cache
*/
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace
.runBuckCommand("build", "-c", "cxx.cache_binaries=true", target.toString())
.assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
buildLog.assertTargetWasFetchedFromCache(target.toString());
assertThat(Files.exists(Paths.get(outputPath + "-LinkMap.txt")), is(true));
}
@Test
public void testSimpleCxxBinaryBuilds() throws Exception {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig());
CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig);
BuildTarget target = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:simple");
CxxSourceRuleFactory cxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(workspace.getDestPath(), target, cxxPlatform, cxxBuckConfig);
BuildTarget binaryTarget = CxxDescriptionEnhancer.createCxxLinkTarget(target, Optional.empty());
String sourceName = "simple.cpp";
String sourceFull = "foo/" + sourceName;
BuildTarget compileTarget = cxxSourceRuleFactory.createCompileBuildTarget(sourceName);
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
target, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor());
BuildTarget aggregatedDepsTarget =
cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
// Do a clean build, verify that it succeeds, and check that all expected targets built
// successfully.
workspace.runBuckCommand("build", target.toString()).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
assertEquals(
ImmutableSet.<BuildTarget>builder()
.add(aggregatedDepsTarget, headerSymlinkTreeTarget, compileTarget, binaryTarget, target)
.build(),
buildLog.getAllTargets());
buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString());
buildLog.assertTargetBuiltLocally(headerSymlinkTreeTarget.toString());
buildLog.assertTargetBuiltLocally(compileTarget.toString());
buildLog.assertTargetBuiltLocally(binaryTarget.toString());
buildLog.assertTargetBuiltLocally(target.toString());
// Clear for new build.
workspace.resetBuildLogFile();
// Check that running a build again results in no builds since everything is up to
// date.
workspace.runBuckCommand("build", target.toString()).assertSuccess();
buildLog = workspace.getBuildLog();
assertEquals(ImmutableSet.of(target, binaryTarget), buildLog.getAllTargets());
buildLog.assertTargetHadMatchingRuleKey(binaryTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(target.toString());
// Clear for new build.
workspace.resetBuildLogFile();
// Update the source file.
workspace.replaceFileContents(sourceFull, "{}", "{ return 0; }");
// Check that running a build again makes the source get recompiled and the binary
// re-linked, but does not cause the header rules to re-run.
workspace.runBuckCommand("build", target.toString()).assertSuccess();
buildLog = workspace.getBuildLog();
assertEquals(
ImmutableSet.<BuildTarget>builder()
.add(aggregatedDepsTarget, compileTarget, binaryTarget, target)
.build(),
buildLog.getAllTargets());
buildLog.assertTargetHadMatchingRuleKey(aggregatedDepsTarget.toString());
buildLog.assertTargetBuiltLocally(compileTarget.toString());
assertThat(
buildLog.getLogEntry(binaryTarget).getSuccessType().get(),
Matchers.not(Matchers.equalTo(BuildRuleSuccessType.MATCHING_RULE_KEY)));
// Clear for new build.
workspace.resetBuildLogFile();
// Update the source file.
workspace.replaceFileContents(sourceFull, "{ return 0; }", "won't compile");
// Check that running a build again makes the source get recompiled and the binary
// re-linked, but does not cause the header rules to re-run.
workspace.runBuckCommand("build", target.toString()).assertFailure();
buildLog = workspace.getBuildLog();
assertEquals(
ImmutableSet.<BuildTarget>builder()
.add(aggregatedDepsTarget, compileTarget, binaryTarget, target)
.build(),
buildLog.getAllTargets());
buildLog.assertTargetHadMatchingRuleKey(aggregatedDepsTarget.toString());
assertThat(
buildLog.getLogEntry(binaryTarget).getStatus(), Matchers.equalTo(BuildRuleStatus.CANCELED));
assertThat(
buildLog.getLogEntry(target).getStatus(), Matchers.equalTo(BuildRuleStatus.CANCELED));
}
@Test
public void testSimpleCxxBinaryWithoutHeader() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
workspace.runBuckCommand("build", "//foo:simple_without_header").assertFailure();
}
@Test
public void testSimpleCxxBinaryWithHeader() throws IOException, InterruptedException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig());
CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig);
BuildTarget target =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:simple_with_header");
CxxSourceRuleFactory cxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(workspace.getDestPath(), target, cxxPlatform, cxxBuckConfig);
BuildTarget binaryTarget = CxxDescriptionEnhancer.createCxxLinkTarget(target, Optional.empty());
String sourceName = "simple_with_header.cpp";
String headerName = "simple_with_header.h";
String headerFull = "foo/" + headerName;
BuildTarget compileTarget = cxxSourceRuleFactory.createCompileBuildTarget(sourceName);
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
target, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor());
BuildTarget aggregatedDepsTarget =
cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
// Do a clean build, verify that it succeeds, and check that all expected targets built
// successfully.
workspace.runBuckCommand("build", target.toString()).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
assertEquals(
ImmutableSet.of(
aggregatedDepsTarget, headerSymlinkTreeTarget, compileTarget, binaryTarget, target),
buildLog.getAllTargets());
buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString());
buildLog.assertTargetBuiltLocally(headerSymlinkTreeTarget.toString());
buildLog.assertTargetBuiltLocally(compileTarget.toString());
buildLog.assertTargetBuiltLocally(binaryTarget.toString());
buildLog.assertTargetBuiltLocally(target.toString());
// Clear for new build.
workspace.resetBuildLogFile();
// Update the source file.
workspace.replaceFileContents(headerFull, "blah = 5", "blah = 6");
// Check that running a build again makes the source get recompiled and the binary
// re-linked, but does not cause the header rules to re-run.
workspace.runBuckCommand("build", target.toString()).assertSuccess();
buildLog = workspace.getBuildLog();
assertEquals(
ImmutableSet.of(
headerSymlinkTreeTarget, aggregatedDepsTarget, compileTarget, binaryTarget, target),
buildLog.getAllTargets());
buildLog.assertTargetHadMatchingInputRuleKey(headerSymlinkTreeTarget.toString());
buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString());
buildLog.assertTargetBuiltLocally(compileTarget.toString());
assertThat(
buildLog.getLogEntry(binaryTarget).getSuccessType().get(),
Matchers.not(Matchers.equalTo(BuildRuleSuccessType.MATCHING_RULE_KEY)));
}
@Test
public void testSimpleCxxBinaryMissingDependencyOnCxxLibraryWithHeader() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
workspace.runBuckCommand("build", "//foo:binary_without_dep").assertFailure();
}
@Test
public void testSimpleCxxBinaryWithDependencyOnCxxLibraryWithHeader()
throws IOException, InterruptedException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
// Setup variables pointing to the sources and targets of the top-level binary rule.
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig());
CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig);
BuildTarget target =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:binary_with_dep");
CxxSourceRuleFactory cxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(workspace.getDestPath(), target, cxxPlatform, cxxBuckConfig);
BuildTarget binaryTarget = CxxDescriptionEnhancer.createCxxLinkTarget(target, Optional.empty());
String sourceName = "foo.cpp";
BuildTarget compileTarget = cxxSourceRuleFactory.createCompileBuildTarget(sourceName);
BuildTarget headerSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
target, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor());
BuildTarget aggregatedDepsTarget =
cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
// Setup variables pointing to the sources and targets of the library dep.
BuildTarget depTarget =
BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:library_with_header");
CxxSourceRuleFactory depCxxSourceRuleFactory =
CxxSourceRuleFactoryHelper.of(
workspace.getDestPath(), depTarget, cxxPlatform, cxxBuckConfig);
String depSourceName = "bar.cpp";
String depSourceFull = "foo/" + depSourceName;
String depHeaderName = "bar.h";
String depHeaderFull = "foo/" + depHeaderName;
BuildTarget depCompileTarget = depCxxSourceRuleFactory.createCompileBuildTarget(depSourceName);
BuildTarget depHeaderSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
depTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor());
BuildTarget depHeaderExportedSymlinkTreeTarget =
CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget(
depTarget,
HeaderVisibility.PUBLIC,
CxxPlatformUtils.getHeaderModeForDefaultPlatform(tmp.getRoot()).getFlavor());
BuildTarget depArchiveTarget =
CxxDescriptionEnhancer.createStaticLibraryBuildTarget(
depTarget, cxxPlatform.getFlavor(), PicType.PDC);
BuildTarget depAggregatedDepsTarget =
depCxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget();
ImmutableList.Builder<BuildTarget> builder = ImmutableList.builder();
builder.add(
depAggregatedDepsTarget,
depHeaderSymlinkTreeTarget,
depHeaderExportedSymlinkTreeTarget,
depCompileTarget,
depArchiveTarget,
depTarget,
aggregatedDepsTarget,
headerSymlinkTreeTarget,
compileTarget,
binaryTarget,
target);
// Do a clean build, verify that it succeeds, and check that all expected targets built
// successfully.
workspace.runBuckCommand("build", target.toString()).assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
assertThat(
buildLog.getAllTargets(),
containsInAnyOrder(builder.build().toArray(new BuildTarget[] {})));
buildLog.assertTargetBuiltLocally(depHeaderSymlinkTreeTarget.toString());
buildLog.assertTargetBuiltLocally(depCompileTarget.toString());
buildLog.assertTargetBuiltLocally(depArchiveTarget.toString());
buildLog.assertTargetBuiltLocally(depTarget.toString());
buildLog.assertTargetBuiltLocally(headerSymlinkTreeTarget.toString());
buildLog.assertTargetBuiltLocally(compileTarget.toString());
buildLog.assertTargetBuiltLocally(binaryTarget.toString());
buildLog.assertTargetBuiltLocally(target.toString());
// Clear for new build.
workspace.resetBuildLogFile();
// Update the source file.
workspace.replaceFileContents(depHeaderFull, "int x", "int y");
// Check that running a build again makes the source get recompiled and the binary
// re-linked, but does not cause the header rules to re-run.
workspace.runBuckCommand("build", target.toString()).assertSuccess();
buildLog = workspace.getBuildLog();
builder = ImmutableList.builder();
builder.add(
depAggregatedDepsTarget,
depCompileTarget,
depArchiveTarget,
depTarget,
depHeaderSymlinkTreeTarget,
depHeaderExportedSymlinkTreeTarget,
headerSymlinkTreeTarget,
aggregatedDepsTarget,
compileTarget,
binaryTarget,
target);
assertThat(
buildLog.getAllTargets(),
containsInAnyOrder(builder.build().toArray(new BuildTarget[] {})));
buildLog.assertTargetBuiltLocally(depAggregatedDepsTarget.toString());
buildLog.assertTargetBuiltLocally(depCompileTarget.toString());
buildLog.assertTargetHadMatchingInputRuleKey(depArchiveTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(depHeaderSymlinkTreeTarget.toString());
buildLog.assertTargetHadMatchingInputRuleKey(depHeaderExportedSymlinkTreeTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(headerSymlinkTreeTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(depTarget.toString());
buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString());
buildLog.assertTargetBuiltLocally(compileTarget.toString());
assertThat(
buildLog.getLogEntry(binaryTarget).getSuccessType().get(),
Matchers.not(Matchers.equalTo(BuildRuleSuccessType.MATCHING_RULE_KEY)));
// Clear for new build.
workspace.resetBuildLogFile();
// Update the source file.
workspace.replaceFileContents(depSourceFull, "x + 5", "x + 6");
// Check that running a build again makes the source get recompiled and the binary
// re-linked, but does not cause the header rules to re-run.
workspace.runBuckCommand("build", target.toString()).assertSuccess();
buildLog = workspace.getBuildLog();
builder = ImmutableList.builder();
builder.add(
depAggregatedDepsTarget,
depCompileTarget,
depArchiveTarget,
depTarget,
compileTarget,
binaryTarget,
target);
assertThat(
buildLog.getAllTargets(),
containsInAnyOrder(builder.build().toArray(new BuildTarget[] {})));
buildLog.assertTargetHadMatchingRuleKey(depAggregatedDepsTarget.toString());
buildLog.assertTargetBuiltLocally(depCompileTarget.toString());
buildLog.assertTargetBuiltLocally(depArchiveTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(depTarget.toString());
buildLog.assertTargetHadMatchingRuleKey(compileTarget.toString());
buildLog.assertTargetBuiltLocally(binaryTarget.toString());
}
@Test
public void testCxxBinaryDepfileBuildWithChangedHeader() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "cxx_binary_depfile_build_with_changed_header", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckCommand("build", "//:bin");
result.assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
buildLog.assertTargetBuiltLocally("//:bin#binary");
buildLog.assertTargetBuiltLocally("//:bin#compile-" + sanitize("bin.c.o") + ",default");
buildLog.assertTargetBuiltLocally("//:lib1#default,static");
workspace.resetBuildLogFile();
workspace.replaceFileContents("lib2.h", "hello", "world");
result = workspace.runBuckCommand("build", "//:bin");
result.assertSuccess();
buildLog = workspace.getBuildLog();
buildLog.assertTargetBuiltLocally("//:bin#binary");
buildLog.assertTargetHadMatchingDepfileRuleKey(
"//:bin#compile-" + sanitize("bin.c.o") + ",default");
buildLog.assertTargetBuiltLocally("//:lib1#default,static");
}
@Test
public void testCxxBinaryDepfileBuildWithAddedHeader() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "cxx_binary_depfile_build_with_added_header", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckCommand("build", "//:bin");
result.assertSuccess();
BuckBuildLog buildLog = workspace.getBuildLog();
buildLog.assertTargetBuiltLocally("//:bin#binary");
buildLog.assertTargetBuiltLocally("//:bin#compile-" + sanitize("bin.c.o") + ",default");
buildLog.assertTargetBuiltLocally("//:lib1#default,static");
workspace.resetBuildLogFile();
workspace.replaceFileContents("BUCK", "[\"lib1.h\"]", "[\"lib1.h\", \"lib2.h\"]");
result = workspace.runBuckCommand("build", "//:bin");
result.assertSuccess();
buildLog = workspace.getBuildLog();
buildLog.assertTargetHadMatchingInputRuleKey("//:bin#binary");
buildLog.assertTargetHadMatchingDepfileRuleKey(
"//:bin#compile-" + sanitize("bin.c.o") + ",default");
buildLog.assertTargetHadMatchingInputRuleKey("//:lib1#default,static");
}
@Test
public void testCxxBinaryWithGeneratedSourceAndHeader() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
workspace.runBuckCommand("build", "//foo:binary_without_dep").assertFailure();
}
@Test
public void testHeaderNamespace() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "header_namespace", tmp);
workspace.setUp();
workspace.runBuckCommand("build", "//:test").assertSuccess();
}
@Test
public void resolveHeadersBehindSymlinkTreesInError() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "resolved", tmp);
workspace.setUp();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
workspace.writeContentsToPath("#invalid_pragma", "lib2.h");
BuildTarget target = BuildTargetFactory.newInstance("//:bin");
ProcessResult result = workspace.runBuckCommand("build", target.toString());
result.assertFailure();
// Verify that the preprocessed source contains no references to the symlink tree used to
// setup the headers.
String error = result.getStderr();
assertThat(
error,
Matchers.not(
Matchers.containsString(filesystem.getBuckPaths().getScratchDir().toString())));
assertThat(
error,
Matchers.not(Matchers.containsString(filesystem.getBuckPaths().getGenDir().toString())));
assertThat(error, Matchers.containsString("In file included from lib1.h:1"));
assertThat(error, Matchers.containsString("from bin.h:1"));
assertThat(error, Matchers.containsString("from bin.cpp:1:"));
assertThat(error, Matchers.containsString("lib2.h:1:2: error: invalid preprocessing"));
}
@Test
public void ndkCxxPlatforms() throws InterruptedException, IOException {
AssumeAndroidPlatform.assumeNdkIsAvailable();
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
boolean isPriorNdk17 = AssumeAndroidPlatform.isArmAvailable();
String armAbiString = isPriorNdk17 ? "arm, " : "";
workspace.writeContentsToPath(
"[ndk]\n"
+ " gcc_version = 4.9\n"
+ (" cpu_abis = " + armAbiString + "armv7, arm64, x86\n")
+ " app_platform = android-21\n",
".buckconfig");
if (isPriorNdk17) {
workspace.runBuckCommand("build", "//foo:simple#android-arm").assertSuccess();
}
workspace.runBuckCommand("build", "//foo:simple#android-armv7").assertSuccess();
workspace.runBuckCommand("build", "//foo:simple#android-arm64").assertSuccess();
workspace.runBuckCommand("build", "//foo:simple#android-x86").assertSuccess();
}
@Test
public void linkerFlags() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "linker_flags", tmp);
workspace.setUp();
workspace.runBuckBuild("//:binary_with_linker_flag").assertFailure("--bad-flag");
workspace.runBuckBuild("//:binary_with_library_dep").assertSuccess();
workspace.runBuckBuild("//:binary_with_exported_flags_library_dep").assertFailure("--bad-flag");
workspace.runBuckBuild("//:binary_with_prebuilt_library_dep").assertFailure("--bad-flag");
// Build binary that has unresolved symbols. Normally this would fail, but should work
// with the proper linker flag.
switch (Platform.detect()) {
case MACOS:
workspace.runBuckBuild("//:binary_with_unresolved_symbols_macos").assertSuccess();
break;
case LINUX:
workspace.runBuckBuild("//:binary_with_unresolved_symbols_linux").assertSuccess();
break;
// $CASES-OMITTED$
default:
break;
}
}
private void platformLinkerFlags(ProjectWorkspace workspace, String target) throws IOException {
workspace.runBuckBuild("//:binary_matches_default_exactly_" + target).assertSuccess();
workspace.runBuckBuild("//:binary_matches_default_" + target).assertSuccess();
ProcessResult result = workspace.runBuckBuild("//:binary_no_match_" + target);
result.assertFailure();
assertThat(result.getStderr(), Matchers.containsString("reference"));
workspace.runBuckBuild("//:binary_with_library_matches_default_" + target).assertSuccess();
workspace
.runBuckBuild("//:binary_with_prebuilt_library_matches_default_" + target)
.assertSuccess();
}
@Test
public void platformLinkerFlags() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "platform_linker_flags", tmp);
workspace.setUp();
// Build binary that has unresolved symbols. Normally this would fail, but should work
// with the proper linker flag.
switch (Platform.detect()) {
case MACOS:
platformLinkerFlags(workspace, "macos");
break;
case LINUX:
platformLinkerFlags(workspace, "linux");
break;
// $CASES-OMITTED$
default:
break;
}
}
@Test
public void perFileFlagsUsedForPreprocessing() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "preprocessing_per_file_flags", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckBuild("//:bin");
result.assertSuccess();
}
@Test
public void correctPerFileFlagsUsedForCompilation() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "compiling_per_file_flags", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckBuild("//:working-bin");
result.assertSuccess();
}
@Test
public void incorrectPerFileFlagsUsedForCompilation() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "compiling_per_file_flags", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckBuild("//:broken-bin");
result.assertFailure();
}
@Test
public void platformPreprocessorFlags() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "platform_preprocessor_flags", tmp);
workspace.setUp();
workspace.runBuckBuild("//:binary_matches_default_exactly").assertSuccess();
workspace.runBuckBuild("//:binary_matches_default").assertSuccess();
ProcessResult result = workspace.runBuckBuild("//:binary_no_match");
result.assertFailure();
assertThat(result.getStderr(), Matchers.containsString("#error"));
workspace.runBuckBuild("//:binary_with_library_matches_default").assertSuccess();
}
@Test
public void platformCompilerFlags() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "platform_compiler_flags", tmp);
workspace.setUp();
workspace.writeContentsToPath("[cxx]\n cxxflags = -Wall -Werror", ".buckconfig");
workspace.runBuckBuild("//:binary_matches_default_exactly").assertSuccess();
workspace.runBuckBuild("//:binary_matches_default").assertSuccess();
ProcessResult result = workspace.runBuckBuild("//:binary_no_match");
result.assertFailure();
assertThat(
result.getStderr(),
Matchers.allOf(Matchers.containsString("non-void"), Matchers.containsString("function")));
workspace.runBuckBuild("//:binary_with_library_matches_default").assertSuccess();
}
@Test
public void platformHeaders() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "platform_headers", tmp);
workspace.setUp();
workspace.writeContentsToPath("[cxx]\n cxxflags = -Wall -Werror", ".buckconfig");
workspace.runBuckBuild("//:binary_matches_default_exactly").assertSuccess();
workspace.runBuckBuild("//:binary_matches_default").assertSuccess();
ProcessResult result = workspace.runBuckBuild("//:binary_no_match");
result.assertFailure();
assertThat(result.getStderr(), Matchers.containsString("header.hpp"));
workspace.runBuckBuild("//:binary_with_library_matches_default").assertSuccess();
}
@Test
public void platformSources() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "platform_sources", tmp);
workspace.setUp();
workspace.writeContentsToPath("[cxx]\n cxxflags = -Wall -Werror", ".buckconfig");
workspace.runBuckBuild("//:binary_matches_default_exactly").assertSuccess();
workspace.runBuckBuild("//:binary_matches_default").assertSuccess();
ProcessResult result = workspace.runBuckBuild("//:binary_no_match");
result.assertFailure();
assertThat(result.getStderr(), Matchers.containsString("answer()"));
workspace.runBuckBuild("//:binary_with_library_matches_default").assertSuccess();
}
@Test
public void buildABinaryIfACxxLibraryDepOnlyDeclaresHeaders() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "cxx_binary_headers_only", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckBuild("//:binary");
result.assertSuccess();
}
@Test
public void buildABinaryIfACxxBinaryTransitivelyDepOnlyDeclaresHeaders() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "cxx_binary_headers_only", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckBuild("//:transitive");
System.out.println(result.getStdout());
System.err.println(result.getStderr());
result.assertSuccess();
}
@Test
public void buildBinaryWithSharedDependencies() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "shared_library", tmp);
workspace.setUp();
ProcessResult processResult = workspace.runBuckBuild("//:clowny_binary");
processResult.assertFailure();
assertThat(
processResult.getStderr(),
Matchers.containsString("in the dependencies have the same output filename"));
}
@Test
public void buildBinaryWithPerFileFlags() throws IOException {
assumeThat(Platform.detect(), is(Platform.MACOS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "per_file_flags", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckBuild("//:binary");
result.assertSuccess();
}
@Test
public void runBinaryUsingSharedLinkStyle() throws IOException {
assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "shared_link_style", tmp);
workspace.setUp();
workspace.runBuckCommand("run", "//:bar").assertSuccess();
}
@Test
public void genruleUsingBinaryUsingSharedLinkStyle() throws IOException {
assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "shared_link_style", tmp);
workspace.setUp();
workspace.runBuckBuild("//:gen").assertSuccess();
}
@Test
public void shBinaryAsLinker() throws IOException {
assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "step_test", tmp);
workspace.setUp();
workspace.runBuckBuild("-c", "cxx.ld=//:cxx", "//:binary_with_unused_header").assertSuccess();
}
@Test
public void buildBinaryUsingStaticPicLinkStyle() throws IOException {
assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "static_pic_link_style", tmp);
workspace.setUp();
workspace
.runBuckCommand(
"build",
// This should only work (on some architectures) if PIC was used to build all included
// object files.
"--config",
"cxx.cxxldflags=-shared",
"//:bar")
.assertSuccess();
}
@Test
public void testStrippedBinaryProducesBothUnstrippedAndStrippedOutputs()
throws IOException, InterruptedException {
assumeTrue(Platform.detect() == Platform.MACOS);
BuildTarget unstrippedTarget = BuildTargetFactory.newInstance("//:test");
BuildTarget strippedTarget =
unstrippedTarget.withAppendedFlavors(StripStyle.DEBUGGING_SYMBOLS.getFlavor());
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "header_namespace", tmp);
workspace.setUp();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
workspace
.runBuckCommand(
"build", "--config", "cxx.cxxflags=-g", strippedTarget.getFullyQualifiedName())
.assertSuccess();
Path strippedPath =
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem, strippedTarget.withAppendedFlavors(CxxStrip.RULE_FLAVOR), "%s"));
Path unstrippedPath =
workspace.getPath(BuildTargetPaths.getGenPath(filesystem, unstrippedTarget, "%s"));
String strippedOut =
workspace.runCommand("dsymutil", "-s", strippedPath.toString()).getStdout().orElse("");
String unstrippedOut =
workspace.runCommand("dsymutil", "-s", unstrippedPath.toString()).getStdout().orElse("");
assertThat(strippedOut, Matchers.containsStringIgnoringCase("dyld_stub_binder"));
assertThat(unstrippedOut, Matchers.containsStringIgnoringCase("dyld_stub_binder"));
assertThat(strippedOut, Matchers.not(Matchers.containsStringIgnoringCase("test.cpp")));
assertThat(unstrippedOut, Matchers.containsStringIgnoringCase("test.cpp"));
}
@Test
public void testStrippedBinaryCanBeFetchedFromCacheAlone() throws Exception {
assumeTrue(Platform.detect() == Platform.MACOS);
BuildTarget strippedTarget =
BuildTargetFactory.newInstance("//:test")
.withFlavors(StripStyle.DEBUGGING_SYMBOLS.getFlavor());
BuildTarget unstrippedTarget =
strippedTarget.withoutFlavors(StripStyle.FLAVOR_DOMAIN.getFlavors());
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "header_namespace", tmp);
workspace.setUp();
workspace.enableDirCache();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
workspace
.runBuckCommand(
"build", "--config", "cxx.cxxflags=-g", strippedTarget.getFullyQualifiedName())
.assertSuccess();
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace
.runBuckCommand(
"build", "--config", "cxx.cxxflags=-g", strippedTarget.getFullyQualifiedName())
.assertSuccess();
Path strippedPath =
workspace.getPath(
BuildTargetPaths.getGenPath(
filesystem, strippedTarget.withAppendedFlavors(CxxStrip.RULE_FLAVOR), "%s"));
Path unstrippedPath =
workspace.getPath(BuildTargetPaths.getGenPath(filesystem, unstrippedTarget, "%s"));
assertThat(Files.exists(strippedPath), Matchers.equalTo(true));
assertThat(Files.exists(unstrippedPath), Matchers.equalTo(false));
}
@Test
public void testStrippedBinaryOutputDiffersFromUnstripped() throws IOException {
assumeTrue(Platform.detect() == Platform.MACOS);
BuildTarget unstrippedTarget = BuildTargetFactory.newInstance("//:test");
BuildTarget strippedTarget =
unstrippedTarget.withFlavors(StripStyle.DEBUGGING_SYMBOLS.getFlavor());
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "header_namespace", tmp);
workspace.setUp();
ProcessResult strippedResult =
workspace.runBuckCommand(
"targets", "--show-output", strippedTarget.getFullyQualifiedName());
strippedResult.assertSuccess();
ProcessResult unstrippedResult =
workspace.runBuckCommand(
"targets", "--show-output", unstrippedTarget.getFullyQualifiedName());
unstrippedResult.assertSuccess();
String strippedOutput = strippedResult.getStdout().split(" ")[1];
String unstrippedOutput = unstrippedResult.getStdout().split(" ")[1];
assertThat(strippedOutput, Matchers.not(Matchers.equalTo(unstrippedOutput)));
}
@Test
public void testBuildingWithAndWithoutLinkerMap() throws Exception {
assumeTrue(Platform.detect() == Platform.MACOS);
BuildTarget target = BuildTargetFactory.newInstance("//:test");
BuildTarget withoutLinkerMapTarget =
target.withAppendedFlavors(LinkerMapMode.NO_LINKER_MAP.getFlavor());
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "header_namespace", tmp);
workspace.setUp();
ProjectFilesystem filesystem =
TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
workspace
.runBuckCommand("build", "--config", "cxx.cxxflags=-g", target.getFullyQualifiedName())
.assertSuccess();
BuildTarget binaryWithLinkerMap = target;
Path binaryWithLinkerMapPath =
workspace.getPath(BuildTargetPaths.getGenPath(filesystem, binaryWithLinkerMap, "%s"));
Path linkerMapPath =
workspace.getPath(
BuildTargetPaths.getGenPath(filesystem, binaryWithLinkerMap, "%s-LinkMap.txt"));
assertThat(Files.exists(binaryWithLinkerMapPath), Matchers.equalTo(true));
assertThat(Files.exists(linkerMapPath), Matchers.equalTo(true));
workspace.runBuckCommand("clean", "--keep-cache").assertSuccess();
workspace
.runBuckCommand(
"build", "--config", "cxx.cxxflags=-g", withoutLinkerMapTarget.getFullyQualifiedName())
.assertSuccess();
BuildTarget binaryWithoutLinkerMap = withoutLinkerMapTarget;
Path binaryWithoutLinkerMapPath =
workspace.getPath(BuildTargetPaths.getGenPath(filesystem, binaryWithoutLinkerMap, "%s"));
linkerMapPath =
workspace.getPath(
BuildTargetPaths.getGenPath(filesystem, binaryWithoutLinkerMap, "%s-LinkMap.txt"));
assertThat(Files.exists(binaryWithoutLinkerMapPath), Matchers.equalTo(true));
assertThat(Files.exists(linkerMapPath), Matchers.equalTo(false));
}
@Test
public void testDisablingLinkCaching() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
workspace.enableDirCache();
workspace.runBuckBuild("-c", "cxx.cache_links=false", "//foo:simple").assertSuccess();
workspace.runBuckCommand("clean", "--keep-cache");
workspace.runBuckBuild("-c", "cxx.cache_links=false", "//foo:simple").assertSuccess();
workspace
.getBuildLog()
.assertTargetBuiltLocally(
CxxDescriptionEnhancer.createCxxLinkTarget(
BuildTargetFactory.newInstance("//foo:simple"), Optional.empty())
.toString());
}
@Test
public void testThinArchives() throws IOException {
CxxPlatform cxxPlatform =
CxxPlatformUtils.build(new CxxBuckConfig(FakeBuckConfig.builder().build()));
BuildRuleResolver ruleResolver = new TestActionGraphBuilder();
assumeTrue(cxxPlatform.getAr().resolve(ruleResolver).supportsThinArchives());
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp);
workspace.setUp();
workspace.enableDirCache();
workspace
.runBuckBuild(
"-c",
"cxx.cache_links=false",
"-c",
"cxx.archive_contents=thin",
"//foo:binary_with_dep")
.assertSuccess();
ImmutableSortedSet<Path> initialObjects =
findFiles(tmp.getRoot(), tmp.getRoot().getFileSystem().getPathMatcher("glob:**/*.o"));
workspace.runBuckCommand("clean", "--keep-cache");
workspace
.runBuckBuild(
"-c",
"cxx.cache_links=false",
"-c",
"cxx.archive_contents=thin",
"//foo:binary_with_dep")
.assertSuccess();
workspace
.getBuildLog()
.assertTargetBuiltLocally(
CxxDescriptionEnhancer.createCxxLinkTarget(
BuildTargetFactory.newInstance("//foo:binary_with_dep"), Optional.empty())
.toString());
ImmutableSortedSet<Path> subsequentObjects =
findFiles(tmp.getRoot(), tmp.getRoot().getFileSystem().getPathMatcher("glob:**/*.o"));
assertThat(initialObjects, Matchers.equalTo(subsequentObjects));
}
/**
* Tests that, if a file has to be rebuilt, but its header dependencies do not, that the header
* tree is still generated into the correct location.
*/
@Test
public void headersShouldBeSetUpCorrectlyOnRebuild() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "cxx_binary_dep_header_tree_materialize", tmp);
workspace.setUp();
workspace.enableDirCache();
workspace.runBuckBuild("//:bin").assertSuccess();
workspace.runBuckCommand("clean", "--keep-cache");
workspace.copyFile("bin.c.new", "bin.c");
workspace.runBuckBuild("//:bin").assertSuccess();
BuckBuildLog log = workspace.getBuildLog();
log.assertTargetBuiltLocally("//:bin#binary");
}
/** Tests --config cxx.declared_platforms */
@Test
public void testDeclaredPlatforms() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "declared_platforms", tmp);
workspace.setUp();
workspace
.runBuckCommand("query", "-c", "cxx.declared_platforms=my-favorite-platform", "//:simple")
.assertSuccess();
}
@Test
public void targetsInPlatformSpecificFlagsDoNotBecomeDependencies() throws Exception {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(
this, "targets_in_platform_specific_flags_do_not_become_dependencies", tmp);
workspace.setUp();
ProcessResult result = workspace.runBuckBuild(":bin");
result.assertSuccess();
}
@Test
public void conflictingHeadersBuildFails() throws Exception {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "headers_conflicts", tmp);
workspace.setUp();
String errorMsg = workspace.runBuckBuild(":main").assertFailure().getStderr();
assertTrue(
errorMsg.contains(
"has dependencies using headers that can be included using the same path"));
}
@Test
public void conflictingHeadersWithWhitelistSucceeds() throws Exception {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "headers_conflicts", tmp);
workspace.setUp();
workspace
.runBuckBuild("-c", "cxx.conflicting_header_basename_whitelist=public.h", ":main")
.assertSuccess();
}
@Test
public void testPlatformDependenciesNotResolvedEagerly() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "cxx_binary_platform_deps", tmp);
workspace.setUp();
workspace.runBuckBuild(":binary#working-platform").assertSuccess();
}
@Test
public void testLinkMapCreated() throws IOException {
assumeThat(Platform.detect(), is(Platform.MACOS));
assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "cxx_binary_linkmap", tmp);
workspace.setUp();
workspace.runBuckBuild(":binary#linkmap").assertSuccess();
}
@Test
public void testLinkMapNotCreated() throws IOException {
assumeThat(Platform.detect(), is(Platform.LINUX));
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "cxx_binary_linkmap", tmp);
workspace.setUp();
try {
workspace.runBuckBuild(":binary#linkmap");
} catch (HumanReadableException e) {
assertEquals(
"Linker for target //:binary#linkmap does not support linker maps.",
e.getHumanReadableErrorMessage());
}
}
private ImmutableSortedSet<Path> findFiles(Path root, PathMatcher matcher) throws IOException {
ImmutableSortedSet.Builder<Path> files = ImmutableSortedSet.naturalOrder();
Files.walkFileTree(
root,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (matcher.matches(file)) {
files.add(file);
}
return FileVisitResult.CONTINUE;
}
});
return files.build();
}
private static ImmutableSet<String> getUniqueLines(String str) {
return ImmutableSet.copyOf(Splitter.on('\n').omitEmptyStrings().split(str));
}
}
|
/*
* 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.dubbo.config;
import junit.framework.TestCase;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.config.api.Greeting;
import org.apache.dubbo.config.support.Parameter;
import org.hamcrest.Matchers;
import org.junit.Test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static org.junit.Assert.assertThat;
public class AbstractConfigTest {
@Test
public void testAppendProperties1() throws Exception {
try {
System.setProperty("dubbo.properties.i", "1");
System.setProperty("dubbo.properties.c", "c");
System.setProperty("dubbo.properties.b", "2");
System.setProperty("dubbo.properties.d", "3");
System.setProperty("dubbo.properties.f", "4");
System.setProperty("dubbo.properties.l", "5");
System.setProperty("dubbo.properties.s", "6");
System.setProperty("dubbo.properties.str", "dubbo");
System.setProperty("dubbo.properties.bool", "true");
PropertiesConfig config = new PropertiesConfig();
AbstractConfig.appendProperties(config);
TestCase.assertEquals(1, config.getI());
TestCase.assertEquals('c', config.getC());
TestCase.assertEquals((byte) 0x02, config.getB());
TestCase.assertEquals(3d, config.getD());
TestCase.assertEquals(4f, config.getF());
TestCase.assertEquals(5L, config.getL());
TestCase.assertEquals(6, config.getS());
TestCase.assertEquals("dubbo", config.getStr());
TestCase.assertTrue(config.isBool());
} finally {
System.clearProperty("dubbo.properties.i");
System.clearProperty("dubbo.properties.c");
System.clearProperty("dubbo.properties.b");
System.clearProperty("dubbo.properties.d");
System.clearProperty("dubbo.properties.f");
System.clearProperty("dubbo.properties.l");
System.clearProperty("dubbo.properties.s");
System.clearProperty("dubbo.properties.str");
System.clearProperty("dubbo.properties.bool");
}
}
@Test
public void testAppendProperties2() throws Exception {
try {
System.setProperty("dubbo.properties.two.i", "2");
PropertiesConfig config = new PropertiesConfig("two");
AbstractConfig.appendProperties(config);
TestCase.assertEquals(2, config.getI());
} finally {
System.clearProperty("dubbo.properties.two.i");
}
}
@Test
public void testAppendProperties3() throws Exception {
try {
Properties p = new Properties();
p.put("dubbo.properties.str", "dubbo");
ConfigUtils.setProperties(p);
PropertiesConfig config = new PropertiesConfig();
AbstractConfig.appendProperties(config);
TestCase.assertEquals("dubbo", config.getStr());
} finally {
System.clearProperty(Constants.DUBBO_PROPERTIES_KEY);
ConfigUtils.setProperties(null);
}
}
@Test
public void testAppendParameters1() throws Exception {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("default.num", "one");
parameters.put("num", "ONE");
AbstractConfig.appendParameters(parameters, new ParameterConfig(1, "hello/world", 30, "password"), "prefix");
TestCase.assertEquals("one", parameters.get("prefix.key.1"));
TestCase.assertEquals("two", parameters.get("prefix.key.2"));
TestCase.assertEquals("ONE,one,1", parameters.get("prefix.num"));
TestCase.assertEquals("hello%2Fworld", parameters.get("prefix.naming"));
TestCase.assertEquals("30", parameters.get("prefix.age"));
TestCase.assertFalse(parameters.containsKey("prefix.key-2"));
TestCase.assertFalse(parameters.containsKey("prefix.secret"));
}
@Test(expected = IllegalStateException.class)
public void testAppendParameters2() throws Exception {
Map<String, String> parameters = new HashMap<String, String>();
AbstractConfig.appendParameters(parameters, new ParameterConfig());
}
@Test
public void testAppendParameters3() throws Exception {
Map<String, String> parameters = new HashMap<String, String>();
AbstractConfig.appendParameters(parameters, null);
TestCase.assertTrue(parameters.isEmpty());
}
@Test
public void testAppendParameters4() throws Exception {
Map<String, String> parameters = new HashMap<String, String>();
AbstractConfig.appendParameters(parameters, new ParameterConfig(1, "hello/world", 30, "password"));
TestCase.assertEquals("one", parameters.get("key.1"));
TestCase.assertEquals("two", parameters.get("key.2"));
TestCase.assertEquals("1", parameters.get("num"));
TestCase.assertEquals("hello%2Fworld", parameters.get("naming"));
TestCase.assertEquals("30", parameters.get("age"));
}
@Test
public void testAppendAttributes1() throws Exception {
Map<String, Object> parameters = new HashMap<String, Object>();
AbstractConfig.appendAttributes(parameters, new AttributeConfig('l', true, (byte) 0x01), "prefix");
TestCase.assertEquals('l', parameters.get("prefix.let"));
TestCase.assertEquals(true, parameters.get("prefix.activate"));
TestCase.assertFalse(parameters.containsKey("prefix.flag"));
}
@Test
public void testAppendAttributes2() throws Exception {
Map<String, Object> parameters = new HashMap<String, Object>();
AbstractConfig.appendAttributes(parameters, new AttributeConfig('l', true, (byte) 0x01));
TestCase.assertEquals('l', parameters.get("let"));
TestCase.assertEquals(true, parameters.get("activate"));
TestCase.assertFalse(parameters.containsKey("flag"));
}
@Test(expected = IllegalStateException.class)
public void checkExtension() throws Exception {
AbstractConfig.checkExtension(Greeting.class, "hello", "world");
}
@Test(expected = IllegalStateException.class)
public void checkMultiExtension1() throws Exception {
AbstractConfig.checkMultiExtension(Greeting.class, "hello", "default,world");
}
@Test(expected = IllegalStateException.class)
public void checkMultiExtension2() throws Exception {
AbstractConfig.checkMultiExtension(Greeting.class, "hello", "default,-world");
}
@Test(expected = IllegalStateException.class)
public void checkLength() throws Exception {
StringBuilder builder = new StringBuilder();
for (int i = 0; i <= 200; i++) {
builder.append("a");
}
AbstractConfig.checkLength("hello", builder.toString());
}
@Test(expected = IllegalStateException.class)
public void checkPathLength() throws Exception {
StringBuilder builder = new StringBuilder();
for (int i = 0; i <= 200; i++) {
builder.append("a");
}
AbstractConfig.checkPathLength("hello", builder.toString());
}
@Test(expected = IllegalStateException.class)
public void checkName() throws Exception {
AbstractConfig.checkName("hello", "world%");
}
@Test
public void checkNameHasSymbol() throws Exception {
try {
AbstractConfig.checkNameHasSymbol("hello", ":*,/ -0123\tabcdABCD");
AbstractConfig.checkNameHasSymbol("mock", "force:return world");
} catch (Exception e) {
TestCase.fail("the value should be legal.");
}
}
@Test
public void checkKey() throws Exception {
try {
AbstractConfig.checkKey("hello", "*,-0123abcdABCD");
} catch (Exception e) {
TestCase.fail("the value should be legal.");
}
}
@Test
public void checkMultiName() throws Exception {
try {
AbstractConfig.checkMultiName("hello", ",-._0123abcdABCD");
} catch (Exception e) {
TestCase.fail("the value should be legal.");
}
}
@Test
public void checkPathName() throws Exception {
try {
AbstractConfig.checkPathName("hello", "/-$._0123abcdABCD");
} catch (Exception e) {
TestCase.fail("the value should be legal.");
}
}
@Test
public void checkMethodName() throws Exception {
try {
AbstractConfig.checkMethodName("hello", "abcdABCD0123abcd");
} catch (Exception e) {
TestCase.fail("the value should be legal.");
}
try {
AbstractConfig.checkMethodName("hello", "0a");
TestCase.fail("the value should be illegal.");
} catch (Exception e) {
// ignore
}
}
@Test
public void checkParameterName() throws Exception {
Map<String, String> parameters = Collections.singletonMap("hello", ":*,/-._0123abcdABCD");
try {
AbstractConfig.checkParameterName(parameters);
} catch (Exception e) {
TestCase.fail("the value should be legal.");
}
}
@Test
@Config(interfaceClass = Greeting.class, filter = {"f1, f2"}, listener = {"l1, l2"},
parameters = {"k1", "v1", "k2", "v2"})
public void appendAnnotation() throws Exception {
Config config = getClass().getMethod("appendAnnotation").getAnnotation(Config.class);
AnnotationConfig annotationConfig = new AnnotationConfig();
annotationConfig.appendAnnotation(Config.class, config);
TestCase.assertSame(Greeting.class, annotationConfig.getInterface());
TestCase.assertEquals("f1, f2", annotationConfig.getFilter());
TestCase.assertEquals("l1, l2", annotationConfig.getListener());
TestCase.assertEquals(2, annotationConfig.getParameters().size());
TestCase.assertEquals("v1", annotationConfig.getParameters().get("k1"));
TestCase.assertEquals("v2", annotationConfig.getParameters().get("k2"));
assertThat(annotationConfig.toString(), Matchers.containsString("filter=\"f1, f2\" "));
assertThat(annotationConfig.toString(), Matchers.containsString("listener=\"l1, l2\" "));
}
private static class PropertiesConfig extends AbstractConfig {
private char c;
private boolean bool;
private byte b;
private int i;
private long l;
private float f;
private double d;
private short s;
private String str;
PropertiesConfig() {
}
PropertiesConfig(String id) {
this.id = id;
}
public char getC() {
return c;
}
public void setC(char c) {
this.c = c;
}
public boolean isBool() {
return bool;
}
public void setBool(boolean bool) {
this.bool = bool;
}
public byte getB() {
return b;
}
public void setB(byte b) {
this.b = b;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public long getL() {
return l;
}
public void setL(long l) {
this.l = l;
}
public float getF() {
return f;
}
public void setF(float f) {
this.f = f;
}
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public short getS() {
return s;
}
public void setS(short s) {
this.s = s;
}
}
private static class ParameterConfig {
private int number;
private String name;
private int age;
private String secret;
ParameterConfig() {
}
ParameterConfig(int number, String name, int age, String secret) {
this.number = number;
this.name = name;
this.age = age;
this.secret = secret;
}
@Parameter(key = "num", append = true)
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@Parameter(key = "naming", append = true, escaped = true, required = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Parameter(excluded = true)
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public Map getParameters() {
Map<String, String> map = new HashMap<String, String>();
map.put("key.1", "one");
map.put("key-2", "two");
return map;
}
}
private static class AttributeConfig {
private char letter;
private boolean activate;
private byte flag;
public AttributeConfig(char letter, boolean activate, byte flag) {
this.letter = letter;
this.activate = activate;
this.flag = flag;
}
@Parameter(attribute = true, key = "let")
public char getLetter() {
return letter;
}
public void setLetter(char letter) {
this.letter = letter;
}
@Parameter(attribute = true)
public boolean isActivate() {
return activate;
}
public void setActivate(boolean activate) {
this.activate = activate;
}
public byte getFlag() {
return flag;
}
public void setFlag(byte flag) {
this.flag = flag;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Config {
Class<?> interfaceClass() default void.class;
String interfaceName() default "";
String[] filter() default {};
String[] listener() default {};
String[] parameters() default {};
}
private static class AnnotationConfig extends AbstractConfig {
private Class interfaceClass;
private String filter;
private String listener;
private Map<String, String> parameters;
public Class getInterface() {
return interfaceClass;
}
public void setInterface(Class interfaceName) {
this.interfaceClass = interfaceName;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public String getListener() {
return listener;
}
public void setListener(String listener) {
this.listener = listener;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
}
}
|
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
/**
* Created by Gabriele Cardosi - gcardosi@cardosi.net on 02/08/16.
*
* Login view classes
*/
package ${package}.client.view.login;
|
package com.harun.androidresimleriyerellestirme;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.harun.androidresimleriyerellestirme", appContext.getPackageName());
}
}
|
package com.google.api.ads.adwords.jaxws.v201607.cm;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* A Feed identifies a source of data and its schema. The data for the Feed can either be
* user-entered via the FeedItemService or system-generated, in which case the data is provided
* automatically.
*
*
* <p>Java class for Feed complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Feed">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="attributes" type="{https://adwords.google.com/api/adwords/cm/v201607}FeedAttribute" maxOccurs="unbounded" minOccurs="0"/>
* <element name="status" type="{https://adwords.google.com/api/adwords/cm/v201607}Feed.Status" minOccurs="0"/>
* <element name="origin" type="{https://adwords.google.com/api/adwords/cm/v201607}Feed.Origin" minOccurs="0"/>
* <element name="systemFeedGenerationData" type="{https://adwords.google.com/api/adwords/cm/v201607}SystemFeedGenerationData" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Feed", propOrder = {
"id",
"name",
"attributes",
"status",
"origin",
"systemFeedGenerationData"
})
public class Feed {
protected Long id;
protected String name;
protected List<FeedAttribute> attributes;
@XmlSchemaType(name = "string")
protected FeedStatus status;
@XmlSchemaType(name = "string")
protected FeedOrigin origin;
protected SystemFeedGenerationData systemFeedGenerationData;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setId(Long value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the attributes property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the attributes property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAttributes().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FeedAttribute }
*
*
*/
public List<FeedAttribute> getAttributes() {
if (attributes == null) {
attributes = new ArrayList<FeedAttribute>();
}
return this.attributes;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link FeedStatus }
*
*/
public FeedStatus getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link FeedStatus }
*
*/
public void setStatus(FeedStatus value) {
this.status = value;
}
/**
* Gets the value of the origin property.
*
* @return
* possible object is
* {@link FeedOrigin }
*
*/
public FeedOrigin getOrigin() {
return origin;
}
/**
* Sets the value of the origin property.
*
* @param value
* allowed object is
* {@link FeedOrigin }
*
*/
public void setOrigin(FeedOrigin value) {
this.origin = value;
}
/**
* Gets the value of the systemFeedGenerationData property.
*
* @return
* possible object is
* {@link SystemFeedGenerationData }
*
*/
public SystemFeedGenerationData getSystemFeedGenerationData() {
return systemFeedGenerationData;
}
/**
* Sets the value of the systemFeedGenerationData property.
*
* @param value
* allowed object is
* {@link SystemFeedGenerationData }
*
*/
public void setSystemFeedGenerationData(SystemFeedGenerationData value) {
this.systemFeedGenerationData = value;
}
}
|
package net.interition.sparqlycode.ahkbp;
public enum DirectiveEnum {
VirtualHost, ServerName, Redirect, ProxyPass, ServerAlias, UNKNOWN;
public static DirectiveEnum getDirective(String directive) {
for( DirectiveEnum constant : DirectiveEnum.values() ) {
if(directive.equalsIgnoreCase(constant.name())) return constant ;
}
return DirectiveEnum.UNKNOWN ;
}
}
|
package org.firstinspires.ftc.teamcode.trajectory.sequencesegment;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.trajectory.TrajectoryMarker;
import java.util.List;
public final class WaitSegment extends SequenceSegment {
public WaitSegment(Pose2d pose, double seconds, List<TrajectoryMarker> markers) {
super(seconds, pose, pose, markers);
}
}
|
/**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2017 Ruhr University Bochum / Hackmanit GmbH
*
* Licensed under Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package de.rub.nds.tlsattacker.core.protocol.handler;
import de.rub.nds.tlsattacker.core.protocol.message.ServerHelloDoneMessage;
import de.rub.nds.tlsattacker.core.protocol.parser.ServerHelloDoneParser;
import de.rub.nds.tlsattacker.core.protocol.preparator.ServerHelloDonePreparator;
import de.rub.nds.tlsattacker.core.protocol.serializer.ServerHelloDoneSerializer;
import de.rub.nds.tlsattacker.core.state.TlsContext;
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class ServerHelloDoneHandlerTest {
private ServerHelloDoneHandler handler;
private TlsContext context;
@Before
public void setUp() {
context = new TlsContext();
handler = new ServerHelloDoneHandler(context);
}
@After
public void tearDown() {
}
/**
* Test of getParser method, of class ServerHelloDoneHandler.
*/
@Test
public void testGetParser() {
assertTrue(handler.getParser(new byte[1], 0) instanceof ServerHelloDoneParser);
}
/**
* Test of getPreparator method, of class ServerHelloDoneHandler.
*/
@Test
public void testGetPreparator() {
assertTrue(handler.getPreparator(new ServerHelloDoneMessage()) instanceof ServerHelloDonePreparator);
}
/**
* Test of getSerializer method, of class ServerHelloDoneHandler.
*/
@Test
public void testGetSerializer() {
assertTrue(handler.getSerializer(new ServerHelloDoneMessage()) instanceof ServerHelloDoneSerializer);
}
/**
* Test of adjustTLSContext method, of class ServerHelloDoneHandler.
*/
@Test
public void testAdjustTLSContext() {
ServerHelloDoneMessage message = new ServerHelloDoneMessage();
handler.adjustTLSContext(message);
// TODO make sure nothing changed
}
}
|
package jp.osaka.appppy.sample.osakacity.app.contents;
import jp.osaka.appppy.sample.osakacity.app.MainActivity;
/**
* メインアクティビティ
*
* @author APPPPY
*/
public class CardCultureAndTouristActivity extends MainActivity {
}
|
/**
* @see https://github.com/JustBurrow/java-lulkr-spring-data-jpa
*/
package kr.lul.spring.data.jpa.time.converter;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;
import kr.lul.common.util.SystemTimeProvider;
import kr.lul.common.util.TimeProvider;
/**
* @author Just Burrow
* @since 2016. 8. 18.
*/
public class LocalDateTimeBigintAttributeConverterTest {
private long now;
private LocalDateTimeBigintAttributeConverter converter;
/**
* @throws java.lang.Exception
* @author Just Burrow
* @since 2016. 8. 18.
*/
@Before
public void setUp() throws Exception {
this.now = System.currentTimeMillis();
TimeProvider timeProvider = new SystemTimeProvider();
this.converter = new LocalDateTimeBigintAttributeConverter(timeProvider);
assertThat(this.converter.getTimeProvider()).isNotNull()
.isSameAs(timeProvider);
}
@Test
public void testWithNow() throws Exception {
// Given
LocalDateTime ldt = LocalDateTime.now();
// When
final long utc = this.converter.convertToDatabaseColumn(ldt);
final LocalDateTime actual = this.converter.convertToEntityAttribute(utc);
// Then
assertThat(utc).isGreaterThanOrEqualTo(this.now);
assertThat(actual).isNotNull()
.isNotSameAs(ldt)
.isEqualTo(ldt);
}
@Test
public void testWithNull() throws Exception {
assertThat(this.converter.convertToEntityAttribute(null)).isNull();
assertThat(this.converter.convertToDatabaseColumn(null)).isNull();
}
}
|
package de.metas.handlingunits.order.api.impl;
/*
* #%L
* de.metas.handlingunits.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.adempiere.model.InterfaceWrapperHelper;
import org.compiere.model.I_C_Order;
import de.metas.handlingunits.IPackingMaterialDocumentLine;
import de.metas.handlingunits.IPackingMaterialDocumentLineSource;
import de.metas.handlingunits.impl.AbstractPackingMaterialDocumentLinesBuilder;
import de.metas.handlingunits.model.I_C_OrderLine;
import de.metas.handlingunits.model.I_M_HU_PackingMaterial;
import de.metas.order.IOrderDAO;
import de.metas.order.IOrderLineBL;
import de.metas.order.OrderLinePriceUpdateRequest;
import de.metas.order.OrderLinePriceUpdateRequest.ResultUOM;
import de.metas.product.IProductBL;
import de.metas.uom.UomId;
import de.metas.util.Check;
import de.metas.util.Services;
import lombok.NonNull;
/**
* Iterates an order's lines and creates additional lines for the HU packing material.
*/
public final class OrderPackingMaterialDocumentLinesBuilder extends AbstractPackingMaterialDocumentLinesBuilder
{
//
// Services; note that this lineBuilder is shortLived, so it's OK to have those services as members
private final transient IOrderDAO orderDAO = Services.get(IOrderDAO.class);
private final transient IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
private final transient IProductBL productBL = Services.get(IProductBL.class);
private final I_C_Order order;
/**
* Creates a new instance of the given order.
*
* @param order
*/
public OrderPackingMaterialDocumentLinesBuilder(@NonNull final I_C_Order order)
{
this.order = order;
}
public void addAllOrderLinesFromOrder()
{
// note that we want all because there might be existing inactive packaging lines to reuse
final List<I_C_OrderLine> orderLinesAll = retrieveAllOrderLinesFromOrder();
//
// Add Packing Material Order Lines first
// and gather regular order lines (sources for packing materials)
final List<IPackingMaterialDocumentLineSource> lines = new ArrayList<>();
for (final I_C_OrderLine orderLine : orderLinesAll)
{
if (orderLine.isPackagingMaterial())
{
final IPackingMaterialDocumentLine pmLine = new OrderLinePackingMaterialDocumentLine(orderLine);
addPackingMaterialDocumentLine(pmLine);
}
else
{
final IPackingMaterialDocumentLineSource pmLineSource = new OrderLinePackingMaterialDocumentLineSource(orderLine);
lines.add(pmLineSource);
}
}
//
// Add regular lines
for (final IPackingMaterialDocumentLineSource line : lines)
{
addSource(line);
}
}
private List<I_C_OrderLine> retrieveAllOrderLinesFromOrder()
{
final List<I_C_OrderLine> orderLinesAll = InterfaceWrapperHelper.createList(
orderDAO.retrieveOrderLines(order),
I_C_OrderLine.class);
return orderLinesAll;
}
/**
* Reset existing packing material order lines, ie.e deactivate and unlink them, and set their quantities to zero.<br>
* They might eventually be removed in {@link #create()}, if they don't get new quantities assigned from the builder.
*
*/
public void deactivateAndUnlinkAllPackingMaterialOrderLinesFromOrder()
{
final List<I_C_OrderLine> oLines = retrieveAllOrderLinesFromOrder();
for (final I_C_OrderLine orderLine : oLines)
{
if (orderLine.isPackagingMaterial())
{
orderLine.setIsActive(false);
orderLine.setQtyEntered(BigDecimal.ZERO);
orderLine.setQtyOrdered(BigDecimal.ZERO);
}
else
{
orderLine.setC_PackingMaterial_OrderLine(null);
}
InterfaceWrapperHelper.save(orderLine);
}
}
@Override
protected void assertValid(final IPackingMaterialDocumentLineSource source)
{
Check.assumeInstanceOf(source, OrderLinePackingMaterialDocumentLineSource.class, "source");
final OrderLinePackingMaterialDocumentLineSource orderLineSource = toImpl(source);
final I_C_OrderLine orderLine = orderLineSource.getC_OrderLine();
Check.assume(order.getC_Order_ID() == orderLine.getC_Order_ID(),
"Order line {} shall be part of {}",
orderLine, order);
}
@Override
protected IPackingMaterialDocumentLine createPackingMaterialDocumentLine(final I_M_HU_PackingMaterial packingMaterial)
{
final I_C_OrderLine orderLine = orderLineBL.createOrderLine(order, I_C_OrderLine.class);
final UomId uomId = productBL.getStockUOMId(packingMaterial.getM_Product_ID());
orderLine.setM_Product_ID(packingMaterial.getM_Product_ID());
orderLine.setC_UOM_ID(uomId.getRepoId()); // prevent the system from picking its default-UOM; there might be no UOM-conversion to/from the product's UOM
orderLine.setIsPackagingMaterial(true);
return new OrderLinePackingMaterialDocumentLine(orderLine);
}
private OrderLinePackingMaterialDocumentLine toImpl(final IPackingMaterialDocumentLine pmLine)
{
return (OrderLinePackingMaterialDocumentLine)pmLine;
}
private OrderLinePackingMaterialDocumentLineSource toImpl(final IPackingMaterialDocumentLineSource source)
{
return (OrderLinePackingMaterialDocumentLineSource)source;
}
@Override
protected void removeDocumentLine(final IPackingMaterialDocumentLine pmLine)
{
final OrderLinePackingMaterialDocumentLine orderLinePMLine = toImpl(pmLine);
final I_C_OrderLine pmOrderLine = orderLinePMLine.getC_OrderLine();
if (!InterfaceWrapperHelper.isNew(pmOrderLine))
{
InterfaceWrapperHelper.delete(pmOrderLine);
}
}
@Override
protected void createDocumentLine(final IPackingMaterialDocumentLine pmLine)
{
final OrderLinePackingMaterialDocumentLine orderLinePMLine = toImpl(pmLine);
final I_C_OrderLine pmOrderLine = orderLinePMLine.getC_OrderLine();
// qtyOrdered is in the product's UOM whereas QtyEntered is in the order line's UOM. They don't have to be the same.
// pmOrderLine.setQtyEntered(pmOrderLine.getQtyOrdered());
final boolean ordereWasInactive = !pmOrderLine.isActive();
pmOrderLine.setIsActive(true);
if (ordereWasInactive)
{
// while the order line was inactive e.g. the order's datePromised might have been changed
orderLineBL.setOrder(pmOrderLine, order);
}
orderLineBL.updatePrices(OrderLinePriceUpdateRequest.builder()
.orderLine(pmOrderLine)
.resultUOM(ResultUOM.CONTEXT_UOM)
.updatePriceEnteredAndDiscountOnlyIfNotAlreadySet(true)
.updateLineNetAmt(true)
.build());
InterfaceWrapperHelper.save(pmOrderLine);
}
@Override
protected void linkSourceToDocumentLine(final IPackingMaterialDocumentLineSource source,
final IPackingMaterialDocumentLine pmLine)
{
final OrderLinePackingMaterialDocumentLineSource orderLineSource = toImpl(source);
final OrderLinePackingMaterialDocumentLine orderLinePMLine = toImpl(pmLine);
final I_C_OrderLine regularOrderLine = orderLineSource.getC_OrderLine();
Check.assume(regularOrderLine.getC_OrderLine_ID() > 0, "Regular order line shall be already saved: {}", regularOrderLine);
final I_C_OrderLine pmOrderLine;
if (orderLinePMLine == null)
{
pmOrderLine = null;
}
else
{
pmOrderLine = orderLinePMLine.getC_OrderLine();
}
regularOrderLine.setC_PackingMaterial_OrderLine(pmOrderLine);
InterfaceWrapperHelper.save(regularOrderLine);
}
}
|
/*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.distributed.dht;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.cache.CacheRebalanceMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.lifecycle.LifecycleBean;
import org.apache.ignite.lifecycle.LifecycleEventType;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheRebalanceMode.ASYNC;
import static org.apache.ignite.cache.CacheRebalanceMode.SYNC;
import static org.apache.ignite.configuration.CacheConfiguration.DFLT_REBALANCE_BATCH_SIZE;
import static org.apache.ignite.configuration.DeploymentMode.CONTINUOUS;
/**
* Test large cache counts.
*/
@SuppressWarnings({"BusyWait"})
public class GridCacheDhtPreloadUnloadSelfTest extends GridCommonAbstractTest {
/** Default backups. */
private static final int DFLT_BACKUPS = 1;
/** Partitions. */
private static final int DFLT_PARTITIONS = 521;
/** Preload batch size. */
private static final int DFLT_BATCH_SIZE = DFLT_REBALANCE_BATCH_SIZE;
/** Number of key backups. Each test method can set this value as required. */
private int backups = DFLT_BACKUPS;
/** Preload mode. */
private CacheRebalanceMode preloadMode = ASYNC;
/** */
private int preloadBatchSize = DFLT_BATCH_SIZE;
/** Number of partitions. */
private int partitions = DFLT_PARTITIONS;
/** */
private LifecycleBean lbean;
/** Network timeout. */
private long netTimeout = 1000;
/**
*
*/
public GridCacheDhtPreloadUnloadSelfTest() {
super(false /*start grid. */);
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration c = super.getConfiguration(igniteInstanceName);
CacheConfiguration cc = defaultCacheConfiguration();
cc.setCacheMode(PARTITIONED);
cc.setRebalanceBatchSize(preloadBatchSize);
cc.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
cc.setRebalanceMode(preloadMode);
cc.setAffinity(new RendezvousAffinityFunction(false, partitions));
cc.setBackups(backups);
cc.setAtomicityMode(TRANSACTIONAL);
if (lbean != null)
c.setLifecycleBeans(lbean);
c.setCacheConfiguration(cc);
c.setDeploymentMode(CONTINUOUS);
c.setNetworkTimeout(netTimeout);
return c;
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
backups = DFLT_BACKUPS;
partitions = DFLT_PARTITIONS;
preloadMode = ASYNC;
preloadBatchSize = DFLT_BATCH_SIZE;
netTimeout = 1000;
}
/** @throws Exception If failed. */
@Test
public void testUnloadZeroBackupsTwoNodes() throws Exception {
preloadMode = SYNC;
backups = 0;
netTimeout = 500;
try {
startGrid(0);
int cnt = 1000;
populate(grid(0).<Integer, String>cache(DEFAULT_CACHE_NAME), cnt);
int gridCnt = 2;
for (int i = 1; i < gridCnt; i++)
startGrid(i);
long wait = 3000;
waitForUnload(gridCnt, cnt, wait);
}
finally {
stopAllGrids();
}
}
/** @throws Exception If failed. */
@Test
public void testUnloadOneBackupTwoNodes() throws Exception {
preloadMode = SYNC;
backups = 1;
netTimeout = 500;
try {
startGrid(0);
int cnt = 1000;
populate(grid(0).<Integer, String>cache(DEFAULT_CACHE_NAME), cnt);
int gridCnt = 2;
for (int i = 1; i < gridCnt; i++)
startGrid(i);
long wait = 2000;
info("Sleeping for " + wait + "ms");
// Unfortunately there is no other way but sleep.
Thread.sleep(wait);
for (int i = 0; i < gridCnt; i++)
info("Grid size [i=" + i + ", size=" + grid(i).cache(DEFAULT_CACHE_NAME).localSize() + ']');
for (int i = 0; i < gridCnt; i++) {
IgniteCache<Integer, String> c = grid(i).cache(DEFAULT_CACHE_NAME);
// Nothing should be unloaded since nodes are backing up each other.
assertEquals(cnt, c.localSize(CachePeekMode.ALL));
}
}
finally {
stopAllGrids();
}
}
/**
*
* @param gridCnt Grid count.
* @param cnt Count.
* @param wait Wait.
* @throws InterruptedException If interrupted.
*/
private void waitForUnload(long gridCnt, long cnt, long wait) throws InterruptedException {
info("Waiting for preloading to complete for " + wait + "ms...");
long endTime = System.currentTimeMillis() + wait;
while (System.currentTimeMillis() < endTime) {
boolean err = false;
for (int i = 0; i < gridCnt; i++) {
IgniteCache<Integer, String> c = grid(i).cache(DEFAULT_CACHE_NAME);
if (c.localSize() >= cnt)
err = true;
}
if (!err)
break;
else
Thread.sleep(500);
}
for (int i = 0; i < gridCnt; i++)
info("Grid size [i=" + i + ", size=" + grid(i).cache(DEFAULT_CACHE_NAME).localSize() + ']');
for (int i = 0; i < gridCnt; i++) {
IgniteCache<Integer, String> c = grid(i).cache(DEFAULT_CACHE_NAME);
assert c.localSize() < cnt;
}
}
/** @throws Exception If failed. */
@Test
public void testUnloadOneBackupThreeNodes() throws Exception {
preloadMode = SYNC;
backups = 1;
netTimeout = 500;
partitions = 23;
try {
startGrid(0);
int cnt = 1000;
populate(grid(0).<Integer, String>cache(DEFAULT_CACHE_NAME), cnt);
int gridCnt = 3;
for (int i = 1; i < gridCnt; i++) {
startGrid(i);
for (int j = 0; j <= i; j++)
info("Grid size [i=" + i + ", size=" + grid(j).cache(DEFAULT_CACHE_NAME).localSize() + ']');
}
long wait = 3000;
waitForUnload(gridCnt, cnt, wait);
}
finally {
stopAllGrids();
}
}
/** @throws Exception If failed. */
@Test
public void testUnloadOneBackThreeNodesWithLifeCycleBean() throws Exception {
preloadMode = SYNC;
backups = 1;
try {
final int cnt = 1000;
lbean = new LifecycleBean() {
@IgniteInstanceResource
private Ignite ignite;
@Override public void onLifecycleEvent(LifecycleEventType evt) {
if (evt == LifecycleEventType.AFTER_NODE_START) {
IgniteCache<Integer, String> c = ignite.cache(DEFAULT_CACHE_NAME);
if (c.putIfAbsent(-1, "true")) {
populate(ignite.<Integer, String>cache(DEFAULT_CACHE_NAME), cnt);
info(">>> POPULATED GRID <<<");
}
}
}
};
int gridCnt = 3;
for (int i = 0; i < gridCnt; i++) {
startGrid(i);
for (int j = 0; j < i; j++)
info("Grid size [i=" + i + ", size=" + grid(j).cache(DEFAULT_CACHE_NAME).localSize() + ']');
}
long wait = 3000;
waitForUnload(gridCnt, cnt, wait);
}
finally {
lbean = null;
stopAllGrids();
}
}
/**
* @param c Cache.
* @param cnt Key count.
*/
@SuppressWarnings("TypeMayBeWeakened")
private void populate(IgniteCache<Integer, String> c, int cnt) {
for (int i = 0; i < cnt; i++)
c.put(i, value(1024));
}
/**
* @param size Size.
* @return Value.
*/
private String value(int size) {
StringBuilder b = new StringBuilder(size / 2 + 1);
for (int i = 0; i < size / 3; i++)
b.append('a' + (i % 26));
return b.toString();
}
}
|
/**
* Copyright (C) 2013 Arman Gal
*
* 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.clevermore.monitor.server.tasks.impl;
import javax.xml.bind.JAXBException;
import org.clevermore.monitor.server.model.DatabaseServer;
import org.clevermore.monitor.server.model.ServerStatus;
import org.clevermore.monitor.server.model.config.DatabaseConfig;
import org.clevermore.monitor.server.model.config.ServerConfig;
import org.clevermore.monitor.server.model.config.ServerGroup;
import org.clevermore.monitor.server.model.config.ServersConfig;
import org.clevermore.monitor.server.tasks.AbstractServersConnectorThread;
public class ServersConnectorThread
extends AbstractServersConnectorThread<ServerStatus, ServersConfig, DatabaseServer> {
public ServersConnectorThread()
throws JAXBException {
super();
}
@Override
public ServerStatus getServerStatus(ServerConfig sc, final ServerGroup serverGroup) {
// keeping history stats for 24 hours
return new ServerStatus(sc, serverGroup, (24 * 60 * 3), (24 * 60 * 3));
}
@Override
public DatabaseServer getDatabaseServer(DatabaseConfig dc) {
return new DatabaseServer(dc);
}
}
|
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* Description:
* 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br>
* Copyright (C), 2001-2018, Yeeku.H.Lee<br>
* This program is protected by copyright laws.<br>
* Program Name:<br>
* Date:<br>
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
public class JTabbedPaneTest
{
JFrame jf = new JFrame("测试Tab页面");
// 创建一个Tab页面的标签放在左边,采用换行布局策略的JTabbedPane
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.LEFT
, JTabbedPane.WRAP_TAB_LAYOUT);
ImageIcon icon = new ImageIcon("ico/close.gif");
String[] layouts = {"换行布局" , "滚动条布局"};
String[] positions = {"左边" , "顶部" , "右边" , "底部"};
Map<String , String> books = new LinkedHashMap<>();
public void init()
{
books.put("疯狂Java讲义" , "java.png");
books.put("轻量级Java EE企业应用实战" , "ee.png");
books.put("疯狂Ajax讲义" , "ajax.png");
books.put("疯狂Android讲义" , "android.png");
books.put("经典Java EE企业应用实战" , "classic.png");
String tip = "可看到本书的封面照片";
// 向JTabbedPane中添加5个标签页面,指定了标题、图标和提示
// 但该标签页面的组件为null
for (String bookName : books.keySet())
{
tabbedPane.addTab(bookName, icon, null , tip);
}
jf.add(tabbedPane, BorderLayout.CENTER);
// 为JTabbedPane添加事件监听器
tabbedPane.addChangeListener(event -> {
// 如果被选择的组件依然是空
if (tabbedPane.getSelectedComponent() == null)
{
// 获取所选标签页
int n = tabbedPane.getSelectedIndex();
// 为指定标前页加载内容
loadTab(n);
}
});
// 系统默认选择第一页,加载第一页内容
loadTab(0);
tabbedPane.setPreferredSize(new Dimension(500 , 300));
// 增加控制标签布局、标签位置的单选按钮
JPanel buttonPanel = new JPanel();
ChangeAction action = new ChangeAction();
buttonPanel.add(new ButtonPanel(action
, "选择标签布局策略" , layouts));
buttonPanel.add (new ButtonPanel(action
, "选择标签位置" , positions));
jf.add(buttonPanel, BorderLayout.SOUTH);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
}
// 为指定标签页加载内容
private void loadTab(int n)
{
String title = tabbedPane.getTitleAt(n);
// 根据标签页的标题获取对应图书封面
ImageIcon bookImage = new ImageIcon("ico/"
+ books.get(title));
tabbedPane.setComponentAt(n , new JLabel(bookImage));
// 改变标签页的图标
tabbedPane.setIconAt(n, new ImageIcon("ico/open.gif"));
}
// 定义改变标签页的布局策略,放置位置的监听器
class ChangeAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JRadioButton source = (JRadioButton)event.getSource();
String selection = source.getActionCommand();
// 设置标签页的标题的布局策略
if (selection.equals(layouts[0]))
{
tabbedPane.setTabLayoutPolicy(
JTabbedPane.WRAP_TAB_LAYOUT);
}
else if (selection.equals(layouts[1]))
{
tabbedPane.setTabLayoutPolicy(
JTabbedPane.SCROLL_TAB_LAYOUT);
}
// 设置标签页上的标题的放置位置
else if (selection.equals(positions[0]))
{
tabbedPane.setTabPlacement(JTabbedPane.LEFT);
}
else if (selection.equals(positions[1]))
{
tabbedPane.setTabPlacement(JTabbedPane.TOP);
}
else if (selection.equals(positions[2]))
{
tabbedPane.setTabPlacement(JTabbedPane.RIGHT);
}
else if (selection.equals(positions[3]))
{
tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);
}
}
}
public static void main(String[] args)
{
new JTabbedPaneTest().init();
}
}
// 定义一个JPanel类扩展类,该类的对象包含多个纵向排列的JRadioButton控件
// 且JPanel扩展类可以指定一个字符串作为TitledBorder
class ButtonPanel extends JPanel
{
private ButtonGroup group;
public ButtonPanel(JTabbedPaneTest.ChangeAction action
, String title, String[] labels)
{
setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
group = new ButtonGroup();
for (int i = 0; labels!= null && i < labels.length; i++)
{
JRadioButton b = new JRadioButton(labels[i]);
b.setActionCommand(labels[i]);
add(b);
// 添加事件监听器
b.addActionListener(action);
group.add(b);
b.setSelected(i == 0);
}
}
}
|
package org.rest.client.jso;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;
public class PendingAnalytics extends JavaScriptObject {
protected PendingAnalytics(){}
public final native String getType() /*-{
return this.type;
}-*/;
public final native JsArrayString getParams() /*-{
return this.params;
}-*/;
}
|
/*
* Copyright (C) 2019 The Turms Project
* https://github.com/turms-im/turms
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: request/turms_request.proto
package im.turms.server.common.access.client.dto.request;
public interface TurmsRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:im.turms.proto.TurmsRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Note: request_id is allowed to be duplicate because
* it is used for clients to identify the response of the same request id in a session
* </pre>
*
* <code>optional int64 request_id = 1;</code>
* @return Whether the requestId field is set.
*/
boolean hasRequestId();
/**
* <pre>
* Note: request_id is allowed to be duplicate because
* it is used for clients to identify the response of the same request id in a session
* </pre>
*
* <code>optional int64 request_id = 1;</code>
* @return The requestId.
*/
long getRequestId();
/**
* <pre>
* User - Session
* </pre>
*
* <code>.im.turms.proto.CreateSessionRequest create_session_request = 3;</code>
* @return Whether the createSessionRequest field is set.
*/
boolean hasCreateSessionRequest();
/**
* <pre>
* User - Session
* </pre>
*
* <code>.im.turms.proto.CreateSessionRequest create_session_request = 3;</code>
* @return The createSessionRequest.
*/
im.turms.server.common.access.client.dto.request.user.CreateSessionRequest getCreateSessionRequest();
/**
* <pre>
* User - Session
* </pre>
*
* <code>.im.turms.proto.CreateSessionRequest create_session_request = 3;</code>
*/
im.turms.server.common.access.client.dto.request.user.CreateSessionRequestOrBuilder getCreateSessionRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteSessionRequest delete_session_request = 4;</code>
* @return Whether the deleteSessionRequest field is set.
*/
boolean hasDeleteSessionRequest();
/**
* <code>.im.turms.proto.DeleteSessionRequest delete_session_request = 4;</code>
* @return The deleteSessionRequest.
*/
im.turms.server.common.access.client.dto.request.user.DeleteSessionRequest getDeleteSessionRequest();
/**
* <code>.im.turms.proto.DeleteSessionRequest delete_session_request = 4;</code>
*/
im.turms.server.common.access.client.dto.request.user.DeleteSessionRequestOrBuilder getDeleteSessionRequestOrBuilder();
/**
* <pre>
* Conversation
* </pre>
*
* <code>.im.turms.proto.QueryConversationsRequest query_conversations_request = 5;</code>
* @return Whether the queryConversationsRequest field is set.
*/
boolean hasQueryConversationsRequest();
/**
* <pre>
* Conversation
* </pre>
*
* <code>.im.turms.proto.QueryConversationsRequest query_conversations_request = 5;</code>
* @return The queryConversationsRequest.
*/
im.turms.server.common.access.client.dto.request.conversation.QueryConversationsRequest getQueryConversationsRequest();
/**
* <pre>
* Conversation
* </pre>
*
* <code>.im.turms.proto.QueryConversationsRequest query_conversations_request = 5;</code>
*/
im.turms.server.common.access.client.dto.request.conversation.QueryConversationsRequestOrBuilder getQueryConversationsRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateConversationRequest update_conversation_request = 6;</code>
* @return Whether the updateConversationRequest field is set.
*/
boolean hasUpdateConversationRequest();
/**
* <code>.im.turms.proto.UpdateConversationRequest update_conversation_request = 6;</code>
* @return The updateConversationRequest.
*/
im.turms.server.common.access.client.dto.request.conversation.UpdateConversationRequest getUpdateConversationRequest();
/**
* <code>.im.turms.proto.UpdateConversationRequest update_conversation_request = 6;</code>
*/
im.turms.server.common.access.client.dto.request.conversation.UpdateConversationRequestOrBuilder getUpdateConversationRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateTypingStatusRequest update_typing_status_request = 7;</code>
* @return Whether the updateTypingStatusRequest field is set.
*/
boolean hasUpdateTypingStatusRequest();
/**
* <code>.im.turms.proto.UpdateTypingStatusRequest update_typing_status_request = 7;</code>
* @return The updateTypingStatusRequest.
*/
im.turms.server.common.access.client.dto.request.conversation.UpdateTypingStatusRequest getUpdateTypingStatusRequest();
/**
* <code>.im.turms.proto.UpdateTypingStatusRequest update_typing_status_request = 7;</code>
*/
im.turms.server.common.access.client.dto.request.conversation.UpdateTypingStatusRequestOrBuilder getUpdateTypingStatusRequestOrBuilder();
/**
* <pre>
* Message
* </pre>
*
* <code>.im.turms.proto.CreateMessageRequest create_message_request = 8;</code>
* @return Whether the createMessageRequest field is set.
*/
boolean hasCreateMessageRequest();
/**
* <pre>
* Message
* </pre>
*
* <code>.im.turms.proto.CreateMessageRequest create_message_request = 8;</code>
* @return The createMessageRequest.
*/
im.turms.server.common.access.client.dto.request.message.CreateMessageRequest getCreateMessageRequest();
/**
* <pre>
* Message
* </pre>
*
* <code>.im.turms.proto.CreateMessageRequest create_message_request = 8;</code>
*/
im.turms.server.common.access.client.dto.request.message.CreateMessageRequestOrBuilder getCreateMessageRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryMessagesRequest query_messages_request = 9;</code>
* @return Whether the queryMessagesRequest field is set.
*/
boolean hasQueryMessagesRequest();
/**
* <code>.im.turms.proto.QueryMessagesRequest query_messages_request = 9;</code>
* @return The queryMessagesRequest.
*/
im.turms.server.common.access.client.dto.request.message.QueryMessagesRequest getQueryMessagesRequest();
/**
* <code>.im.turms.proto.QueryMessagesRequest query_messages_request = 9;</code>
*/
im.turms.server.common.access.client.dto.request.message.QueryMessagesRequestOrBuilder getQueryMessagesRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateMessageRequest update_message_request = 10;</code>
* @return Whether the updateMessageRequest field is set.
*/
boolean hasUpdateMessageRequest();
/**
* <code>.im.turms.proto.UpdateMessageRequest update_message_request = 10;</code>
* @return The updateMessageRequest.
*/
im.turms.server.common.access.client.dto.request.message.UpdateMessageRequest getUpdateMessageRequest();
/**
* <code>.im.turms.proto.UpdateMessageRequest update_message_request = 10;</code>
*/
im.turms.server.common.access.client.dto.request.message.UpdateMessageRequestOrBuilder getUpdateMessageRequestOrBuilder();
/**
* <pre>
* Group Member
* </pre>
*
* <code>.im.turms.proto.CreateGroupMemberRequest create_group_member_request = 11;</code>
* @return Whether the createGroupMemberRequest field is set.
*/
boolean hasCreateGroupMemberRequest();
/**
* <pre>
* Group Member
* </pre>
*
* <code>.im.turms.proto.CreateGroupMemberRequest create_group_member_request = 11;</code>
* @return The createGroupMemberRequest.
*/
im.turms.server.common.access.client.dto.request.group.member.CreateGroupMemberRequest getCreateGroupMemberRequest();
/**
* <pre>
* Group Member
* </pre>
*
* <code>.im.turms.proto.CreateGroupMemberRequest create_group_member_request = 11;</code>
*/
im.turms.server.common.access.client.dto.request.group.member.CreateGroupMemberRequestOrBuilder getCreateGroupMemberRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteGroupMemberRequest delete_group_member_request = 12;</code>
* @return Whether the deleteGroupMemberRequest field is set.
*/
boolean hasDeleteGroupMemberRequest();
/**
* <code>.im.turms.proto.DeleteGroupMemberRequest delete_group_member_request = 12;</code>
* @return The deleteGroupMemberRequest.
*/
im.turms.server.common.access.client.dto.request.group.member.DeleteGroupMemberRequest getDeleteGroupMemberRequest();
/**
* <code>.im.turms.proto.DeleteGroupMemberRequest delete_group_member_request = 12;</code>
*/
im.turms.server.common.access.client.dto.request.group.member.DeleteGroupMemberRequestOrBuilder getDeleteGroupMemberRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryGroupMembersRequest query_group_members_request = 13;</code>
* @return Whether the queryGroupMembersRequest field is set.
*/
boolean hasQueryGroupMembersRequest();
/**
* <code>.im.turms.proto.QueryGroupMembersRequest query_group_members_request = 13;</code>
* @return The queryGroupMembersRequest.
*/
im.turms.server.common.access.client.dto.request.group.member.QueryGroupMembersRequest getQueryGroupMembersRequest();
/**
* <code>.im.turms.proto.QueryGroupMembersRequest query_group_members_request = 13;</code>
*/
im.turms.server.common.access.client.dto.request.group.member.QueryGroupMembersRequestOrBuilder getQueryGroupMembersRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateGroupMemberRequest update_group_member_request = 14;</code>
* @return Whether the updateGroupMemberRequest field is set.
*/
boolean hasUpdateGroupMemberRequest();
/**
* <code>.im.turms.proto.UpdateGroupMemberRequest update_group_member_request = 14;</code>
* @return The updateGroupMemberRequest.
*/
im.turms.server.common.access.client.dto.request.group.member.UpdateGroupMemberRequest getUpdateGroupMemberRequest();
/**
* <code>.im.turms.proto.UpdateGroupMemberRequest update_group_member_request = 14;</code>
*/
im.turms.server.common.access.client.dto.request.group.member.UpdateGroupMemberRequestOrBuilder getUpdateGroupMemberRequestOrBuilder();
/**
* <pre>
* User
* </pre>
*
* <code>.im.turms.proto.QueryUserProfileRequest query_user_profile_request = 100;</code>
* @return Whether the queryUserProfileRequest field is set.
*/
boolean hasQueryUserProfileRequest();
/**
* <pre>
* User
* </pre>
*
* <code>.im.turms.proto.QueryUserProfileRequest query_user_profile_request = 100;</code>
* @return The queryUserProfileRequest.
*/
im.turms.server.common.access.client.dto.request.user.QueryUserProfileRequest getQueryUserProfileRequest();
/**
* <pre>
* User
* </pre>
*
* <code>.im.turms.proto.QueryUserProfileRequest query_user_profile_request = 100;</code>
*/
im.turms.server.common.access.client.dto.request.user.QueryUserProfileRequestOrBuilder getQueryUserProfileRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryNearbyUsersRequest query_nearby_users_request = 101;</code>
* @return Whether the queryNearbyUsersRequest field is set.
*/
boolean hasQueryNearbyUsersRequest();
/**
* <code>.im.turms.proto.QueryNearbyUsersRequest query_nearby_users_request = 101;</code>
* @return The queryNearbyUsersRequest.
*/
im.turms.server.common.access.client.dto.request.user.QueryNearbyUsersRequest getQueryNearbyUsersRequest();
/**
* <code>.im.turms.proto.QueryNearbyUsersRequest query_nearby_users_request = 101;</code>
*/
im.turms.server.common.access.client.dto.request.user.QueryNearbyUsersRequestOrBuilder getQueryNearbyUsersRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryUserOnlineStatusesRequest query_user_online_statuses_request = 102;</code>
* @return Whether the queryUserOnlineStatusesRequest field is set.
*/
boolean hasQueryUserOnlineStatusesRequest();
/**
* <code>.im.turms.proto.QueryUserOnlineStatusesRequest query_user_online_statuses_request = 102;</code>
* @return The queryUserOnlineStatusesRequest.
*/
im.turms.server.common.access.client.dto.request.user.QueryUserOnlineStatusesRequest getQueryUserOnlineStatusesRequest();
/**
* <code>.im.turms.proto.QueryUserOnlineStatusesRequest query_user_online_statuses_request = 102;</code>
*/
im.turms.server.common.access.client.dto.request.user.QueryUserOnlineStatusesRequestOrBuilder getQueryUserOnlineStatusesRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateUserLocationRequest update_user_location_request = 103;</code>
* @return Whether the updateUserLocationRequest field is set.
*/
boolean hasUpdateUserLocationRequest();
/**
* <code>.im.turms.proto.UpdateUserLocationRequest update_user_location_request = 103;</code>
* @return The updateUserLocationRequest.
*/
im.turms.server.common.access.client.dto.request.user.UpdateUserLocationRequest getUpdateUserLocationRequest();
/**
* <code>.im.turms.proto.UpdateUserLocationRequest update_user_location_request = 103;</code>
*/
im.turms.server.common.access.client.dto.request.user.UpdateUserLocationRequestOrBuilder getUpdateUserLocationRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateUserOnlineStatusRequest update_user_online_status_request = 104;</code>
* @return Whether the updateUserOnlineStatusRequest field is set.
*/
boolean hasUpdateUserOnlineStatusRequest();
/**
* <code>.im.turms.proto.UpdateUserOnlineStatusRequest update_user_online_status_request = 104;</code>
* @return The updateUserOnlineStatusRequest.
*/
im.turms.server.common.access.client.dto.request.user.UpdateUserOnlineStatusRequest getUpdateUserOnlineStatusRequest();
/**
* <code>.im.turms.proto.UpdateUserOnlineStatusRequest update_user_online_status_request = 104;</code>
*/
im.turms.server.common.access.client.dto.request.user.UpdateUserOnlineStatusRequestOrBuilder getUpdateUserOnlineStatusRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateUserRequest update_user_request = 105;</code>
* @return Whether the updateUserRequest field is set.
*/
boolean hasUpdateUserRequest();
/**
* <code>.im.turms.proto.UpdateUserRequest update_user_request = 105;</code>
* @return The updateUserRequest.
*/
im.turms.server.common.access.client.dto.request.user.UpdateUserRequest getUpdateUserRequest();
/**
* <code>.im.turms.proto.UpdateUserRequest update_user_request = 105;</code>
*/
im.turms.server.common.access.client.dto.request.user.UpdateUserRequestOrBuilder getUpdateUserRequestOrBuilder();
/**
* <pre>
* User Relationship
* </pre>
*
* <code>.im.turms.proto.CreateFriendRequestRequest create_friend_request_request = 200;</code>
* @return Whether the createFriendRequestRequest field is set.
*/
boolean hasCreateFriendRequestRequest();
/**
* <pre>
* User Relationship
* </pre>
*
* <code>.im.turms.proto.CreateFriendRequestRequest create_friend_request_request = 200;</code>
* @return The createFriendRequestRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.CreateFriendRequestRequest getCreateFriendRequestRequest();
/**
* <pre>
* User Relationship
* </pre>
*
* <code>.im.turms.proto.CreateFriendRequestRequest create_friend_request_request = 200;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.CreateFriendRequestRequestOrBuilder getCreateFriendRequestRequestOrBuilder();
/**
* <code>.im.turms.proto.CreateRelationshipGroupRequest create_relationship_group_request = 201;</code>
* @return Whether the createRelationshipGroupRequest field is set.
*/
boolean hasCreateRelationshipGroupRequest();
/**
* <code>.im.turms.proto.CreateRelationshipGroupRequest create_relationship_group_request = 201;</code>
* @return The createRelationshipGroupRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.CreateRelationshipGroupRequest getCreateRelationshipGroupRequest();
/**
* <code>.im.turms.proto.CreateRelationshipGroupRequest create_relationship_group_request = 201;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.CreateRelationshipGroupRequestOrBuilder getCreateRelationshipGroupRequestOrBuilder();
/**
* <code>.im.turms.proto.CreateRelationshipRequest create_relationship_request = 202;</code>
* @return Whether the createRelationshipRequest field is set.
*/
boolean hasCreateRelationshipRequest();
/**
* <code>.im.turms.proto.CreateRelationshipRequest create_relationship_request = 202;</code>
* @return The createRelationshipRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.CreateRelationshipRequest getCreateRelationshipRequest();
/**
* <code>.im.turms.proto.CreateRelationshipRequest create_relationship_request = 202;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.CreateRelationshipRequestOrBuilder getCreateRelationshipRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteRelationshipGroupRequest delete_relationship_group_request = 203;</code>
* @return Whether the deleteRelationshipGroupRequest field is set.
*/
boolean hasDeleteRelationshipGroupRequest();
/**
* <code>.im.turms.proto.DeleteRelationshipGroupRequest delete_relationship_group_request = 203;</code>
* @return The deleteRelationshipGroupRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.DeleteRelationshipGroupRequest getDeleteRelationshipGroupRequest();
/**
* <code>.im.turms.proto.DeleteRelationshipGroupRequest delete_relationship_group_request = 203;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.DeleteRelationshipGroupRequestOrBuilder getDeleteRelationshipGroupRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteRelationshipRequest delete_relationship_request = 204;</code>
* @return Whether the deleteRelationshipRequest field is set.
*/
boolean hasDeleteRelationshipRequest();
/**
* <code>.im.turms.proto.DeleteRelationshipRequest delete_relationship_request = 204;</code>
* @return The deleteRelationshipRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.DeleteRelationshipRequest getDeleteRelationshipRequest();
/**
* <code>.im.turms.proto.DeleteRelationshipRequest delete_relationship_request = 204;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.DeleteRelationshipRequestOrBuilder getDeleteRelationshipRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryFriendRequestsRequest query_friend_requests_request = 205;</code>
* @return Whether the queryFriendRequestsRequest field is set.
*/
boolean hasQueryFriendRequestsRequest();
/**
* <code>.im.turms.proto.QueryFriendRequestsRequest query_friend_requests_request = 205;</code>
* @return The queryFriendRequestsRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.QueryFriendRequestsRequest getQueryFriendRequestsRequest();
/**
* <code>.im.turms.proto.QueryFriendRequestsRequest query_friend_requests_request = 205;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.QueryFriendRequestsRequestOrBuilder getQueryFriendRequestsRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryRelatedUserIdsRequest query_related_user_ids_request = 206;</code>
* @return Whether the queryRelatedUserIdsRequest field is set.
*/
boolean hasQueryRelatedUserIdsRequest();
/**
* <code>.im.turms.proto.QueryRelatedUserIdsRequest query_related_user_ids_request = 206;</code>
* @return The queryRelatedUserIdsRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.QueryRelatedUserIdsRequest getQueryRelatedUserIdsRequest();
/**
* <code>.im.turms.proto.QueryRelatedUserIdsRequest query_related_user_ids_request = 206;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.QueryRelatedUserIdsRequestOrBuilder getQueryRelatedUserIdsRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryRelationshipGroupsRequest query_relationship_groups_request = 207;</code>
* @return Whether the queryRelationshipGroupsRequest field is set.
*/
boolean hasQueryRelationshipGroupsRequest();
/**
* <code>.im.turms.proto.QueryRelationshipGroupsRequest query_relationship_groups_request = 207;</code>
* @return The queryRelationshipGroupsRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.QueryRelationshipGroupsRequest getQueryRelationshipGroupsRequest();
/**
* <code>.im.turms.proto.QueryRelationshipGroupsRequest query_relationship_groups_request = 207;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.QueryRelationshipGroupsRequestOrBuilder getQueryRelationshipGroupsRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryRelationshipsRequest query_relationships_request = 208;</code>
* @return Whether the queryRelationshipsRequest field is set.
*/
boolean hasQueryRelationshipsRequest();
/**
* <code>.im.turms.proto.QueryRelationshipsRequest query_relationships_request = 208;</code>
* @return The queryRelationshipsRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.QueryRelationshipsRequest getQueryRelationshipsRequest();
/**
* <code>.im.turms.proto.QueryRelationshipsRequest query_relationships_request = 208;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.QueryRelationshipsRequestOrBuilder getQueryRelationshipsRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateFriendRequestRequest update_friend_request_request = 209;</code>
* @return Whether the updateFriendRequestRequest field is set.
*/
boolean hasUpdateFriendRequestRequest();
/**
* <code>.im.turms.proto.UpdateFriendRequestRequest update_friend_request_request = 209;</code>
* @return The updateFriendRequestRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.UpdateFriendRequestRequest getUpdateFriendRequestRequest();
/**
* <code>.im.turms.proto.UpdateFriendRequestRequest update_friend_request_request = 209;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.UpdateFriendRequestRequestOrBuilder getUpdateFriendRequestRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateRelationshipGroupRequest update_relationship_group_request = 210;</code>
* @return Whether the updateRelationshipGroupRequest field is set.
*/
boolean hasUpdateRelationshipGroupRequest();
/**
* <code>.im.turms.proto.UpdateRelationshipGroupRequest update_relationship_group_request = 210;</code>
* @return The updateRelationshipGroupRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.UpdateRelationshipGroupRequest getUpdateRelationshipGroupRequest();
/**
* <code>.im.turms.proto.UpdateRelationshipGroupRequest update_relationship_group_request = 210;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.UpdateRelationshipGroupRequestOrBuilder getUpdateRelationshipGroupRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateRelationshipRequest update_relationship_request = 211;</code>
* @return Whether the updateRelationshipRequest field is set.
*/
boolean hasUpdateRelationshipRequest();
/**
* <code>.im.turms.proto.UpdateRelationshipRequest update_relationship_request = 211;</code>
* @return The updateRelationshipRequest.
*/
im.turms.server.common.access.client.dto.request.user.relationship.UpdateRelationshipRequest getUpdateRelationshipRequest();
/**
* <code>.im.turms.proto.UpdateRelationshipRequest update_relationship_request = 211;</code>
*/
im.turms.server.common.access.client.dto.request.user.relationship.UpdateRelationshipRequestOrBuilder getUpdateRelationshipRequestOrBuilder();
/**
* <pre>
* Group
* </pre>
*
* <code>.im.turms.proto.CreateGroupRequest create_group_request = 300;</code>
* @return Whether the createGroupRequest field is set.
*/
boolean hasCreateGroupRequest();
/**
* <pre>
* Group
* </pre>
*
* <code>.im.turms.proto.CreateGroupRequest create_group_request = 300;</code>
* @return The createGroupRequest.
*/
im.turms.server.common.access.client.dto.request.group.CreateGroupRequest getCreateGroupRequest();
/**
* <pre>
* Group
* </pre>
*
* <code>.im.turms.proto.CreateGroupRequest create_group_request = 300;</code>
*/
im.turms.server.common.access.client.dto.request.group.CreateGroupRequestOrBuilder getCreateGroupRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteGroupRequest delete_group_request = 301;</code>
* @return Whether the deleteGroupRequest field is set.
*/
boolean hasDeleteGroupRequest();
/**
* <code>.im.turms.proto.DeleteGroupRequest delete_group_request = 301;</code>
* @return The deleteGroupRequest.
*/
im.turms.server.common.access.client.dto.request.group.DeleteGroupRequest getDeleteGroupRequest();
/**
* <code>.im.turms.proto.DeleteGroupRequest delete_group_request = 301;</code>
*/
im.turms.server.common.access.client.dto.request.group.DeleteGroupRequestOrBuilder getDeleteGroupRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryGroupRequest query_group_request = 302;</code>
* @return Whether the queryGroupRequest field is set.
*/
boolean hasQueryGroupRequest();
/**
* <code>.im.turms.proto.QueryGroupRequest query_group_request = 302;</code>
* @return The queryGroupRequest.
*/
im.turms.server.common.access.client.dto.request.group.QueryGroupRequest getQueryGroupRequest();
/**
* <code>.im.turms.proto.QueryGroupRequest query_group_request = 302;</code>
*/
im.turms.server.common.access.client.dto.request.group.QueryGroupRequestOrBuilder getQueryGroupRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryJoinedGroupIdsRequest query_joined_group_ids_request = 303;</code>
* @return Whether the queryJoinedGroupIdsRequest field is set.
*/
boolean hasQueryJoinedGroupIdsRequest();
/**
* <code>.im.turms.proto.QueryJoinedGroupIdsRequest query_joined_group_ids_request = 303;</code>
* @return The queryJoinedGroupIdsRequest.
*/
im.turms.server.common.access.client.dto.request.group.QueryJoinedGroupIdsRequest getQueryJoinedGroupIdsRequest();
/**
* <code>.im.turms.proto.QueryJoinedGroupIdsRequest query_joined_group_ids_request = 303;</code>
*/
im.turms.server.common.access.client.dto.request.group.QueryJoinedGroupIdsRequestOrBuilder getQueryJoinedGroupIdsRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryJoinedGroupInfosRequest query_joined_group_infos_request = 304;</code>
* @return Whether the queryJoinedGroupInfosRequest field is set.
*/
boolean hasQueryJoinedGroupInfosRequest();
/**
* <code>.im.turms.proto.QueryJoinedGroupInfosRequest query_joined_group_infos_request = 304;</code>
* @return The queryJoinedGroupInfosRequest.
*/
im.turms.server.common.access.client.dto.request.group.QueryJoinedGroupInfosRequest getQueryJoinedGroupInfosRequest();
/**
* <code>.im.turms.proto.QueryJoinedGroupInfosRequest query_joined_group_infos_request = 304;</code>
*/
im.turms.server.common.access.client.dto.request.group.QueryJoinedGroupInfosRequestOrBuilder getQueryJoinedGroupInfosRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateGroupRequest update_group_request = 305;</code>
* @return Whether the updateGroupRequest field is set.
*/
boolean hasUpdateGroupRequest();
/**
* <code>.im.turms.proto.UpdateGroupRequest update_group_request = 305;</code>
* @return The updateGroupRequest.
*/
im.turms.server.common.access.client.dto.request.group.UpdateGroupRequest getUpdateGroupRequest();
/**
* <code>.im.turms.proto.UpdateGroupRequest update_group_request = 305;</code>
*/
im.turms.server.common.access.client.dto.request.group.UpdateGroupRequestOrBuilder getUpdateGroupRequestOrBuilder();
/**
* <pre>
* Group Blocklist
* </pre>
*
* <code>.im.turms.proto.CreateGroupBlockedUserRequest create_group_blocked_user_request = 400;</code>
* @return Whether the createGroupBlockedUserRequest field is set.
*/
boolean hasCreateGroupBlockedUserRequest();
/**
* <pre>
* Group Blocklist
* </pre>
*
* <code>.im.turms.proto.CreateGroupBlockedUserRequest create_group_blocked_user_request = 400;</code>
* @return The createGroupBlockedUserRequest.
*/
im.turms.server.common.access.client.dto.request.group.blocklist.CreateGroupBlockedUserRequest getCreateGroupBlockedUserRequest();
/**
* <pre>
* Group Blocklist
* </pre>
*
* <code>.im.turms.proto.CreateGroupBlockedUserRequest create_group_blocked_user_request = 400;</code>
*/
im.turms.server.common.access.client.dto.request.group.blocklist.CreateGroupBlockedUserRequestOrBuilder getCreateGroupBlockedUserRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteGroupBlockedUserRequest delete_group_blocked_user_request = 401;</code>
* @return Whether the deleteGroupBlockedUserRequest field is set.
*/
boolean hasDeleteGroupBlockedUserRequest();
/**
* <code>.im.turms.proto.DeleteGroupBlockedUserRequest delete_group_blocked_user_request = 401;</code>
* @return The deleteGroupBlockedUserRequest.
*/
im.turms.server.common.access.client.dto.request.group.blocklist.DeleteGroupBlockedUserRequest getDeleteGroupBlockedUserRequest();
/**
* <code>.im.turms.proto.DeleteGroupBlockedUserRequest delete_group_blocked_user_request = 401;</code>
*/
im.turms.server.common.access.client.dto.request.group.blocklist.DeleteGroupBlockedUserRequestOrBuilder getDeleteGroupBlockedUserRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryGroupBlockedUserIdsRequest query_group_blocked_user_ids_request = 402;</code>
* @return Whether the queryGroupBlockedUserIdsRequest field is set.
*/
boolean hasQueryGroupBlockedUserIdsRequest();
/**
* <code>.im.turms.proto.QueryGroupBlockedUserIdsRequest query_group_blocked_user_ids_request = 402;</code>
* @return The queryGroupBlockedUserIdsRequest.
*/
im.turms.server.common.access.client.dto.request.group.blocklist.QueryGroupBlockedUserIdsRequest getQueryGroupBlockedUserIdsRequest();
/**
* <code>.im.turms.proto.QueryGroupBlockedUserIdsRequest query_group_blocked_user_ids_request = 402;</code>
*/
im.turms.server.common.access.client.dto.request.group.blocklist.QueryGroupBlockedUserIdsRequestOrBuilder getQueryGroupBlockedUserIdsRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryGroupBlockedUserInfosRequest query_group_blocked_user_infos_request = 403;</code>
* @return Whether the queryGroupBlockedUserInfosRequest field is set.
*/
boolean hasQueryGroupBlockedUserInfosRequest();
/**
* <code>.im.turms.proto.QueryGroupBlockedUserInfosRequest query_group_blocked_user_infos_request = 403;</code>
* @return The queryGroupBlockedUserInfosRequest.
*/
im.turms.server.common.access.client.dto.request.group.blocklist.QueryGroupBlockedUserInfosRequest getQueryGroupBlockedUserInfosRequest();
/**
* <code>.im.turms.proto.QueryGroupBlockedUserInfosRequest query_group_blocked_user_infos_request = 403;</code>
*/
im.turms.server.common.access.client.dto.request.group.blocklist.QueryGroupBlockedUserInfosRequestOrBuilder getQueryGroupBlockedUserInfosRequestOrBuilder();
/**
* <pre>
* Group Enrollment
* </pre>
*
* <code>.im.turms.proto.CheckGroupJoinQuestionsAnswersRequest check_group_join_questions_answers_request = 500;</code>
* @return Whether the checkGroupJoinQuestionsAnswersRequest field is set.
*/
boolean hasCheckGroupJoinQuestionsAnswersRequest();
/**
* <pre>
* Group Enrollment
* </pre>
*
* <code>.im.turms.proto.CheckGroupJoinQuestionsAnswersRequest check_group_join_questions_answers_request = 500;</code>
* @return The checkGroupJoinQuestionsAnswersRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.CheckGroupJoinQuestionsAnswersRequest getCheckGroupJoinQuestionsAnswersRequest();
/**
* <pre>
* Group Enrollment
* </pre>
*
* <code>.im.turms.proto.CheckGroupJoinQuestionsAnswersRequest check_group_join_questions_answers_request = 500;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.CheckGroupJoinQuestionsAnswersRequestOrBuilder getCheckGroupJoinQuestionsAnswersRequestOrBuilder();
/**
* <code>.im.turms.proto.CreateGroupInvitationRequest create_group_invitation_request = 501;</code>
* @return Whether the createGroupInvitationRequest field is set.
*/
boolean hasCreateGroupInvitationRequest();
/**
* <code>.im.turms.proto.CreateGroupInvitationRequest create_group_invitation_request = 501;</code>
* @return The createGroupInvitationRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.CreateGroupInvitationRequest getCreateGroupInvitationRequest();
/**
* <code>.im.turms.proto.CreateGroupInvitationRequest create_group_invitation_request = 501;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.CreateGroupInvitationRequestOrBuilder getCreateGroupInvitationRequestOrBuilder();
/**
* <code>.im.turms.proto.CreateGroupJoinRequestRequest create_group_join_request_request = 502;</code>
* @return Whether the createGroupJoinRequestRequest field is set.
*/
boolean hasCreateGroupJoinRequestRequest();
/**
* <code>.im.turms.proto.CreateGroupJoinRequestRequest create_group_join_request_request = 502;</code>
* @return The createGroupJoinRequestRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.CreateGroupJoinRequestRequest getCreateGroupJoinRequestRequest();
/**
* <code>.im.turms.proto.CreateGroupJoinRequestRequest create_group_join_request_request = 502;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.CreateGroupJoinRequestRequestOrBuilder getCreateGroupJoinRequestRequestOrBuilder();
/**
* <code>.im.turms.proto.CreateGroupJoinQuestionRequest create_group_join_question_request = 503;</code>
* @return Whether the createGroupJoinQuestionRequest field is set.
*/
boolean hasCreateGroupJoinQuestionRequest();
/**
* <code>.im.turms.proto.CreateGroupJoinQuestionRequest create_group_join_question_request = 503;</code>
* @return The createGroupJoinQuestionRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.CreateGroupJoinQuestionRequest getCreateGroupJoinQuestionRequest();
/**
* <code>.im.turms.proto.CreateGroupJoinQuestionRequest create_group_join_question_request = 503;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.CreateGroupJoinQuestionRequestOrBuilder getCreateGroupJoinQuestionRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteGroupInvitationRequest delete_group_invitation_request = 504;</code>
* @return Whether the deleteGroupInvitationRequest field is set.
*/
boolean hasDeleteGroupInvitationRequest();
/**
* <code>.im.turms.proto.DeleteGroupInvitationRequest delete_group_invitation_request = 504;</code>
* @return The deleteGroupInvitationRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.DeleteGroupInvitationRequest getDeleteGroupInvitationRequest();
/**
* <code>.im.turms.proto.DeleteGroupInvitationRequest delete_group_invitation_request = 504;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.DeleteGroupInvitationRequestOrBuilder getDeleteGroupInvitationRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteGroupJoinRequestRequest delete_group_join_request_request = 505;</code>
* @return Whether the deleteGroupJoinRequestRequest field is set.
*/
boolean hasDeleteGroupJoinRequestRequest();
/**
* <code>.im.turms.proto.DeleteGroupJoinRequestRequest delete_group_join_request_request = 505;</code>
* @return The deleteGroupJoinRequestRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.DeleteGroupJoinRequestRequest getDeleteGroupJoinRequestRequest();
/**
* <code>.im.turms.proto.DeleteGroupJoinRequestRequest delete_group_join_request_request = 505;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.DeleteGroupJoinRequestRequestOrBuilder getDeleteGroupJoinRequestRequestOrBuilder();
/**
* <code>.im.turms.proto.DeleteGroupJoinQuestionRequest delete_group_join_question_request = 506;</code>
* @return Whether the deleteGroupJoinQuestionRequest field is set.
*/
boolean hasDeleteGroupJoinQuestionRequest();
/**
* <code>.im.turms.proto.DeleteGroupJoinQuestionRequest delete_group_join_question_request = 506;</code>
* @return The deleteGroupJoinQuestionRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.DeleteGroupJoinQuestionRequest getDeleteGroupJoinQuestionRequest();
/**
* <code>.im.turms.proto.DeleteGroupJoinQuestionRequest delete_group_join_question_request = 506;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.DeleteGroupJoinQuestionRequestOrBuilder getDeleteGroupJoinQuestionRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryGroupInvitationsRequest query_group_invitations_request = 507;</code>
* @return Whether the queryGroupInvitationsRequest field is set.
*/
boolean hasQueryGroupInvitationsRequest();
/**
* <code>.im.turms.proto.QueryGroupInvitationsRequest query_group_invitations_request = 507;</code>
* @return The queryGroupInvitationsRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.QueryGroupInvitationsRequest getQueryGroupInvitationsRequest();
/**
* <code>.im.turms.proto.QueryGroupInvitationsRequest query_group_invitations_request = 507;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.QueryGroupInvitationsRequestOrBuilder getQueryGroupInvitationsRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryGroupJoinRequestsRequest query_group_join_requests_request = 508;</code>
* @return Whether the queryGroupJoinRequestsRequest field is set.
*/
boolean hasQueryGroupJoinRequestsRequest();
/**
* <code>.im.turms.proto.QueryGroupJoinRequestsRequest query_group_join_requests_request = 508;</code>
* @return The queryGroupJoinRequestsRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.QueryGroupJoinRequestsRequest getQueryGroupJoinRequestsRequest();
/**
* <code>.im.turms.proto.QueryGroupJoinRequestsRequest query_group_join_requests_request = 508;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.QueryGroupJoinRequestsRequestOrBuilder getQueryGroupJoinRequestsRequestOrBuilder();
/**
* <code>.im.turms.proto.QueryGroupJoinQuestionsRequest query_group_join_questions_request = 509;</code>
* @return Whether the queryGroupJoinQuestionsRequest field is set.
*/
boolean hasQueryGroupJoinQuestionsRequest();
/**
* <code>.im.turms.proto.QueryGroupJoinQuestionsRequest query_group_join_questions_request = 509;</code>
* @return The queryGroupJoinQuestionsRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.QueryGroupJoinQuestionsRequest getQueryGroupJoinQuestionsRequest();
/**
* <code>.im.turms.proto.QueryGroupJoinQuestionsRequest query_group_join_questions_request = 509;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.QueryGroupJoinQuestionsRequestOrBuilder getQueryGroupJoinQuestionsRequestOrBuilder();
/**
* <code>.im.turms.proto.UpdateGroupJoinQuestionRequest update_group_join_question_request = 510;</code>
* @return Whether the updateGroupJoinQuestionRequest field is set.
*/
boolean hasUpdateGroupJoinQuestionRequest();
/**
* <code>.im.turms.proto.UpdateGroupJoinQuestionRequest update_group_join_question_request = 510;</code>
* @return The updateGroupJoinQuestionRequest.
*/
im.turms.server.common.access.client.dto.request.group.enrollment.UpdateGroupJoinQuestionRequest getUpdateGroupJoinQuestionRequest();
/**
* <code>.im.turms.proto.UpdateGroupJoinQuestionRequest update_group_join_question_request = 510;</code>
*/
im.turms.server.common.access.client.dto.request.group.enrollment.UpdateGroupJoinQuestionRequestOrBuilder getUpdateGroupJoinQuestionRequestOrBuilder();
/**
* <pre>
* Storage
* </pre>
*
* <code>.im.turms.proto.DeleteResourceRequest delete_resource_request = 1000;</code>
* @return Whether the deleteResourceRequest field is set.
*/
boolean hasDeleteResourceRequest();
/**
* <pre>
* Storage
* </pre>
*
* <code>.im.turms.proto.DeleteResourceRequest delete_resource_request = 1000;</code>
* @return The deleteResourceRequest.
*/
im.turms.server.common.access.client.dto.request.storage.DeleteResourceRequest getDeleteResourceRequest();
/**
* <pre>
* Storage
* </pre>
*
* <code>.im.turms.proto.DeleteResourceRequest delete_resource_request = 1000;</code>
*/
im.turms.server.common.access.client.dto.request.storage.DeleteResourceRequestOrBuilder getDeleteResourceRequestOrBuilder();
/**
* <code>.im.turms.proto.QuerySignedGetUrlRequest query_signed_get_url_request = 1001;</code>
* @return Whether the querySignedGetUrlRequest field is set.
*/
boolean hasQuerySignedGetUrlRequest();
/**
* <code>.im.turms.proto.QuerySignedGetUrlRequest query_signed_get_url_request = 1001;</code>
* @return The querySignedGetUrlRequest.
*/
im.turms.server.common.access.client.dto.request.storage.QuerySignedGetUrlRequest getQuerySignedGetUrlRequest();
/**
* <code>.im.turms.proto.QuerySignedGetUrlRequest query_signed_get_url_request = 1001;</code>
*/
im.turms.server.common.access.client.dto.request.storage.QuerySignedGetUrlRequestOrBuilder getQuerySignedGetUrlRequestOrBuilder();
/**
* <code>.im.turms.proto.QuerySignedPutUrlRequest query_signed_put_url_request = 1002;</code>
* @return Whether the querySignedPutUrlRequest field is set.
*/
boolean hasQuerySignedPutUrlRequest();
/**
* <code>.im.turms.proto.QuerySignedPutUrlRequest query_signed_put_url_request = 1002;</code>
* @return The querySignedPutUrlRequest.
*/
im.turms.server.common.access.client.dto.request.storage.QuerySignedPutUrlRequest getQuerySignedPutUrlRequest();
/**
* <code>.im.turms.proto.QuerySignedPutUrlRequest query_signed_put_url_request = 1002;</code>
*/
im.turms.server.common.access.client.dto.request.storage.QuerySignedPutUrlRequestOrBuilder getQuerySignedPutUrlRequestOrBuilder();
public im.turms.server.common.access.client.dto.request.TurmsRequest.KindCase getKindCase();
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.core.build.buildable.context.BuildableContext;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.build.execution.context.StepExecutionContext;
import com.facebook.buck.core.filesystems.RelPath;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.attr.HasRuntimeDeps;
import com.facebook.buck.core.rules.attr.SupportsInputBasedRuleKey;
import com.facebook.buck.core.rules.impl.AbstractBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.io.filesystem.BuildCellRelativePath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.step.AbstractExecutionStep;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.StepExecutionResult;
import com.facebook.buck.step.StepExecutionResults;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class UnstrippedNativeLibraries extends AbstractBuildRuleWithDeclaredAndExtraDeps
implements HasRuntimeDeps, SupportsInputBasedRuleKey {
@AddToRuleKey private final ImmutableSortedSet<SourcePath> inputs;
UnstrippedNativeLibraries(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams buildRuleParams,
SourcePathRuleFinder ruleFinder,
ImmutableSortedSet<SourcePath> inputs) {
super(
buildTarget,
projectFilesystem,
buildRuleParams
.withoutExtraDeps()
.withDeclaredDeps(ImmutableSortedSet.copyOf(ruleFinder.filterBuildRuleInputs(inputs))));
this.inputs = inputs;
}
@Override
public ImmutableList<? extends Step> getBuildSteps(
BuildContext buildContext, BuildableContext buildableContext) {
buildableContext.recordArtifact(getOutputPath().getPath());
return ImmutableList.<Step>builder()
.addAll(
MakeCleanDirectoryStep.of(
BuildCellRelativePath.fromCellRelativePath(
buildContext.getBuildCellRootPath(),
getProjectFilesystem(),
getOutputPath().getParent())))
.add(
new AbstractExecutionStep("write_native_libs_paths") {
@Override
public StepExecutionResult execute(StepExecutionContext context) throws IOException {
List<String> lines =
inputs.stream()
.map(
sp ->
getProjectFilesystem()
.relativize(
buildContext.getSourcePathResolver().getAbsolutePath(sp)))
.map(Object::toString)
.collect(Collectors.toList());
getProjectFilesystem().writeLinesToPath(lines, getOutputPath());
return StepExecutionResults.SUCCESS;
}
})
.build();
}
private RelPath getOutputPath() {
return BuildTargetPaths.getGenPath(
getProjectFilesystem().getBuckPaths(), getBuildTarget(), "%s/unstripped-native-libs.txt");
}
@Override
public SourcePath getSourcePathToOutput() {
return ExplicitBuildTargetSourcePath.of(getBuildTarget(), getOutputPath());
}
@Override
public Stream<BuildTarget> getRuntimeDeps(BuildRuleResolver buildRuleResolver) {
return buildRuleResolver.filterBuildRuleInputs(inputs.stream()).map(BuildRule::getBuildTarget);
}
}
|
package com.chizganov.puzzlers.leetcode.may;
import java.util.HashSet;
import java.util.Set;
/**
* <a href="https://leetcode.com/explore/featured/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3317/">JewelsAndStones challenge</a>
*
* @author Ev Chizganov
*/
class JewelsAndStones {
int numJewelsInStones(String J, String S) {
Set<Character> jewelsSet = new HashSet<>((int) (J.length() / 0.75f) + 1);
int jewelsNum = 0;
for (char c : J.toCharArray())
jewelsSet.add(c);
for (char c : S.toCharArray())
if (jewelsSet.contains(c)) jewelsNum++;
return jewelsNum;
}
}
|
package com.ngrok.definitions;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import java.util.Optional;
/**
* A class encapsulating the {@link EventStreamList} resource.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class EventStreamList implements Pageable {
@JsonProperty("event_streams")
@JsonInclude(value = JsonInclude.Include.NON_ABSENT)
private final java.util.List<EventStream> eventStreams;
@JsonProperty("uri")
@JsonInclude(value = JsonInclude.Include.NON_ABSENT)
private final java.net.URI uri;
@JsonProperty("next_page_uri")
@JsonInclude(value = JsonInclude.Include.NON_ABSENT)
private final Optional<java.net.URI> nextPageUri;
/**
* Creates a new instance of {@link EventStreamList}.
*
* @param eventStreams The list of all Event Streams on this account.
* @param uri URI of the Event Stream list API resource.
* @param nextPageUri URI of the next page, or null if there is no next page.
*/
@JsonCreator
public EventStreamList(
@JsonProperty("event_streams") final java.util.List<EventStream> eventStreams,
@JsonProperty("uri") final java.net.URI uri,
@JsonProperty("next_page_uri") final Optional<java.net.URI> nextPageUri
) {
this.eventStreams = Objects.requireNonNull(eventStreams, "eventStreams is required");
this.uri = Objects.requireNonNull(uri, "uri is required");
this.nextPageUri = nextPageUri != null ? nextPageUri : Optional.empty();
}
/**
* The list of all Event Streams on this account.
*
* @return the value of the property as a {@link java.util.List<EventStream>}
*/
public java.util.List<EventStream> getEventStreams() {
return this.eventStreams;
}
/**
* URI of the Event Stream list API resource.
*
* @return the value of the property as a {@link java.net.URI}
*/
public java.net.URI getUri() {
return this.uri;
}
/**
* URI of the next page, or null if there is no next page.
*
* @return the value of the property as a {@link java.net.URI} wrapped in an {@link Optional}
*/
public Optional<java.net.URI> getNextPageUri() {
return this.nextPageUri;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EventStreamList other = (EventStreamList) o;
return
this.eventStreams.equals(other.eventStreams)&&
this.uri.equals(other.uri)&&
this.nextPageUri.equals(other.nextPageUri);
}
@Override
public int hashCode() {
return Objects.hash(
this.eventStreams,
this.uri,
this.nextPageUri
);
}
@Override
public String toString() {
return "EventStreamList{" +
"eventStreams='" + this.eventStreams +
"', uri='" + this.uri +
"', nextPageUri='" + this.nextPageUri.map(Object::toString).orElse("(null)") +
"'}";
}
}
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.fixtures;
import org.fest.swing.core.Robot;
import org.fest.swing.core.matcher.DialogMatcher;
import org.fest.swing.core.matcher.JLabelMatcher;
import org.fest.swing.driver.JTextComponentDriver;
import org.fest.swing.fixture.ContainerFixture;
import org.jetbrains.annotations.NotNull;
import javax.swing.text.JTextComponent;
import java.awt.*;
import static com.intellij.testGuiFramework.framework.GuiTestUtil.findAndClickOkButton;
//TODO: probably should drop it from IDEA GUI testing framework
public class ResourceChooserDialogFixture extends ComponentFixture<ResourceChooserDialogFixture, Dialog>
implements ContainerFixture<Dialog> {
@NotNull
public static ResourceChooserDialogFixture findDialog(@NotNull Robot robot) {
Dialog jDialog = robot.finder().find(DialogMatcher.withTitle("Select Resource Directory").andShowing());
return new ResourceChooserDialogFixture(robot, jDialog);
}
private ResourceChooserDialogFixture(@NotNull Robot robot, Dialog target) {
super(ResourceChooserDialogFixture.class, robot, target);
}
public void setDirectoryName(@NotNull String directory) {
Container parent = robot().finder().find(target(), JLabelMatcher.withText("Directory name:")).getParent();
JTextComponent directoryField = robot().finder().findByType(parent, JTextComponent.class, true);
JTextComponentDriver driver = new JTextComponentDriver(robot());
driver.selectAll(directoryField);
driver.setText(directoryField, directory);
}
@NotNull
public ResourceChooserDialogFixture clickOK() {
findAndClickOkButton(this);
return this;
}
}
|
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.youlai.common.core.constant;
/**
* 常量
*
* @author Mark sunlightcs@gmail.com
*/
public class RenrenConstant {
/** 超级管理员ID */
public static final int SUPER_ADMIN = 1;
/**
* 当前页码
*/
public static final String PAGE = "page";
/**
* 每页显示记录数
*/
public static final String LIMIT = "limit";
/**
* 排序字段
*/
public static final String ORDER_FIELD = "sidx";
/**
* 排序方式
*/
public static final String ORDER = "order";
/**
* 升序
*/
public static final String ASC = "asc";
/**
* 菜单类型
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年11月15日 下午1:24:29
*/
public enum MenuType {
/**
* 目录
*/
CATALOG(0),
/**
* 菜单
*/
MENU(1),
/**
* 按钮
*/
BUTTON(2);
private int value;
MenuType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* 定时任务状态
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年12月3日 上午12:07:22
*/
public enum ScheduleStatus {
/**
* 正常
*/
NORMAL(0),
/**
* 暂停
*/
PAUSE(1);
private int value;
ScheduleStatus(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* 云服务商
*/
public enum CloudService {
/**
* 七牛云
*/
QINIU(1),
/**
* 阿里云
*/
ALIYUN(2),
/**
* 腾讯云
*/
QCLOUD(3);
private int value;
CloudService(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.itest.springboot;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;
/**
* Builder for the {@code ITestConfig} that enforces defaults values.
*/
public class ITestConfigBuilder {
public static final String CONFIG_PREFIX = "itest.springboot.";
private ITestConfig config;
public ITestConfigBuilder() {
this.config = new ITestConfig();
}
public ITestConfigBuilder(ITestConfig config) {
this.config = config;
}
public ITestConfigBuilder module(String module) {
config.setModuleName(module);
return this;
}
public ITestConfigBuilder mavenGroup(String mavenGroup) {
config.setMavenGroup(mavenGroup);
return this;
}
public ITestConfigBuilder mavenVersion(String mavenVersion) {
config.setMavenVersion(mavenVersion);
return this;
}
public ITestConfigBuilder modulesPath(String path) {
config.setModulesPath(path);
return this;
}
public ITestConfigBuilder basePath(String basePath) {
config.setModuleBasePath(basePath);
return this;
}
public ITestConfigBuilder unitTestExpectedNumber(int number) {
config.setUnitTestsExpectedNumber(number);
return this;
}
public ITestConfigBuilder unitTestBasePackage(String pack) {
config.setUnitTestBasePackage(pack);
return this;
}
public ITestConfigBuilder unitTestInclusionPattern(String pattern) {
config.setUnitTestInclusionPattern(pattern);
return this;
}
public ITestConfigBuilder unitTestExclusionPattern(String pattern) {
config.setUnitTestExclusionPattern(pattern);
return this;
}
public ITestConfigBuilder autostart(Boolean autostart) {
config.setAutoStartComponent(autostart);
return this;
}
public ITestConfigBuilder resource(String file, String dest) {
if (config.getResources() == null) {
config.setResources(new HashMap<>());
}
config.getResources().put(file, dest);
return this;
}
public ITestConfigBuilder dependency(String dependencyCanonicalForm) {
if (config.getAdditionalDependencies() == null) {
config.setAdditionalDependencies(new HashSet<>());
}
config.getAdditionalDependencies().add(dependencyCanonicalForm);
return this;
}
public ITestConfigBuilder exclusion(String exclusionCanonicalForm) {
if (exclusionCanonicalForm.split(":").length != 2) {
throw new IllegalArgumentException("Expected exclusion in the form groupId:artifactId, got: " + exclusionCanonicalForm);
}
if (config.getMavenExclusions() == null) {
config.setMavenExclusions(new HashSet<String>());
}
config.getMavenExclusions().add(exclusionCanonicalForm);
return this;
}
public ITestConfigBuilder resource(String file) {
return resource(file, file);
}
public ITestConfigBuilder disableJmx(String name) {
if (config.getJmxDisabledNames() == null) {
config.setJmxDisabledNames(new TreeSet<String>());
}
config.getJmxDisabledNames().add(name);
return this;
}
public ITestConfigBuilder systemProperty(String name, String value) {
if (config.getSystemProperties() == null) {
config.setSystemProperties(new HashMap<String, String>());
}
config.getSystemProperties().put(name, value);
return this;
}
public ITestConfigBuilder customLog(Boolean value) {
config.setUseCustomLog(value);
return this;
}
public ITestConfigBuilder ignoreLibraryMismatch(String libraryPrefix) {
if (config.getIgnoreLibraryMismatch() == null) {
config.setIgnoreLibraryMismatch(new HashSet<String>());
}
config.getIgnoreLibraryMismatch().add(libraryPrefix);
return this;
}
public ITestConfigBuilder testLibraryVersion(String groupIdArtifactId, String version) {
if (config.getTestLibraryVersions() == null) {
config.setTestLibraryVersions(new HashMap<>());
}
config.getTestLibraryVersions().put(groupIdArtifactId, version);
return this;
}
public ITestConfigBuilder includeTestDependencies(Boolean includeTestDependencies) {
config.setIncludeTestDependencies(includeTestDependencies);
return this;
}
public ITestConfigBuilder unitTestsEnabled(Boolean unitTestsEnabled) {
config.setUnitTestEnabled(unitTestsEnabled);
return this;
}
public ITestConfigBuilder springBootVersion(String springBootVersion) {
config.setSpringBootVersion(springBootVersion);
return this;
}
public ITestConfig build() {
// Checking conditions
if (config.getModuleName() == null) {
fail("ModuleName is required");
}
// Set the defaults
if (config.getUnitTestEnabled() == null) {
config.setUnitTestEnabled(booleanPropertyOr("unitTestEnabled", true));
}
if (config.getMavenGroup() == null) {
config.setMavenGroup(propertyOr("mavenGroup", "org.apache.camel"));
}
if (config.getMavenVersion() == null) {
config.setMavenVersion(propertyOr("mavenVersion", null));
}
if (config.getMavenOfflineResolution() == null) {
config.setMavenOfflineResolution(booleanPropertyOr("mavenOfflineResolution", false));
}
if (config.getUnitTestInclusionPattern() == null) {
config.setUnitTestInclusionPattern(propertyOr("unitTestInclusionPattern", "^.*Test$")); // All tests
}
if (config.getUnitTestExclusionPattern() == null) {
config.setUnitTestExclusionPattern(propertyOr("unitTestExclusionPattern", ".*(\\.integration\\..*|IntegrationTest$)")); // Integration test
}
if (config.getIncludeTestDependencies() == null) {
config.setIncludeTestDependencies(booleanPropertyOr("includeTestDependencies", config.getUnitTestEnabled()));
}
if (config.getIncludeProvidedDependencies() == null) {
config.setIncludeProvidedDependencies(booleanPropertyOr("includeProvidedDependencies", false));
}
if (config.getModulesPath() == null) {
config.setModulesPath(propertyOr("modulesPath", "../components-starter/"));
}
if (config.getModuleBasePath() == null) {
config.setModuleBasePath(config.getModulesPath() + config.getModuleName() + "-starter");
}
if (config.getUnitTestBasePackage() == null) {
config.setUnitTestBasePackage(propertyOr("unitTestBasePackage", "org.apache.camel"));
}
if (config.getAutoStartComponent() == null) {
config.setAutoStartComponent(booleanPropertyOr("autostartComponent", true));
}
if (config.getResources() == null) {
config.setResources(new HashMap<>());
}
if (config.getAdditionalDependencies() == null) {
config.setAdditionalDependencies(new HashSet<>());
}
if (config.getMavenExclusions() == null) {
config.setMavenExclusions(new HashSet<>());
}
if (config.getJmxDisabledNames() == null) {
config.setJmxDisabledNames(new HashSet<>());
}
if (config.getSystemProperties() == null) {
config.setSystemProperties(new HashMap<>());
}
if (config.getUseCustomLog() == null) {
config.setUseCustomLog(booleanPropertyOr("useCustomLog", true));
}
if (config.getIgnoreLibraryMismatch() == null) {
config.setIgnoreLibraryMismatch(new HashSet<>());
}
if (config.getTestLibraryVersions() == null) {
config.setTestLibraryVersions(new HashMap<>());
}
if (config.getSpringBootVersion() == null) {
config.setSpringBootVersion(propertyOr("springBootVersion", null));
}
return config;
}
private void fail(String msg) {
throw new IllegalStateException("Configuration is not complete: " + msg);
}
private String propertyOr(String name, String defaultVal) {
String res = System.getProperty(CONFIG_PREFIX + name);
if (res == null) {
res = defaultVal;
}
return res;
}
private Boolean booleanPropertyOr(String name, Boolean defaultVal) {
String prop = propertyOr(name, null);
Boolean res = defaultVal;
if (prop != null) {
res = Boolean.valueOf(prop);
}
return res;
}
private Integer integerPropertyOr(String name, Integer defaultVal) {
String prop = propertyOr(name, null);
Integer res = defaultVal;
if (prop != null) {
res = Integer.valueOf(prop);
}
return res;
}
}
|
package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.security.risk.authentication.cancel response.
*
* @author auto create
* @since 1.0, 2019-01-07 20:51:15
*/
public class AlipaySecurityRiskAuthenticationCancelResponse extends AlipayResponse {
private static final long serialVersionUID = 5867135113936749155L;
/**
* 返回取消结果
*/
@ApiField("biz_result")
private String bizResult;
public void setBizResult(String bizResult) {
this.bizResult = bizResult;
}
public String getBizResult( ) {
return this.bizResult;
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/talent/v4beta1/event.proto
package com.google.cloud.talent.v4beta1;
public interface JobEventOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.talent.v4beta1.JobEvent)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required.
* The type of the event (see
* [JobEventType][google.cloud.talent.v4beta1.JobEvent.JobEventType]).
* </pre>
*
* <code>.google.cloud.talent.v4beta1.JobEvent.JobEventType type = 1;</code>
*/
int getTypeValue();
/**
*
*
* <pre>
* Required.
* The type of the event (see
* [JobEventType][google.cloud.talent.v4beta1.JobEvent.JobEventType]).
* </pre>
*
* <code>.google.cloud.talent.v4beta1.JobEvent.JobEventType type = 1;</code>
*/
com.google.cloud.talent.v4beta1.JobEvent.JobEventType getType();
/**
*
*
* <pre>
* Required.
* The [job name(s)][google.cloud.talent.v4beta1.Job.name] associated with
* this event. For example, if this is an
* [impression][google.cloud.talent.v4beta1.JobEvent.JobEventType.IMPRESSION]
* event, this field contains the identifiers of all jobs shown to the job
* seeker. If this was a
* [view][google.cloud.talent.v4beta1.JobEvent.JobEventType.VIEW] event, this
* field contains the identifier of the viewed job.
* The format is
* "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}", for
* example, "projects/api-test-project/tenants/foo/jobs/1234".
* </pre>
*
* <code>repeated string jobs = 2;</code>
*/
java.util.List<java.lang.String> getJobsList();
/**
*
*
* <pre>
* Required.
* The [job name(s)][google.cloud.talent.v4beta1.Job.name] associated with
* this event. For example, if this is an
* [impression][google.cloud.talent.v4beta1.JobEvent.JobEventType.IMPRESSION]
* event, this field contains the identifiers of all jobs shown to the job
* seeker. If this was a
* [view][google.cloud.talent.v4beta1.JobEvent.JobEventType.VIEW] event, this
* field contains the identifier of the viewed job.
* The format is
* "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}", for
* example, "projects/api-test-project/tenants/foo/jobs/1234".
* </pre>
*
* <code>repeated string jobs = 2;</code>
*/
int getJobsCount();
/**
*
*
* <pre>
* Required.
* The [job name(s)][google.cloud.talent.v4beta1.Job.name] associated with
* this event. For example, if this is an
* [impression][google.cloud.talent.v4beta1.JobEvent.JobEventType.IMPRESSION]
* event, this field contains the identifiers of all jobs shown to the job
* seeker. If this was a
* [view][google.cloud.talent.v4beta1.JobEvent.JobEventType.VIEW] event, this
* field contains the identifier of the viewed job.
* The format is
* "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}", for
* example, "projects/api-test-project/tenants/foo/jobs/1234".
* </pre>
*
* <code>repeated string jobs = 2;</code>
*/
java.lang.String getJobs(int index);
/**
*
*
* <pre>
* Required.
* The [job name(s)][google.cloud.talent.v4beta1.Job.name] associated with
* this event. For example, if this is an
* [impression][google.cloud.talent.v4beta1.JobEvent.JobEventType.IMPRESSION]
* event, this field contains the identifiers of all jobs shown to the job
* seeker. If this was a
* [view][google.cloud.talent.v4beta1.JobEvent.JobEventType.VIEW] event, this
* field contains the identifier of the viewed job.
* The format is
* "projects/{project_id}/tenants/{tenant_id}/jobs/{job_id}", for
* example, "projects/api-test-project/tenants/foo/jobs/1234".
* </pre>
*
* <code>repeated string jobs = 2;</code>
*/
com.google.protobuf.ByteString getJobsBytes(int index);
/**
*
*
* <pre>
* Optional.
* The [profile name][google.cloud.talent.v4beta1.Profile.name] associated
* with this client event.
* The format is
* "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}",
* for example, "projects/api-test-project/tenants/foo/profiles/bar".
* </pre>
*
* <code>string profile = 3;</code>
*/
java.lang.String getProfile();
/**
*
*
* <pre>
* Optional.
* The [profile name][google.cloud.talent.v4beta1.Profile.name] associated
* with this client event.
* The format is
* "projects/{project_id}/tenants/{tenant_id}/profiles/{profile_id}",
* for example, "projects/api-test-project/tenants/foo/profiles/bar".
* </pre>
*
* <code>string profile = 3;</code>
*/
com.google.protobuf.ByteString getProfileBytes();
}
|
import com.solacesystems.solclientj.core.SolEnum;
import com.solacesystems.solclientj.core.Solclient;
import com.solacesystems.solclientj.core.SolclientException;
import com.solacesystems.solclientj.core.event.MessageCallback;
import com.solacesystems.solclientj.core.event.SessionEventCallback;
import com.solacesystems.solclientj.core.handle.ContextHandle;
import com.solacesystems.solclientj.core.handle.Handle;
import com.solacesystems.solclientj.core.handle.MessageHandle;
import com.solacesystems.solclientj.core.handle.SessionHandle;
import com.solacesystems.solclientj.core.resource.Topic;
import java.nio.ByteBuffer;
import java.util.ArrayList;
public class TopicPublisher {
/**
* @param args
*/
public static void main(String[] args) throws SolclientException {
// Check command line arguments
if (args.length != 3) {
System.out.println("Usage: TopicPublisher <host:port> <client-username@message-vpn> <client-password>");
System.out.println();
System.exit(-1);
}
String[] userSplit = args[1].split("@");
if (userSplit.length != 2) {
System.out.println("Usage: TopicPublisher <host:port> <client-username@message-vpn> <client-password>");
System.out.println();
System.exit(-1);
}
if (userSplit[0].isEmpty()) {
System.out.println("No client-username entered");
System.out.println();
System.exit(-1);
}
if (userSplit[1].isEmpty()) {
System.out.println("No message-vpn entered");
System.out.println();
System.exit(-1);
}
String host = args[0];
String username = userSplit[0];
String vpnName = userSplit[1];
String password = args[2];
System.out.println("TopicPublisher initializing...");
// Initialize the API first
System.out.println(" Initializing the Java RTO Messaging API...");
int rc = Solclient.init(new String[0]);
assertReturnCode("Solclient.init()", rc, SolEnum.ReturnCode.OK);
// Create the context
System.out.println(" Creating a context ...");
final ContextHandle contextHandle = Solclient.Allocator.newContextHandle();
rc = Solclient.createContextForHandle(contextHandle, new String[0]);
assertReturnCode("Solclient.createContextForHandle()", rc, SolEnum.ReturnCode.OK);
// Create the Session
System.out.println(" Creating a session ...");
// [Session] -> create the session properties
ArrayList<String> sessionProperties = new ArrayList<String>();
sessionProperties.add(SessionHandle.PROPERTIES.HOST);
sessionProperties.add(host);
sessionProperties.add(SessionHandle.PROPERTIES.USERNAME);
sessionProperties.add(username);
sessionProperties.add(SessionHandle.PROPERTIES.PASSWORD);
sessionProperties.add(password);
sessionProperties.add(SessionHandle.PROPERTIES.VPN_NAME);
sessionProperties.add(vpnName);
String[] props = new String[sessionProperties.size()];
// [Session] -> define a message callback
MessageCallback messageCallback = new MessageCallback() {
@Override
public void onMessage(Handle handle) {
// Nothing to do here for publisher.
}
};
// [Session] -> define a session event callback to events such as
// connect/disconnect events
SessionEventCallback sessionEventCallback = new SessionEventCallback() {
@Override
public void onEvent(SessionHandle sessionHandle) {
System.out.println(" Received SessionEvent:" + sessionHandle.getSessionEvent());
}
};
// [Session] -> create a session handle and the actual session
final SessionHandle sessionHandle = Solclient.Allocator.newSessionHandle();
rc = contextHandle.createSessionForHandle(sessionHandle, sessionProperties.toArray(props), messageCallback,
sessionEventCallback);
assertReturnCode("contextHandle.createSession()", rc, SolEnum.ReturnCode.OK);
// [Session] -> finally connect the session
System.out.println(" Connecting session ...");
rc = sessionHandle.connect();
assertReturnCode("sessionHandle.connect()", rc, SolEnum.ReturnCode.OK);
// [Cleanup] -> disconnect session
sessionHandle.disconnect();
sessionHandle.destroy();
// [Cleanup] -> destroy the context
contextHandle.destroy();
}
/**
* Helper method to validate return codes.
*
* @param operation
* @param returnCode
* @param rc
* @throws IllegalStateException
*/
private static void assertReturnCode(String operation, int returnCode, int... rc) throws IllegalStateException {
boolean oneRCMatched = false;
for (int i = 0; i < rc.length; i++) {
if (rc[i] == returnCode) {
oneRCMatched = true;
break;
}
}
if (!oneRCMatched) {
throw new IllegalStateException(String.format("'%s' returned unexpected returnCode %d:%s", operation,
returnCode, SolEnum.ReturnCode.toString(returnCode)));
}
}
}
|
/*
* Copyright 1999-2018 Alibaba Group Holding 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.taobao.csp.sentinel.dashboard.discovery;
import java.util.List;
import java.util.Set;
public interface MachineDiscovery {
long MAX_CLIENT_LIVE_TIME_MS = 1000 * 60 * 5;
String UNKNOWN_APP_NAME = "CLUSTER_NOT_STARTED";
List<String> getAppNames();
Set<AppInfo> getBriefApps();
AppInfo getDetailApp(String app);
long addMachine(MachineInfo machineInfo);
}
|
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.i18n;
import java.util.Locale;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.LocaleResolver;
/**
* {@link LocaleResolver}实现的抽象基类。 提供对默认语言环境的支持。
*
* @author Juergen Hoeller
* @since 1.2.9
* @see #setDefaultLocale
*/
public abstract class AbstractLocaleResolver implements LocaleResolver {
@Nullable
private Locale defaultLocale;
/**
* Set a default Locale that this resolver will return if no other locale found.
*/
public void setDefaultLocale(@Nullable Locale defaultLocale) {
this.defaultLocale = defaultLocale;
}
/**
* Return the default Locale that this resolver is supposed to fall back to, if any.
*/
@Nullable
protected Locale getDefaultLocale() {
return this.defaultLocale;
}
}
|
package unluac.test;
public class LuaSpec {
public enum NumberFormat {
DEFAULT,
FLOAT,
INT32,
INT64
}
public LuaSpec() {
this.isDefault = true;
this.version = 0;
this.numberFormat = NumberFormat.DEFAULT;
this.strip = false;
}
public LuaSpec(int version) {
this.isDefault = false;
this.version = version;
this.numberFormat = NumberFormat.DEFAULT;
this.strip = false;
}
public String id() {
String id = "lua";
id += Integer.toHexString(version);
return id;
}
public void setNumberFormat(NumberFormat format) {
this.numberFormat = format;
}
public void setStrip(boolean strip) {
this.strip = strip;
}
public String getLuaCName() {
return "luac" + getVersionString() + getNumberFormatString();
}
public String[] getArgs() {
if (strip) {
return new String[]{"-s"};
} else {
return new String[]{};
}
}
public boolean compatible(String filename) {
int version = 0;
int underscore = filename.indexOf('_');
if (underscore != -1) {
String prefix = filename.substring(0, underscore);
try {
version = Integer.parseInt(prefix, 16);
} catch (NumberFormatException e) {
}
}
return version == 0 || this.version >= version;
}
private String getVersionString() {
if (isDefault) {
return "";
} else {
return Integer.toHexString(version);
}
}
private String getNumberFormatString() {
switch (numberFormat) {
case DEFAULT:
return "";
case FLOAT:
return "_float";
case INT32:
return "_int32";
case INT64:
return "_int64";
default:
throw new IllegalStateException();
}
}
private boolean isDefault;
private int version;
private NumberFormat numberFormat;
private boolean strip;
}
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package io.flutter.plugins.flutter_plugin_android_lifecycle;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int alpha = 0x7f010000;
public static final int font = 0x7f010005;
public static final int fontProviderAuthority = 0x7f010006;
public static final int fontProviderCerts = 0x7f010007;
public static final int fontProviderFetchStrategy = 0x7f010008;
public static final int fontProviderFetchTimeout = 0x7f010009;
public static final int fontProviderPackage = 0x7f01000a;
public static final int fontProviderQuery = 0x7f01000b;
public static final int fontStyle = 0x7f01000c;
public static final int fontVariationSettings = 0x7f01000d;
public static final int fontWeight = 0x7f01000e;
public static final int ttcIndex = 0x7f01001a;
}
public static final class color {
private color() {}
public static final int notification_action_color_filter = 0x7f02000b;
public static final int notification_icon_bg_color = 0x7f02000c;
public static final int ripple_material_light = 0x7f02000f;
public static final int secondary_text_default_material_light = 0x7f020011;
}
public static final class dimen {
private dimen() {}
public static final int compat_button_inset_horizontal_material = 0x7f030000;
public static final int compat_button_inset_vertical_material = 0x7f030001;
public static final int compat_button_padding_horizontal_material = 0x7f030002;
public static final int compat_button_padding_vertical_material = 0x7f030003;
public static final int compat_control_corner_material = 0x7f030004;
public static final int compat_notification_large_icon_max_height = 0x7f030005;
public static final int compat_notification_large_icon_max_width = 0x7f030006;
public static final int notification_action_icon_size = 0x7f030007;
public static final int notification_action_text_size = 0x7f030008;
public static final int notification_big_circle_margin = 0x7f030009;
public static final int notification_content_margin_start = 0x7f03000a;
public static final int notification_large_icon_height = 0x7f03000b;
public static final int notification_large_icon_width = 0x7f03000c;
public static final int notification_main_column_padding_top = 0x7f03000d;
public static final int notification_media_narrow_margin = 0x7f03000e;
public static final int notification_right_icon_size = 0x7f03000f;
public static final int notification_right_side_padding_top = 0x7f030010;
public static final int notification_small_icon_background_padding = 0x7f030011;
public static final int notification_small_icon_size_as_large = 0x7f030012;
public static final int notification_subtext_size = 0x7f030013;
public static final int notification_top_pad = 0x7f030014;
public static final int notification_top_pad_large_text = 0x7f030015;
}
public static final class drawable {
private drawable() {}
public static final int notification_action_background = 0x7f040016;
public static final int notification_bg = 0x7f040017;
public static final int notification_bg_low = 0x7f040018;
public static final int notification_bg_low_normal = 0x7f040019;
public static final int notification_bg_low_pressed = 0x7f04001a;
public static final int notification_bg_normal = 0x7f04001b;
public static final int notification_bg_normal_pressed = 0x7f04001c;
public static final int notification_icon_background = 0x7f04001d;
public static final int notification_template_icon_bg = 0x7f04001e;
public static final int notification_template_icon_low_bg = 0x7f04001f;
public static final int notification_tile_bg = 0x7f040020;
public static final int notify_panel_notification_icon_bg = 0x7f040021;
}
public static final class id {
private id() {}
public static final int accessibility_action_clickable_span = 0x7f050000;
public static final int accessibility_custom_action_0 = 0x7f050001;
public static final int accessibility_custom_action_1 = 0x7f050002;
public static final int accessibility_custom_action_10 = 0x7f050003;
public static final int accessibility_custom_action_11 = 0x7f050004;
public static final int accessibility_custom_action_12 = 0x7f050005;
public static final int accessibility_custom_action_13 = 0x7f050006;
public static final int accessibility_custom_action_14 = 0x7f050007;
public static final int accessibility_custom_action_15 = 0x7f050008;
public static final int accessibility_custom_action_16 = 0x7f050009;
public static final int accessibility_custom_action_17 = 0x7f05000a;
public static final int accessibility_custom_action_18 = 0x7f05000b;
public static final int accessibility_custom_action_19 = 0x7f05000c;
public static final int accessibility_custom_action_2 = 0x7f05000d;
public static final int accessibility_custom_action_20 = 0x7f05000e;
public static final int accessibility_custom_action_21 = 0x7f05000f;
public static final int accessibility_custom_action_22 = 0x7f050010;
public static final int accessibility_custom_action_23 = 0x7f050011;
public static final int accessibility_custom_action_24 = 0x7f050012;
public static final int accessibility_custom_action_25 = 0x7f050013;
public static final int accessibility_custom_action_26 = 0x7f050014;
public static final int accessibility_custom_action_27 = 0x7f050015;
public static final int accessibility_custom_action_28 = 0x7f050016;
public static final int accessibility_custom_action_29 = 0x7f050017;
public static final int accessibility_custom_action_3 = 0x7f050018;
public static final int accessibility_custom_action_30 = 0x7f050019;
public static final int accessibility_custom_action_31 = 0x7f05001a;
public static final int accessibility_custom_action_4 = 0x7f05001b;
public static final int accessibility_custom_action_5 = 0x7f05001c;
public static final int accessibility_custom_action_6 = 0x7f05001d;
public static final int accessibility_custom_action_7 = 0x7f05001e;
public static final int accessibility_custom_action_8 = 0x7f05001f;
public static final int accessibility_custom_action_9 = 0x7f050020;
public static final int action_container = 0x7f050022;
public static final int action_divider = 0x7f050023;
public static final int action_image = 0x7f050024;
public static final int action_text = 0x7f050025;
public static final int actions = 0x7f050026;
public static final int async = 0x7f05002a;
public static final int blocking = 0x7f05002c;
public static final int chronometer = 0x7f050032;
public static final int dialog_button = 0x7f050036;
public static final int forever = 0x7f05003c;
public static final int icon = 0x7f05003d;
public static final int icon_group = 0x7f05003e;
public static final int info = 0x7f050040;
public static final int italic = 0x7f050041;
public static final int line1 = 0x7f050044;
public static final int line3 = 0x7f050045;
public static final int normal = 0x7f050048;
public static final int notification_background = 0x7f050049;
public static final int notification_main_column = 0x7f05004a;
public static final int notification_main_column_container = 0x7f05004b;
public static final int right_icon = 0x7f05004d;
public static final int right_side = 0x7f05004e;
public static final int tag_accessibility_actions = 0x7f050052;
public static final int tag_accessibility_clickable_spans = 0x7f050053;
public static final int tag_accessibility_heading = 0x7f050054;
public static final int tag_accessibility_pane_title = 0x7f050055;
public static final int tag_screen_reader_focusable = 0x7f050056;
public static final int tag_transition_group = 0x7f050057;
public static final int tag_unhandled_key_event_manager = 0x7f050058;
public static final int tag_unhandled_key_listeners = 0x7f050059;
public static final int text = 0x7f05005a;
public static final int text2 = 0x7f05005b;
public static final int time = 0x7f05005c;
public static final int title = 0x7f05005d;
}
public static final class integer {
private integer() {}
public static final int status_bar_notification_info_maxnum = 0x7f060002;
}
public static final class layout {
private layout() {}
public static final int custom_dialog = 0x7f070000;
public static final int notification_action = 0x7f070001;
public static final int notification_action_tombstone = 0x7f070002;
public static final int notification_template_custom_big = 0x7f070009;
public static final int notification_template_icon_group = 0x7f07000a;
public static final int notification_template_part_chronometer = 0x7f07000e;
public static final int notification_template_part_time = 0x7f07000f;
}
public static final class string {
private string() {}
public static final int status_bar_notification_info_overflow = 0x7f090019;
}
public static final class style {
private style() {}
public static final int TextAppearance_Compat_Notification = 0x7f0a0001;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0a0002;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0a0004;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0a0007;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0a0009;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0a000b;
public static final int Widget_Compat_NotificationActionText = 0x7f0a000c;
}
public static final class styleable {
private styleable() {}
public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f010000 };
public static final int ColorStateListItem_android_color = 0;
public static final int ColorStateListItem_android_alpha = 1;
public static final int ColorStateListItem_alpha = 2;
public static final int[] FontFamily = { 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f010005, 0x7f01000c, 0x7f01000d, 0x7f01000e, 0x7f01001a };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_android_ttcIndex = 3;
public static final int FontFamilyFont_android_fontVariationSettings = 4;
public static final int FontFamilyFont_font = 5;
public static final int FontFamilyFont_fontStyle = 6;
public static final int FontFamilyFont_fontVariationSettings = 7;
public static final int FontFamilyFont_fontWeight = 8;
public static final int FontFamilyFont_ttcIndex = 9;
public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 };
public static final int GradientColor_android_startColor = 0;
public static final int GradientColor_android_endColor = 1;
public static final int GradientColor_android_type = 2;
public static final int GradientColor_android_centerX = 3;
public static final int GradientColor_android_centerY = 4;
public static final int GradientColor_android_gradientRadius = 5;
public static final int GradientColor_android_tileMode = 6;
public static final int GradientColor_android_centerColor = 7;
public static final int GradientColor_android_startX = 8;
public static final int GradientColor_android_startY = 9;
public static final int GradientColor_android_endX = 10;
public static final int GradientColor_android_endY = 11;
public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 };
public static final int GradientColorItem_android_color = 0;
public static final int GradientColorItem_android_offset = 1;
}
}
|
package br.com.jfernando.mudi.controller;
import java.security.Principal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import br.com.jfernando.mudi.model.Pedido;
import br.com.jfernando.mudi.model.StatusPedido;
import br.com.jfernando.mudi.repository.PedidoRepository;
@Controller
@RequestMapping("usuario")
public class UserController {
@Autowired
private PedidoRepository pedidoRepository;
@GetMapping("pedido")
public String home(Model model, Principal principal) {
List<Pedido> pedidos = pedidoRepository.findByUser(principal.getName());
model.addAttribute("pedidos", pedidos);
return "usuario/home"; //nome da view.
}
@GetMapping("pedido/{status}")
public String byStatus(@PathVariable String status, Model model, Principal principal) {
List<Pedido> pedidos = pedidoRepository.findByUserAndStatus
(StatusPedido.valueOf(status.toUpperCase()), principal.getName());
model.addAttribute("pedidos", pedidos);
model.addAttribute("status", status);
return "usuario/home";
}
@ExceptionHandler(IllegalArgumentException.class)
public String onError() {
return "redirect:/usuario/home";
}
}
|
/**
* Copyright © 2013 enioka. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.enioka.jqm.model;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.enioka.jqm.jdbc.DatabaseException;
import com.enioka.jqm.jdbc.DbConn;
import com.enioka.jqm.jdbc.NoResultException;
import com.enioka.jqm.jdbc.NonUniqueResultException;
import com.enioka.jqm.jdbc.QueryResult;
/**
* <strong>Not part of any API - this an internal JQM class and may change without notice.</strong> <br>
* Persistence class for storing the PKI root key.
*/
public class PKI implements Serializable
{
private static final long serialVersionUID = -1830546620049033739L;
private Integer id;
private String prettyName;
private String pemPK;
private String pemCert;
public Integer getId()
{
return id;
}
void setId(Integer id)
{
this.id = id;
}
public String getPrettyName()
{
return prettyName;
}
public void setPrettyName(String prettyName)
{
this.prettyName = prettyName;
}
public String getPemPK()
{
return pemPK;
}
public void setPemPK(String pemPK)
{
this.pemPK = pemPK;
}
public String getPemCert()
{
return pemCert;
}
public void setPemCert(String pemCert)
{
this.pemCert = pemCert;
}
public static List<PKI> select(DbConn cnx, String query_key, Object... args)
{
List<PKI> res = new ArrayList<>();
try
{
ResultSet rs = cnx.runSelect(query_key, args);
while (rs.next())
{
PKI tmp = new PKI();
tmp.id = rs.getInt(1);
tmp.pemCert = rs.getString(2);
tmp.pemPK = rs.getString(3);
tmp.prettyName = rs.getString(4);
res.add(tmp);
}
}
catch (SQLException e)
{
throw new DatabaseException(e);
}
return res;
}
public static PKI select_key(DbConn cnx, String key)
{
List<PKI> pp = select(cnx, "pki_select_by_key", key);
if (pp.size() == 0)
{
throw new NoResultException("No PKI with key " + key);
}
if (pp.size() > 1)
{
throw new NonUniqueResultException("Configuration is not valid");
}
return pp.get(0);
}
public static int create(DbConn cnx, String alias, String pemPK, String pemCert)
{
QueryResult qr = cnx.runUpdate("pki_insert", pemCert, pemPK, alias);
return qr.getGeneratedId();
}
}
|
package org.opencds.cqf.tooling.npm;
import java.io.IOException;
import java.io.InputStream;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.r5.model.Library;
public interface ILibraryReader {
public Library readLibrary(InputStream stream) throws FHIRFormatError, IOException;
}
|
/*
* 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.context.support;
import java.io.IOException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
/**
* Convenient base class for {@link org.springframework.context.ApplicationContext}
* implementations, drawing configuration from XML documents containing bean definitions
* understood by an {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}.
*
* <p>Subclasses just have to implement the {@link #getConfigResources} and/or
* the {@link #getConfigLocations} method. Furthermore, they might override
* the {@link #getResourceByPath} hook to interpret relative paths in an
* environment-specific fashion, and/or {@link #getResourcePatternResolver}
* for extended pattern resolution.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see #getConfigResources
* @see #getConfigLocations
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
*/
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
private boolean validating = true;
/**
* Create a new AbstractXmlApplicationContext with no parent.
*/
public AbstractXmlApplicationContext() {
}
/**
* Create a new AbstractXmlApplicationContext with the given parent context.
* @param parent the parent context
*/
public AbstractXmlApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
/**
* Set whether to use XML validation. Default is {@code true}.
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Loads the bean definitions via an XmlBeanDefinitionReader.
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
* @see #initBeanDefinitionReader
* @see #loadBeanDefinitions
我们可以看到,此方法将通过一个 XmlBeanDefinitionReader 实例来加载各个 Bean。*/
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
// 给这个 BeanFactory 实例化一个 XmlBeanDefinitionReader
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
// 对beanDefinitionReader进行环境变量配置
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
// 初始化 BeanDefinitionReader,其实这个是提供给子类覆写的,
initBeanDefinitionReader(beanDefinitionReader);
// 配置文件读取
loadBeanDefinitions(beanDefinitionReader);
}
/**
* Initialize the bean definition reader used for loading the bean
* definitions of this context. Default implementation is empty.
* <p>Can be overridden in subclasses, e.g. for turning off XML validation
* or using a different XmlBeanDefinitionParser implementation.
* @param reader the bean definition reader used by this context
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader#setDocumentReaderClass
*/
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
reader.setValidating(this.validating);
}
/**
* Load the bean definitions with the given XmlBeanDefinitionReader.
* <p>The lifecycle of the bean factory is handled by the {@link #refreshBeanFactory}
* method; hence this method is just supposed to load and/or register bean definitions.
* @param reader the XmlBeanDefinitionReader to use
* @throws BeansException in case of bean registration errors
* @throws IOException if the required XML document isn't found
* @see #refreshBeanFactory
* @see #getConfigLocations
* @see #getResources
* @see #getResourcePatternResolver
*/
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
/**
* Return an array of Resource objects, referring to the XML bean definition
* files that this context should be built with.
* <p>The default implementation returns {@code null}. Subclasses can override
* this to provide pre-built Resource objects rather than location Strings.
* @return an array of Resource objects, or {@code null} if none
* @see #getConfigLocations()
*/
@Nullable
protected Resource[] getConfigResources() {
return null;
}
}
|
import java.util.LinkedList;
class Monitor {
LinkedList<Request> requests_s0, requests_s1, requests_s2, requests_s3;
Request request_s1_1, request_s1_2;
private int idx;
private boolean cpu;
double util_time_s0, util_time_s1_1, util_time_s1_2, util_time_s2, util_time_s3, no_of_requests, no_of_requests_s0,
no_of_requests_s1, no_of_requests_s2, no_of_requests_s3, no_of_monitor_requests, response_time, response_time_s0,
response_time_s1, response_time_s2, response_time_s3, dropped_s2, no_of_completed_requests,
no_of_completed_requests_s0, no_of_completed_requests_s1, no_of_completed_requests_s2,
no_of_completed_requests_s3;
public Monitor() {
idx = -1;
cpu = false;
request_s1_1 = null;
request_s1_2 = null;
requests_s0 = new LinkedList<Request>();
requests_s1 = new LinkedList<Request>();
requests_s2 = new LinkedList<Request>();
requests_s3 = new LinkedList<Request>();
util_time_s0 = 0;
util_time_s1_1 = 0;
util_time_s1_2 = 0;
util_time_s2 = 0;
util_time_s3 = 0;
no_of_monitor_requests = 0;
no_of_requests = 0;
no_of_requests_s0 = 0;
no_of_requests_s1 = 0;
no_of_requests_s2 = 0;
no_of_requests_s3 = 0;
response_time = 0;
response_time_s0 = 0;
response_time_s1 = 0;
response_time_s2 = 0;
response_time_s3 = 0;
dropped_s2 = 0;
no_of_completed_requests = 0;
no_of_completed_requests_s0 = 0;
no_of_completed_requests_s1 = 0;
no_of_completed_requests_s2 = 0;
no_of_completed_requests_s3 = 0;
}
public int getID() {
return ++idx;
}
public double getUtilS0(double time) {
return util_time_s0 / time;
}
public double getUtilS1_1(double time) {
return util_time_s1_1 / time;
}
public double getUtilS1_2(double time) {
return util_time_s1_2 / time;
}
public double getUtilS2(double time) {
return util_time_s2 / time;
}
public double getUtilS3(double time) {
return util_time_s3 / time;
}
public double averageResponseTimeS0() {
return response_time_s0 / no_of_completed_requests_s0;
}
public double averageResponseTimeS1() {
return response_time_s1 / no_of_completed_requests_s1;
}
public double averageResponseTimeS2() {
return response_time_s2 / no_of_completed_requests_s2;
}
public double averageResponseTimeS3() {
return response_time_s3 / no_of_completed_requests_s3;
}
public double averageResponseTime() {
return response_time / no_of_completed_requests;
}
public double averageQueueLengthS0() {
return no_of_requests_s0 / no_of_monitor_requests;
}
public double averageQueueLengthS1() {
return no_of_requests_s1 / no_of_monitor_requests;
}
public double averageQueueLengthS2() {
return no_of_requests_s2 / no_of_monitor_requests;
}
public double averageQueueLengthS3() {
return no_of_requests_s3 / no_of_monitor_requests;
}
public double averageQueueLength() {
return no_of_requests / no_of_monitor_requests;
}
public boolean getNextCPU() {
cpu = !cpu;
return cpu;
}
}
|
package nfs.entities.races.normalRaces;
import nfs.entities.cars.Car;
import nfs.entities.races.Race;
import nfs.utilities.Constants;
public abstract class NormalRace extends Race{
protected NormalRace(int length, String route, int prizePool) {
super(length, route, prizePool);
}
@Override
protected int getPrize(int place) {
int prize = this.getPrizePool();
switch(place) {
case 1:
prize = (prize * Constants.NORMAL_RACE_FIRST_PLACE_PRIZE_PERCENTAGE) / Constants.MAXIMUM_PERCENTAGE;
break;
case 2:
prize = (prize * Constants.NORMAL_RACE_SECOND_PLACE_PRIZE_PERCENTAGE) / Constants.MAXIMUM_PERCENTAGE;
break;
case 3:
prize = (prize * Constants.NORMAL_RACE_THIRD_PLACE_PRIZE_PERCENTAGE) / Constants.MAXIMUM_PERCENTAGE;
break;
}
return prize;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(super.toString());
result.append(this.getWinningStats());
return result.toString();
}
}
|
package edu.neu.ccs.pyramid.tmp;
//package edu.neu.ccs.pyramid.tmp;
//import edu.neu.ccs.pyramid.util.DirWalker;
import edu.neu.ccs.pyramid.util.DirWalker;
import org.apache.commons.io.FileUtils;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import java.io.File;
import java.util.*;
/**
* Created by chengli on 3/4/17.
*/
public class IndexBuilder {
static String[] extLabels={
"Bacterial Infections and Mycoses",
"Virus Diseases",
"Parasitic Diseases",
"Neoplasms",
"Musculoskeletal Diseases",
"Digestive System Diseases",
"Stomatognathic Diseases",
"Respiratory Tract Diseases",
"Otorhinolaryngologic Diseases",
"Nervous System Diseases",
"Eye Diseases",
"Urologic and Male Genital Diseases",
"Female Genital Diseases and Pregnancy Complications",
"Cardiovascular Diseases",
"Hemic and Lymphatic Diseases",
"Neonatal Diseases and Abnormalities",
"Skin and Connective Tissue Diseases",
"Nutritional and Metabolic Diseases",
"Endocrine Diseases",
"Immunologic Diseases",
"Disorders of Environmental Origin",
"Animal Diseases",
"Pathological Conditions, Signs and Symptoms"
};
public static XContentBuilder getBuilder(File file, Map<String, Set<String>> nameToCodesMap) throws Exception{
System.out.println("file=" + file.getCanonicalPath());
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
builder.field("body",getBody(file));
builder.field("file_name",getFileName(file));
builder.array("codes",getCodes(file,nameToCodesMap));
// todo test
// if (getExtLabels(file, nameToCodesMap).length!=1){
// builder.array("real_labels", getExtLabels(file, nameToCodesMap));
// }
builder.array("real_labels", getExtLabels(file, nameToCodesMap));
builder.field("split",getTrainOrTest(file));
builder.field("body_field_length",numWords(getBody(file)));
builder.endObject();
return builder;
}
static int numWords(String body){
return body.split("\\s+").length;
}
static String getBody(File file) throws Exception{
String entireFileText = FileUtils.readFileToString(file);
return entireFileText;
}
static String getFileName(File file) throws Exception{
String fullPath = file.getAbsolutePath();
return fullPath;
}
static String[] getLabels(File file, Map<String, Set<String>> nameToCodesMap) throws Exception{
String name = file.getName();
return nameToCodesMap.get(name)
.stream().sorted().map(IndexBuilder::codeToLabel).map(label -> ""+label)
.toArray(String[]::new);
}
static String[] getCodes(File file, Map<String, Set<String>> nameToCodesMap) throws Exception{
String name = file.getName();
return nameToCodesMap.get(name)
.stream().sorted()
.toArray(String[]::new);
}
static String getTrainOrTest(File file) throws Exception{
String name = file.getParentFile().getParentFile().getName();
String res = null;
if (name.equals("training")){
res = "train";
} else {
res = "test";
}
return res;
}
static String[] getExtLabels(File file,Map<String, Set<String>> nameToCodesMap) throws Exception{
String name = file.getName();
// System.out.println(name);
return nameToCodesMap.get(name)
.stream().sorted().map(IndexBuilder::codeToLabel).map(label -> extLabels[label])
.toArray(String[]::new);
}
public static int codeToLabel(String code){
String withoutC = code.substring(1);
String simplified;
if (withoutC.startsWith("0")){
simplified = withoutC.substring(1);
} else {
simplified = withoutC;
}
//return 0 for C01
System.out.println("simplified="+simplified);
int label = Integer.parseInt(simplified) -1;
return label;
}
public static Map<String, Set<String>> collectCodes(String folder) throws Exception{
Map<String, Set<String>> map = new HashMap<>();
List<File> files = DirWalker.getFiles(folder);
for (File file: files){
String name = file.getName();
String labelCode = file.getParentFile().getName();
if (!map.containsKey(name)){
map.put(name, new HashSet<>());
}
map.get(name).add(labelCode);
}
return map;
}
}
|
/**
* 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 2012-2015 the original author or authors.
*/
package org.assertj.maven;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.contentOf;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.assertj.core.util.Arrays.array;
import static org.assertj.core.util.Lists.newArrayList;
import static org.assertj.maven.AssertJAssertionsGeneratorMojo.shouldHaveNonEmptyPackagesOrClasses;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.assertj.assertions.generator.BaseAssertionGenerator;
import org.assertj.assertions.generator.description.ClassDescription;
import org.assertj.maven.generator.AssertionsGenerator;
import org.assertj.maven.generator.AssertionsGeneratorReport;
import org.assertj.maven.test.All;
import org.assertj.maven.test.Employee;
import org.assertj.maven.test.name.Name;
import org.assertj.maven.test.name.NameService;
import org.assertj.maven.test2.adress.Address;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class AssertJAssertionsGeneratorMojoTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private AssertJAssertionsGeneratorMojo assertjAssertionsGeneratorMojo;
private MavenProject mavenProject;
@Before
public void setUp() throws Exception {
mavenProject = mock(MavenProject.class);
assertjAssertionsGeneratorMojo = new AssertJAssertionsGeneratorMojo();
assertjAssertionsGeneratorMojo.project = mavenProject;
assertjAssertionsGeneratorMojo.targetDir = temporaryFolder.getRoot().getAbsolutePath();
}
@Test
public void executing_plugin_with_classes_and_packages_parameter_only_should_pass() throws Exception {
assertjAssertionsGeneratorMojo.packages = array("org.assertj.maven.test", "org.assertj.maven.test2");
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.Employee");
List<String> classes = newArrayList(Employee.class.getName(), Address.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
// check that expected assertions file exist (we don't check the content we suppose the generator works).
assertThat(assertionsFileFor(Employee.class)).exists();
assertThat(assertionsFileFor(Address.class)).exists();
assertThat(assertionsEntryPointFile("Assertions.java")).exists();
assertThat(assertionsEntryPointFile("BddAssertions.java")).exists();
assertThat(assertionsEntryPointFile("SoftAssertions.java")).exists();
}
@Test
public void executing_plugin_with_hierarchical_option_should_generate_hierarchical_assertions() throws Exception {
assertjAssertionsGeneratorMojo.packages = array("org.assertj.maven.test", "org.assertj.maven.test2");
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.Employee");
assertjAssertionsGeneratorMojo.hierarchical = true;
List<String> classes = newArrayList(Employee.class.getName(), Address.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
// check that expected assertions file exist (we don't check the content we suppose the generator works).
assertThat(assertionsFileFor(Employee.class)).exists();
assertThat(abstractAssertionsFileFor(Employee.class)).exists();
assertThat(assertionsFileFor(Address.class)).exists();
assertThat(abstractAssertionsFileFor(Address.class)).exists();
assertThat(assertionsEntryPointFile("Assertions.java")).exists();
assertThat(assertionsEntryPointFile("BddAssertions.java")).exists();
assertThat(assertionsEntryPointFile("SoftAssertions.java")).exists();
}
@Test
public void should_generate_assertions_with_user_templates() throws Exception {
// GIVEN
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.All");
assertjAssertionsGeneratorMojo.templates = new Templates();
assertjAssertionsGeneratorMojo.templates.templatesDirectory = "src/test/resources/templates/";
assertjAssertionsGeneratorMojo.templates.objectAssertion = "my_has_assertion_template.txt";
assertjAssertionsGeneratorMojo.templates.bddEntryPointAssertionMethod = "my_bdd_assertion_entry_point_method_template.txt";
assertjAssertionsGeneratorMojo.templates.bddEntryPointAssertionClass = "my_bdd_assertions_entry_point_class_template.txt";
assertjAssertionsGeneratorMojo.templates.hierarchicalAssertionAbstractClass = "my_custom_abstract_assertion_class_template.txt";
assertjAssertionsGeneratorMojo.templates.assertionClass = "my_custom_assertion_class_template.txt";
assertjAssertionsGeneratorMojo.templates.hierarchicalAssertionConcreteClass = "my_custom_hierarchical_assertion_class_template.txt";
assertjAssertionsGeneratorMojo.templates.characterAssertion = "my_has_assertion_template_for_character.txt";
assertjAssertionsGeneratorMojo.templates.charAssertion = "my_has_assertion_template_for_char.txt";
assertjAssertionsGeneratorMojo.templates.realNumberAssertion = "my_has_assertion_template_for_real_number.txt";
assertjAssertionsGeneratorMojo.templates.realNumberWrapperAssertion = "my_has_assertion_template_for_real_number_wrapper.txt";
assertjAssertionsGeneratorMojo.templates.wholeNumberAssertion = "my_has_assertion_template_for_whole_number.txt";
assertjAssertionsGeneratorMojo.templates.wholeNumberWrapperAssertion = "my_has_assertion_template_for_whole_number_wrapper.txt";
assertjAssertionsGeneratorMojo.templates.arrayAssertion = "my_has_elements_assertion_template_for_array.txt";
assertjAssertionsGeneratorMojo.templates.iterableAssertion = "my_has_elements_assertion_template_for_iterable.txt";
assertjAssertionsGeneratorMojo.templates.booleanAssertion = "my_is_assertion_template.txt";
assertjAssertionsGeneratorMojo.templates.booleanWrapperAssertion = "my_is_wrapper_assertion_template.txt";
assertjAssertionsGeneratorMojo.templates.junitSoftEntryPointAssertionClass = "my_junit_soft_assertions_entry_point_class_template.txt";
assertjAssertionsGeneratorMojo.templates.softEntryPointAssertionMethod = "my_soft_assertion_entry_point_method_template.txt";
assertjAssertionsGeneratorMojo.templates.softEntryPointAssertionClass = "my_soft_assertions_entry_point_class_template.txt";
assertjAssertionsGeneratorMojo.templates.assertionEntryPointMethod = "my_standard_assertion_entry_point_method_template.txt";
assertjAssertionsGeneratorMojo.templates.assertionsEntryPointClass = "my_standard_assertions_entry_point_class_template.txt";
List<String> classes = newArrayList(All.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
// WHEN
assertjAssertionsGeneratorMojo.execute();
// check that expected assertions file exist (we don't check the content we suppose the generator works).
File allAssertFile = assertionsFileFor(All.class);
assertThat(allAssertFile).exists();
// check that its content was done using custom templates
assertThat(contentOf(allAssertFile)).contains("my_custom_assertion_class_template",
"my_has_assertion_template_for_character",
"my_has_assertion_template_for_char",
"my_has_assertion_template_for_real_number",
"my_has_assertion_template_for_real_number_wrapper",
"my_has_assertion_template_for_whole_number",
"my_has_assertion_template_for_whole_number_wrapper",
"my_has_assertion_template",
"my_has_elements_assertion_template_for_array",
"my_has_elements_assertion_template_for_iterable",
"my_is_assertion_template",
"my_is_wrapper_assertion_template");
assertThat(contentOf(assertionsEntryPointFile("Assertions.java"))).contains("my_standard_assertion_entry_point_method_template",
"my_standard_assertions_entry_point_class_template");
assertThat(contentOf(assertionsEntryPointFile("BddAssertions.java"))).contains("my_bdd_assertion_entry_point_method_template",
"my_bdd_assertions_entry_point_class_template");
assertThat(contentOf(assertionsEntryPointFile("SoftAssertions.java"))).contains("my_soft_assertion_entry_point_method_template",
"my_soft_assertions_entry_point_class_template");
assertThat(contentOf(assertionsEntryPointFile("JUnitSoftAssertions.java"))).contains("my_junit_soft_assertions_entry_point_class_template");
}
@Test
public void shoud_not_generate_assertions_for_assert_classes() throws Exception {
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.MyAssert");
assertjAssertionsGeneratorMojo.packages = array("some.package");
assertjAssertionsGeneratorMojo.hierarchical = true;
assertjAssertionsGeneratorMojo.execute();
assertThat(assertionsFileFor("org.assertj.maven.test.MyAssertAssert")).doesNotExist();
}
@Test
public void shoud_not_generate_assertions_for_assertions_classes() throws Exception {
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.MyAssertions");
assertjAssertionsGeneratorMojo.packages = array("some.package");
assertjAssertionsGeneratorMojo.execute();
assertThat(assertionsFileFor("org.assertj.maven.test.MyAssertionsAssert")).doesNotExist();
}
@Test
public void executing_plugin_with_classes_parameter_only_should_pass() throws Exception {
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.Employee",
"org.assertj.maven.test2.adress.Address");
List<String> classes = newArrayList(Address.class.getName());
assertjAssertionsGeneratorMojo.hierarchical = true;
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
// check that expected assertions file exist (we don't check the content we suppose the generator works).
assertThat(assertionsFileFor(Employee.class)).exists();
assertThat(assertionsFileFor(Address.class)).exists();
assertThat(assertionsEntryPointFile("Assertions.java")).exists();
assertThat(assertionsEntryPointFile("BddAssertions.java")).exists();
assertThat(assertionsEntryPointFile("SoftAssertions.java")).exists();
}
@Test
public void executing_plugin_with_custom_entry_point_class_package_should_pass() throws Exception {
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.Employee");
assertjAssertionsGeneratorMojo.entryPointClassPackage = "my.custom.pkg";
List<String> classes = newArrayList(Employee.class.getName(), Address.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
assertThat(assertionsFileFor(Employee.class)).exists();
assertThat(assertionsEntryPointFileWithCustomPackage()).exists();
}
@Test
public void should_not_generate_entry_point_classes_if_disabled() throws Exception {
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.Employee");
List<String> classes = newArrayList(Employee.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.generateAssertions = false;
assertjAssertionsGeneratorMojo.generateBddAssertions = false;
assertjAssertionsGeneratorMojo.generateSoftAssertions = false;
assertjAssertionsGeneratorMojo.generateJUnitSoftAssertions = false;
assertjAssertionsGeneratorMojo.execute();
// check that expected assertions file exist (we don't check the content we suppose the generator works).
assertThat(assertionsFileFor(Employee.class)).exists();
assertThat(assertionsEntryPointFile("Assertions.java")).doesNotExist();
assertThat(assertionsEntryPointFile("BddAssertions.java")).doesNotExist();
assertThat(assertionsEntryPointFile("SoftAssertions.java")).doesNotExist();
assertThat(assertionsEntryPointFile("JUniSoftAssertions.java")).doesNotExist();
}
@Test
public void executing_plugin_with_fake_package_should_not_generate_anything() throws Exception {
assertjAssertionsGeneratorMojo.packages = array("fakepackage");
List<String> classes = newArrayList();
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
assertThat(temporaryFolder.getRoot().list()).isEmpty();
}
@Test
public void executing_plugin_with_skip_set_to_true_should_not_generate_anything() throws Exception {
assertjAssertionsGeneratorMojo.packages = array("org.assertj.maven.test.Employee");
assertjAssertionsGeneratorMojo.skip = true;
List<String> classes = newArrayList();
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
assertThat(temporaryFolder.getRoot().list()).isEmpty();
}
@Test
public void plugin_should_only_generate_assertions_for_included_classes() throws Exception {
assertjAssertionsGeneratorMojo.packages = array("org.assertj.maven.test");
assertjAssertionsGeneratorMojo.includes = array(".*Name");
List<String> classes = newArrayList(Employee.class.getName(), Name.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
assertThat(assertionsFileFor(Name.class)).exists();
assertThat(assertionsFileFor(NameService.class)).doesNotExist();
assertThat(assertionsFileFor(Employee.class)).doesNotExist();
}
@Test
public void plugin_should_not_generate_assertions_for_excluded_classes() throws Exception {
assertjAssertionsGeneratorMojo.packages = array("org.assertj.maven.test");
assertjAssertionsGeneratorMojo.excludes = array(".*Employee", ".*Service");
List<String> classes = newArrayList(Employee.class.getName(), Name.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
assertThat(assertionsFileFor(Name.class)).exists();
assertThat(assertionsFileFor(NameService.class)).doesNotExist();
assertThat(assertionsFileFor(Employee.class)).doesNotExist();
}
@Test
public void plugin_should_not_generate_any_assertions_as_all_package_classes_are_excluded() throws Exception {
assertjAssertionsGeneratorMojo.packages = array("org.assertj.maven.test");
assertjAssertionsGeneratorMojo.excludes = array(".*Employ..", ".*Name.*");
List<String> classes = newArrayList(Employee.class.getName(), Name.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
assertThat(assertionsFileFor(Name.class)).doesNotExist();
assertThat(assertionsFileFor(NameService.class)).doesNotExist();
assertThat(assertionsFileFor(Employee.class)).doesNotExist();
}
@Test
public void plugin_should_not_generate_assertions_for_classes_matching_both_include_and_exclude_pattern() throws Exception {
assertjAssertionsGeneratorMojo.packages = array("org.assertj.maven.test");
assertjAssertionsGeneratorMojo.includes = array(".*Employee", ".*Name.*");
assertjAssertionsGeneratorMojo.excludes = array(".*Employee", ".*Service");
List<String> classes = newArrayList(Employee.class.getName(), Name.class.getName());
when(mavenProject.getCompileClasspathElements()).thenReturn(classes);
assertjAssertionsGeneratorMojo.execute();
assertThat(assertionsFileFor(Name.class)).exists();
assertThat(assertionsFileFor(NameService.class)).doesNotExist();
assertThat(assertionsFileFor(Employee.class)).doesNotExist();
}
@SuppressWarnings("unchecked")
@Test
public void executing_plugin_with_error_should_be_reported_in_generator_report() throws Exception {
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.Employee");
when(mavenProject.getCompileClasspathElements()).thenReturn(newArrayList(Employee.class.getName()));
// let's throws an IOException when generating custom assertions
AssertionsGenerator generator = new AssertionsGenerator(Thread.currentThread().getContextClassLoader());
BaseAssertionGenerator baseGenerator = mock(BaseAssertionGenerator.class);
generator.setBaseGenerator(baseGenerator);
when(baseGenerator.generateCustomAssertionFor(any(ClassDescription.class))).thenThrow(IOException.class);
AssertionsGeneratorReport report = assertjAssertionsGeneratorMojo.executeWithAssertionGenerator(generator);
assertThat(report.getReportedException()).isInstanceOf(IOException.class);
assertThat(temporaryFolder.getRoot().list()).isEmpty();
}
@Test
public void input_classes_not_found_should_be_listed_in_generator_report() throws Exception {
assertjAssertionsGeneratorMojo.classes = array("org.assertj.maven.test.Employee", "org.Foo", "org.Bar");
when(mavenProject.getCompileClasspathElements()).thenReturn(newArrayList(Employee.class.getName()));
AssertionsGenerator generator = new AssertionsGenerator(Thread.currentThread().getContextClassLoader());
AssertionsGeneratorReport report = assertjAssertionsGeneratorMojo.executeWithAssertionGenerator(generator);
// check that expected assertions file exist (we don't check the content we suppose the generator works).
assertThat(assertionsFileFor(Employee.class)).exists();
assertThat(report.getInputClassesNotFound()).as("check report").containsExactly("org.Bar", "org.Foo");
}
@Test
public void should_fail_if_packages_and_classes_parameters_are_null() throws Exception {
try {
assertjAssertionsGeneratorMojo.execute();
failBecauseExceptionWasNotThrown(MojoFailureException.class);
} catch (MojoFailureException e) {
assertThat(e).hasMessage(shouldHaveNonEmptyPackagesOrClasses());
}
}
private File assertionsFileFor(Class<?> clazz) {
return new File(temporaryFolder.getRoot(), basePathName(clazz) + "Assert.java");
}
private File assertionsFileFor(String className) {
return new File(temporaryFolder.getRoot(), className.replace('.', File.separatorChar) + ".java");
}
private File abstractAssertionsFileFor(Class<?> clazz) {
return new File(temporaryFolder.getRoot(), basePathName("Abstract", clazz) + "Assert.java");
}
private static String basePathName(Class<?> clazz) {
return basePathName("", clazz);
}
private static String basePathName(String prefix, Class<?> clazz) {
return clazz.getPackage().getName().replace('.', File.separatorChar) + File.separator + prefix
+ clazz.getSimpleName();
}
private File assertionsEntryPointFile(String simpleName) {
return new File(temporaryFolder.getRoot(), "org.assertj.maven.test".replace('.', File.separatorChar)
+ File.separator + simpleName);
}
private File assertionsEntryPointFileWithCustomPackage() {
return new File(temporaryFolder.getRoot(), "my.custom.pkg".replace('.', File.separatorChar) + File.separator
+ "Assertions.java");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.