text
stringlengths 7
1.01M
|
|---|
package com.victuxbb.systemdesigns.tinyurlkgs.domain;
public class Base64Dictionary {
private final Character[] characters = new Character[]{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '-', '_'};
public Character[] getCharacters() {
return characters;
}
}
|
package uk.ac.excites.ucl.sapelliviewer.db;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import java.util.List;
import io.reactivex.Single;
import uk.ac.excites.ucl.sapelliviewer.datamodel.UserInfo;
@Dao
public interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertUserInfo(UserInfo userInfo);
@Update
void updateUserInfo(UserInfo projectInfo);
@Delete
void deleteUserInfo(UserInfo projectInfo);
@Query("SELECT * FROM UserInfo")
Single<UserInfo> getUserInfo();
@Query("DELETE FROM UserInfo")
public void clearPrevUser();
}
|
package controllers;
import play.mvc.*;
import play.libs.Json;
import java.util.Map;
import java.util.HashMap;
import views.html.*;
public class HomeController extends Controller {
public Result index() {
String name = request().getQueryString("name");
Map<String, String> helloWorld = new HashMap();
helloWorld.put("id", "1");
helloWorld.put("content", String.format("Hello %s!", name));
return ok(Json.toJson(helloWorld));
}
}
|
package cn.hutool.core.date;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.BetweenFormatter.Level;
import cn.hutool.core.date.format.FastDateFormat;
import cn.hutool.core.util.RandomUtil;
import org.junit.Assert;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.TimeZone;
/**
* 时间工具单元测试<br>
* 此单元测试依赖时区为中国+08:00
*
* <pre>
* export TZ=Asia/Shanghai
* </pre>
*
* @author Looly
*/
public class DateUtilTest {
@Test
public void nowTest() {
// 当前时间
Date date = DateUtil.date();
Assert.assertNotNull(date);
// 当前时间
Date date2 = DateUtil.date(Calendar.getInstance());
Assert.assertNotNull(date2);
// 当前时间
Date date3 = DateUtil.date(System.currentTimeMillis());
Assert.assertNotNull(date3);
// 当前日期字符串,格式:yyyy-MM-dd HH:mm:ss
String now = DateUtil.now();
Assert.assertNotNull(now);
// 当前日期字符串,格式:yyyy-MM-dd
String today = DateUtil.today();
Assert.assertNotNull(today);
}
@Test
public void formatAndParseTest() {
String dateStr = "2017-03-01";
Date date = DateUtil.parse(dateStr);
String format = DateUtil.format(date, "yyyy/MM/dd");
Assert.assertEquals("2017/03/01", format);
// 常用格式的格式化
String formatDate = DateUtil.formatDate(date);
Assert.assertEquals("2017-03-01", formatDate);
String formatDateTime = DateUtil.formatDateTime(date);
Assert.assertEquals("2017-03-01 00:00:00", formatDateTime);
String formatTime = DateUtil.formatTime(date);
Assert.assertEquals("00:00:00", formatTime);
}
@Test
public void beginAndEndTest() {
String dateStr = "2017-03-01 00:33:23";
Date date = DateUtil.parse(dateStr);
// 一天的开始
Date beginOfDay = DateUtil.beginOfDay(date);
Assert.assertEquals("2017-03-01 00:00:00", beginOfDay.toString());
// 一天的结束
Date endOfDay = DateUtil.endOfDay(date);
Assert.assertEquals("2017-03-01 23:59:59", endOfDay.toString());
}
@Test
public void endOfDayTest() {
final DateTime parse = DateUtil.parse("2020-05-31 00:00:00");
Assert.assertEquals("2020-05-31 23:59:59", DateUtil.endOfDay(parse).toString());
}
@Test
public void truncateTest(){
String dateStr2 = "2020-02-29 12:59:34";
Date date2 = DateUtil.parse(dateStr2);
final DateTime dateTime = DateUtil.truncate(date2, DateField.MINUTE);
Assert.assertEquals("2020-02-29 12:59:00", dateTime.toString());
}
@Test
public void beginOfWeekTest() {
String dateStr = "2017-03-01 22:33:23";
DateTime date = DateUtil.parse(dateStr);
Objects.requireNonNull(date).setFirstDayOfWeek(Week.MONDAY);
// 一周的开始
Date beginOfWeek = DateUtil.beginOfWeek(date);
Assert.assertEquals("2017-02-27 00:00:00", beginOfWeek.toString());
// 一周的结束
Date endOfWeek = DateUtil.endOfWeek(date);
Assert.assertEquals("2017-03-05 23:59:59", endOfWeek.toString());
Calendar calendar = DateUtil.calendar(date);
// 一周的开始
Calendar begin = DateUtil.beginOfWeek(calendar);
Assert.assertEquals("2017-02-27 00:00:00", DateUtil.date(begin).toString());
// 一周的结束
Calendar end = DateUtil.endOfWeek(calendar);
Assert.assertEquals("2017-03-05 23:59:59", DateUtil.date(end).toString());
}
@Test
public void beginOfWeekTest2() {
String beginStr = "2020-03-11";
DateTime date = DateUtil.parseDate(beginStr);
Calendar calendar = date.toCalendar();
final Calendar begin = DateUtil.beginOfWeek(calendar, false);
Assert.assertEquals("2020-03-08 00:00:00", DateUtil.date(begin).toString());
Calendar calendar2 = date.toCalendar();
final Calendar end = DateUtil.endOfWeek(calendar2, false);
Assert.assertEquals("2020-03-14 23:59:59", DateUtil.date(end).toString());
}
@Test
public void offsetDateTest() {
String dateStr = "2017-03-01 22:33:23";
Date date = DateUtil.parse(dateStr);
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
Assert.assertEquals("2017-03-03 22:33:23", newDate.toString());
// 偏移天
DateTime newDate2 = DateUtil.offsetDay(date, 3);
Assert.assertEquals("2017-03-04 22:33:23", newDate2.toString());
// 偏移小时
DateTime newDate3 = DateUtil.offsetHour(date, -3);
Assert.assertEquals("2017-03-01 19:33:23", newDate3.toString());
// 偏移月
DateTime offsetMonth = DateUtil.offsetMonth(date, -1);
Assert.assertEquals("2017-02-01 22:33:23", offsetMonth.toString());
}
@Test
public void offsetMonthTest() {
DateTime st = DateUtil.parseDate("2018-05-31");
List<DateTime> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
list.add(DateUtil.offsetMonth(st, i));
}
Assert.assertEquals("2018-05-31 00:00:00", list.get(0).toString());
Assert.assertEquals("2018-06-30 00:00:00", list.get(1).toString());
Assert.assertEquals("2018-07-31 00:00:00", list.get(2).toString());
Assert.assertEquals("2018-08-31 00:00:00", list.get(3).toString());
}
@Test
public void betweenTest() {
String dateStr1 = "2017-03-01 22:34:23";
Date date1 = DateUtil.parse(dateStr1);
String dateStr2 = "2017-04-01 23:56:14";
Date date2 = DateUtil.parse(dateStr2);
// 相差月
long betweenMonth = DateUtil.betweenMonth(date1, date2, false);
Assert.assertEquals(1, betweenMonth);// 相差一个月
// 反向
betweenMonth = DateUtil.betweenMonth(date2, date1, false);
Assert.assertEquals(1, betweenMonth);// 相差一个月
// 相差天
long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);
Assert.assertEquals(31, betweenDay);// 相差一个月,31天
// 反向
betweenDay = DateUtil.between(date2, date1, DateUnit.DAY);
Assert.assertEquals(31, betweenDay);// 相差一个月,31天
// 相差小时
long betweenHour = DateUtil.between(date1, date2, DateUnit.HOUR);
Assert.assertEquals(745, betweenHour);
// 反向
betweenHour = DateUtil.between(date2, date1, DateUnit.HOUR);
Assert.assertEquals(745, betweenHour);
// 相差分
long betweenMinute = DateUtil.between(date1, date2, DateUnit.MINUTE);
Assert.assertEquals(44721, betweenMinute);
// 反向
betweenMinute = DateUtil.between(date2, date1, DateUnit.MINUTE);
Assert.assertEquals(44721, betweenMinute);
// 相差秒
long betweenSecond = DateUtil.between(date1, date2, DateUnit.SECOND);
Assert.assertEquals(2683311, betweenSecond);
// 反向
betweenSecond = DateUtil.between(date2, date1, DateUnit.SECOND);
Assert.assertEquals(2683311, betweenSecond);
// 相差秒
long betweenMS = DateUtil.between(date1, date2, DateUnit.MS);
Assert.assertEquals(2683311000L, betweenMS);
// 反向
betweenMS = DateUtil.between(date2, date1, DateUnit.MS);
Assert.assertEquals(2683311000L, betweenMS);
}
@Test
public void betweenTest2() {
long between = DateUtil.between(DateUtil.parse("2019-05-06 02:15:00"), DateUtil.parse("2019-05-06 02:20:00"), DateUnit.HOUR);
Assert.assertEquals(0, between);
}
@Test
public void formatChineseDateTest() {
String formatChineseDate = DateUtil.formatChineseDate(DateUtil.parse("2018-02-24"), true, false);
Assert.assertEquals("二〇一八年二月二十四日", formatChineseDate);
}
@Test
public void formatChineseDateTimeTest() {
String formatChineseDateTime = DateUtil.formatChineseDate(DateUtil.parse("2018-02-24 12:13:14"), true, true);
Assert.assertEquals("二〇一八年二月二十四日一十二时一十三分一十四秒", formatChineseDateTime);
}
@Test
public void formatBetweenTest() {
String dateStr1 = "2017-03-01 22:34:23";
Date date1 = DateUtil.parse(dateStr1);
String dateStr2 = "2017-04-01 23:56:14";
Date date2 = DateUtil.parse(dateStr2);
long between = DateUtil.between(date1, date2, DateUnit.MS);
String formatBetween = DateUtil.formatBetween(between, Level.MINUTE);
Assert.assertEquals("31天1小时21分", formatBetween);
}
@Test
public void timerTest() {
TimeInterval timer = DateUtil.timer();
// ---------------------------------
// -------这是执行过程
// ---------------------------------
timer.interval();// 花费毫秒数
timer.intervalRestart();// 返回花费时间,并重置开始时间
timer.intervalMinute();// 花费分钟数
}
@Test
public void currentTest() {
long current = DateUtil.current();
String currentStr = String.valueOf(current);
Assert.assertEquals(13, currentStr.length());
long currentNano = DateUtil.current();
String currentNanoStr = String.valueOf(currentNano);
Assert.assertNotNull(currentNanoStr);
}
@Test
public void weekOfYearTest() {
// 第一周周日
int weekOfYear1 = DateUtil.weekOfYear(DateUtil.parse("2016-01-03"));
Assert.assertEquals(1, weekOfYear1);
// 第二周周四
int weekOfYear2 = DateUtil.weekOfYear(DateUtil.parse("2016-01-07"));
Assert.assertEquals(2, weekOfYear2);
}
@Test
public void timeToSecondTest() {
int second = DateUtil.timeToSecond("00:01:40");
Assert.assertEquals(100, second);
second = DateUtil.timeToSecond("00:00:40");
Assert.assertEquals(40, second);
second = DateUtil.timeToSecond("01:00:00");
Assert.assertEquals(3600, second);
second = DateUtil.timeToSecond("00:00:00");
Assert.assertEquals(0, second);
}
@Test
public void secondToTimeTest() {
String time = DateUtil.secondToTime(3600);
Assert.assertEquals("01:00:00", time);
time = DateUtil.secondToTime(3800);
Assert.assertEquals("01:03:20", time);
time = DateUtil.secondToTime(0);
Assert.assertEquals("00:00:00", time);
time = DateUtil.secondToTime(30);
Assert.assertEquals("00:00:30", time);
}
@Test
public void secondToTimeTest2() {
String s1 = "55:02:18";
String s2 = "55:00:50";
int i = DateUtil.timeToSecond(s1) + DateUtil.timeToSecond(s2);
String s = DateUtil.secondToTime(i);
Assert.assertEquals("110:03:08", s);
}
@Test
public void parseTest2() {
// 转换时间与SimpleDateFormat结果保持一致即可
String birthday = "700403";
Date birthDate = DateUtil.parse(birthday, "yyMMdd");
// 获取出生年(完全表现形式,如:2010)
int sYear = DateUtil.year(birthDate);
Assert.assertEquals(1970, sYear);
}
@Test
public void parseTest3() {
String dateStr = "2018-10-10 12:11:11";
Date date = DateUtil.parse(dateStr);
String format = DateUtil.format(date, DatePattern.NORM_DATETIME_PATTERN);
Assert.assertEquals(dateStr, format);
}
@Test
public void parseTest4() {
String ymd = DateUtil.parse("2019-3-21 12:20:15", "yyyy-MM-dd").toString(DatePattern.PURE_DATE_PATTERN);
Assert.assertEquals("20190321", ymd);
}
@Test
public void parseTest5() {
// 测试时间解析
//noinspection ConstantConditions
String time = DateUtil.parse("22:12:12").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("22:12:12", time);
//noinspection ConstantConditions
time = DateUtil.parse("2:12:12").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("02:12:12", time);
//noinspection ConstantConditions
time = DateUtil.parse("2:2:12").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("02:02:12", time);
//noinspection ConstantConditions
time = DateUtil.parse("2:2:1").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("02:02:01", time);
//noinspection ConstantConditions
time = DateUtil.parse("22:2:1").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("22:02:01", time);
//noinspection ConstantConditions
time = DateUtil.parse("2:22:1").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("02:22:01", time);
// 测试两位时间解析
//noinspection ConstantConditions
time = DateUtil.parse("2:22").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("02:22:00", time);
//noinspection ConstantConditions
time = DateUtil.parse("12:22").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("12:22:00", time);
//noinspection ConstantConditions
time = DateUtil.parse("12:2").toString(DatePattern.NORM_TIME_FORMAT);
Assert.assertEquals("12:02:00", time);
}
@Test
public void parseTest6() {
String str = "Tue Jun 4 16:25:15 +0800 2019";
DateTime dateTime = DateUtil.parse(str);
assert dateTime != null;
Assert.assertEquals("2019-06-04 16:25:15", dateTime.toString());
}
@Test
public void parseTest7() {
String str = "2019-06-01T19:45:43.000 +0800";
DateTime dateTime = DateUtil.parse(str, "yyyy-MM-dd'T'HH:mm:ss.SSS Z");
Assert.assertEquals("2019-06-01 19:45:43", dateTime.toString());
}
@Test
public void parseTest8() {
String str = "2020-06-28T02:14:13.000Z";
DateTime dateTime = DateUtil.parse(str);
assert dateTime != null;
Assert.assertEquals("2020-06-28 02:14:13", dateTime.toString());
}
@Test
public void parseAndOffsetTest() {
// 检查UTC时间偏移是否准确
String str = "2019-09-17T13:26:17.948Z";
DateTime dateTime = DateUtil.parse(str);
assert dateTime != null;
Assert.assertEquals("2019-09-17 13:26:17", dateTime.toString());
DateTime offset = DateUtil.offsetHour(dateTime, 8);
Assert.assertEquals("2019-09-17 21:26:17", offset.toString());
}
@Test
public void parseDateTest() {
String dateStr = "2018-4-10";
Date date = DateUtil.parseDate(dateStr);
String format = DateUtil.format(date, DatePattern.NORM_DATE_PATTERN);
Assert.assertEquals("2018-04-10", format);
}
@Test
public void parseToDateTimeTest1() {
String dateStr1 = "2017-02-01";
String dateStr2 = "2017/02/01";
String dateStr3 = "2017.02.01";
String dateStr4 = "2017年02月01日";
DateTime dt1 = DateUtil.parse(dateStr1);
DateTime dt2 = DateUtil.parse(dateStr2);
DateTime dt3 = DateUtil.parse(dateStr3);
DateTime dt4 = DateUtil.parse(dateStr4);
Assert.assertEquals(dt1, dt2);
Assert.assertEquals(dt2, dt3);
Assert.assertEquals(dt3, dt4);
}
@Test
public void parseToDateTimeTest2() {
String dateStr1 = "2017-02-01 12:23";
String dateStr2 = "2017/02/01 12:23";
String dateStr3 = "2017.02.01 12:23";
String dateStr4 = "2017年02月01日 12:23";
DateTime dt1 = DateUtil.parse(dateStr1);
DateTime dt2 = DateUtil.parse(dateStr2);
DateTime dt3 = DateUtil.parse(dateStr3);
DateTime dt4 = DateUtil.parse(dateStr4);
Assert.assertEquals(dt1, dt2);
Assert.assertEquals(dt2, dt3);
Assert.assertEquals(dt3, dt4);
}
@Test
public void parseToDateTimeTest3() {
String dateStr1 = "2017-02-01 12:23:45";
String dateStr2 = "2017/02/01 12:23:45";
String dateStr3 = "2017.02.01 12:23:45";
String dateStr4 = "2017年02月01日 12时23分45秒";
DateTime dt1 = DateUtil.parse(dateStr1);
DateTime dt2 = DateUtil.parse(dateStr2);
DateTime dt3 = DateUtil.parse(dateStr3);
DateTime dt4 = DateUtil.parse(dateStr4);
Assert.assertEquals(dt1, dt2);
Assert.assertEquals(dt2, dt3);
Assert.assertEquals(dt3, dt4);
}
@Test
public void parseToDateTimeTest4() {
String dateStr1 = "2017-02-01 12:23:45";
String dateStr2 = "20170201122345";
DateTime dt1 = DateUtil.parse(dateStr1);
DateTime dt2 = DateUtil.parse(dateStr2);
Assert.assertEquals(dt1, dt2);
}
@Test
public void parseToDateTimeTest5() {
String dateStr1 = "2017-02-01";
String dateStr2 = "20170201";
DateTime dt1 = DateUtil.parse(dateStr1);
DateTime dt2 = DateUtil.parse(dateStr2);
Assert.assertEquals(dt1, dt2);
}
@Test
public void parseUTCTest() {
String dateStr1 = "2018-09-13T05:34:31Z";
DateTime dt = DateUtil.parseUTC(dateStr1);
// parse方法支持UTC格式测试
DateTime dt2 = DateUtil.parse(dateStr1);
Assert.assertEquals(dt, dt2);
// 默认使用Pattern对应的时区,即UTC时区
String dateStr = dt.toString();
Assert.assertEquals("2018-09-13 05:34:31", dateStr);
// 使用当前(上海)时区
dateStr = dt.toString(TimeZone.getTimeZone("GMT+8:00"));
Assert.assertEquals("2018-09-13 13:34:31", dateStr);
dateStr1 = "2018-09-13T13:34:32+0800";
dt = DateUtil.parseUTC(dateStr1);
dateStr = dt.toString(TimeZone.getTimeZone("GMT+8:00"));
Assert.assertEquals("2018-09-13 13:34:32", dateStr);
dateStr1 = "2018-09-13T13:34:33+08:00";
dt = DateUtil.parseUTC(dateStr1);
dateStr = dt.toString(TimeZone.getTimeZone("GMT+8:00"));
Assert.assertEquals("2018-09-13 13:34:33", dateStr);
dateStr1 = "2018-09-13T13:34:34+0800";
dt = DateUtil.parse(dateStr1);
assert dt != null;
dateStr = dt.toString(TimeZone.getTimeZone("GMT+8:00"));
Assert.assertEquals("2018-09-13 13:34:34", dateStr);
dateStr1 = "2018-09-13T13:34:35+08:00";
dt = DateUtil.parse(dateStr1);
assert dt != null;
dateStr = dt.toString(TimeZone.getTimeZone("GMT+8:00"));
Assert.assertEquals("2018-09-13 13:34:35", dateStr);
dateStr1 = "2018-09-13T13:34:36.999+0800";
dt = DateUtil.parseUTC(dateStr1);
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DatePattern.NORM_DATETIME_MS_PATTERN);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
dateStr = dt.toString(simpleDateFormat);
Assert.assertEquals("2018-09-13 13:34:36.999", dateStr);
dateStr1 = "2018-09-13T13:34:37.999+08:00";
dt = DateUtil.parseUTC(dateStr1);
dateStr = dt.toString(simpleDateFormat);
Assert.assertEquals("2018-09-13 13:34:37.999", dateStr);
dateStr1 = "2018-09-13T13:34:38.999+0800";
dt = DateUtil.parse(dateStr1);
assert dt != null;
dateStr = dt.toString(simpleDateFormat);
Assert.assertEquals("2018-09-13 13:34:38.999", dateStr);
dateStr1 = "2018-09-13T13:34:39.999+08:00";
dt = DateUtil.parse(dateStr1);
assert dt != null;
dateStr = dt.toString(simpleDateFormat);
Assert.assertEquals("2018-09-13 13:34:39.999", dateStr);
}
@Test
public void parseCSTTest(){
String dateStr = "Wed Sep 16 11:26:23 CST 2009";
SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.JDK_DATETIME_PATTERN, Locale.US);
final DateTime parse = DateUtil.parse(dateStr, sdf);
DateTime dateTime = DateUtil.parseCST(dateStr);
Assert.assertEquals(parse, dateTime);
dateTime = DateUtil.parse(dateStr);
Assert.assertEquals(parse, dateTime);
}
@Test
public void parseCSTTest2(){
String dateStr = "Wed Sep 16 11:26:23 CST 2009";
SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.JDK_DATETIME_PATTERN, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
final DateTime parse = DateUtil.parse(dateStr, sdf);
FastDateFormat fdf = FastDateFormat.getInstance(DatePattern.JDK_DATETIME_PATTERN, TimeZone.getTimeZone("America/Chicago"), Locale.US);
final DateTime parse2 = DateUtil.parse(dateStr, fdf);
Assert.assertEquals(parse, parse2);
}
@Test
public void parseJDkTest() {
String dateStr = "Thu May 16 17:57:18 GMT+08:00 2019";
DateTime time = DateUtil.parse(dateStr);
Assert.assertEquals("2019-05-16 17:57:18", Objects.requireNonNull(time).toString());
}
@Test
public void parseISOTest() {
String dateStr = "2020-04-23T02:31:00.000Z";
DateTime time = DateUtil.parse(dateStr);
Assert.assertEquals("2020-04-23 02:31:00", Objects.requireNonNull(time).toString());
}
@Test
public void endOfYearTest() {
DateTime date = DateUtil.date();
date.setField(DateField.YEAR, 2019);
DateTime endOfYear = DateUtil.endOfYear(date);
Assert.assertEquals("2019-12-31 23:59:59", endOfYear.toString());
}
@Test
public void endOfQuarterTest() {
Date date = DateUtil.endOfQuarter(
DateUtil.parse("2020-05-31 00:00:00"));
Assert.assertEquals("2020-06-30 23:59:59", DateUtil.format(date,"yyyy-MM-dd HH:mm:ss"));
}
@Test
public void endOfWeekTest() {
// 周日
DateTime now = DateUtil.parse("2019-09-15 13:00");
DateTime startOfWeek = DateUtil.beginOfWeek(now);
Assert.assertEquals("2019-09-09 00:00:00", startOfWeek.toString());
DateTime endOfWeek = DateUtil.endOfWeek(now);
Assert.assertEquals("2019-09-15 23:59:59", endOfWeek.toString());
long between = DateUtil.between(endOfWeek, startOfWeek, DateUnit.DAY);
// 周一和周日相距6天
Assert.assertEquals(6, between);
}
@Test
public void dayOfWeekTest() {
int dayOfWeek = DateUtil.dayOfWeek(DateUtil.parse("2018-03-07"));
Assert.assertEquals(Calendar.WEDNESDAY, dayOfWeek);
Week week = DateUtil.dayOfWeekEnum(DateUtil.parse("2018-03-07"));
Assert.assertEquals(Week.WEDNESDAY, week);
}
@Test
public void rangeTest() {
DateTime start = DateUtil.parse("2017-01-01");
DateTime end = DateUtil.parse("2017-01-03");
// 测试包含开始和结束情况下步进为1的情况
DateRange range = DateUtil.range(start, end, DateField.DAY_OF_YEAR);
Assert.assertEquals(range.next(), DateUtil.parse("2017-01-01"));
Assert.assertEquals(range.next(), DateUtil.parse("2017-01-02"));
Assert.assertEquals(range.next(), DateUtil.parse("2017-01-03"));
try {
range.next();
Assert.fail("已超过边界,下一个元素不应该存在!");
} catch (NoSuchElementException ignored) {
}
// 测试多步进的情况
range = new DateRange(start, end, DateField.DAY_OF_YEAR, 2);
Assert.assertEquals(range.next(), DateUtil.parse("2017-01-01"));
Assert.assertEquals(range.next(), DateUtil.parse("2017-01-03"));
// 测试不包含开始结束时间的情况
range = new DateRange(start, end, DateField.DAY_OF_YEAR, 1, false, false);
Assert.assertEquals(range.next(), DateUtil.parse("2017-01-02"));
try {
range.next();
Assert.fail("不包含结束时间情况下,下一个元素不应该存在!");
} catch (NoSuchElementException ignored) {
}
}
@Test
public void rangeToListTest() {
DateTime start = DateUtil.parse("2017-01-01");
DateTime end = DateUtil.parse("2017-01-31");
List<DateTime> rangeToList = DateUtil.rangeToList(start, end, DateField.DAY_OF_YEAR);
Assert.assertEquals(rangeToList.get(0), DateUtil.parse("2017-01-01"));
Assert.assertEquals(rangeToList.get(1), DateUtil.parse("2017-01-02"));
}
@Test
public void yearAndQTest() {
String yearAndQuarter = DateUtil.yearAndQuarter(DateUtil.parse("2018-12-01"));
Assert.assertEquals("20184", yearAndQuarter);
LinkedHashSet<String> yearAndQuarters = DateUtil.yearAndQuarter(DateUtil.parse("2018-09-10"), DateUtil.parse("2018-12-20"));
List<String> list = CollUtil.list(false, yearAndQuarters);
Assert.assertEquals(2, list.size());
Assert.assertEquals("20183", list.get(0));
Assert.assertEquals("20184", list.get(1));
LinkedHashSet<String> yearAndQuarters2 = DateUtil.yearAndQuarter(DateUtil.parse("2018-10-10"), DateUtil.parse("2018-12-10"));
List<String> list2 = CollUtil.list(false, yearAndQuarters2);
Assert.assertEquals(1, list2.size());
Assert.assertEquals("20184", list2.get(0));
}
@Test
public void formatHttpDateTest() {
String formatHttpDate = DateUtil.formatHttpDate(DateUtil.parse("2019-01-02 22:32:01"));
Assert.assertEquals("Wed, 02 Jan 2019 14:32:01 GMT", formatHttpDate);
}
@Test
public void toInstantTest(){
LocalDateTime localDateTime = LocalDateTime.parse("2017-05-06T08:30:00", DateTimeFormatter.ISO_DATE_TIME);
Instant instant = DateUtil.toInstant(localDateTime);
Assert.assertEquals("2017-05-06T00:30:00Z", instant.toString());
LocalDate localDate = localDateTime.toLocalDate();
instant = DateUtil.toInstant(localDate);
Assert.assertNotNull(instant);
LocalTime localTime = localDateTime.toLocalTime();
instant = DateUtil.toInstant(localTime);
Assert.assertNotNull(instant);
}
@Test
public void dateTest(){
LocalDateTime localDateTime = LocalDateTime.parse("2017-05-06T08:30:00", DateTimeFormatter.ISO_DATE_TIME);
DateTime date = DateUtil.date(localDateTime);
Assert.assertEquals("2017-05-06 08:30:00", date.toString());
}
@Test
public void dateTest2(){
// 测试负数日期
long dateLong = -1497600000;
final DateTime date = DateUtil.date(dateLong);
Assert.assertEquals("1969-12-15 00:00:00", date.toString());
}
@Test
public void ageTest(){
String d1 = "2000-02-29";
String d2 = "2018-02-28";
final int age = DateUtil.age(DateUtil.parseDate(d1), DateUtil.parseDate(d2));
Assert.assertEquals(18, age);
}
@Test(expected = IllegalArgumentException.class)
public void ageTest2(){
String d1 = "2019-02-29";
String d2 = "2018-02-28";
DateUtil.age(DateUtil.parseDate(d1), DateUtil.parseDate(d2));
}
@Test
public void isExpiredTest(){
DateTime startDate = DateUtil.parse("2019-12-01 17:02:30");
DateTime endDate = DateUtil.parse("2019-12-02 17:02:30");
int length = 3;
//noinspection deprecation
boolean expired = DateUtil.isExpired(startDate, DateField.DAY_OF_YEAR, length, endDate);
Assert.assertTrue(expired);
}
@Test
public void localDateTimeTest() {
// 测试字符串与LocalDateTime的互相转换
String strDate = "2019-12-01 17:02:30";
LocalDateTime ldt = DateUtil.parseLocalDateTime(strDate);
String strDate1 = DateUtil.formatLocalDateTime(ldt);
Assert.assertEquals(strDate, strDate1);
String strDate2 = "2019-12-01 17:02:30.111";
ldt = DateUtil.parseLocalDateTime(strDate2, DatePattern.NORM_DATETIME_MS_PATTERN);
strDate1 = DateUtil.format(ldt, DatePattern.NORM_DATETIME_PATTERN);
Assert.assertEquals(strDate, strDate1);
}
@Test
public void localDateTimeTest2() {
// 测试字符串与LocalDateTime的互相转换
String strDate = "2019-12-01";
final LocalDateTime localDateTime = DateUtil.parseLocalDateTime(strDate, "yyyy-MM-dd");
Assert.assertEquals(strDate, DateUtil.format(localDateTime, DatePattern.NORM_DATE_PATTERN));
}
@Test
public void betweenWeekTest() {
final DateTime start = DateUtil.parse("2019-03-05");
final DateTime end = DateUtil.parse("2019-10-05");
final long weekCount = DateUtil.betweenWeek(start, end, true);
Assert.assertEquals(30L, weekCount);
}
@Test
public void betweenDayTest() {
for (int i = 0; i < 1000; i++) {
String datr = RandomUtil.randomInt(1900, 2099) + "-01-20";
long betweenDay = DateUtil.betweenDay(
DateUtil.parseDate("1970-01-01"),
DateUtil.parseDate(datr), false);
Assert.assertEquals(Math.abs(LocalDate.parse(datr).toEpochDay()), betweenDay);
}
}
@Test
public void dayOfYearTest() {
int dayOfYear = DateUtil.dayOfYear(DateUtil.parse("2020-01-01"));
Assert.assertEquals(1, dayOfYear);
int lengthOfYear = DateUtil.lengthOfYear(2020);
Assert.assertEquals(366, lengthOfYear);
}
@SuppressWarnings("ConstantConditions")
@Test
public void parseSingleNumberTest(){
DateTime dateTime = DateUtil.parse("2020-5-08");
Assert.assertEquals("2020-05-08 00:00:00", dateTime.toString());
dateTime = DateUtil.parse("2020-5-8");
Assert.assertEquals("2020-05-08 00:00:00", dateTime.toString());
dateTime = DateUtil.parse("2020-05-8");
Assert.assertEquals("2020-05-08 00:00:00", dateTime.toString());
//datetime
dateTime = DateUtil.parse("2020-5-8 3:12:3");
Assert.assertEquals("2020-05-08 03:12:03", dateTime.toString());
dateTime = DateUtil.parse("2020-5-8 3:2:3");
Assert.assertEquals("2020-05-08 03:02:03", dateTime.toString());
dateTime = DateUtil.parse("2020-5-8 3:12:13");
Assert.assertEquals("2020-05-08 03:12:13", dateTime.toString());
dateTime = DateUtil.parse("2020-5-8 4:12:26.223");
Assert.assertEquals("2020-05-08 04:12:26", dateTime.toString());
}
@SuppressWarnings("ConstantConditions")
@Test
public void parseISO8601Test(){
String dt = "2020-06-03 12:32:12,333";
final DateTime parse = DateUtil.parse(dt);
Assert.assertEquals("2020-06-03 12:32:12", parse.toString());
}
@Test(expected = DateException.class)
public void parseNotFitTest(){
//https://github.com/looly/hutool/issues/1332
// 在日期格式不匹配的时候,测试是否正常报错
final DateTime parse = DateUtil.parse("2020-12-23", DatePattern.PURE_DATE_PATTERN);
}
}
|
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.api.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
/**
* <p>
* Generic interface to provide a Reader or InputStream for the underlying IO resource.
* </p>
*/
public interface Resource extends Serializable {
/**
* Open an InputStream to the resource, the user must close this when finished.
*
* @return
* @throws IOException
*/
public InputStream getInputStream() throws IOException;
/**
* Opens a Reader to the resource, the user most close this when finished.
* @return
* @throws IOException
*/
public Reader getReader() throws IOException;
/**
* Returns the name of the resource, if one is available.
*/
public String getSourcePath();
/**
* Returns the path that should be used when writing this resource down
* to KieFileSystem
*/
public String getTargetPath();
/**
* Returns the type of the resource if one could be inferred by the
* extension of the resource of if it was explicitly set.
*/
public ResourceType getResourceType();
/**
* Returns the configuration for the resource if one is available
*/
public ResourceConfiguration getConfiguration();
/**
* Sets this resource name. Some services require a resource to be
* named and it is not always possible to infer a name automatically.
* For instance, a file resource automatically infers its name from the
* file and path, but a byte array resource has to be given a name.
*
* @param path the path of the resource
*
* @return the resource itself in order to use it as a fluent API
*/
public Resource setSourcePath( String path );
/**
* In case this resource should be written to a different path
* when writing it down to the KieFileSystem, this property
* allows the application to set such path.
*
* @param path the path of the resource
*
* @return the resource itself in order to use it as a fluent API
*/
public Resource setTargetPath( String path );
/**
* Sets the resource type. For some resources it is possible to infer
* the type by the file name extension for instance. When it is not
* possible to infer it automatically, the user is expected to set it.
*
* @param type the resource type
*
* @return the resource itself in order to use it as a fluent API
*/
public Resource setResourceType( ResourceType type );
/**
* Sets the resource configuration in case it is necessary.
*
* @param conf the resource configuration
*
* @return the resource itself in order to use it as a fluent API
*/
public Resource setConfiguration( ResourceConfiguration conf );
}
|
package com.banuba.sdk.manager;
import androidx.annotation.Nullable;
import com.banuba.sdk.camera.Facing;
/**
* Encapsulates info about Banuba SDK Manager ({@link BanubaSdkManager}) Configuration.
*/
final public class BanubaSdkManagerConfiguration {
private final boolean mIsMirrored;
private final Facing mFacing;
@Nullable
private final IResolutionController mResolutionController;
@Nullable
private final IFpsController mFpsController;
@Nullable
private final IAutoRotationHandler mAutoRotationHandler;
private BanubaSdkManagerConfiguration(Builder builder) {
this.mIsMirrored = builder.mIsMirrored;
this.mFacing = builder.mFacing;
this.mResolutionController = builder.mResolutionController;
this.mFpsController = builder.mFpsController;
this.mAutoRotationHandler = builder.mAutoRotationHandler;
}
/**
* Return is camera should be mirrored value.
*
* @return image from camera should be mirrored.
*/
public boolean isFacingMirrored() {
return mIsMirrored;
}
/**
* Get camera facing.
*
* @return camera {@link Facing} value.
*/
public Facing getFacing() {
return mFacing;
}
/**
* Get resolution controlller.
*
* @return {@link IResolutionController}.
*/
@Nullable
public IResolutionController getResolutionController() {
return mResolutionController;
}
/**
* Get FPS controller.
*
* @return {@link IFpsController}.
*/
@Nullable
public IFpsController getFpsController() {
return mFpsController;
}
/**
* Get auto rotation handler.
*
* @return {@link IAutoRotationHandler}.
*/
@Nullable
public IAutoRotationHandler getAutoRotationHandler() {
return mAutoRotationHandler;
}
/**
* Create new {@link Builder} instance.
*
* @return {@link Builder} instance.
*/
public static Builder newInstance() {
return new Builder();
}
/**
* Create new {@link Builder} instance.
*
* @param defaultFacing Default {@link Facing} value.
* @param isFacingMirrored Is mirroring required value.
* @return {@link Builder} instance.
*/
public static Builder newInstance(Facing defaultFacing, boolean isFacingMirrored) {
return new Builder(defaultFacing, isFacingMirrored);
}
public static class Builder {
private boolean mIsMirrored = true;
private Facing mFacing = Facing.FRONT;
@Nullable
private IResolutionController mResolutionController;
@Nullable
private IFpsController mFpsController;
@Nullable
private IAutoRotationHandler mAutoRotationHandler;
private Builder() {
}
private Builder(Facing defaultFacing, boolean isFacingMirrored) {
this.mFacing = defaultFacing;
this.mIsMirrored = isFacingMirrored;
}
/**
* Set is mirroring required.
*
* @param isFacingMirrored If mirroring required value.
* @return {@link Builder} instance.
*/
public Builder setFacingMirrored(boolean isFacingMirrored) {
this.mIsMirrored = isFacingMirrored;
return this;
}
/**
* Set camere {@link Facing}.
*
* @param facing Camera {@link Facing} value.
* @return {@link Builder} instance.
*/
public Builder setFacing(Facing facing) {
this.mFacing = facing;
return this;
}
/**
* Set {@link IResolutionController}.
*
* @param controller {@link IResolutionController} value.
* @return {@link Builder} instance.
*/
public Builder setResolutionController(@Nullable IResolutionController controller) {
this.mResolutionController = controller;
return this;
}
/**
* Set {@link IFpsController}.
*
* @param controller {@link IFpsController} value.
* @return {@link Builder} instance.
*/
public Builder setFpsController(@Nullable IFpsController controller) {
this.mFpsController = controller;
return this;
}
/**
* Set {@link IAutoRotationHandler}.
*
* @param handler {@link IAutoRotationHandler} value.
* @return {@link Builder} instance.
*/
public Builder setAutoRotationHandler(@Nullable IAutoRotationHandler handler) {
this.mAutoRotationHandler = handler;
return this;
}
/**
* Build {@link BanubaSdkManagerConfiguration} object.
*
* @return {@link BanubaSdkManagerConfiguration} object.
*/
public BanubaSdkManagerConfiguration build() {
return new BanubaSdkManagerConfiguration(this);
}
}
}
|
/**
* Copyright 2011 Link Intersystems GmbH <rene.link@link-intersystems.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.link_intersystems.lang.reflect.testclasses;
import java.util.List;
public class GenericBoundType extends GenericClassWithBeanType<List<String[]>> {
}
|
package eu.stratuslab.marketplace.server.store.file;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import eu.stratuslab.marketplace.server.util.ResourceTestBase;
import eu.stratuslab.marketplace.server.utils.MetadataFileUtils;
public class FileMonitorTest extends ResourceTestBase {
private static String tmpDir;
@BeforeClass
public static void setUp() throws Exception {
tmpDir = getTempDir("marketplace");
MetadataFileUtils.createIfNotExists(tmpDir);
}
@AfterClass
public static void tearDown() throws Exception {
FileUtils.deleteDirectory(new File(tmpDir));
}
@Test
public void testGetFiles() throws Exception {
FileMonitor monitor = new FileMonitor(tmpDir, ".xml");
File tmpFile = File.createTempFile("test", ".xml", new File(tmpDir));
Thread.sleep(6 * 1000L);
File monitorFile = monitor.getFile();
assertNotNull(monitorFile);
assertThat(monitorFile.getCanonicalPath(), is(tmpFile.getCanonicalPath()));
}
@Test
public void testFileOrder() throws Exception {
FileMonitor monitor = new FileMonitor(tmpDir, ".xml");
File file1 = new File(tmpDir + File.separator + "2012-08-02T10:25:09Z.xml");
File file2 = new File(tmpDir + File.separator + "2013-08-02T10:25:09Z.xml");
File file3 = new File(tmpDir + File.separator + "2013-11-02T10:25:09Z.xml");
file1.createNewFile();
file3.createNewFile();
file2.createNewFile();
Thread.sleep(6 * 1000L);
assertThat(monitor.getFile().getCanonicalPath(), is(file1.getCanonicalPath()));
assertThat(monitor.getFile().getCanonicalPath(), is(file2.getCanonicalPath()));
assertThat(monitor.getFile().getCanonicalPath(), is(file3.getCanonicalPath()));
}
}
|
/**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* 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.kaazing.gateway.resource.address.ws;
public class MockWsDraft extends WsResourceAddressFactorySpi {
@Override
public String getSchemeName() {
return "ws-draft";
}
@Override
protected String getProtocolName() {
return "ws/draft-7x";
}
@Override
protected String getRootSchemeName() {
return "ws";
}
}
|
package io.renren.utils.wxpay;
import org.jboss.logging.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.util.Properties;
/**
* 创建时间:2016年6月14日 下午7:47:27
*
* @author andy
* @version 2.2
*/
public class ConfigUtil {
private static final Logger LOG = Logger.getLogger(ConfigUtil.class);
private static Properties config = null;
/**
* 返回系统config.properties配置信息
* @param key key值
* @return value值
*/
public static String getProperty(String key) {
if (config == null) {
synchronized (ConfigUtil.class) {
if (null == config) {
try {
Resource resource = new ClassPathResource("config.properties");
config = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
}
}
}
}
return config.getProperty(key);
}
}
|
package com.dipasquale.ai.common.fitness;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import java.io.Serial;
import java.io.Serializable;
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
final class MaximumFitnessDeterminer implements FitnessDeterminer, Serializable {
@Serial
private static final long serialVersionUID = -6792059173769832477L;
private boolean initialized = false;
private float value = 0f;
@Override
public float get() {
return value;
}
@Override
public void add(final float fitness) {
if (!initialized) {
initialized = true;
value = fitness;
} else {
value = Math.max(value, fitness);
}
}
@Override
public void clear() {
initialized = false;
value = 0f;
}
}
|
/*
* 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.features.python.toolchain;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rulekey.AddsToRuleKey;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
@BuckStyleValue
public abstract class PythonVersion implements AddsToRuleKey {
@AddToRuleKey
public abstract String getInterpreterName();
@AddToRuleKey
public abstract String getVersionString(); // X.Y
@Override
public String toString() {
return getInterpreterName() + " " + getVersionString();
}
public static PythonVersion of(String interpreterName, String versionString) {
return ImmutablePythonVersion.ofImpl(interpreterName, versionString);
}
}
|
/*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2020, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.memory.trailing.trail.flatten;
import org.chocosolver.memory.trailing.StoredInt;
import org.chocosolver.memory.trailing.trail.IStoredIntTrail;
public class StoredIntTrail implements IStoredIntTrail {
/**
* Load factor
*/
private final double loadfactor;
/**
* Stack of backtrackable search variables.
*/
private StoredInt[] variableStack;
/**
* Stack of values (former values that need be restored upon backtracking).
*/
private int[] valueStack;
/**
* Stack of timestamps indicating the world where the former value
* had been written.
*/
private int[] stampStack;
/**
* Points the level of the last entry.
*/
private int currentLevel;
/**
* A stack of pointers (for each start of a world).
*/
private int[] worldStartLevels;
/**
* Constructs a trail with predefined size.
*
* @param nUpdates maximal number of updates that will be stored
* @param nWorlds maximal number of worlds that will be stored
* @param loadfactor load factor for structures
*/
public StoredIntTrail(int nUpdates, int nWorlds, double loadfactor) {
currentLevel = 0;
variableStack = new StoredInt[nUpdates];
valueStack = new int[nUpdates];
stampStack = new int[nUpdates];
worldStartLevels = new int[nWorlds];
this.loadfactor = loadfactor;
}
/**
* Moving up to the next world.
*
* @param worldIndex current world index
*/
@Override
public void worldPush(int worldIndex) {
worldStartLevels[worldIndex] = currentLevel;
if (worldIndex == worldStartLevels.length - 1) {
resizeWorldCapacity((int) (worldStartLevels.length * loadfactor));
}
}
/**
* Moving down to the previous world.
*
* @param worldIndex current world index
*/
@Override
public void worldPop(int worldIndex) {
final int wsl = worldStartLevels[worldIndex];
while (currentLevel > wsl) {
currentLevel--;
final StoredInt v = variableStack[currentLevel];
v._set(valueStack[currentLevel], stampStack[currentLevel]);
}
}
/**
* Comits a world: merging it with the previous one.
*/
@Override
public void worldCommit(int worldIndex) {
// principle:
// currentLevel decreases to end of previous world
// updates of the committed world are scanned:
// if their stamp is the previous one (merged with the current one) -> remove the update (garbage collecting this position for the next update)
// otherwise update the worldStamp
final int startLevel = worldStartLevels[worldIndex];
final int prevWorld = worldIndex - 1;
int writeIdx = startLevel;
for (int level = startLevel; level < currentLevel; level++) {
final StoredInt var = variableStack[level];
final int val = valueStack[level];
final int stamp = stampStack[level];
var.overrideTimeStamp(prevWorld);// update the stamp of the variable (current stamp refers to a world that no longer exists)
if (stamp != prevWorld) {
// shift the update if needed
if (writeIdx != level) {
valueStack[writeIdx] = val;
variableStack[writeIdx] = var;
stampStack[writeIdx] = stamp;
}
writeIdx++;
} //else:writeIdx is not incremented and the update will be discarded (since a good one is in prevWorld)
}
currentLevel = writeIdx;
}
/**
* Reacts when a StoredInt is modified: push the former value & timestamp
* on the stacks.
*/
@Override
public void savePreviousState(StoredInt v, int oldValue, int oldStamp) {
valueStack[currentLevel] = oldValue;
variableStack[currentLevel] = v;
stampStack[currentLevel] = oldStamp;
currentLevel++;
if (currentLevel == variableStack.length) {
resizeUpdateCapacity();
}
}
@Override
public void buildFakeHistory(StoredInt v, int initValue, int olderStamp) {
// from world 0 to fromStamp (excluded), create a fake history based on initValue
// kind a copy of the current elements
// first save the current state on the top of the stack
savePreviousState(v, initValue, olderStamp - 1);
// second: ensures capacities
while (currentLevel + olderStamp > variableStack.length) {
resizeUpdateCapacity();
}
int i1, f, s = currentLevel;
for (int w = olderStamp; w > 1; w--) {
f = worldStartLevels[w];
i1 = f + w - 1;
s -= f;
System.arraycopy(variableStack, f, variableStack, i1, s);
System.arraycopy(valueStack, f, valueStack, i1, s);
System.arraycopy(stampStack, f, stampStack, i1, s);
variableStack[i1 - 1] = v;
valueStack[i1 - 1] = initValue;
stampStack[i1 - 1] = w - 2;
worldStartLevels[w] += w - 1;
currentLevel++;
s = f;
}
}
private void resizeUpdateCapacity() {
final int newCapacity = (int) (variableStack.length * loadfactor);
// first, copy the stack of variables
final StoredInt[] tmp1 = new StoredInt[newCapacity];
System.arraycopy(variableStack, 0, tmp1, 0, variableStack.length);
variableStack = tmp1;
// then, copy the stack of former values
final int[] tmp2 = new int[newCapacity];
System.arraycopy(valueStack, 0, tmp2, 0, valueStack.length);
valueStack = tmp2;
// then, copy the stack of world stamps
final int[] tmp3 = new int[newCapacity];
System.arraycopy(stampStack, 0, tmp3, 0, stampStack.length);
stampStack = tmp3;
}
private void resizeWorldCapacity(int newWorldCapacity) {
final int[] tmp = new int[newWorldCapacity];
System.arraycopy(worldStartLevels, 0, tmp, 0, worldStartLevels.length);
worldStartLevels = tmp;
}
}
|
package com.eeefff.limiter.core.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.eeefff.limiter.common.vo.Result;
import com.eeefff.limiter.core.service.ClientService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Controller
@RequestMapping(value = "/ip-limiter/client", produces = MediaType.APPLICATION_JSON_VALUE)
public class ClientRegisterController {
@Autowired
private ClientService clientRegisterService;
@ResponseBody
@RequestMapping("/registerToServer")
public Result<String> registerToServer() {
Result<String> result = Result.empty();
log.info("往IP限流控制台发起注册");
boolean registerResult = clientRegisterService.registerToServer();
if (registerResult) {
result.setSuccess(true);
result.setData("往IP限流控制台发起注册成功.");
log.info("往IP限流控制台发起注册成功.");
} else {
result.setCode(-1);
result.setSuccess(false);
result.setData("往IP限流控制台发起注册失败!");
log.info("往IP限流控制台发起注册失败!");
}
return result;
}
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.datamigration.v2018_03_31_preview;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Database specific information for SQL to SQL migration task inputs.
*/
public class MigrateSqlServerSqlServerDatabaseInput {
/**
* Name of the database.
*/
@JsonProperty(value = "name")
private String name;
/**
* Name of the database at destination.
*/
@JsonProperty(value = "restoreDatabaseName")
private String restoreDatabaseName;
/**
* Backup file share information for this database.
*/
@JsonProperty(value = "backupFileShare")
private FileShare backupFileShare;
/**
* The list of database files.
*/
@JsonProperty(value = "databaseFiles")
private List<DatabaseFileInput> databaseFiles;
/**
* Get name of the database.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set name of the database.
*
* @param name the name value to set
* @return the MigrateSqlServerSqlServerDatabaseInput object itself.
*/
public MigrateSqlServerSqlServerDatabaseInput withName(String name) {
this.name = name;
return this;
}
/**
* Get name of the database at destination.
*
* @return the restoreDatabaseName value
*/
public String restoreDatabaseName() {
return this.restoreDatabaseName;
}
/**
* Set name of the database at destination.
*
* @param restoreDatabaseName the restoreDatabaseName value to set
* @return the MigrateSqlServerSqlServerDatabaseInput object itself.
*/
public MigrateSqlServerSqlServerDatabaseInput withRestoreDatabaseName(String restoreDatabaseName) {
this.restoreDatabaseName = restoreDatabaseName;
return this;
}
/**
* Get backup file share information for this database.
*
* @return the backupFileShare value
*/
public FileShare backupFileShare() {
return this.backupFileShare;
}
/**
* Set backup file share information for this database.
*
* @param backupFileShare the backupFileShare value to set
* @return the MigrateSqlServerSqlServerDatabaseInput object itself.
*/
public MigrateSqlServerSqlServerDatabaseInput withBackupFileShare(FileShare backupFileShare) {
this.backupFileShare = backupFileShare;
return this;
}
/**
* Get the list of database files.
*
* @return the databaseFiles value
*/
public List<DatabaseFileInput> databaseFiles() {
return this.databaseFiles;
}
/**
* Set the list of database files.
*
* @param databaseFiles the databaseFiles value to set
* @return the MigrateSqlServerSqlServerDatabaseInput object itself.
*/
public MigrateSqlServerSqlServerDatabaseInput withDatabaseFiles(List<DatabaseFileInput> databaseFiles) {
this.databaseFiles = databaseFiles;
return this;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode.snapshot;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry;
import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffType;
import org.apache.hadoop.hdfs.server.namenode.INode;
import org.apache.hadoop.hdfs.server.namenode.INodeDirectory;
import org.apache.hadoop.hdfs.server.namenode.INodeFile;
import org.apache.hadoop.hdfs.server.namenode.INodeReference;
import org.apache.hadoop.hdfs.server.namenode.snapshot.DirectoryWithSnapshotFeature.ChildrenDiff;
import org.apache.hadoop.hdfs.util.Diff.ListType;
import com.google.common.base.Preconditions;
import com.google.common.primitives.SignedBytes;
/**
* A class describing the difference between snapshots of a snapshottable
* directory.
*/
class SnapshotDiffInfo {
/** Compare two inodes based on their full names */
public static final Comparator<INode> INODE_COMPARATOR =
new Comparator<INode>() {
@Override
public int compare(INode left, INode right) {
if (left == null) {
return right == null ? 0 : -1;
} else {
if (right == null) {
return 1;
} else {
int cmp = compare(left.getParent(), right.getParent());
return cmp == 0 ? SignedBytes.lexicographicalComparator().compare(
left.getLocalNameBytes(), right.getLocalNameBytes()) : cmp;
}
}
}
};
static class RenameEntry {
private byte[][] sourcePath;
private byte[][] targetPath;
void setSource(INode source, byte[][] sourceParentPath) {
Preconditions.checkState(sourcePath == null);
sourcePath = new byte[sourceParentPath.length + 1][];
System.arraycopy(sourceParentPath, 0, sourcePath, 0,
sourceParentPath.length);
sourcePath[sourcePath.length - 1] = source.getLocalNameBytes();
}
void setTarget(INode target, byte[][] targetParentPath) {
targetPath = new byte[targetParentPath.length + 1][];
System.arraycopy(targetParentPath, 0, targetPath, 0,
targetParentPath.length);
targetPath[targetPath.length - 1] = target.getLocalNameBytes();
}
void setTarget(byte[][] targetPath) {
this.targetPath = targetPath;
}
boolean isRename() {
return sourcePath != null && targetPath != null;
}
byte[][] getSourcePath() {
return sourcePath;
}
byte[][] getTargetPath() {
return targetPath;
}
}
/** The root directory of the snapshots */
private final INodeDirectorySnapshottable snapshotRoot;
/** The starting point of the difference */
private final Snapshot from;
/** The end point of the difference */
private final Snapshot to;
/**
* A map recording modified INodeFile and INodeDirectory and their relative
* path corresponding to the snapshot root. Sorted based on their names.
*/
private final SortedMap<INode, byte[][]> diffMap =
new TreeMap<INode, byte[][]>(INODE_COMPARATOR);
/**
* A map capturing the detailed difference about file creation/deletion.
* Each key indicates a directory whose children have been changed between
* the two snapshots, while its associated value is a {@link ChildrenDiff}
* storing the changes (creation/deletion) happened to the children (files).
*/
private final Map<INodeDirectory, ChildrenDiff> dirDiffMap =
new HashMap<INodeDirectory, ChildrenDiff>();
private final Map<Long, RenameEntry> renameMap =
new HashMap<Long, RenameEntry>();
SnapshotDiffInfo(INodeDirectorySnapshottable snapshotRoot, Snapshot start,
Snapshot end) {
this.snapshotRoot = snapshotRoot;
this.from = start;
this.to = end;
}
/** Add a dir-diff pair */
void addDirDiff(INodeDirectory dir, byte[][] relativePath, ChildrenDiff diff) {
dirDiffMap.put(dir, diff);
diffMap.put(dir, relativePath);
// detect rename
for (INode created : diff.getList(ListType.CREATED)) {
if (created.isReference()) {
RenameEntry entry = getEntry(created.getId());
if (entry.getTargetPath() == null) {
entry.setTarget(created, relativePath);
}
}
}
for (INode deleted : diff.getList(ListType.DELETED)) {
if (deleted instanceof INodeReference.WithName) {
RenameEntry entry = getEntry(deleted.getId());
entry.setSource(deleted, relativePath);
}
}
}
Snapshot getFrom() {
return from;
}
Snapshot getTo() {
return to;
}
private RenameEntry getEntry(long inodeId) {
RenameEntry entry = renameMap.get(inodeId);
if (entry == null) {
entry = new RenameEntry();
renameMap.put(inodeId, entry);
}
return entry;
}
void setRenameTarget(long inodeId, byte[][] path) {
getEntry(inodeId).setTarget(path);
}
/** Add a modified file */
void addFileDiff(INodeFile file, byte[][] relativePath) {
diffMap.put(file, relativePath);
}
/** @return True if {@link #from} is earlier than {@link #to} */
boolean isFromEarlier() {
return Snapshot.ID_COMPARATOR.compare(from, to) < 0;
}
/**
* Generate a {@link SnapshotDiffReport} based on detailed diff information.
* @return A {@link SnapshotDiffReport} describing the difference
*/
public SnapshotDiffReport generateReport() {
List<DiffReportEntry> diffReportList = new ArrayList<DiffReportEntry>();
for (INode node : diffMap.keySet()) {
diffReportList.add(new DiffReportEntry(DiffType.MODIFY, diffMap
.get(node), null));
if (node.isDirectory()) {
List<DiffReportEntry> subList = generateReport(dirDiffMap.get(node),
diffMap.get(node), isFromEarlier(), renameMap);
diffReportList.addAll(subList);
}
}
return new SnapshotDiffReport(snapshotRoot.getFullPathName(),
Snapshot.getSnapshotName(from), Snapshot.getSnapshotName(to),
diffReportList);
}
/**
* Interpret the ChildrenDiff and generate a list of {@link DiffReportEntry}.
* @param dirDiff The ChildrenDiff.
* @param parentPath The relative path of the parent.
* @param fromEarlier True indicates {@code diff=later-earlier},
* False indicates {@code diff=earlier-later}
* @param renameMap A map containing information about rename operations.
* @return A list of {@link DiffReportEntry} as the diff report.
*/
private List<DiffReportEntry> generateReport(ChildrenDiff dirDiff,
byte[][] parentPath, boolean fromEarlier, Map<Long, RenameEntry> renameMap) {
List<DiffReportEntry> list = new ArrayList<DiffReportEntry>();
List<INode> created = dirDiff.getList(ListType.CREATED);
List<INode> deleted = dirDiff.getList(ListType.DELETED);
byte[][] fullPath = new byte[parentPath.length + 1][];
System.arraycopy(parentPath, 0, fullPath, 0, parentPath.length);
for (INode cnode : created) {
RenameEntry entry = renameMap.get(cnode.getId());
if (entry == null || !entry.isRename()) {
fullPath[fullPath.length - 1] = cnode.getLocalNameBytes();
list.add(new DiffReportEntry(fromEarlier ? DiffType.CREATE
: DiffType.DELETE, fullPath));
}
}
for (INode dnode : deleted) {
RenameEntry entry = renameMap.get(dnode.getId());
if (entry != null && entry.isRename()) {
list.add(new DiffReportEntry(DiffType.RENAME,
fromEarlier ? entry.getSourcePath() : entry.getTargetPath(),
fromEarlier ? entry.getTargetPath() : entry.getSourcePath()));
} else {
fullPath[fullPath.length - 1] = dnode.getLocalNameBytes();
list.add(new DiffReportEntry(fromEarlier ? DiffType.DELETE
: DiffType.CREATE, fullPath));
}
}
return list;
}
}
|
import java.util.ArrayList;
import java.util.List;
public class MyBot {
public static void main(String[] args) throws java.io.IOException {
final InitPackage iPackage = Networking.getInit();
final int myID = iPackage.myID;
final GameMap gameMap = iPackage.map;
Networking.sendInit("JasonTheDestroyer");
while (true) {
List<Move> moves = new ArrayList<Move>();
Networking.updateFrame(gameMap);
for (int y = 0; y < gameMap.height; y++) {
for (int x = 0; x < gameMap.width; x++) {
final Location location = gameMap.getLocation(x, y);
final Site site = location.getSite();
if (site.owner == myID) {
moves.add(new Move(location, moveToLocation(location,locationAfterDirection(location, weakestSite(location)))));
/* if (nextToEnemy()) {
moves.add(new Move(location, moveToLocation(weakestSite(location))));
} else {
moves.add(new Move(location, );
}
moves.add(new Move(location, Direction.randomDirec=tion())); */
}
}
Networking.sendFrame(moves);
}
}
}
// Build a method that will identify the area that you control
// Build a method that will help you identify
/* private Direction expandToArea(location) {
}
*/
/* private static boolean overStacking(Location location) {
if(weakestSite(location) || ally(weakes))
if(location.getSite.strength + locationAfterDirection(location, weakestSite(location)).strength <= 255) {
return false;
} else {
return true;
}
}
*/
private Location locationAfterDirection(Location location, Direction direction, GameMap gameMap) {
if (Direction.NORTH.equals(direction)) {
return gameMap.getLocation(location.getX(),location.getY()+1);
}
if (Direction.SOUTH.equals(direction)) {
return gameMap.getLocation(location.getX(),location.getY()-1);
}
if (Direction.WEST.equals(direction)) {
return gameMap.getLocation((location.getX()-1), location.getY());
}
if (Direction.EAST == direction) {
return gameMap.getLocation(location.getX()+1, location.getY());
}
return location;
}
private Direction weakestSite(Location location, GameMap gameMap) {
int[] t1 = {(location.getX() + 1), location.getSite().strength};
int[] t2 = {(location.getX() - 1), location.getSite().strength};
int[] t3 = {location.getY() + 1, location.getSite().strength};
int[] t4 = {location.getY() - 1, location.getSite().strength};
int[][] t = {t3, t1, t4, t2};
int locationStrength = 255;
int weakest;
for (int i = 0; i < 4; i++) {
if (t[i][1] <= locationStrength) {
weakest = i;
locationStrength = t[i][2];
}
}
if (weakest == 1) {
return Direction.NORTH;
} else if (weakest == 2) {
return Direction.EAST;
} else if (weakest == 3) {
return Direction.SOUTH;
} else if (weakest == 4) {
return Direction.WEST;
}
return Direction.NORTH;
}
private boolean ally(Location location) { return location.getSite().owner == myID; }
private Location nearestEnemy(Location loc, GameMap gameMap) {
Location EndOfTheMap = new gameMap.getLocation(gameMap.height, gameMap.width);
Location CornerOfMap = new gameMap.getLocation(0, 0);
int distance = getDistance(CornerOfMap, EndOfTheMap);
Location closest = loc;
for (int y = 0; y < gameMap.height; y++) {
for (int x = 0; x < gameMap.width; x++) {
final Location location = gameMap.getLocation(x, y);
final Site site = location.getSite();
if (distance <= getDistance(loc, location) && site.owner != myID) {
closest = direction;
}
}
}
return closest;
}
// combine the for loops
private boolean nextToEnemy(GameMap gameMap) {
for (int y = 0; y < gameMap.height; y++) {
for (int x = 0; x < gameMap.width; x++) {
final Location location = gameMap.getLocation(x, y);
final Site site = location.getSite();
if (1 == getDistance(nearestEnemy(location))) {
return true;
}
}
}
return false;
}
/*
private Direction directionOfEnemy() {
}
*/
/* This method identifies the direciton in which all of the blocks move, does not work if the positions are the same
therefore a loop should be set up to end the direction when the positions or equal otherwise there would be an error */
private Direction moveToLocation(Location locationStart, Location locationFinish) {
int[] x = {locationStart.getX, locationFinish.getX};
int[] y = {locationStart.getY, locationFinish.getY};
if (x[0] != x[1]) {
if(x[0] > x[1]) {
return Direction.WEST;
} else {
return Direction.EAST;
}
} else if (y[0] != y[1]) {
if(y[0] > y[1]) {
return Direction.SOUTH;
} else {
return Direction.NORTH;
}
} else {
return Direction.NORTH; // Returns north if the values match
}
}
}
|
package project.components.receipts_components;
import javax.swing.ImageIcon;
import project.MainFrame;
import project.actions.receipts_actions.PointSubmitAL;
import project.components.goods_components.BasicSmallButton;
public class PointSubmitBtn extends BasicSmallButton {
PointSubmitAL pAL;
public PointSubmitBtn(MainFrame main, ImageIcon img, int xPos, int yPos, int xSize, int ySize) {
super(img);
addActionListener(pAL = new PointSubmitAL(main));
setBounds(xPos, yPos, xSize, ySize);
}
}
|
package com.serdarormanli.kalah.model;
import lombok.Value;
@Value
public class Message {
MessageType messageType;
int indexOfPit;
public static Message snapshot() {
return new Message(MessageType.LATEST_SNAPSHOT, 0);
}
public static Message play(int indexOfPit) {
return new Message(MessageType.PLAY, indexOfPit);
}
}
|
package com.linkedin.metadata.kafka;
import com.linkedin.data.template.RecordTemplate;
import com.linkedin.events.metadata.ChangeType;
import com.linkedin.metadata.EventUtils;
import com.linkedin.metadata.builders.graph.BaseGraphBuilder;
import com.linkedin.metadata.builders.graph.GraphBuilder;
import com.linkedin.metadata.builders.graph.RegisteredGraphBuilders;
import com.linkedin.metadata.builders.search.BaseIndexBuilder;
import com.linkedin.metadata.builders.search.SnapshotProcessor;
import com.linkedin.metadata.dao.internal.BaseGraphWriterDAO;
import com.linkedin.metadata.dao.utils.RecordUtils;
import com.linkedin.metadata.snapshot.Snapshot;
import com.linkedin.metadata.kafka.elasticsearch.ElasticsearchConnector;
import com.linkedin.metadata.kafka.elasticsearch.MCEElasticEvent;
import com.linkedin.mxe.MetadataAuditEvent;
import com.linkedin.mxe.Topics;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.avro.generic.GenericRecord;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@EnableKafka
public class MetadataAuditEventsProcessor {
// Doc Type should be updated when ElasticSearch Version is upgraded.
private static final String DOC_TYPE = "doc";
private ElasticsearchConnector elasticSearchConnector;
private SnapshotProcessor snapshotProcessor;
private BaseGraphWriterDAO graphWriterDAO;
private Set<BaseIndexBuilder<? extends RecordTemplate>> indexBuilders;
public MetadataAuditEventsProcessor(ElasticsearchConnector elasticSearchConnector,
SnapshotProcessor snapshotProcessor, BaseGraphWriterDAO graphWriterDAO,
Set<BaseIndexBuilder<? extends RecordTemplate>> indexBuilders) {
this.elasticSearchConnector = elasticSearchConnector;
this.snapshotProcessor = snapshotProcessor;
this.graphWriterDAO = graphWriterDAO;
this.indexBuilders = indexBuilders;
log.info("registered index builders {}", indexBuilders);
}
@KafkaListener(id = "mae-consumer-job-client", topics = "${KAFKA_TOPIC_NAME:" + Topics.METADATA_AUDIT_EVENT + "}")
public void consume(final ConsumerRecord<String, GenericRecord> consumerRecord) {
final GenericRecord record = consumerRecord.value();
log.debug("Got MAE");
try {
final MetadataAuditEvent event = EventUtils.avroToPegasusMAE(record);
if (event.hasNewSnapshot()) {
final Snapshot snapshot = event.getNewSnapshot();
log.info(snapshot.toString());
updateElasticsearch(snapshot);
updateNeo4j(RecordUtils.getSelectedRecordTemplateFromUnion(snapshot));
}
} catch (Exception e) {
log.error("Error deserializing message: {}", e.toString());
log.error("Message: {}", record.toString());
}
}
/**
* Process snapshot and update Neo4j
*
* @param snapshot Snapshot
*/
private void updateNeo4j(final RecordTemplate snapshot) {
try {
final BaseGraphBuilder graphBuilder = RegisteredGraphBuilders.getGraphBuilder(snapshot.getClass()).get();
final GraphBuilder.GraphUpdates updates = graphBuilder.build(snapshot);
if (!updates.getEntities().isEmpty()) {
graphWriterDAO.addEntities(updates.getEntities());
}
for (GraphBuilder.RelationshipUpdates update : updates.getRelationshipUpdates()) {
graphWriterDAO.addRelationships(update.getRelationships(), update.getPreUpdateOperation());
}
} catch (Exception ex) {
log.error(ex.toString() + " " + Arrays.toString(ex.getStackTrace()));
}
}
/**
* Process snapshot and update Elasticsearch
*
* @param snapshot Snapshot
*/
private void updateElasticsearch(final Snapshot snapshot) {
List<RecordTemplate> docs = new ArrayList<>();
try {
docs = snapshotProcessor.getDocumentsToUpdate(snapshot);
} catch (Exception e) {
log.error("Error in getting documents from snapshot: {}", e.toString());
}
for (RecordTemplate doc : docs) {
MCEElasticEvent elasticEvent = new MCEElasticEvent(doc);
BaseIndexBuilder indexBuilderForDoc = null;
for (BaseIndexBuilder indexBuilder : indexBuilders) {
Class docType = indexBuilder.getDocumentType();
if (docType.isInstance(doc)) {
indexBuilderForDoc = indexBuilder;
break;
}
}
if (indexBuilderForDoc == null) {
continue;
}
elasticEvent.setIndex(indexBuilderForDoc.getDocumentType().getSimpleName().toLowerCase());
elasticEvent.setType(DOC_TYPE);
try {
String urn = indexBuilderForDoc.getDocumentType().getMethod("getUrn").invoke(doc).toString();
elasticEvent.setId(URLEncoder.encode(urn.toLowerCase(), "UTF-8"));
} catch (UnsupportedEncodingException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
log.error("Failed to encode the urn with error: {}", e.toString());
continue;
}
elasticEvent.setActionType(ChangeType.UPDATE);
elasticSearchConnector.feedElasticEvent(elasticEvent);
}
}
}
|
package io.xmeta.impl.exceptions;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ExceptionWrapper {
public static final int SHORT_STRING_LENGTH = 150;
private static final String NON_THIN_CHARS = "[^iIl1\\.,']";
private static int textWidth(String str) {
return str.length() - str.replaceAll(NON_THIN_CHARS, "").length() / 2;
}
public static String ellipseString(String text, int targetLength) {
if (textWidth(text) <= targetLength) {
return text;
}
int end = text.lastIndexOf(' ', targetLength - 3);
if (end == -1) {
return text.substring(0, targetLength - 3) + "...";
}
int newEnd = end;
do {
end = newEnd;
newEnd = text.indexOf(' ', end + 1);
if (newEnd == -1) {
newEnd = text.length();
}
} while (textWidth(text.substring(0, newEnd) + "...") < targetLength);
return text.substring(0, end) + "...";
}
public static String getCause(Exception exception) {
StringBuilder exceptionCauses = new StringBuilder();
Throwable cause = exception.getCause();
int counter = 0;
while (cause != null && counter <= 50) {
exceptionCauses.append(cause.getMessage()).append(System.lineSeparator());
cause = cause.getCause();
counter++;
}
return exceptionCauses.toString();
}
public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
public static String wrapExceptionInMeaningMessage(Exception exception) {
String exceptionMessage = exception.getMessage();
if (exceptionMessage != null) {
if (exceptionMessage.contains("SerializationException")) {
return ExceptionErrorMessages.SERIALIZER_EXCEPTION.getDescription();
}
if (exceptionMessage.contains("ResponseException")) {
return ExceptionErrorMessages.RESPONSE_EXCEPTION.getDescription();
}
if (exceptionMessage.contains("ConnectionException")) {
return ExceptionErrorMessages.CONNECTION_EXCEPTION.getDescription();
}
if (exceptionMessage.length() > SHORT_STRING_LENGTH) {
return ellipseString(exceptionMessage, SHORT_STRING_LENGTH);
}
return exceptionMessage;
} else {
return ExceptionErrorMessages.ERROR_OCCURRED.getDescription();
}
}
}
|
/*
* Copyright (C) 2016 Red Hat, 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.syndesis.server.api.generator.swagger.util;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import io.swagger.models.ModelImpl;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.properties.IntegerProperty;
import io.syndesis.server.api.generator.APIValidationContext;
import io.syndesis.server.api.generator.swagger.AbstractSwaggerConnectorTest;
import io.syndesis.server.api.generator.swagger.SwaggerModelInfo;
import io.syndesis.server.jsondb.impl.JsonRecordSupport;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import static io.syndesis.server.api.generator.swagger.TestHelper.resource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
public class SwaggerHelperTest extends AbstractSwaggerConnectorTest {
@Test
public void shouldDeserializeSerializeWithoutLoosingEnumValues() throws JSONException {
final String document = "{\"swagger\":\"2.0\",\"definitions\":{\"Test\":{\"type\":\"object\",\"properties\":{\"key\":{\"type\":\"integer\",\"enum\":[1,2,3]}}}}}}}}}";
final SwaggerModelInfo info = SwaggerHelper.parse(document, APIValidationContext.CONSUMED_API);
final Swagger parsed = info.getModel();
final String serialized = SwaggerHelper.serialize(parsed);
JSONAssert.assertEquals(document,
serialized, JSONCompareMode.STRICT);
}
@Test
public void shouldSanitizeListOfTags() {
assertThat(SwaggerHelper.sanitizeTags(Arrays.asList("tag", "wag ", " bag", ".]t%a$g#[/")))
.containsExactly("tag", "wag", "bag");
}
@Test
public void shouldSanitizeTags() {
assertThat(SwaggerHelper.sanitizeTag("tag")).isEqualTo("tag");
assertThat(SwaggerHelper.sanitizeTag(".]t%a$g#[/")).isEqualTo("tag");
final char[] str = new char[1024];
final String randomString = IntStream.range(0, str.length)
.map(x -> (int) (Character.MAX_CODE_POINT * Math.random())).mapToObj(i -> new String(Character.toChars(i)))
.collect(Collectors.joining(""));
final String sanitized = SwaggerHelper.sanitizeTag(randomString);
assertThatCode(() -> JsonRecordSupport.validateKey(sanitized)).doesNotThrowAnyException();
}
@Test
public void shouldSerializeWithoutAddingResponseSchema() throws JSONException {
final Swagger document = new Swagger().path("/api", new Path()
.get(new Operation()
.response(200, new Response()
.responseSchema(new ModelImpl()
.type("object")
.property("key", new IntegerProperty())))));
final String serialized = SwaggerHelper.serialize(document);
JSONAssert.assertEquals(
"{\"swagger\":\"2.0\",\"paths\":{\"/api\":{\"get\":{\"responses\":{\"200\":{\"schema\":{\"type\":\"object\",\"properties\":{\"key\":{\"type\":\"integer\",\"format\":\"int32\"}}}}}}}}}",
serialized, JSONCompareMode.STRICT);
}
@Test
public void testThatAllSwaggerFilesAreValid() throws IOException {
final String[] specifications = {"/swagger/concur.swagger.json", "/swagger/petstore.swagger.json",
"/swagger/todo.swagger.yaml"};
for (final String specificationFile : specifications) {
final String specification = resource(specificationFile);
final SwaggerModelInfo info = SwaggerHelper.parse(specification, APIValidationContext.CONSUMED_API);
assertThat(info.getErrors())
.withFailMessage("Specification " + specificationFile + " has errors: " + info.getErrors()).isEmpty();
}
}
@Test
public void testThatInvalidFieldPetstoreSwaggerIsInvalid() throws IOException {
final String specification = resource("/swagger/invalid/invalid-field.petstore.swagger.json");
final SwaggerModelInfo info = SwaggerHelper.parse(specification, APIValidationContext.CONSUMED_API);
assertThat(info.getErrors()).hasSize(1);
assertThat(info.getWarnings()).isEmpty();
assertThat(info.getErrors().get(0).message())
.startsWith("object instance has properties which are not allowed by the schema");
assertThat(info.getErrors().get(0).property()).contains("/paths/~1pet/put");
assertThat(info.getErrors().get(0).error()).contains("validation");
}
@Test
public void testThatInvalidSchemePetstoreSwaggerIsInvalid() throws IOException {
final String specification = resource("/swagger/invalid/invalid-scheme.petstore.swagger.json");
final SwaggerModelInfo info = SwaggerHelper.parse(specification, APIValidationContext.CONSUMED_API);
assertThat(info.getErrors()).hasSize(1);
assertThat(info.getWarnings()).hasSize(1);
assertThat(info.getErrors().get(0).message()).startsWith("instance value (\"httpz\") not found in enum");
assertThat(info.getErrors().get(0).property()).contains("/schemes/0");
assertThat(info.getErrors().get(0).error()).contains("validation");
assertThat(info.getWarnings().get(0).message()).startsWith("Unable to determine the scheme");
assertThat(info.getWarnings().get(0).property()).contains("/schemes");
assertThat(info.getWarnings().get(0).error()).contains("missing-schemes");
}
@Test
public void testThatInvalidTypePetstoreSwaggerIsInvalid() throws IOException {
final String specification = resource("/swagger/invalid/invalid-type.petstore.swagger.json");
final SwaggerModelInfo info = SwaggerHelper.parse(specification, APIValidationContext.CONSUMED_API);
assertThat(info.getErrors()).hasSize(1);
assertThat(info.getWarnings()).isEmpty();
assertThat(info.getErrors().get(0).message()).startsWith("instance failed to match exactly one schema");
assertThat(info.getErrors().get(0).property()).contains("/paths/~1pet~1{petId}/post/parameters/2");
assertThat(info.getErrors().get(0).error()).contains("validation");
}
@Test
public void testThatWarningPetstoreSwaggerContainsWarnings() throws IOException {
final String specification = resource("/swagger/invalid/warning-petstore.swagger.json");
final SwaggerModelInfo info = SwaggerHelper.parse(specification, APIValidationContext.CONSUMED_API);
assertThat(info.getErrors()).isEmpty();
assertThat(info.getWarnings()).hasSize(3);
}
}
|
package org.chain3j.protocol.scs.methods.response;
import java.math.BigInteger;
import org.chain3j.protocol.core.Response;
import org.chain3j.utils.Numeric;
/**
* BigNumber response type.
* Return the block number of the MicroChain.
*/
public class ScsGetBalance extends Response<String> {
public BigInteger getBalance() {
return Numeric.decodeQuantity(getResult());
}
}
|
/*
* Copyright 2012 Roman Kashitsyn
*
* 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.rulesdsl.rules;
import com.google.common.base.Predicate;
import org.rulesdsl.Rule;
/**
* @author Roman Kashitsyn
* @since 1.0
*/
public abstract class AbstractRule<I, O> implements Rule<I, O> {
private final Predicate<? super I> predicate;
public AbstractRule(Predicate<? super I> predicate) {
this.predicate = predicate;
}
public O apply(I x) {
if( !isDefinedAt(x) ) {
throw new RuleNotApplicableException("Input " + x + " does not match " + predicate);
}
return getValue(x);
}
public boolean isDefinedAt(I x) {
return predicate.apply(x);
}
protected abstract O getValue(I input);
protected Predicate<? super I> getPredicate() {
return predicate;
}
}
|
package implementations.collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class JCLSFuture<T> implements Future<T>{
private T obj;
public JCLSFuture(T obj) {
this.obj = obj;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public T get() throws InterruptedException, ExecutionException {
return obj;
}
@Override
public T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return obj;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
}
|
package spotify.recommendation.login;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import spotify.recommendation.SessionConst;
import spotify.recommendation.entity.Member;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
@Controller
@RequiredArgsConstructor
public class LoginController {
private final LoginService loginService;
@GetMapping("/login")
public String loginForm(@ModelAttribute("loginForm") LoginForm loginForm){
return "login/loginForm";
}
@PostMapping("/login")
public String login(@Valid @ModelAttribute LoginForm form, BindingResult bindingResult, @RequestParam(defaultValue="/") String redirectURL, HttpServletRequest request){
if(bindingResult.hasErrors()){
return "login/loginForm";
}
Member loginMember = loginService.login(form.getEmail(), form.getPassword());
if(loginMember == null){
bindingResult.reject("loginFail", "이메일 또는 비밀번호가 맞지 않습니다.");
return "login/loginForm";
}
HttpSession session = request.getSession();
session.setAttribute(SessionConst.LOGIN_MEMBER, loginMember);
return "redirect:" + redirectURL;
}
@PostMapping("/logout")
public String logout(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if(session != null){
session.invalidate();
}
return "redirect:/";
}
private void expireCookie(HttpServletResponse response, String cookieName) {
Cookie cookie = new Cookie(cookieName, null);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
|
/*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.security.web.authentication.logout;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
/**
* Logs a principal out.
* <p>
* Polls a series of {@link LogoutHandler}s. The handlers should be specified in the order
* they are required. Generally you will want to call logout handlers
* <code>TokenBasedRememberMeServices</code> and <code>SecurityContextLogoutHandler</code>
* (in that order).
* <p>
* After logout, a redirect will be performed to the URL determined by either the
* configured <tt>LogoutSuccessHandler</tt> or the <tt>logoutSuccessUrl</tt>, depending on
* which constructor was used.
*
* @author Ben Alex
* @author Eddú Meléndez
*/
public class LogoutFilter extends GenericFilterBean {
// ~ Instance fields
// ================================================================================================
private RequestMatcher logoutRequestMatcher;
private final LogoutHandler handler;
private final LogoutSuccessHandler logoutSuccessHandler;
// ~ Constructors
// ===================================================================================================
/**
* Constructor which takes a <tt>LogoutSuccessHandler</tt> instance to determine the
* target destination after logging out. The list of <tt>LogoutHandler</tt>s are
* intended to perform the actual logout functionality (such as clearing the security
* context, invalidating the session, etc.).
*/
public LogoutFilter(LogoutSuccessHandler logoutSuccessHandler,
LogoutHandler... handlers) {
this.handler = new CompositeLogoutHandler(handlers);
Assert.notNull(logoutSuccessHandler, "logoutSuccessHandler cannot be null");
this.logoutSuccessHandler = logoutSuccessHandler;
setFilterProcessesUrl("/logout");
}
public LogoutFilter(String logoutSuccessUrl, LogoutHandler... handlers) {
this.handler = new CompositeLogoutHandler(handlers);
Assert.isTrue(
!StringUtils.hasLength(logoutSuccessUrl)
|| UrlUtils.isValidRedirectUrl(logoutSuccessUrl),
() -> logoutSuccessUrl + " isn't a valid redirect URL");
SimpleUrlLogoutSuccessHandler urlLogoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
if (StringUtils.hasText(logoutSuccessUrl)) {
urlLogoutSuccessHandler.setDefaultTargetUrl(logoutSuccessUrl);
}
logoutSuccessHandler = urlLogoutSuccessHandler;
setFilterProcessesUrl("/logout");
}
// ~ Methods
// ========================================================================================================
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (requiresLogout(request, response)) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (logger.isDebugEnabled()) {
logger.debug("Logging out user '" + auth
+ "' and transferring to logout destination");
}
this.handler.logout(request, response, auth);
logoutSuccessHandler.onLogoutSuccess(request, response, auth);
return;
}
chain.doFilter(request, response);
}
/**
* Allow subclasses to modify when a logout should take place.
*
* @param request the request
* @param response the response
*
* @return <code>true</code> if logout should occur, <code>false</code> otherwise
*/
protected boolean requiresLogout(HttpServletRequest request,
HttpServletResponse response) {
return logoutRequestMatcher.matches(request);
}
public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) {
Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null");
this.logoutRequestMatcher = logoutRequestMatcher;
}
public void setFilterProcessesUrl(String filterProcessesUrl) {
this.logoutRequestMatcher = new AntPathRequestMatcher(filterProcessesUrl);
}
}
|
/*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.core.spi.store.tiering;
import org.ehcache.config.ResourceType;
import org.ehcache.core.spi.store.StoreAccessException;
import org.ehcache.core.spi.store.Store;
import org.ehcache.spi.service.PluralService;
import org.ehcache.spi.service.Service;
import org.ehcache.spi.service.ServiceConfiguration;
import java.util.Collection;
import java.util.function.Function;
/**
* Authoritative tier, that is the lower most tier of a multi tiered store.
* <p>
* By design this tier will always hold all the mappings contained in the {@link org.ehcache.Cache}
*
* @param <K> the key type
* @param <V> the value type
*/
public interface AuthoritativeTier<K, V> extends Store<K, V> {
/**
* Marks the mapping as not evictable and returns it atomically.
*
* @return the value holder
*
* @throws StoreAccessException if the mapping can't be retrieved or updated.
*/
ValueHolder<V> getAndFault(K key) throws StoreAccessException;
/**
* Marks the mapping as not evictable and performs computeIfAbsent() atomically.
*
* @return the value holder.
*
* @throws StoreAccessException if the mapping can't be retrieved or updated.
*/
ValueHolder<V> computeIfAbsentAndFault(K key, Function<? super K, ? extends V> mappingFunction) throws StoreAccessException;
/**
* This marks a mapping as evictable again if it matches the {@link org.ehcache.core.spi.store.Store.ValueHolder}
* received.
*
* @return {@code true} if a mapping exists for that key, the mapping was faulted, and the value of the
* {@code ValueHolder} is equal to the value of the mapping in the {@code AuthoritativeTier}, {@code false} otherwise
*
* @throws IllegalArgumentException if the {@code ValueHolder} is not an instance from the CachingTier
*/
boolean flush(K key, ValueHolder<V> valueHolder);
/**
* Sets the {@link InvalidationValve} to be used by this {@code AuthoritativeTier}.
* <p>
* The invalidation valve provides a way for the {@code AuthoritativeTier} to force invalidation of
* {@link CachingTier} entries when that is required.
*
* @param valve the valve to use for triggering invalidations
*/
void setInvalidationValve(InvalidationValve valve);
/**
* Invalidation valve, that is the mechanism through which an {@link AuthoritativeTier} can request invalidations
* from the {@link CachingTier}.
*/
interface InvalidationValve {
/**
* Requests an invalidation of all {@link CachingTier} mappings.
*
* @throws StoreAccessException when en error occurs while invalidating mappings
*/
void invalidateAll() throws StoreAccessException;
/**
* Requests an invalidation of all {@link CachingTier} mappings whose key's hashcode matches the provided one.
*
* @throws StoreAccessException when en error occurs while invalidating mappings
*/
void invalidateAllWithHash(long hash) throws StoreAccessException;
}
/**
* {@link Service} interface for providing {@link AuthoritativeTier} instances.
* <p>
* Multiple providers may exist in a given {@link org.ehcache.CacheManager}.
*/
@PluralService
interface Provider extends Service {
/**
* Creates a new {@link AuthoritativeTier} instance using the provided configuration.
*
* @param storeConfig the {@code Store} configuration
* @param serviceConfigs a collection of service configurations
* @param <K> the key type for this tier
* @param <V> the value type for this tier
*
* @return the new authoritative tier
*/
<K, V> AuthoritativeTier<K, V> createAuthoritativeTier(Store.Configuration<K, V> storeConfig, ServiceConfiguration<?>... serviceConfigs);
/**
* Releases an {@link AuthoritativeTier}.
*
* @param resource the authoritative tier to release
*
* @throws IllegalArgumentException if this provider does not know about this authoritative tier
*/
void releaseAuthoritativeTier(AuthoritativeTier<?, ?> resource);
/**
* Initialises an {@link AuthoritativeTier}.
*
* @param resource the authoritative tier to initialise
*/
void initAuthoritativeTier(AuthoritativeTier<?, ?> resource);
/**
* Gets the internal ranking for the {@link AuthoritativeTier} instances provided by this {@code Provider} of the
* authority's ability to handle the specified resource.
* <p>
* A higher rank value indicates a more capable {@code AuthoritativeTier}.
*
* @param authorityResource the {@code ResourceType} for the authority to handle
* @param serviceConfigs the collection of {@code ServiceConfiguration} instances that may contribute
* to the ranking
*
* @return a non-negative rank indicating the ability of a {@code AuthoritativeTier} created by this {@code Provider}
* to handle the resource type specified by {@code authorityResource}; a rank of 0 indicates the authority
* can not handle the type specified in {@code authorityResource}
*/
int rankAuthority(ResourceType<?> authorityResource, Collection<ServiceConfiguration<?>> serviceConfigs);
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Shopify Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.careusolutions.careuandroid.domain.interactor;
import com.shopify.buy3.Storefront;
final class CheckoutShippingRatesFragment implements Storefront.AvailableShippingRatesQueryDefinition {
@Override public void define(final Storefront.AvailableShippingRatesQuery query) {
query
.ready()
.shippingRates(new CheckoutShippingRateFragment());
}
}
|
/*
* 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.prestosql.benchmark;
import io.prestosql.testing.LocalQueryRunner;
import static io.prestosql.benchmark.BenchmarkQueryRunner.createLocalQueryRunner;
public class SqlBetweenBenchmark
extends AbstractSqlBenchmark
{
public SqlBetweenBenchmark(LocalQueryRunner localQueryRunner)
{
super(localQueryRunner, "sql_between_long", 10, 30, "SELECT COUNT(*) FROM orders WHERE custkey BETWEEN 10000 AND 20000 OR custkey BETWEEN 30000 AND 35000 OR custkey BETWEEN 50000 AND 51000");
}
public static void main(String[] args)
{
new SqlBetweenBenchmark(createLocalQueryRunner()).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out));
}
}
|
package Practice_Books;
public class BookArrayTest {
public static void main(String[] args){
Book[] bookShelf = new Book[5];
bookShelf[0] = new Book("토지", "박경리");
bookShelf[1] = new Book("태백산맥", "조정래");
bookShelf[2] = new Book("당신들의 천국", "이청준");
bookShelf[3] = new Book("나목", "박완서");
bookShelf[4] =
new Book("데미안", "헤르만 헤세");
for (int i = 0; i < bookShelf.length; i++) {
System.out.println(bookShelf[i]);
bookShelf[i].showBookInfo();
}
}
}
|
/**
* @Author LengYun
* @Since 2022/01/13 14:28
* @Description
*/
package com.iuaenasong.oj.remoteJudge.task.Impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.iuaenasong.oj.pojo.entity.judge.JudgeCase;
import com.iuaenasong.oj.utils.CodeForcesUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import com.iuaenasong.oj.remoteJudge.entity.RemoteJudgeDTO;
import com.iuaenasong.oj.remoteJudge.entity.RemoteJudgeRes;
import com.iuaenasong.oj.remoteJudge.task.RemoteJudgeStrategy;
import com.iuaenasong.oj.utils.Constants;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Slf4j(topic = "oj")
public class CodeForcesJudge extends RemoteJudgeStrategy {
public static final String IMAGE_HOST = "https://codeforces.com";
public static final String HOST = "https://codeforces.com";
public static final String LOGIN_URL = "/enter";
public static final String SUBMIT_URL = "/contest/%s/submit";
public static final String SUBMISSION_RESULT_URL = "/api/user.status?handle=%s&from=1&count=%s";
public static final String CE_INFO_URL = "/data/submitSource";
public static final String MY_SUBMISSION = "/problemset/status?my=on";
protected static final Map<String, Constants.Judge> statusMap = new HashMap<String, Constants.Judge>() {{
put("FAILED", Constants.Judge.STATUS_SUBMITTED_FAILED);
put("OK", Constants.Judge.STATUS_ACCEPTED);
put("PARTIAL", Constants.Judge.STATUS_PARTIAL_ACCEPTED);
put("COMPILATION_ERROR", Constants.Judge.STATUS_COMPILE_ERROR);
put("RUNTIME_ERROR", Constants.Judge.STATUS_RUNTIME_ERROR);
put("WRONG_ANSWER", Constants.Judge.STATUS_WRONG_ANSWER);
put("PRESENTATION_ERROR", Constants.Judge.STATUS_PRESENTATION_ERROR);
put("TIME_LIMIT_EXCEEDED", Constants.Judge.STATUS_TIME_LIMIT_EXCEEDED);
put("MEMORY_LIMIT_EXCEEDED", Constants.Judge.STATUS_MEMORY_LIMIT_EXCEEDED);
put("IDLENESS_LIMIT_EXCEEDED", Constants.Judge.STATUS_RUNTIME_ERROR);
put("SECURITY_VIOLATED", Constants.Judge.STATUS_RUNTIME_ERROR);
put("CRASHED", Constants.Judge.STATUS_SYSTEM_ERROR);
put("INPUT_PREPARATION_CRASHED", Constants.Judge.STATUS_SYSTEM_ERROR);
put("CHALLENGED", Constants.Judge.STATUS_SYSTEM_ERROR);
put("SKIPPED", Constants.Judge.STATUS_SYSTEM_ERROR);
put("TESTING", Constants.Judge.STATUS_JUDGING);
put("REJECTED", Constants.Judge.STATUS_SYSTEM_ERROR);
put("RUNNING & JUDGING", Constants.Judge.STATUS_JUDGING);
}};
@Override
public void submit() {
RemoteJudgeDTO remoteJudgeDTO = getRemoteJudgeDTO();
if (remoteJudgeDTO.getCompleteProblemId() == null || remoteJudgeDTO.getUserCode() == null) {
return;
}
HttpRequest httpRequest = HttpUtil.createGet(IMAGE_HOST);
httpRequest.setConnectionTimeout(60000);
httpRequest.setReadTimeout(60000);
httpRequest.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36 Edg/91.0.864.48");
httpRequest.header("cookie", "RCPC=" + CodeForcesUtils.getRCPC());
HttpResponse httpResponse = httpRequest.execute();
String homePage = httpResponse.body();
if (homePage.contains("Redirecting... Please, wait.")) {
List<String> list = ReUtil.findAll("[a-z0-9]+[a-z0-9]{31}", homePage, 0, new ArrayList<>());
CodeForcesUtils.updateRCPC(list);
httpRequest.removeHeader("cookie");
httpRequest.header("cookie","RCPC="+CodeForcesUtils.getRCPC());
httpResponse = httpRequest.execute();
homePage = httpResponse.body();
}
if (!homePage.contains("/logout\">") || !homePage.contains("<a href=\"/profile/" + remoteJudgeDTO.getUsername() + "\"")) {
login();
if (remoteJudgeDTO.getLoginStatus() != HttpStatus.SC_MOVED_TEMPORARILY) {
log.error("进行题目提交时发生错误:登录失败,可能原因账号或密码错误,登录失败!" + CodeForcesJudge.class.getName() + ",题号:" + remoteJudgeDTO.getCompleteProblemId());
return;
}
} else {
remoteJudgeDTO.setCookies(httpResponse.getCookies());
}
long nowTime = DateUtil.currentSeconds();
submitCode(remoteJudgeDTO);
if (remoteJudgeDTO.getSubmitStatus() == 403) {
// 如果提交出现403可能是cookie失效了,再执行登录,重新提交
remoteJudgeDTO.setCookies(null);
login();
if (remoteJudgeDTO.getLoginStatus() != HttpStatus.SC_MOVED_TEMPORARILY) {
log.error("CF进行题目提交时发生错误:登录失败,可能原因账号或密码错误,登录失败!" + CodeForcesJudge.class.getName() + ",题号:" + remoteJudgeDTO.getCompleteProblemId());
return;
}
submitCode(remoteJudgeDTO);
if (remoteJudgeDTO.getSubmitStatus() == 403) {
String log = String.format("Codeforces[%s] [%s]:Failed to submit code, caused by `403 Forbidden`", remoteJudgeDTO.getContestId(), remoteJudgeDTO.getCompleteProblemId());
throw new RuntimeException(log);
}
}
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 获取提交的题目id
Long maxRunId = getMaxRunId(nowTime);
remoteJudgeDTO.setSubmitId(maxRunId);
}
@SuppressWarnings("unchecked")
private Long getMaxRunId(long nowTime) {
RemoteJudgeDTO remoteJudgeDTO = getRemoteJudgeDTO();
int retryNum = 0;
// 防止cf的nginx限制访问频率,重试5次
while (retryNum != 10) {
HttpResponse httpResponse = getMaxIdForSubmissionResult(remoteJudgeDTO.getUsername(), 30);
if (httpResponse.getStatus() == 200) {
try {
Map<String, Object> json = JSONUtil.parseObj(httpResponse.body());
List<Map<String, Object>> results = (List<Map<String, Object>>) json.get("result");
for (Map<String, Object> result : results) {
Long runId = Long.valueOf(result.get("id").toString());
long creationTimeSeconds = Long.parseLong(result.get("creationTimeSeconds").toString());
if (creationTimeSeconds < nowTime && retryNum < 8) {
continue;
}
Map<String, Object> problem = (Map<String, Object>) result.get("problem");
if (remoteJudgeDTO.getContestId().equals(problem.get("contestId").toString()) &&
remoteJudgeDTO.getProblemNum().equals(problem.get("index").toString())) {
return runId;
}
}
} catch (Exception e) {
log.error("进行题目获取runID发生错误:获取提交ID失败," + CodeForcesJudge.class.getName()
+ ",题号:" + remoteJudgeDTO.getCompleteProblemId() + ",异常描述:" + e);
return -1L;
}
}
retryNum++;
}
return -1L;
}
// CF的这个接口有每两秒的访问限制,所以需要加锁,保证只有一次查询
public static synchronized HttpResponse getMaxIdForSubmissionResult(String username, Integer count) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
String url = HOST + String.format(SUBMISSION_RESULT_URL, username, count);
return HttpUtil.createGet(url)
.timeout(30000)
.execute();
}
@Override
public RemoteJudgeRes result() {
// 清除当前线程的cookies缓存
HttpRequest.getCookieManager().getCookieStore().removeAll();
RemoteJudgeDTO remoteJudgeDTO = getRemoteJudgeDTO();
if (remoteJudgeDTO.getCookies() == null) {
login();
}
HttpRequest homeRequest = HttpUtil.createGet(HOST + MY_SUBMISSION);
homeRequest.cookie(remoteJudgeDTO.getCookies());
HttpResponse homeResponse = homeRequest.execute();
String csrfToken = ReUtil.get("data-csrf='(\\w+)'", homeResponse.body(), 1);
HttpRequest httpRequest = HttpUtil.createPost(HOST + CE_INFO_URL)
.cookie(remoteJudgeDTO.getCookies())
.timeout(30000);
httpRequest.form(MapUtil
.builder(new HashMap<String, Object>())
.put("csrf_token", csrfToken)
.put("submissionId", remoteJudgeDTO.getSubmitId()).map());
HttpResponse httpResponse = httpRequest.execute();
RemoteJudgeRes remoteJudgeRes = RemoteJudgeRes.builder()
.status(Constants.Judge.STATUS_JUDGING.getStatus())
.build();
if (httpResponse.getStatus() == 200) {
JSONObject submissionInfoJson = JSONUtil.parseObj(httpResponse.body());
String compilationError = submissionInfoJson.getStr("compilationError");
if ("true".equals(compilationError)) {
remoteJudgeRes
.setMemory(0)
.setTime(0)
.setStatus(Constants.Judge.STATUS_COMPILE_ERROR.getStatus());
String CEMsg = submissionInfoJson.getStr("checkerStdoutAndStderr#1");
if (StringUtils.isEmpty(CEMsg)) {
remoteJudgeRes.setErrorInfo("Oops! Because Codeforces does not provide compilation details, it is unable to provide the reason for compilation failure!");
} else {
remoteJudgeRes.setErrorInfo(CEMsg);
}
return remoteJudgeRes;
}
Integer testcaseNum = remoteJudgeDTO.getTestcaseNum();
Integer maxTime = remoteJudgeDTO.getMaxTime();
Integer maxMemory = remoteJudgeDTO.getMaxMemory();
if (testcaseNum == null) {
testcaseNum = 1;
maxTime = 0;
maxMemory = 0;
}
List<JudgeCase> judgeCaseList = new ArrayList<>();
String testCountStr = submissionInfoJson.getStr("testCount");
int testCount = Integer.parseInt(testCountStr);
for (; testcaseNum <= testCount; testcaseNum++) {
String verdict = submissionInfoJson.getStr("verdict#" + testcaseNum);
if (StringUtils.isEmpty(verdict)){
continue;
}
Constants.Judge judgeRes = statusMap.get(verdict);
Integer time = Integer.parseInt(submissionInfoJson.getStr("timeConsumed#" + testcaseNum));
Integer memory = Integer.parseInt(submissionInfoJson.getStr("memoryConsumed#" + testcaseNum)) / 1024;
String msg = submissionInfoJson.getStr("checkerStdoutAndStderr#" + testcaseNum);
judgeCaseList.add(new JudgeCase()
.setSubmitId(remoteJudgeDTO.getJudgeId())
.setPid(remoteJudgeDTO.getPid())
.setUid(remoteJudgeDTO.getUid())
.setTime(time)
.setMemory(memory)
.setStatus(judgeRes.getStatus())
.setUserOutput(msg));
if (time > maxTime) {
maxTime = time;
}
if (memory > maxMemory) {
maxMemory = memory;
}
}
remoteJudgeDTO.setTestcaseNum(testcaseNum);
remoteJudgeDTO.setMaxMemory(maxMemory);
remoteJudgeDTO.setMaxTime(maxTime);
remoteJudgeRes.setJudgeCaseList(judgeCaseList);
if ("true".equals(submissionInfoJson.getStr("waiting"))) {
return remoteJudgeRes;
}
Constants.Judge finalJudgeRes = statusMap.get(submissionInfoJson.getStr("verdict#" + testCount));
remoteJudgeRes.setStatus(finalJudgeRes.getStatus())
.setTime(maxTime)
.setMemory(maxMemory);
return remoteJudgeRes;
} else {
// 非200则说明cf没有提供编译失败的详情
remoteJudgeRes.setStatus(Constants.Judge.STATUS_SYSTEM_ERROR.getStatus())
.setMemory(0)
.setTime(0)
.setErrorInfo("Oops! Error in obtaining the judging result. The status code returned by the interface is " + httpResponse.getStatus() + ".");
return remoteJudgeRes;
}
}
public HashMap<String, Object> getCsrfToken(String url, boolean needTTA) {
RemoteJudgeDTO remoteJudgeDTO = getRemoteJudgeDTO();
HttpRequest request = HttpUtil.createGet(url);
if (remoteJudgeDTO.getCookies() == null) {
request.header("cookie", "RCPC=" + CodeForcesUtils.getRCPC());
} else {
request.cookie(remoteJudgeDTO.getCookies());
}
HttpResponse response = request.execute();
String body = response.body();
if (body.contains("Redirecting... Please, wait.")) {
List<String> list = ReUtil.findAll("[a-z0-9]+[a-z0-9]{31}", body, 0, new ArrayList<>());
CodeForcesUtils.updateRCPC(list);
request.removeHeader("cookie");
request.header("cookie", "RCPC=" + CodeForcesUtils.getRCPC());
response = request.execute();
body = response.body();
}
remoteJudgeDTO.setCookies(response.getCookies());
HashMap<String, Object> res = new HashMap<>();
String ftaa = response.getCookieValue("70a7c28f3de");
res.put("ftaa", ftaa);
String bfaa = ReUtil.get("_bfaa = \"(.{32})\"", body, 1);
if (StringUtils.isEmpty(bfaa)) {
bfaa = response.getCookieValue("raa");
if (StringUtils.isEmpty(bfaa)) {
bfaa = response.getCookieValue("bfaa");
}
}
res.put("bfaa", bfaa);
String csrfToken = ReUtil.get("data-csrf='(\\w+)'", body, 1);
res.put("csrf_token", csrfToken);
if (needTTA) {
String _39ce7 = response.getCookieValue("39ce7");
int _tta = 0;
for (int c = 0; c < _39ce7.length(); c++) {
_tta = (_tta + (c + 1) * (c + 2) * _39ce7.charAt(c)) % 1009;
if (c % 3 == 0)
_tta++;
if (c % 2 == 0)
_tta *= 2;
if (c > 0)
_tta -= (_39ce7.charAt(c / 2) / 2) * (_tta % 5);
while (_tta < 0)
_tta += 1009;
while (_tta >= 1009)
_tta -= 1009;
}
res.put("_tta", _tta);
}
return res;
}
@Override
public void login() {
// 清除当前线程的cookies缓存
HttpRequest.getCookieManager().getCookieStore().removeAll();
RemoteJudgeDTO remoteJudgeDTO = getRemoteJudgeDTO();
HashMap<String, Object> keyMap = getCsrfToken(IMAGE_HOST + LOGIN_URL, false);
HttpRequest httpRequest = new HttpRequest(IMAGE_HOST + LOGIN_URL);
httpRequest.setConnectionTimeout(60000);
httpRequest.setReadTimeout(60000);
httpRequest.setMethod(Method.POST);
httpRequest.cookie(remoteJudgeDTO.getCookies());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("csrf_token", keyMap.get("csrf_token"));
hashMap.put("action", "enter");
hashMap.put("ftaa", keyMap.get("ftaa"));
hashMap.put("bfaa", keyMap.get("bfaa"));
hashMap.put("handleOrEmail", remoteJudgeDTO.getUsername());
hashMap.put("password", remoteJudgeDTO.getPassword());
hashMap.put("remember", "on");
httpRequest.form(hashMap);
HttpResponse response = httpRequest.execute();
remoteJudgeDTO.setCookies(response.getCookies());
remoteJudgeDTO.setLoginStatus(response.getStatus());
}
protected String getSubmitUrl(String contestNum) {
return IMAGE_HOST + String.format(SUBMIT_URL, contestNum);
}
public void submitCode(RemoteJudgeDTO remoteJudgeDTO) {
HashMap<String, Object> keyMap = getCsrfToken(getSubmitUrl(remoteJudgeDTO.getContestId()), true);
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("csrf_token", keyMap.get("csrf_token"));
paramMap.put("_tta", keyMap.get("_tta"));
paramMap.put("bfaa", keyMap.get("bfaa"));
paramMap.put("ftaa", keyMap.get("ftaa"));
paramMap.put("action", "submitSolutionFormSubmitted");
paramMap.put("submittedProblemIndex", remoteJudgeDTO.getProblemNum());
paramMap.put("contestId", remoteJudgeDTO.getContestId());
paramMap.put("programTypeId", getLanguage(remoteJudgeDTO.getLanguage()));
paramMap.put("tabsize", 4);
paramMap.put("source", remoteJudgeDTO.getUserCode() + getRandomBlankString());
paramMap.put("sourceCodeConfirmed", true);
paramMap.put("doNotShowWarningAgain", "on");
HttpRequest request = HttpUtil.createPost(getSubmitUrl(remoteJudgeDTO.getContestId()) + "?csrf_token=" + keyMap.get("csrf_token"));
request.setConnectionTimeout(60000);
request.setReadTimeout(60000);
request.form(paramMap);
request.cookie(remoteJudgeDTO.getCookies());
request.header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36");
HttpResponse response = request.execute();
remoteJudgeDTO.setSubmitStatus(response.getStatus());
if (response.getStatus() != HttpStatus.SC_MOVED_TEMPORARILY) {
if (response.body().contains("error for__programTypeId")) {
String log = String.format("Codeforces[%s] [%s]:Failed to submit code, caused by `Language Rejected`", remoteJudgeDTO.getContestId(), remoteJudgeDTO.getProblemNum());
throw new RuntimeException(log);
}
if (response.body().contains("error for__source")) {
String log = String.format("Codeforces[%s] [%s]:Failed to submit code, caused by `Source Code Error`", remoteJudgeDTO.getContestId(), remoteJudgeDTO.getProblemNum());
throw new RuntimeException(log);
}
}
}
@Override
public String getLanguage(String language) {
if (language.startsWith("GNU GCC C11")) {
return "43";
} else if (language.startsWith("Clang++17 Diagnostics")) {
return "52";
} else if (language.startsWith("GNU G++11")) {
return "50";
} else if (language.startsWith("GNU G++14")) {
return "50";
} else if (language.startsWith("GNU G++17")) {
return "54";
} else if (language.startsWith("GNU G++20")) {
return "73";
} else if (language.startsWith("Microsoft Visual C++ 2017")) {
return "59";
} else if (language.startsWith("C# 8, .NET Core")) {
return "65";
} else if (language.startsWith("C# Mono")) {
return "9";
} else if (language.startsWith("D DMD32")) {
return "28";
} else if (language.startsWith("Go")) {
return "32";
} else if (language.startsWith("Haskell GHC")) {
return "12";
} else if (language.startsWith("Java 11")) {
return "60";
} else if (language.startsWith("Java 1.8")) {
return "36";
} else if (language.startsWith("Kotlin")) {
return "48";
} else if (language.startsWith("OCaml")) {
return "19";
} else if (language.startsWith("Delphi")) {
return "3";
} else if (language.startsWith("Free Pascal")) {
return "4";
} else if (language.startsWith("PascalABC.NET")) {
return "51";
} else if (language.startsWith("Perl")) {
return "13";
} else if (language.startsWith("PHP")) {
return "6";
} else if (language.startsWith("Python 2")) {
return "7";
} else if (language.startsWith("Python 3")) {
return "31";
} else if (language.startsWith("PyPy 2")) {
return "40";
} else if (language.startsWith("PyPy 3")) {
return "41";
} else if (language.startsWith("Ruby")) {
return "67";
} else if (language.startsWith("Rust")) {
return "49";
} else if (language.startsWith("Scala")) {
return "20";
} else if (language.startsWith("JavaScript")) {
return "34";
} else if (language.startsWith("Node.js")) {
return "55";
} else {
return null;
}
}
protected String getRandomBlankString() {
StringBuilder string = new StringBuilder("\n");
int random = new Random().nextInt(Integer.MAX_VALUE);
while (random > 0) {
string.append(random % 2 == 0 ? ' ' : '\t');
random /= 2;
}
return string.toString();
}
}
|
/* 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.activiti.bpmn.converter;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.BoundaryEvent;
import org.activiti.bpmn.model.ErrorEventDefinition;
import org.activiti.bpmn.model.EventDefinition;
import org.apache.commons.lang.StringUtils;
/**
* @author Tijs Rademakers
*/
public class BoundaryEventXMLConverter extends BaseBpmnXMLConverter {
public static String getXMLType() {
return ELEMENT_EVENT_BOUNDARY;
}
public static Class<? extends BaseElement> getBpmnElementType() {
return BoundaryEvent.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_EVENT_BOUNDARY;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr) {
BoundaryEvent boundaryEvent = new BoundaryEvent();
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_CANCELACTIVITY))) {
String cancelActivity = xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_CANCELACTIVITY);
if (ATTRIBUTE_VALUE_TRUE.equalsIgnoreCase(cancelActivity)) {
boundaryEvent.setCancelActivity(true);
}
}
boundaryEvent.setAttachedToRefId(xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_ATTACHEDTOREF));
parseChildElements(getXMLElementName(), boundaryEvent, xtr);
// Explicitly set cancel activity to false for error boundary events
if (boundaryEvent.getEventDefinitions().size() == 1) {
EventDefinition eventDef = boundaryEvent.getEventDefinitions().get(0);
if (eventDef instanceof ErrorEventDefinition) {
boundaryEvent.setCancelActivity(false);
}
}
return boundaryEvent;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, XMLStreamWriter xtw) throws Exception {
BoundaryEvent boundaryEvent = (BoundaryEvent) element;
if (boundaryEvent.getAttachedToRef() != null) {
writeDefaultAttribute(ATTRIBUTE_BOUNDARY_ATTACHEDTOREF, boundaryEvent.getAttachedToRef().getId(), xtw);
}
if (boundaryEvent.getEventDefinitions().size() == 1) {
EventDefinition eventDef = boundaryEvent.getEventDefinitions().get(0);
if (eventDef instanceof ErrorEventDefinition == false) {
writeDefaultAttribute(ATTRIBUTE_BOUNDARY_CANCELACTIVITY, String.valueOf(boundaryEvent.isCancelActivity()).toLowerCase(), xtw);
}
}
}
@Override
protected void writeAdditionalChildElements(BaseElement element, XMLStreamWriter xtw) throws Exception {
BoundaryEvent boundaryEvent = (BoundaryEvent) element;
writeEventDefinitions(boundaryEvent.getEventDefinitions(), xtw);
}
}
|
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.storage.keyvalue;
import org.hyperledger.besu.ethereum.bonsai.BonsaiWorldStateKeyValueStorage;
import org.hyperledger.besu.ethereum.chain.BlockchainStorage;
import org.hyperledger.besu.ethereum.goquorum.GoQuorumPrivateKeyValueStorage;
import org.hyperledger.besu.ethereum.goquorum.GoQuorumPrivateStorage;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions;
import org.hyperledger.besu.ethereum.storage.StorageProvider;
import org.hyperledger.besu.ethereum.worldstate.DataStorageFormat;
import org.hyperledger.besu.ethereum.worldstate.WorldStatePreimageStorage;
import org.hyperledger.besu.ethereum.worldstate.WorldStateStorage;
import org.hyperledger.besu.plugin.services.storage.KeyValueStorage;
import org.hyperledger.besu.plugin.services.storage.SegmentIdentifier;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class KeyValueStorageProvider implements StorageProvider {
private final Function<SegmentIdentifier, KeyValueStorage> storageCreator;
private final KeyValueStorage worldStatePreimageStorage;
private final KeyValueStorage privateWorldStatePreimageStorage;
private final boolean isWorldStateIterable;
private final Map<SegmentIdentifier, KeyValueStorage> storageInstances = new HashMap<>();
public KeyValueStorageProvider(
final Function<SegmentIdentifier, KeyValueStorage> storageCreator,
final KeyValueStorage worldStatePreimageStorage,
final boolean segmentIsolationSupported) {
this.storageCreator = storageCreator;
this.worldStatePreimageStorage = worldStatePreimageStorage;
this.privateWorldStatePreimageStorage = null;
this.isWorldStateIterable = segmentIsolationSupported;
}
public KeyValueStorageProvider(
final Function<SegmentIdentifier, KeyValueStorage> storageCreator,
final KeyValueStorage worldStatePreimageStorage,
final KeyValueStorage privateWorldStatePreimageStorage,
final boolean segmentIsolationSupported) {
this.storageCreator = storageCreator;
this.worldStatePreimageStorage = worldStatePreimageStorage;
this.privateWorldStatePreimageStorage = privateWorldStatePreimageStorage;
this.isWorldStateIterable = segmentIsolationSupported;
}
@Override
public BlockchainStorage createBlockchainStorage(final ProtocolSchedule protocolSchedule) {
return new KeyValueStoragePrefixedKeyBlockchainStorage(
getStorageBySegmentIdentifier(KeyValueSegmentIdentifier.BLOCKCHAIN),
ScheduleBasedBlockHeaderFunctions.create(protocolSchedule));
}
@Override
public WorldStateStorage createWorldStateStorage(final DataStorageFormat dataStorageFormat) {
if (dataStorageFormat.equals(DataStorageFormat.BONSAI)) {
return new BonsaiWorldStateKeyValueStorage(this);
} else {
return new WorldStateKeyValueStorage(
getStorageBySegmentIdentifier(KeyValueSegmentIdentifier.WORLD_STATE));
}
}
@Override
public WorldStatePreimageStorage createWorldStatePreimageStorage() {
return new WorldStatePreimageKeyValueStorage(worldStatePreimageStorage);
}
@Override
public KeyValueStorage getStorageBySegmentIdentifier(final SegmentIdentifier segment) {
return storageInstances.computeIfAbsent(segment, storageCreator);
}
@Override
public WorldStateStorage createPrivateWorldStateStorage() {
return new WorldStateKeyValueStorage(
getStorageBySegmentIdentifier(KeyValueSegmentIdentifier.GOQUORUM_PRIVATE_WORLD_STATE));
}
@Override
public WorldStatePreimageStorage createPrivateWorldStatePreimageStorage() {
return new WorldStatePreimageKeyValueStorage(privateWorldStatePreimageStorage);
}
@Override
public GoQuorumPrivateStorage createGoQuorumPrivateStorage() {
return new GoQuorumPrivateKeyValueStorage(
getStorageBySegmentIdentifier(KeyValueSegmentIdentifier.GOQUORUM_PRIVATE_STORAGE));
}
@Override
public boolean isWorldStateIterable() {
return isWorldStateIterable;
}
@Override
public void close() throws IOException {
for (final KeyValueStorage kvs : storageInstances.values()) {
kvs.close();
}
}
}
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.examples.ramsetecommand;
import edu.wpi.first.wpilibj.kinematics.DifferentialDriveKinematics;
/**
* The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean
* constants. This class should not be used for any other purpose. All constants should be
* declared globally (i.e. public static). Do not put anything functional in this class.
*
* <p>It is advised to statically import this class (or one of its inner classes) wherever the
* constants are needed, to reduce verbosity.
*/
public final class Constants {
public static final class DriveConstants {
public static final int kLeftMotor1Port = 0;
public static final int kLeftMotor2Port = 1;
public static final int kRightMotor1Port = 2;
public static final int kRightMotor2Port = 3;
public static final int[] kLeftEncoderPorts = new int[]{0, 1};
public static final int[] kRightEncoderPorts = new int[]{2, 3};
public static final boolean kLeftEncoderReversed = false;
public static final boolean kRightEncoderReversed = true;
public static final double kTrackwidthMeters = 0.69;
public static final DifferentialDriveKinematics kDriveKinematics =
new DifferentialDriveKinematics(kTrackwidthMeters);
public static final int kEncoderCPR = 1024;
public static final double kWheelDiameterMeters = 0.15;
public static final double kEncoderDistancePerPulse =
// Assumes the encoders are directly mounted on the wheel shafts
(kWheelDiameterMeters * Math.PI) / (double) kEncoderCPR;
public static final boolean kGyroReversed = true;
// These are example values only - DO NOT USE THESE FOR YOUR OWN ROBOT!
// These characterization values MUST be determined either experimentally or theoretically
// for *your* robot's drive.
// The Robot Characterization Toolsuite provides a convenient tool for obtaining these
// values for your robot.
public static final double ksVolts = 0.22;
public static final double kvVoltSecondsPerMeter = 1.98;
public static final double kaVoltSecondsSquaredPerMeter = 0.2;
// Example value only - as above, this must be tuned for your drive!
public static final double kPDriveVel = 8.5;
}
public static final class OIConstants {
public static final int kDriverControllerPort = 1;
}
public static final class AutoConstants {
public static final double kMaxSpeedMetersPerSecond = 3;
public static final double kMaxAccelerationMetersPerSecondSquared = 3;
// Reasonable baseline values for a RAMSETE follower in units of meters and seconds
public static final double kRamseteB = 2;
public static final double kRamseteZeta = 0.7;
}
}
|
package com.digirati.elucidate.repository.impl;
import java.sql.Types;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.digirati.elucidate.common.repository.impl.AbstractRepositoryJDBCImpl;
import com.digirati.elucidate.infrastructure.database.rowmapper.AnnotationTemporalRowMapper;
import com.digirati.elucidate.model.annotation.temporal.AnnotationTemporal;
import com.digirati.elucidate.repository.AnnotationTemporalStoreRepository;
@Repository
public class AnnotationTemporalStoreRepositoryJDBCImpl extends AbstractRepositoryJDBCImpl implements AnnotationTemporalStoreRepository {
public static final String REPOSITORY_NAME = "annotationTemporalStoreRepositoryJDBCImpl";
@Autowired
public AnnotationTemporalStoreRepositoryJDBCImpl(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
@Override
@Transactional(readOnly = false)
public AnnotationTemporal createAnnotationTemporal(Integer annotationPk, Integer bodyPk, Integer targetPk, String type, Date value, String temporalJson) {
String sql = "SELECT * FROM annotation_temporal_create(?, ?, ?, ?, ?, ?)";
Object[] params = {annotationPk, bodyPk, targetPk, type, value, temporalJson};
int[] sqlTypes = {Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.TIMESTAMP, Types.OTHER};
return queryForObject(sql, params, sqlTypes, new AnnotationTemporalRowMapper());
}
@Override
@Transactional(readOnly = false)
public List<AnnotationTemporal> deleteAnnotationTemporals(Integer annotationPk, Integer bodyPk, Integer targetPk) {
String sql = "SELECT * FROM annotation_temporal_delete(?, ?, ?)";
Object[] params = {annotationPk, bodyPk, targetPk};
int[] sqlTypes = {Types.INTEGER, Types.INTEGER, Types.INTEGER};
return queryForList(sql, params, sqlTypes, new AnnotationTemporalRowMapper());
}
}
|
package com.feedhenry.armark.Sub_menus;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.feedhenry.armark.R;
public class Sub_menu_categorias extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_menu_categorias);
}
}
|
package com.dm.wallpaper.board.adapters;
import android.animation.AnimatorInflater;
import android.animation.StateListAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.danimahardhika.android.helpers.animation.AnimationHelper;
import com.danimahardhika.android.helpers.core.ColorHelper;
import com.danimahardhika.android.helpers.core.DrawableHelper;
import com.danimahardhika.android.helpers.core.WindowHelper;
import com.danimahardhika.android.helpers.permission.PermissionHelper;
import com.danimahardhika.cafebar.CafeBar;
import com.danimahardhika.cafebar.CafeBarTheme;
import com.dm.wallpaper.board.R;
import com.dm.wallpaper.board.R2;
import com.dm.wallpaper.board.activities.WallpaperBoardPreviewActivity;
import com.dm.wallpaper.board.databases.Database;
import com.dm.wallpaper.board.helpers.TypefaceHelper;
import com.dm.wallpaper.board.items.PopupItem;
import com.dm.wallpaper.board.items.Wallpaper;
import com.dm.wallpaper.board.preferences.Preferences;
import com.dm.wallpaper.board.tasks.WallpaperApplyTask;
import com.dm.wallpaper.board.utils.Popup;
import com.dm.wallpaper.board.utils.Extras;
import com.dm.wallpaper.board.utils.ImageConfig;
import com.dm.wallpaper.board.utils.WallpaperDownloader;
import com.kogitune.activitytransition.ActivityTransitionLauncher;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import static com.dm.wallpaper.board.helpers.ViewHelper.setCardViewToFlat;
/*
* Wallpaper Board
*
* Copyright (c) 2017 Dani Mahardhika
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class LatestAdapter extends RecyclerView.Adapter<LatestAdapter.ViewHolder> {
private final Context mContext;
private List<Wallpaper> mWallpapers;
private final DisplayImageOptions.Builder mOptions;
public LatestAdapter(@NonNull Context context, @NonNull List<Wallpaper> wallpapers) {
mContext = context;
mWallpapers = wallpapers;
mOptions = ImageConfig.getRawDefaultImageOptions();
mOptions.resetViewBeforeLoading(true);
mOptions.cacheInMemory(true);
mOptions.cacheOnDisk(true);
mOptions.displayer(new FadeInBitmapDisplayer(700));
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(
R.layout.fragment_latest_item_grid, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Wallpaper wallpaper = mWallpapers.get(position);
holder.name.setText(wallpaper.getName());
holder.author.setText(wallpaper.getAuthor());
if (mContext.getResources().getBoolean(R.bool.enable_wallpaper_download)) {
holder.download.setVisibility(View.VISIBLE);
} else {
holder.download.setVisibility(View.GONE);
}
setFavorite(holder.favorite, Color.WHITE, position, false);
resetImageViewHeight(holder.image, wallpaper.getDimensions());
ImageLoader.getInstance().displayImage(
wallpaper.getThumbUrl(),
new ImageViewAware(holder.image),
mOptions.build(),
ImageConfig.getBigThumbnailSize(),
new SimpleImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
int color;
if (wallpaper.getColor() == 0) {
color = ColorHelper.getAttributeColor(
mContext, R.attr.card_background);
} else {
color = wallpaper.getColor();
}
holder.card.setCardBackgroundColor(color);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
if (loadedImage != null && wallpaper.getColor() == 0) {
Palette.from(loadedImage).generate(palette -> {
int vibrant = ColorHelper.getAttributeColor(
mContext, R.attr.card_background);
int color = palette.getVibrantColor(vibrant);
if (color == vibrant)
color = palette.getMutedColor(vibrant);
holder.card.setCardBackgroundColor(color);
wallpaper.setColor(color);
Database.get(mContext).updateWallpaper(wallpaper);
});
}
}
},
null);
}
@Override
public int getItemCount() {
return mWallpapers.size();
}
private void resetImageViewHeight(@NonNull ImageView imageView, ImageSize imageSize) {
if (imageSize == null) imageSize = new ImageSize(400, 300);
int width = WindowHelper.getScreenSize(mContext).x;
int spanCount = mContext.getResources().getInteger(R.integer.latest_wallpapers_column_count);
if (spanCount > 1) {
width = width/spanCount;
}
double scaleFactor = (double) width / (double) imageSize.getWidth();
double measuredHeight = (double) imageSize.getHeight() * scaleFactor;
imageView.getLayoutParams().height = Double.valueOf(measuredHeight).intValue();
imageView.requestLayout();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R2.id.image)
ImageView image;
@BindView(R2.id.name)
TextView name;
@BindView(R2.id.author)
TextView author;
@BindView(R2.id.favorite)
ImageView favorite;
@BindView(R2.id.download)
ImageView download;
@BindView(R2.id.apply)
ImageView apply;
@BindView(R2.id.card)
CardView card;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mContext.getResources().getInteger(R.integer.latest_wallpapers_column_count) == 1) {
if (card.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams) {
StaggeredGridLayoutManager.LayoutParams params =
(StaggeredGridLayoutManager.LayoutParams) card.getLayoutParams();
params.leftMargin = 0;
params.rightMargin = 0;
params.topMargin = 0;
params.bottomMargin = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.setMarginEnd(0);
}
}
} else {
setCardViewToFlat(card);
}
if (!Preferences.get(mContext).isShadowEnabled()) {
card.setCardElevation(0f);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(mContext, R.animator.card_lift);
card.setStateListAnimator(stateListAnimator);
}
if (mContext.getResources().getBoolean(R.bool.enable_wallpaper_download)) {
download.setImageDrawable(DrawableHelper.getTintedDrawable(
mContext, R.drawable.ic_toolbar_download, Color.WHITE));
download.setOnClickListener(this);
}
apply.setImageDrawable(DrawableHelper.getTintedDrawable(
mContext, R.drawable.ic_toolbar_apply_options, Color.WHITE));
card.setOnClickListener(this);
favorite.setOnClickListener(this);
apply.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int id = view.getId();
int position = getAdapterPosition();
if (id == R.id.favorite) {
if (position < 0 || position > mWallpapers.size()) return;
boolean isFavorite = mWallpapers.get(position).isFavorite();
Database.get(mContext).favoriteWallpaper(
mWallpapers.get(position).getUrl(), !isFavorite);
mWallpapers.get(position).setFavorite(!isFavorite);
setFavorite(favorite, name.getCurrentTextColor(), position, true);
CafeBar.builder(mContext)
.theme(CafeBarTheme.Custom(ColorHelper.getAttributeColor(
mContext, R.attr.card_background)))
.fitSystemWindow()
.floating(true)
.typeface(TypefaceHelper.getRegular(mContext), TypefaceHelper.getBold(mContext))
.content(String.format(
mContext.getResources().getString(mWallpapers.get(position).isFavorite() ?
R.string.wallpaper_favorite_added : R.string.wallpaper_favorite_removed),
mWallpapers.get(position).getName()))
.icon(mWallpapers.get(position).isFavorite() ?
R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove)
.show();
} else if (id == R.id.download) {
if (PermissionHelper.isStorageGranted(mContext)) {
WallpaperDownloader.prepare(mContext)
.wallpaper(mWallpapers.get(position))
.start();
return;
}
PermissionHelper.requestStorage(mContext);
} else if (id == R.id.apply) {
Popup popup = Popup.Builder(mContext)
.to(apply)
.list(PopupItem.getApplyItems(mContext))
.callback((applyPopup, i) -> {
PopupItem item = applyPopup.getItems().get(i);
if (item.getType() == PopupItem.Type.WALLPAPER_CROP) {
Preferences.get(mContext).setCropWallpaper(!item.getCheckboxValue());
item.setCheckboxValue(Preferences.get(mContext).isCropWallpaper());
applyPopup.updateItem(i, item);
return;
} else if (item.getType() == PopupItem.Type.LOCKSCREEN) {
WallpaperApplyTask.prepare(mContext)
.wallpaper(mWallpapers.get(position))
.to(WallpaperApplyTask.Apply.LOCKSCREEN)
.start(AsyncTask.THREAD_POOL_EXECUTOR);
} else if (item.getType() == PopupItem.Type.HOMESCREEN) {
WallpaperApplyTask.prepare(mContext)
.wallpaper(mWallpapers.get(position))
.to(WallpaperApplyTask.Apply.HOMESCREEN)
.start(AsyncTask.THREAD_POOL_EXECUTOR);
}
applyPopup.dismiss();
})
.build();
if (mContext.getResources().getBoolean(R.bool.enable_wallpaper_download)) {
popup.removeItem(popup.getItems().size() - 1);
}
popup.show();
} else if (id == R.id.card) {
if (WallpapersAdapter.sIsClickable) {
WallpapersAdapter.sIsClickable = false;
try {
Bitmap bitmap = null;
if (image.getDrawable() != null) {
bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
}
final Intent intent = new Intent(mContext, WallpaperBoardPreviewActivity.class);
intent.putExtra(Extras.EXTRA_URL, mWallpapers.get(position).getUrl());
ActivityTransitionLauncher.with((AppCompatActivity) mContext)
.from(image, Extras.EXTRA_IMAGE)
.image(bitmap)
.launch(intent);
} catch (Exception e) {
WallpapersAdapter.sIsClickable = true;
}
}
}
}
}
public void setWallpapers(@NonNull List<Wallpaper> wallpapers) {
mWallpapers = wallpapers;
notifyDataSetChanged();
}
private void setFavorite(@NonNull ImageView imageView, @ColorInt int color, int position, boolean animate) {
if (position < 0 || position > mWallpapers.size()) return;
boolean isFavorite = mWallpapers.get(position).isFavorite();
if (animate) {
AnimationHelper.show(imageView)
.interpolator(new LinearOutSlowInInterpolator())
.callback(new AnimationHelper.Callback() {
@Override
public void onAnimationStart() {
imageView.setImageDrawable(DrawableHelper.getTintedDrawable(mContext,
isFavorite ? R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove, color));
}
@Override
public void onAnimationEnd() {
}
})
.start();
return;
}
imageView.setImageDrawable(DrawableHelper.getTintedDrawable(mContext,
isFavorite ? R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove, color));
}
}
|
package com.jetfiretool.db.sql;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
/**
* {@link PreparedStatement} 包装类,用于添加拦截方法功能<br>
* 拦截方法包括:
*
* <pre>
* 1. 提供参数注入
* 2. 提供SQL打印日志拦截
* </pre>
*
* @author Jetfire
* @since 4.1.0
*/
public class StatementWrapper implements PreparedStatement {
private PreparedStatement rawStatement;
@Override
public ResultSet executeQuery(String sql) throws SQLException {
return rawStatement.executeQuery(sql);
}
@Override
public int executeUpdate(String sql) throws SQLException {
return rawStatement.executeUpdate(sql);
}
@Override
public void close() throws SQLException {
rawStatement.close();
}
@Override
public int getMaxFieldSize() throws SQLException {
return rawStatement.getMaxFieldSize();
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
rawStatement.setMaxFieldSize(max);
}
@Override
public int getMaxRows() throws SQLException {
return rawStatement.getMaxRows();
}
@Override
public void setMaxRows(int max) throws SQLException {
rawStatement.setMaxRows(max);
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
rawStatement.setEscapeProcessing(enable);
}
@Override
public int getQueryTimeout() throws SQLException {
return rawStatement.getQueryTimeout();
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
rawStatement.setQueryTimeout(seconds);
}
@Override
public void cancel() throws SQLException {
rawStatement.cancel();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return rawStatement.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
rawStatement.clearWarnings();
}
@Override
public void setCursorName(String name) throws SQLException {
rawStatement.setCursorName(name);
}
@Override
public boolean execute(String sql) throws SQLException {
return rawStatement.execute(sql);
}
@Override
public ResultSet getResultSet() throws SQLException {
return rawStatement.getResultSet();
}
@Override
public int getUpdateCount() throws SQLException {
return rawStatement.getUpdateCount();
}
@Override
public boolean getMoreResults() throws SQLException {
return rawStatement.getMoreResults();
}
@Override
public void setFetchDirection(int direction) throws SQLException {
rawStatement.setFetchDirection(direction);
}
@Override
public int getFetchDirection() throws SQLException {
return rawStatement.getFetchDirection();
}
@Override
public void setFetchSize(int rows) throws SQLException {
rawStatement.setFetchSize(rows);
}
@Override
public int getFetchSize() throws SQLException {
return rawStatement.getFetchSize();
}
@Override
public int getResultSetConcurrency() throws SQLException {
return rawStatement.getResultSetConcurrency();
}
@Override
public int getResultSetType() throws SQLException {
return rawStatement.getResultSetType();
}
@Override
public void addBatch(String sql) throws SQLException {
rawStatement.addBatch(sql);
}
@Override
public void clearBatch() throws SQLException {
rawStatement.clearBatch();
}
@Override
public int[] executeBatch() throws SQLException {
return rawStatement.executeBatch();
}
@Override
public Connection getConnection() throws SQLException {
return rawStatement.getConnection();
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return rawStatement.getMoreResults(current);
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return rawStatement.getGeneratedKeys();
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return rawStatement.executeUpdate(sql, autoGeneratedKeys);
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return rawStatement.executeUpdate(sql, columnIndexes);
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
return rawStatement.executeUpdate(sql, columnNames);
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return rawStatement.execute(sql, autoGeneratedKeys);
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return rawStatement.execute(sql, columnIndexes);
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
return rawStatement.execute(sql, columnNames);
}
@Override
public int getResultSetHoldability() throws SQLException {
return rawStatement.getResultSetHoldability();
}
@Override
public boolean isClosed() throws SQLException {
return rawStatement.isClosed();
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
rawStatement.setPoolable(poolable);
}
@Override
public boolean isPoolable() throws SQLException {
return rawStatement.isPoolable();
}
@Override
public void closeOnCompletion() throws SQLException {
rawStatement.closeOnCompletion();
}
@Override
public boolean isCloseOnCompletion() throws SQLException {
return rawStatement.isCloseOnCompletion();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return rawStatement.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return rawStatement.isWrapperFor(iface);
}
@Override
public ResultSet executeQuery() throws SQLException {
return rawStatement.executeQuery();
}
@Override
public int executeUpdate() throws SQLException {
return rawStatement.executeUpdate();
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
rawStatement.setNull(parameterIndex, sqlType);
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
rawStatement.setBoolean(parameterIndex, x);
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
rawStatement.setByte(parameterIndex, x);
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
rawStatement.setShort(parameterIndex, x);
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
rawStatement.setInt(parameterIndex, x);
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
rawStatement.setLong(parameterIndex, x);
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
rawStatement.setFloat(parameterIndex, x);
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
rawStatement.setDouble(parameterIndex, x);
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
rawStatement.setBigDecimal(parameterIndex, x);
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
rawStatement.setString(parameterIndex, x);
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
rawStatement.setBytes(parameterIndex, x);
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
rawStatement.setDate(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
rawStatement.setTime(parameterIndex, x);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
rawStatement.setTimestamp(parameterIndex, x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
rawStatement.setAsciiStream(parameterIndex, x, length);
}
@Override
@Deprecated
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
rawStatement.setUnicodeStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
rawStatement.setBinaryStream(parameterIndex, x, length);
}
@Override
public void clearParameters() throws SQLException {
rawStatement.clearParameters();
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
rawStatement.setObject(parameterIndex, x, targetSqlType, targetSqlType);
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
rawStatement.setObject(parameterIndex, x);
}
@Override
public boolean execute() throws SQLException {
return rawStatement.execute();
}
@Override
public void addBatch() throws SQLException {
rawStatement.addBatch();
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
rawStatement.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
rawStatement.setRef(parameterIndex, x);
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
rawStatement.setBlob(parameterIndex, x);
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
rawStatement.setClob(parameterIndex, x);
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
rawStatement.setArray(parameterIndex, x);
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return rawStatement.getMetaData();
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
rawStatement.setDate(parameterIndex, x, cal);
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
rawStatement.setTime(parameterIndex, x, cal);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
rawStatement.setTimestamp(parameterIndex, x, cal);
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
rawStatement.setNull(parameterIndex, sqlType, typeName);
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
rawStatement.setURL(parameterIndex, x);
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
return rawStatement.getParameterMetaData();
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
rawStatement.setRowId(parameterIndex, x);
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
rawStatement.setNString(parameterIndex, value);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
rawStatement.setCharacterStream(parameterIndex, value, length);
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
rawStatement.setNClob(parameterIndex, value);
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
rawStatement.setClob(parameterIndex, reader, length);
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
rawStatement.setBlob(parameterIndex, inputStream, length);
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
rawStatement.setNClob(parameterIndex, reader, length);
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
rawStatement.setSQLXML(parameterIndex, xmlObject);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
rawStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
rawStatement.setAsciiStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
rawStatement.setBinaryStream(parameterIndex, x, length);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
rawStatement.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
rawStatement.setAsciiStream(parameterIndex, x);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
rawStatement.setBinaryStream(parameterIndex, x);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
rawStatement.setCharacterStream(parameterIndex, reader);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
rawStatement.setNCharacterStream(parameterIndex, value);
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
rawStatement.setClob(parameterIndex, reader);
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
rawStatement.setBlob(parameterIndex, inputStream);
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
rawStatement.setNClob(parameterIndex, reader);
}
}
|
/*
*
* Copyright 2002-2004 The Ant-Contrib project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.antcontrib.cpptasks.parser;
public class FilenameState extends AbstractParserState {
private final StringBuilder buf = new StringBuilder();
private final char[] terminators;
public FilenameState(AbstractParser parser, char[] terminators) {
super(parser);
this.terminators = terminators.clone();
}
public AbstractParserState consume(char ch) {
for (char terminator : terminators) {
if (ch == terminator) {
getParser().addFilename(buf.toString());
buf.setLength(0);
return null;
}
}
if (ch == '\n') {
buf.setLength(0);
return getParser().getNewLineState();
}
buf.append(ch);
return this;
}
}
|
/*
* Copyright 2013 University of Chicago and Argonne National Laboratory
*
* 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 exm.stc.tclbackend.tree;
public abstract class Expression extends TclTree
{
@Override
public final void appendTo(StringBuilder sb) {
appendTo(sb, ExprContext.TCL_CODE);
}
public static enum ExprContext {
TCL_CODE,
VALUE_STRING,
LIST_STRING,
}
/**
*
* @param sb
* @param mode how to escape expression
*/
public abstract void appendTo(StringBuilder sb, ExprContext mode);
/**
* @return true if we can include in a string that is valid tcl list
*/
public abstract boolean supportsStringList();
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.appservice;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/** Defines values for BackupRestoreOperationType. */
public enum BackupRestoreOperationType {
/** Enum value Default. */
DEFAULT("Default"),
/** Enum value Clone. */
CLONE("Clone"),
/** Enum value Relocation. */
RELOCATION("Relocation"),
/** Enum value Snapshot. */
SNAPSHOT("Snapshot"),
/** Enum value CloudFS. */
CLOUD_FS("CloudFS");
/** The actual serialized value for a BackupRestoreOperationType instance. */
private final String value;
BackupRestoreOperationType(String value) {
this.value = value;
}
/**
* Parses a serialized value to a BackupRestoreOperationType instance.
*
* @param value the serialized value to parse.
* @return the parsed BackupRestoreOperationType object, or null if unable to parse.
*/
@JsonCreator
public static BackupRestoreOperationType fromString(String value) {
BackupRestoreOperationType[] items = BackupRestoreOperationType.values();
for (BackupRestoreOperationType item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
}
return null;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
}
|
/*
* Copyright (c) 2020-2021, wvkity(wvkity@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.github.mybatisx.core.condition;
import io.github.mybatisx.Objects;
import io.github.mybatisx.constant.Constants;
import io.github.mybatisx.support.constant.Slot;
import io.github.mybatisx.support.constant.Symbol;
import io.github.mybatisx.support.criteria.Criteria;
/**
* 特殊条件(字段相等)
* @author wvkity
* @created 2021-05-17
* @since 1.0.0
*/
public class SpecialCondition implements Criterion {
private static final long serialVersionUID = -3226684503336166627L;
private final Criteria<?> criteria;
private final String tableAlias;
private final String column;
private final Criteria<?> otherCriteria;
private final String otherTableAlias;
private final String otherColumn;
private final Symbol symbol;
private final Slot slot;
public SpecialCondition(Criteria<?> criteria, String tableAlias, String column, Criteria<?> otherCriteria,
String otherTableAlias, String otherColumn, Symbol symbol, Slot slot) {
this.criteria = criteria;
this.tableAlias = tableAlias;
this.column = column;
this.otherCriteria = otherCriteria;
this.otherTableAlias = otherTableAlias;
this.otherColumn = otherColumn;
this.symbol = Objects.isNull(symbol) ? Symbol.EQ : symbol;
this.slot = slot;
}
protected String getAlias(final Criteria<?> criteria, final String alias) {
return Objects.isNotBlank(alias) ? alias : Objects.nonNull(criteria) ? criteria.as() : null;
}
@Override
public Symbol getSymbol() {
return this.symbol;
}
@Override
public String getColumn() {
return this.column;
}
@Override
public String getSegment() {
final StringBuilder builder = new StringBuilder(60);
if (Objects.nonNull(this.slot)) {
builder.append(this.slot.getSegment()).append(Constants.SPACE);
}
final String as = this.getAlias(this.criteria, this.tableAlias);
final String oas = this.getAlias(this.otherCriteria, this.otherTableAlias);
if (Objects.isNotBlank(as)) {
builder.append(as).append(Constants.DOT);
}
builder.append(this.column).append(Constants.SPACE).append(this.symbol.getSegment()).append(Constants.SPACE);
if (Objects.isNotBlank(oas)) {
builder.append(oas).append(Constants.DOT);
}
builder.append(this.otherColumn);
return builder.toString();
}
}
|
package svenhjol.charm.mixin.mineshaft_improvements;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.StructureFeatureManager;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.MineShaftPieces;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import svenhjol.charm.module.mineshaft_improvements.MineshaftImprovements;
import java.util.Random;
@Mixin(value = {
MineShaftPieces.MineShaftCorridor.class,
MineShaftPieces.MineShaftRoom.class
})
public class GenerateMineshaftPiecesMixin {
/**
* Defers to the generatePiece method if a vanilla mineshaft piece generated.
* This allows the MineshaftImprovements module to hack at the piece.
*/
@Inject(
method = "postProcess",
at = @At("RETURN")
)
private void hookGenerate(WorldGenLevel world, StructureFeatureManager structure, ChunkGenerator gen, Random rand, BoundingBox box, ChunkPos chunkPos, BlockPos blockPos, CallbackInfoReturnable<Boolean> cir) {
if (cir.getReturnValue()) // if a piece did generate
MineshaftImprovements.generatePiece((StructurePiece)(Object)this, world, structure, gen, rand, box, chunkPos, blockPos);
}
}
|
/*
* Copyright 2021 DataCanvas
*
* 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.dingodb.raft.error;
// Refer to SOFAJRaft: <A>https://github.com/sofastack/sofa-jraft/<A/>
public class LogNotFoundException extends IllegalStateException {
private static final long serialVersionUID = -140969527148366390L;
public LogNotFoundException() {
super();
}
public LogNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public LogNotFoundException(String s) {
super(s);
}
public LogNotFoundException(Throwable cause) {
super(cause);
}
}
|
package swim.iot.util;
public class EnvConfig {
/**
* Configuration environment variables for Event Hub
*/
public static final String EVENT_HUB_CONNSTRING = envCorrection(System.getenv("EVENT_HUB_CONNSTRING"), "");
public static final String EVENT_HUB_NAME = envCorrection(System.getenv("EVENT_HUB_NAME"), "");
/**
* Configuration environment variable for device name
*/
public static final String EDGE_DEVICE_NAME = envCorrection(System.getenv("EDGE_DEVICE_NAME"), "localSimulator");
/**
* Configuration environment variables for ADLS Gen2
*/
public static final String ADLS_ACCOUNT_NAME = envCorrection(System.getenv("ADLS_ACCOUNT_NAME"), "");
public static final String ADLS_ACCOUNT_KEY = envCorrection(System.getenv("ADLS_ACCOUNT_KEY"), "");
public static final String FILE_SYSTEM = envCorrection(System.getenv("FILE_SYSTEM"), "");
/**
* Helper function that standards parsing environment variables
*
* @param env
* @return "" or env.trim()
*/
private static String envCorrection(String env, String defaultValue) {
if (env == null || env.isEmpty()) {
return defaultValue;
} else return env.trim();
}
}
|
/*
* Copyright 2018-2021 innoQ Deutschland GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.innoq.spring.cookie.flash.codec.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.springframework.web.servlet.FlashMap;
import java.io.IOException;
import java.util.List;
import java.util.Map;
final class FlashMapDeserializer extends StdDeserializer<FlashMap> {
private final ObjectMapper objectMapper = new ObjectMapper();
public FlashMapDeserializer() {
super(FlashMap.class);
}
@Override
public FlashMap deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
final JsonNode root = objectMapper.readTree(p);
final FlashMap flashMap = new FlashMap();
final JsonNode attributes = root.findValue("attributes");
handleAttributes(flashMap, attributes);
final JsonNode expirationTime = root.findValue("expirationTime");
handleExpirationTime(flashMap, expirationTime);
final JsonNode targetRequestParams = root.findValue("targetRequestParams");
handleTargetRequestParams(flashMap, targetRequestParams);
final JsonNode targetRequestPath = root.findValue("targetRequestPath");
handleTargetRequestPath(flashMap, targetRequestPath);
return flashMap;
}
private void handleAttributes(FlashMap flashMap, JsonNode node) {
if (node == null || !node.isObject()) {
return;
}
final Map<String, Object> attributes =
objectMapper.convertValue(node, new TypeReference<Map<String, Object>>() {});
flashMap.putAll(attributes);
}
private void handleExpirationTime(FlashMap flashMap, JsonNode node) {
if (node == null || !node.isNumber()) {
return;
}
final long expirationTime = node.asLong();
flashMap.setExpirationTime(expirationTime);
}
private void handleTargetRequestParams(FlashMap flashMap, JsonNode node) {
if (node == null || !node.isObject()) {
return;
}
final Map<String, List<String>> targetRequestParams =
objectMapper.convertValue(node, new TypeReference<Map<String, List<String>>>() {});
targetRequestParams.forEach((key, values) ->
values.forEach(value ->
flashMap.addTargetRequestParam(key, value)));
}
private void handleTargetRequestPath(FlashMap flashMap, JsonNode node) {
if (node == null || !node.isTextual()) {
return;
}
final String targetRequestPath = node.asText();
flashMap.setTargetRequestPath(targetRequestPath);
}
}
|
package mage.abilities.effects.common.discard;
import mage.abilities.Ability;
import mage.abilities.dynamicvalue.DynamicValue;
import mage.abilities.dynamicvalue.common.StaticValue;
import mage.abilities.effects.OneShotEffect;
import mage.cards.Card;
import mage.cards.Cards;
import mage.cards.CardsImpl;
import mage.constants.Outcome;
import mage.constants.TargetController;
import mage.constants.Zone;
import mage.filter.FilterCard;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.players.Player;
import mage.target.TargetCard;
import mage.util.CardUtil;
import java.util.List;
import java.util.UUID;
/**
* @author noxx
*/
public class DiscardCardYouChooseTargetEffect extends OneShotEffect {
private FilterCard filter;
private TargetController targetController;
private DynamicValue numberCardsToReveal;
private final DynamicValue numberCardsToDiscard;
private boolean revealAllCards;
private static final FilterCard filterOneCard = new FilterCard("one card");
public DiscardCardYouChooseTargetEffect() {
this(StaticFilters.FILTER_CARD_A);
}
public DiscardCardYouChooseTargetEffect(TargetController targetController) {
this(StaticFilters.FILTER_CARD_A, targetController);
}
public DiscardCardYouChooseTargetEffect(DynamicValue numberCardsToDiscard, TargetController targetController) {
this(numberCardsToDiscard, StaticFilters.FILTER_CARD_CARDS, targetController);
}
public DiscardCardYouChooseTargetEffect(FilterCard filter) {
this(filter, TargetController.OPPONENT);
}
public DiscardCardYouChooseTargetEffect(TargetController targetController, int numberCardsToReveal) {
this(filterOneCard, targetController, StaticValue.get(numberCardsToReveal));
}
public DiscardCardYouChooseTargetEffect(TargetController targetController, DynamicValue numberCardsToReveal) {
this(filterOneCard, targetController, numberCardsToReveal);
}
public DiscardCardYouChooseTargetEffect(FilterCard filter, TargetController targetController, DynamicValue numberCardsToReveal) {
super(Outcome.Discard);
this.targetController = targetController;
this.filter = filter;
this.revealAllCards = false;
this.numberCardsToReveal = numberCardsToReveal;
this.numberCardsToDiscard = StaticValue.get(1);
staticText = this.setText();
}
public DiscardCardYouChooseTargetEffect(FilterCard filter, TargetController targetController) {
this(StaticValue.get(1), filter, targetController);
}
public DiscardCardYouChooseTargetEffect(DynamicValue numberCardsToDiscard,
FilterCard filter, TargetController targetController) {
super(Outcome.Discard);
this.targetController = targetController;
this.filter = filter;
this.numberCardsToDiscard = numberCardsToDiscard;
this.numberCardsToReveal = null;
this.revealAllCards = true;
staticText = this.setText();
}
public DiscardCardYouChooseTargetEffect(final DiscardCardYouChooseTargetEffect effect) {
super(effect);
this.filter = effect.filter;
this.targetController = effect.targetController;
this.numberCardsToDiscard = effect.numberCardsToDiscard;
this.numberCardsToReveal = effect.numberCardsToReveal;
this.revealAllCards = effect.revealAllCards;
}
@Override
public boolean apply(Game game, Ability source) {
Player player = game.getPlayer(targetPointer.getFirst(game, source));
Player controller = game.getPlayer(source.getControllerId());
if (player == null || controller == null) {
return false;
}
if (revealAllCards) {
this.numberCardsToReveal = StaticValue.get(player.getHand().size());
}
int numberToReveal = this.numberCardsToReveal.calculate(game, source, this);
if (numberToReveal <= 0) {
return true;
}
Cards revealedCards = new CardsImpl();
numberToReveal = Math.min(player.getHand().size(), numberToReveal);
if (player.getHand().size() > numberToReveal) {
TargetCard chosenCards = new TargetCard(numberToReveal, numberToReveal,
Zone.HAND, new FilterCard("card in " + player.getName() + "'s hand"));
chosenCards.setNotTarget(true);
if (chosenCards.canChoose(source.getSourceId(), player.getId(), game)
&& player.chooseTarget(Outcome.Discard, player.getHand(), chosenCards, source, game)) {
if (!chosenCards.getTargets().isEmpty()) {
List<UUID> targets = chosenCards.getTargets();
for (UUID targetid : targets) {
Card card = game.getCard(targetid);
if (card != null) {
revealedCards.add(card);
}
}
}
}
} else {
revealedCards.addAll(player.getHand());
}
Card sourceCard = game.getCard(source.getSourceId());
player.revealCards(sourceCard != null ? sourceCard.getIdName() + " ("
+ sourceCard.getZoneChangeCounter(game) + ')' : "Discard", revealedCards, game);
boolean result = true;
int filteredCardsCount = revealedCards.count(filter, source.getSourceId(), source.getControllerId(), game);
int numberToDiscard = Math.min(this.numberCardsToDiscard.calculate(game, source, this), filteredCardsCount);
if (numberToDiscard <= 0) {
return result;
}
TargetCard target = new TargetCard(numberToDiscard, Zone.HAND, filter);
if (!controller.choose(Outcome.Benefit, revealedCards, target, game)) {
return result;
}
result = !player.discard(new CardsImpl(target.getTargets()), false, source, game).isEmpty();
return result;
}
@Override
public DiscardCardYouChooseTargetEffect copy() {
return new DiscardCardYouChooseTargetEffect(this);
}
private String setText() {
StringBuilder sb = new StringBuilder("target ");
switch (targetController) {
case OPPONENT:
sb.append("opponent");
break;
case ANY:
sb.append("player");
break;
default:
throw new UnsupportedOperationException("target controller not supported");
}
if (revealAllCards) {
sb.append(" reveals their hand");
} else {
if (numberCardsToReveal instanceof StaticValue) {
sb.append(" reveals ");
sb.append(CardUtil.numberToText(((StaticValue) numberCardsToReveal).getValue())).append(" cards");
sb.append(" from their hand");
} else {
sb.append(" reveals a number of cards from their hand equal to ");
sb.append(numberCardsToReveal.getMessage());
}
}
sb.append(". You choose ");
boolean discardMultipleCards = !numberCardsToDiscard.toString().equals("1");
if (discardMultipleCards) {
sb.append(numberCardsToDiscard).append(' ').append(filter.getMessage());
} else {
sb.append(CardUtil.addArticle(filter.getMessage()));
}
if (revealAllCards) {
sb.append(filter.getMessage().contains("from it") ? "." : " from it.");
} else {
sb.append(" of them.");
}
sb.append(" That player discards ").append(discardMultipleCards ? "those cards" : "that card");
return sb.toString();
}
}
|
package org.commcare.views;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.commcare.activities.FormEntryActivity;
import org.commcare.dalvik.R;
import org.commcare.interfaces.WidgetChangedListener;
import org.commcare.logic.PendingCalloutInterface;
import org.commcare.models.ODKStorage;
import org.commcare.preferences.FormEntryPreferences;
import org.commcare.util.LogTypes;
import org.commcare.utils.BlockingActionsManager;
import org.commcare.utils.CompoundIntentList;
import org.commcare.utils.MarkupUtil;
import org.commcare.views.widgets.DateTimeWidget;
import org.commcare.views.widgets.IntentWidget;
import org.commcare.views.widgets.QuestionWidget;
import org.commcare.views.widgets.StringWidget;
import org.commcare.views.widgets.TimeWidget;
import org.commcare.views.widgets.WidgetFactory;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.services.Logger;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/**
* @author carlhartung
*/
public class QuestionsView extends ScrollView
implements OnLongClickListener, WidgetChangedListener {
// starter random number for view IDs
private final static int VIEW_ID = 12345;
private final LinearLayout mView;
private final LinearLayout.LayoutParams mLayout;
private final ArrayList<QuestionWidget> widgets;
private final ArrayList<View> dividers;
private final int mQuestionFontsize;
private WidgetChangedListener wcListener;
private boolean hasListener = false;
private int widgetIdCount = 0;
private int mViewBannerCount = 0;
private SpannableStringBuilder mGroupLabel;
private final BlockingActionsManager blockingActionsManager;
/**
* If enabled, we use dividers between question prompts
*/
private static final boolean SEPERATORS_ENABLED = false;
public QuestionsView(Context context, BlockingActionsManager blockingActionsManager) {
super(context);
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
String question_font =
settings.getString(FormEntryPreferences.KEY_FONT_SIZE, ODKStorage.DEFAULT_FONTSIZE);
mQuestionFontsize = Integer.valueOf(question_font);
widgets = new ArrayList<>();
dividers = new ArrayList<>();
mView = (LinearLayout)inflate(getContext(), R.layout.odkview_layout, null);
mLayout =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mGroupLabel = null;
this.blockingActionsManager = blockingActionsManager;
}
public QuestionsView(Context context, FormEntryPrompt[] questionPrompts,
FormEntryCaption[] groups, WidgetFactory factory,
WidgetChangedListener wcl, BlockingActionsManager blockingActionsManager) {
this(context, blockingActionsManager);
if (wcl != null) {
hasListener = true;
wcListener = wcl;
}
// display which group you are in as well as the question
mGroupLabel = deriveGroupText(groups);
String hintText = getHintText(questionPrompts);
addHintText(hintText);
boolean first = true;
for (FormEntryPrompt p : questionPrompts) {
if (!first) {
View divider = new View(getContext());
if (SEPERATORS_ENABLED) {
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
divider.setMinimumHeight(3);
} else {
divider.setMinimumHeight(0);
}
dividers.add(divider);
mView.addView(divider);
} else {
first = false;
}
QuestionWidget qw;
// if question or answer type is not supported, use text widget
qw = factory.createWidgetFromPrompt(p,
getContext(),
FormEntryActivity.mFormController.indexIsInCompact(p.getIndex()));
qw.setLongClickable(true);
qw.setOnLongClickListener(this);
qw.setId(VIEW_ID + widgetIdCount++);
//Suppress the hint text if we bubbled it
if (hintText != null) {
qw.hideHintText();
}
widgets.add(qw);
mView.addView(qw, mLayout);
qw.setChangedListeners(this, blockingActionsManager);
}
markLastStringWidget();
addView(mView);
}
private void removeQuestionFromIndex(int i) {
int dividerIndex = Math.max(i - 1, 0);
if (dividerIndex < dividers.size()) {
mView.removeView(dividers.get(dividerIndex));
dividers.remove(dividerIndex);
}
if (i < widgets.size()) {
mView.removeView(widgets.get(i));
widgets.get(i).unsetListeners();
widgets.remove(i);
}
}
public void removeQuestionsFromIndex(ArrayList<Integer> indexes) {
//Always gotta move backwards when removing, ensure that this list
//goes backwards
Collections.sort(indexes);
Collections.reverse(indexes);
for (int i = 0; i < indexes.size(); i++) {
removeQuestionFromIndex(indexes.get(i));
}
}
public void addQuestionToIndex(FormEntryPrompt fep, WidgetFactory factory, int i, boolean inCompactGroup) {
View divider = new View(getContext());
if (SEPERATORS_ENABLED) {
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
divider.setMinimumHeight(3);
} else {
divider.setMinimumHeight(0);
}
int dividerIndex = mViewBannerCount;
if (i > 0) {
dividerIndex += 2 * i - 1;
}
mView.addView(divider, getViewIndex(dividerIndex));
dividers.add(Math.max(0, i - 1), divider);
QuestionWidget qw = factory.createWidgetFromPrompt(fep, getContext(), inCompactGroup);
qw.setLongClickable(true);
qw.setOnLongClickListener(this);
qw.setId(VIEW_ID + widgetIdCount++);
//Suppress the hint text if we bubbled it
// if(hintText != null) { //TODO figure this out
// qw.hideHintText();
// }
widgets.add(i, qw);
mView.addView(qw, getViewIndex(2 * i + mViewBannerCount), mLayout);
qw.setChangedListeners(this, blockingActionsManager);
}
/**
* @return a HashMap of answers entered by the user for this set of widgets
*/
public HashMap<FormIndex, IAnswerData> getAnswers() {
HashMap<FormIndex, IAnswerData> answers = new HashMap<>();
for (QuestionWidget q : widgets) {
// The FormEntryPrompt has the FormIndex, which is where the answer gets stored. The
// QuestionWidget has the answer the user has entered.
FormEntryPrompt p = q.getPrompt();
answers.put(p.getIndex(), q.getAnswer());
}
return answers;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int newHeight = MeasureSpec.getSize(heightMeasureSpec);
int oldHeight = this.getMeasuredHeight();
if (oldHeight == 0 || Math.abs(((newHeight * 1.0 - oldHeight) / oldHeight)) > .2) {
// Update the frame size and hint height based on the new height
for (QuestionWidget qw : this.widgets) {
qw.updateFrameSize(newHeight);
qw.updateHintHeight(newHeight / 4);
}
} else {
// Check to see if any of our QuestionWidgets have a hint text that was initially
// displayed without proper height spec information
for (QuestionWidget qw : this.widgets) {
if (qw.hintTextNeedsHeightSpec) {
qw.updateHintHeight(newHeight / 4);
}
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void updateConstraintRelevancies(QuestionWidget changedWidget) {
if (hasListener) {
wcListener.widgetEntryChanged(changedWidget);
}
}
/**
* Returns the hierarchy of groups to which the question belongs.
*/
private SpannableStringBuilder deriveGroupText(FormEntryCaption[] groups) {
SpannableStringBuilder s = new SpannableStringBuilder("");
String t;
String m;
int i;
// list all groups in one string
for (FormEntryCaption g : groups) {
i = g.getMultiplicity() + 1;
t = g.getLongText();
m = g.getMarkdownText();
if (m != null) {
Spannable markdownSpannable = MarkupUtil.returnMarkdown(getContext(), m);
s.append(markdownSpannable);
} else if (t != null && !t.trim().equals("")) {
s.append(t);
} else {
continue;
}
if (g.repeats() && i > 0) {
s.append(" (").append(String.valueOf(i)).append(")");
}
s.append(" > ");
}
//remove the trailing " > "
if (s.length() > 0) {
s.delete(s.length() - 2, s.length());
}
return s;
}
/**
* Ugh, the coupling here sucks, but this returns the group label
* to be used for this odk view.
*/
public SpannableStringBuilder getGroupLabel() {
return mGroupLabel;
}
private String getHintText(FormEntryPrompt[] questionPrompts) {
//Figure out if we share hint text between questions
String hintText = null;
if (questionPrompts.length > 1) {
hintText = questionPrompts[0].getHintText();
for (FormEntryPrompt p : questionPrompts) {
//If something doesn't have hint text at all,
//bail
String curHintText = p.getHintText();
//Otherwise see if it matches
if (curHintText == null || !curHintText.equals(hintText)) {
//If not, we can't do this trick
hintText = null;
break;
}
}
}
return hintText;
}
private void addHintText(String hintText) {
if (hintText != null && !hintText.equals("")) {
TextView mHelpText = new TextView(getContext());
mHelpText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize - 3);
mHelpText.setPadding(0, -5, 0, 7);
// wrap to the widget of view
mHelpText.setHorizontallyScrolling(false);
mHelpText.setText(hintText);
mHelpText.setTypeface(null, Typeface.ITALIC);
mViewBannerCount++;
mView.addView(mHelpText, mLayout);
}
}
public void setFocus(Context context, int indexOfLastChangedWidget) {
QuestionWidget widgetToFocus = null;
if (indexOfLastChangedWidget != -1 && indexOfLastChangedWidget < widgets.size()) {
widgetToFocus = widgets.get(indexOfLastChangedWidget);
} else if (widgets.size() > 0) {
widgetToFocus = widgets.get(0);
}
if (widgetToFocus != null) {
scrollToWidget(widgetToFocus);
widgetToFocus.setFocus(context);
}
}
private void scrollToWidget(final QuestionWidget widget) {
new Handler().post(() -> QuestionsView.this.scrollTo(0, widget.getTop()));
}
/**
* @param pendingIntentWidget - the widget for which a callout from form entry just occurred,
* if there is one
* @return the index of the widget that focus was restored to, or -1 if there was no
* widget that just called out
*/
public int restoreFocusToQuestionThatCalledOut(Context context, QuestionWidget pendingIntentWidget) {
if (pendingIntentWidget != null) {
int index = widgets.indexOf(pendingIntentWidget);
setFocus(context, index);
return index;
}
return -1;
}
/**
* Called when another activity returns information to answer this question.
*/
public void setBinaryData(Object answer, PendingCalloutInterface pendingCalloutInterface) {
FormIndex questionFormIndex = pendingCalloutInterface.getPendingCalloutFormIndex();
if (questionFormIndex == null) {
Logger.log(LogTypes.SOFT_ASSERT,
"No pending callout index was set when trying to attach pending data.");
return;
}
for (QuestionWidget q : widgets) {
if (questionFormIndex.equals(q.getFormId())) {
q.setBinaryData(answer);
return;
}
}
Logger.log(LogTypes.SOFT_ASSERT,
"Unable to find question widget to attach pending data to.");
}
/**
* @return true if the answer was cleared, false otherwise.
*/
public boolean clearAnswer() {
// If there's only one widget, clear the answer.
// If there are more, then force a long-press to clear the answer.
if (widgets.size() == 1 && !widgets.get(0).getPrompt().isReadOnly()) {
widgets.get(0).clearAnswer();
return true;
} else {
return false;
}
}
public ArrayList<QuestionWidget> getWidgets() {
return widgets;
}
public boolean isQuestionList() {
return widgets.size() > 1;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener l) {
for (QuestionWidget qw : widgets) {
qw.setOnFocusChangeListener(l);
}
}
public void teardownView() {
for (QuestionWidget widget : widgets) {
widget.unsetListeners();
widget.setOnCreateContextMenuListener(null);
}
wcListener = null;
}
@Override
public boolean onLongClick(View v) {
return false;
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (QuestionWidget qw : widgets) {
qw.cancelLongPress();
}
}
@Override
public void widgetEntryChanged(QuestionWidget changedWidget) {
updateConstraintRelevancies(changedWidget);
markLastStringWidget();
}
private void markLastStringWidget() {
StringWidget last = null;
for (QuestionWidget q : widgets) {
if (q instanceof StringWidget) {
if (last != null) {
last.setLastQuestion(false);
}
last = (StringWidget)q;
last.setLastQuestion(true);
}
}
}
/**
* Translate question index to view index.
*
* @param questionIndex Index in the list of questions.
* @return Index of question's view in mView.
*/
private int getViewIndex(int questionIndex) {
return questionIndex;
}
/**
* Takes in a form entry prompt that is obtained generically and if there
* is already one on screen (which, for instance, may have cached some of its data)
* returns the object in use currently.
*/
public FormEntryPrompt getOnScreenPrompt(FormEntryPrompt prompt) {
FormIndex index = prompt.getIndex();
for (QuestionWidget widget : this.getWidgets()) {
if (widget.getFormId().equals(index)) {
return widget.getPrompt();
}
}
return prompt;
}
public void restoreTimePickerData() {
// On honeycomb and above this is handled by calling:
// TimePicker.setSaveFromParentEnabled(false);
// TimePicker.setSaveEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
//csims@dimagi.com - 22/08/2012 - For release only, fix immediately.
//There is a _horribly obnoxious_ bug in TimePickers that messes up how they work
//on screen rotation. We need to re-do any setAnswers that we perform on them after
//onResume.
try {
if (getWidgets() != null) {
for (QuestionWidget qw : getWidgets()) {
if (qw instanceof DateTimeWidget) {
((DateTimeWidget)qw).setAnswer();
} else if (qw instanceof TimeWidget) {
((TimeWidget)qw).setAnswer();
}
}
}
} catch (Exception e) {
//if this fails, we _really_ don't want to mess anything up. this is a last minute
//fix
}
}
}
public CompoundIntentList getAggregateIntentCallout() {
CompoundIntentList compoundedCallout = null;
for (QuestionWidget widget : this.getWidgets()) {
if (widget instanceof IntentWidget) {
boolean expectResult = compoundedCallout != null;
compoundedCallout = ((IntentWidget)widget).addToCompoundIntent(compoundedCallout);
if (compoundedCallout == null && expectResult) {
return null;
}
}
}
if (compoundedCallout == null || compoundedCallout.getNumberOfCallouts() <= 1) {
return null;
}
return compoundedCallout;
}
}
|
package org.jabref.model.search.rules;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.Keyword;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.InternalField;
import org.jabref.search.SearchBaseVisitor;
import org.jabref.search.SearchLexer;
import org.jabref.search.SearchParser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ParseTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The search query must be specified in an expression that is acceptable by the Search.g4 grammar.
* <p>
* This class implements the "Advanced Search Mode" described in the help
*/
public class GrammarBasedSearchRule implements SearchRule {
private static final Logger LOGGER = LoggerFactory.getLogger(GrammarBasedSearchRule.class);
private final boolean caseSensitiveSearch;
private final boolean regExpSearch;
private ParseTree tree;
private String query;
public static class ThrowingErrorListener extends BaseErrorListener {
public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener();
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
int line, int charPositionInLine, String msg, RecognitionException e)
throws ParseCancellationException {
throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg);
}
}
public GrammarBasedSearchRule(boolean caseSensitiveSearch, boolean regExpSearch) throws RecognitionException {
this.caseSensitiveSearch = caseSensitiveSearch;
this.regExpSearch = regExpSearch;
}
public static boolean isValid(boolean caseSensitive, boolean regExp, String query) {
return new GrammarBasedSearchRule(caseSensitive, regExp).validateSearchStrings(query);
}
public boolean isCaseSensitiveSearch() {
return this.caseSensitiveSearch;
}
public boolean isRegExpSearch() {
return this.regExpSearch;
}
public ParseTree getTree() {
return this.tree;
}
public String getQuery() {
return this.query;
}
private void init(String query) throws ParseCancellationException {
if (Objects.equals(this.query, query)) {
return;
}
SearchLexer lexer = new SearchLexer(new ANTLRInputStream(query));
lexer.removeErrorListeners(); // no infos on file system
lexer.addErrorListener(ThrowingErrorListener.INSTANCE);
SearchParser parser = new SearchParser(new CommonTokenStream(lexer));
parser.removeErrorListeners(); // no infos on file system
parser.addErrorListener(ThrowingErrorListener.INSTANCE);
parser.setErrorHandler(new BailErrorStrategy()); // ParseCancelationException on parse errors
tree = parser.start();
this.query = query;
}
@Override
public boolean applyRule(String query, BibEntry bibEntry) {
try {
return new BibtexSearchVisitor(caseSensitiveSearch, regExpSearch, bibEntry).visit(tree);
} catch (Exception e) {
LOGGER.debug("Search failed", e);
return false;
}
}
@Override
public boolean validateSearchStrings(String query) {
try {
init(query);
return true;
} catch (ParseCancellationException e) {
LOGGER.debug("Search query invalid", e);
return false;
}
}
public enum ComparisonOperator {
EXACT, CONTAINS, DOES_NOT_CONTAIN;
public static ComparisonOperator build(String value) {
if ("CONTAINS".equalsIgnoreCase(value) || "=".equals(value)) {
return CONTAINS;
} else if ("MATCHES".equalsIgnoreCase(value) || "==".equals(value)) {
return EXACT;
} else {
return DOES_NOT_CONTAIN;
}
}
}
public static class Comparator {
private final ComparisonOperator operator;
private final Pattern fieldPattern;
private final Pattern valuePattern;
public Comparator(String field, String value, ComparisonOperator operator, boolean caseSensitive, boolean regex) {
this.operator = operator;
int option = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
this.fieldPattern = Pattern.compile(regex ? field : "\\Q" + field + "\\E", option);
this.valuePattern = Pattern.compile(regex ? value : "\\Q" + value + "\\E", option);
}
public boolean compare(BibEntry entry) {
// special case for searching for entrytype=phdthesis
if (fieldPattern.matcher(InternalField.TYPE_HEADER.getName()).matches()) {
return matchFieldValue(entry.getType().getName());
}
// special case for searching a single keyword
if (fieldPattern.matcher("anykeyword").matches()) {
return entry.getKeywords(',').stream().map(Keyword::toString).anyMatch(this::matchFieldValue);
}
// specification of fieldsKeys to search is done in the search expression itself
Set<Field> fieldsKeys = entry.getFields();
// special case for searching allfields=cat and title=dog
if (!fieldPattern.matcher("anyfield").matches()) {
// Filter out the requested fields
fieldsKeys = fieldsKeys.stream().filter(matchFieldKey()).collect(Collectors.toSet());
}
for (Field field : fieldsKeys) {
Optional<String> fieldValue = entry.getLatexFreeField(field);
if (fieldValue.isPresent()) {
if (matchFieldValue(fieldValue.get())) {
return true;
}
}
}
// special case of asdf!=whatever and entry does not contain asdf
return fieldsKeys.isEmpty() && (operator == ComparisonOperator.DOES_NOT_CONTAIN);
}
private Predicate<Field> matchFieldKey() {
return field -> fieldPattern.matcher(field.getName()).matches();
}
public boolean matchFieldValue(String content) {
Matcher matcher = valuePattern.matcher(content);
if (operator == ComparisonOperator.CONTAINS) {
return matcher.find();
} else if (operator == ComparisonOperator.EXACT) {
return matcher.matches();
} else if (operator == ComparisonOperator.DOES_NOT_CONTAIN) {
return !matcher.find();
} else {
throw new IllegalStateException("MUST NOT HAPPEN");
}
}
}
/**
* Search results in boolean. It may be later on converted to an int.
*/
static class BibtexSearchVisitor extends SearchBaseVisitor<Boolean> {
private final boolean caseSensitive;
private final boolean regex;
private final BibEntry entry;
public BibtexSearchVisitor(boolean caseSensitive, boolean regex, BibEntry bibEntry) {
this.caseSensitive = caseSensitive;
this.regex = regex;
this.entry = bibEntry;
}
public boolean comparison(String field, ComparisonOperator operator, String value) {
return new Comparator(field, value, operator, caseSensitive, regex).compare(entry);
}
@Override
public Boolean visitStart(SearchParser.StartContext ctx) {
return visit(ctx.expression());
}
@Override
public Boolean visitComparison(SearchParser.ComparisonContext context) {
// remove possible enclosing " symbols
String right = context.right.getText();
if (right.startsWith("\"") && right.endsWith("\"")) {
right = right.substring(1, right.length() - 1);
}
Optional<SearchParser.NameContext> fieldDescriptor = Optional.ofNullable(context.left);
if (fieldDescriptor.isPresent()) {
return comparison(fieldDescriptor.get().getText(), ComparisonOperator.build(context.operator.getText()), right);
} else {
return new ContainBasedSearchRule(caseSensitive).applyRule(right, entry);
}
}
@Override
public Boolean visitUnaryExpression(SearchParser.UnaryExpressionContext ctx) {
return !visit(ctx.expression()); // negate
}
@Override
public Boolean visitParenExpression(SearchParser.ParenExpressionContext ctx) {
return visit(ctx.expression()); // ignore parenthesis
}
@Override
public Boolean visitBinaryExpression(SearchParser.BinaryExpressionContext ctx) {
if ("AND".equalsIgnoreCase(ctx.operator.getText())) {
return visit(ctx.left) && visit(ctx.right); // and
} else {
return visit(ctx.left) || visit(ctx.right); // or
}
}
}
}
|
package com.poiji.option;
import com.poiji.annotation.ExcelCellName;
import com.poiji.bind.mapping.PoijiLogCellFormat;
import com.poiji.bind.mapping.PoijiNumberFormat;
import com.poiji.config.Casting;
import com.poiji.config.DefaultCasting;
import com.poiji.config.DefaultFormatting;
import com.poiji.config.Formatting;
import com.poiji.exception.PoijiException;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import static com.poiji.util.PoijiConstants.DEFAULT_DATE_FORMATTER;
import static com.poiji.util.PoijiConstants.DEFAULT_DATE_PATTERN;
import static com.poiji.util.PoijiConstants.DEFAULT_DATE_TIME_FORMATTER;
/**
* Created by hakan on 17/01/2017.
*/
public final class PoijiOptions {
private int skip;
private int limit;
private int sheetIndex;
private String password;
private String dateRegex;
private String dateTimeRegex;
private String datePattern;
private boolean dateLenient;
private boolean trimCellValue;
private boolean ignoreHiddenSheets;
private boolean preferNullOverDefault;
private DateTimeFormatter dateFormatter;
private DateTimeFormatter dateTimeFormatter;
private Casting casting;
private int headerStart;
private int headerCount;
private String sheetName;
private boolean caseInsensitive;
private boolean ignoreWhitespaces;
private PoijiLogCellFormat poijiLogCellFormat;
private PoijiNumberFormat numberFormat;
private boolean namedHeaderMandatory;
private boolean disableXLSXNumberCellFormat;
private String listDelimiter;
private Formatting formatting;
public PoijiNumberFormat getPoijiNumberFormat() {
return numberFormat;
}
private PoijiOptions setPoijiNumberFormat(PoijiNumberFormat numberFormat) {
this.numberFormat = numberFormat;
return this;
}
public PoijiLogCellFormat getPoijiCellFormat() {
return poijiLogCellFormat;
}
private PoijiOptions setPoijiLogCellFormat(PoijiLogCellFormat poijiLogCellFormat) {
this.poijiLogCellFormat = poijiLogCellFormat;
return this;
}
private PoijiOptions() {
super();
}
private PoijiOptions setSkip(int skip) {
this.skip = skip;
return this;
}
public int getLimit() {
return limit;
}
public PoijiOptions setLimit(int limit) {
this.limit = limit;
return this;
}
private PoijiOptions setDatePattern(String datePattern) {
this.datePattern = datePattern;
return this;
}
private PoijiOptions setDateFormatter(DateTimeFormatter dateFormatter) {
this.dateFormatter = dateFormatter;
return this;
}
private PoijiOptions setDateTimeFormatter(DateTimeFormatter dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
return this;
}
private PoijiOptions setPreferNullOverDefault(boolean preferNullOverDefault) {
this.preferNullOverDefault = preferNullOverDefault;
return this;
}
public String getPassword() {
return password;
}
private PoijiOptions setPassword(String password) {
this.password = password;
return this;
}
public String datePattern() {
return datePattern;
}
public DateTimeFormatter dateFormatter() {
return dateFormatter;
}
public DateTimeFormatter dateTimeFormatter() {
return dateTimeFormatter;
}
public boolean preferNullOverDefault() {
return preferNullOverDefault;
}
/**
* the number of skipped rows
*
* @return n rows skipped
*/
public int skip() {
return skip;
}
public boolean ignoreHiddenSheets() {
return ignoreHiddenSheets;
}
private PoijiOptions setIgnoreHiddenSheets(boolean ignoreHiddenSheets) {
this.ignoreHiddenSheets = ignoreHiddenSheets;
return this;
}
public boolean trimCellValue() {
return trimCellValue;
}
public PoijiOptions setTrimCellValue(boolean trimCellValue) {
this.trimCellValue = trimCellValue;
return this;
}
public Casting getCasting() {
return casting;
}
public PoijiOptions setCasting(Casting casting) {
this.casting = casting;
return this;
}
private PoijiOptions setSheetIndex(int sheetIndex) {
this.sheetIndex = sheetIndex;
return this;
}
public int sheetIndex() {
return sheetIndex;
}
public String getDateRegex() {
return dateRegex;
}
private PoijiOptions setDateRegex(String dateRegex) {
this.dateRegex = dateRegex;
return this;
}
public String getDateTimeRegex() {
return dateTimeRegex;
}
private PoijiOptions setDateTimeRegex(String dateTimeRegex) {
this.dateTimeRegex = dateTimeRegex;
return this;
}
public boolean getDateLenient() {
return dateLenient;
}
private PoijiOptions setDateLenient(boolean dateLenient) {
this.dateLenient = dateLenient;
return this;
}
public int getHeaderStart() {
return headerStart;
}
public int getHeaderCount() {
return headerCount;
}
private PoijiOptions setHeaderStart(int headerStart) {
this.headerStart = headerStart;
return this;
}
private PoijiOptions setHeaderCount(int headerCount) {
this.headerCount = headerCount;
return this;
}
private PoijiOptions setSheetName(String sheetName) {
this.sheetName = sheetName;
return this;
}
public String getSheetName() {
return sheetName;
}
public boolean getCaseInsensitive() {
return caseInsensitive;
}
private PoijiOptions setCaseInsensitive(final boolean caseInsensitive) {
this.caseInsensitive = caseInsensitive;
return this;
}
public boolean getIgnoreWhitespaces() {
return ignoreWhitespaces;
}
private PoijiOptions setIgnoreWhitespaces(final boolean ignoreWhitespaces) {
this.ignoreWhitespaces = ignoreWhitespaces;
return this;
}
public boolean getNamedHeaderMandatory() {
return namedHeaderMandatory;
}
private PoijiOptions setNamedHeaderMandatory(boolean namedHeaderMandatory) {
this.namedHeaderMandatory = namedHeaderMandatory;
return this;
}
private PoijiOptions disableXLSXNumberCellFormat(boolean disableXLSXNumberCellFormat) {
this.disableXLSXNumberCellFormat = disableXLSXNumberCellFormat;
return this;
}
public boolean isDisableXLSXNumberCellFormat() {
return disableXLSXNumberCellFormat;
}
public String getListDelimiter() {
return listDelimiter;
}
private PoijiOptions setListDelimiter(String listDelimiter) {
this.listDelimiter = listDelimiter;
return this;
}
public Formatting getFormatting() {
return formatting;
}
private PoijiOptions setFormatting(Formatting formatting) {
this.formatting = formatting;
return this;
}
public static class PoijiOptionsBuilder {
private int sheetIndex;
private String password;
private String dateRegex;
private String dateTimeRegex;
private boolean dateLenient;
private boolean trimCellValue;
private boolean ignoreHiddenSheets;
private boolean preferNullOverDefault;
private String datePattern = DEFAULT_DATE_PATTERN;
private DateTimeFormatter dateFormatter = DEFAULT_DATE_FORMATTER;
private DateTimeFormatter dateTimeFormatter = DEFAULT_DATE_TIME_FORMATTER;
private Casting casting = new DefaultCasting();
private Formatting formatting = new DefaultFormatting();
private PoijiLogCellFormat cellFormat;
private PoijiNumberFormat numberFormat;
private int headerStart = 0;
private int headerCount = 1;
private int skip = 1;
private int limit = 0;
private String sheetName;
private boolean caseInsensitive;
private boolean ignoreWhitespaces;
private boolean namedHeaderMandatory;
private boolean disabledXLSXNumberCellFormat;
private String listDelimiter = ",";
private PoijiOptionsBuilder() {
}
private PoijiOptionsBuilder(int skip) {
this.skip = skip;
}
/**
* Skip a number of rows after the header row. The header row is not counted.
*
* @param skip ignored row number after the header row
* @return builder itself
*/
public static PoijiOptionsBuilder settings(int skip) {
if (skip <= 0) {
throw new PoijiException("Poiji already skips the header. Skip index must be greater than 1");
}
return new PoijiOptionsBuilder(skip + 1);
}
public static PoijiOptionsBuilder settings() {
return new PoijiOptionsBuilder();
}
/**
* set a date formatter, default date time formatter is "dd/M/yyyy"
* for java.time.LocalDate
*
* @param dateFormatter date time formatter
* @return this
*/
public PoijiOptionsBuilder dateFormatter(DateTimeFormatter dateFormatter) {
this.dateFormatter = dateFormatter;
return this;
}
/**
* set a date time formatter, default date time formatter is "dd/M/yyyy HH:mm:ss"
* for java.time.LocalDateTime
*
* @param dateTimeFormatter date time formatter
* @return this
*/
public PoijiOptionsBuilder dateTimeFormatter(DateTimeFormatter dateTimeFormatter) {
this.dateTimeFormatter = dateTimeFormatter;
return this;
}
/**
* set date pattern, default date format is "dd/M/yyyy" for
* java.util.Date
*
* @param datePattern date time formatter
* @return this
*/
public PoijiOptionsBuilder datePattern(String datePattern) {
this.datePattern = datePattern;
return this;
}
/**
* set whether or not to use null instead of default values for Integer,
* Double, Float, Long, String and java.util.Date types.
*
* @param preferNullOverDefault boolean
* @return this
*/
public PoijiOptionsBuilder preferNullOverDefault(boolean preferNullOverDefault) {
this.preferNullOverDefault = preferNullOverDefault;
return this;
}
public PoijiOptions build() {
return new PoijiOptions()
.setSkip(skip + headerStart + headerCount - 1)
.setPassword(password)
.setPreferNullOverDefault(preferNullOverDefault)
.setDatePattern(datePattern)
.setDateFormatter(dateFormatter)
.setDateTimeFormatter(dateTimeFormatter)
.setSheetIndex(sheetIndex)
.setSheetName(sheetName)
.setIgnoreHiddenSheets(ignoreHiddenSheets)
.setTrimCellValue(trimCellValue)
.setDateRegex(dateRegex)
.setDateTimeRegex(dateTimeRegex)
.setDateLenient(dateLenient)
.setHeaderStart(headerStart)
.setHeaderCount(headerCount)
.setCasting(casting)
.setLimit(limit)
.setPoijiLogCellFormat(cellFormat)
.setPoijiNumberFormat(numberFormat)
.setCaseInsensitive(caseInsensitive)
.setIgnoreWhitespaces(ignoreWhitespaces)
.setNamedHeaderMandatory(namedHeaderMandatory)
.disableXLSXNumberCellFormat(disabledXLSXNumberCellFormat)
.setListDelimiter(listDelimiter)
.setFormatting(formatting);
}
/**
* set sheet index, default is 0
*
* @param sheetIndex number
* @return this
*/
public PoijiOptionsBuilder sheetIndex(int sheetIndex) {
if (sheetIndex < 0) {
throw new PoijiException("Sheet index must be greater than or equal to 0");
}
this.sheetIndex = sheetIndex;
return this;
}
/**
* Set the sheet Name
*
* @param sheetName excel sheet name
* @return this
*/
public PoijiOptionsBuilder sheetName(String sheetName) {
this.sheetName = sheetName;
return this;
}
/**
* skip a number of rows after the header row. The header row is not counted.
*
* @param skip number
* @return this
*/
public PoijiOptionsBuilder skip(int skip) {
if (skip <= 0) {
throw new PoijiException("Poiji already skips the header. Skip index must be greater than 1");
}
this.skip = skip + 1;
return this;
}
/**
* limit a number of rows after the header & skipped rows row. The header & skipped rows are not counted.
*
* @param limit number
* @return this
*/
public PoijiOptionsBuilder limit(int limit) {
if (limit < 1) {
throw new PoijiException("limit must be greater than 0");
}
this.limit = limit;
return this;
}
/**
* set password for encrypted excel file, Default is null
*
* @param password excel password
* @return this
*/
public PoijiOptionsBuilder password(String password) {
this.password = password;
return this;
}
/**
* Ignore hidden sheets
*
* @param ignoreHiddenSheets whether or not to ignore any hidden sheets
* in the work book.
* @return this
*/
public PoijiOptionsBuilder ignoreHiddenSheets(boolean ignoreHiddenSheets) {
this.ignoreHiddenSheets = ignoreHiddenSheets;
return this;
}
/**
* Trim cell value
*
* @param trimCellValue trim the cell value before processing work book.
* @return this
*/
public PoijiOptionsBuilder trimCellValue(boolean trimCellValue) {
this.trimCellValue = trimCellValue;
return this;
}
/**
* Date regex, if would like to specify a regex patter the date must be
* in, e.g.\\d{2}/\\d{1}/\\d{4}.
*
* @param dateRegex date regex pattern
* @return this
*/
public PoijiOptionsBuilder dateRegex(String dateRegex) {
this.dateRegex = dateRegex;
return this;
}
/**
* DateTime regex, if would like to specify a regex patter the date time must be
* in, e.g.\\d{2}/\\d{1}/\\d{4} \\d{2}:\\d{2}:\\d{2}.
*
* @param dateTimeRegex date regex pattern
* @return this
*/
public PoijiOptionsBuilder dateTimeRegex(String dateTimeRegex) {
this.dateTimeRegex = dateTimeRegex;
return this;
}
/**
* If the simple date format is lenient, use to
* set how strict the date formatting must be, defaults to lenient false.
* It works only for java.util.Date.
*
* @param dateLenient true or false
* @return this
*/
public PoijiOptionsBuilder dateLenient(boolean dateLenient) {
this.dateLenient = dateLenient;
return this;
}
/**
* Use a custom casting implementation
*
* @param casting custom casting implementation
* @return this
*/
public PoijiOptionsBuilder withCasting(Casting casting) {
Objects.requireNonNull(casting);
this.casting = casting;
return this;
}
/**
* This is to set the row which the unmarshall will
* use to start reading header titles, incase the
* header is not in row 0.
*
* @param headerStart an index number of the excel header to start reading header
* @return this
*/
public PoijiOptionsBuilder headerStart(int headerStart) {
if (headerStart < 0) {
throw new PoijiException("Header index must be greater than 0");
}
this.headerStart = headerStart;
return this;
}
/**
* This is to set the number of row contains headers
* <br/>
* Set 0 to indicate that no header in the excel file.
* Default - 1.
*
* @param headerCount an index number of the excel header to start reading header
* @return this
*/
public PoijiOptionsBuilder headerCount(int headerCount) {
if (headerCount < 0) {
throw new PoijiException("Number of header row must be greater than 0");
}
this.headerCount = headerCount;
return this;
}
/**
* Permits case insensitive column names mapping for annotation {@link ExcelCellName}.
* Default - false.
*
* @param caseInsensitive true or false
*/
public PoijiOptionsBuilder caseInsensitive(final boolean caseInsensitive) {
this.caseInsensitive = caseInsensitive;
return this;
}
/**
* Ignore white space before and after column names for annotation {@link ExcelCellName}.
* Default - false.
*
* @param ignoreWhitespaces true or false
*/
public PoijiOptionsBuilder ignoreWhitespaces(final boolean ignoreWhitespaces) {
this.ignoreWhitespaces = ignoreWhitespaces;
return this;
}
/**
* Add cell format option to see each internal cell's excel format for files ending with xlsx format.
* This option should be enabled for debugging purpose.
*
* @param cellFormat poiji cell format instance
*/
public PoijiOptionsBuilder poijiLogCellFormat(final PoijiLogCellFormat cellFormat) {
this.cellFormat = cellFormat;
return this;
}
/**
* Change the default cell formats of a xlsx excel file by overriding
*
* @param numberFormat poiji number format instance
*/
public PoijiOptionsBuilder poijiNumberFormat(final PoijiNumberFormat numberFormat) {
this.numberFormat = numberFormat;
return this;
}
/**
* Set true if all headers named in {@link ExcelCellName} are mandatory, otherwise false
*
* @param namedHeaderMandatory fieldas are mandatory or not
*/
public PoijiOptionsBuilder namedHeaderMandatory(boolean namedHeaderMandatory) {
this.namedHeaderMandatory = namedHeaderMandatory;
return this;
}
/**
* Disable the cell format of all the number cells of an excel file ending with xlsx
*
* @return this
*/
public PoijiOptionsBuilder disableXLSXNumberCellFormat() {
this.disabledXLSXNumberCellFormat = true;
return this;
}
/**
* Use different delimiter to split the list of items of a cell
*
* @param delimiter by default delimiter is ','
* @return this
*/
public PoijiOptionsBuilder addListDelimiter(String delimiter) {
this.listDelimiter = delimiter;
return this;
}
/**
* Use a custom excel header format implementation
*
* @param formatting custom header format implementation
* @return this
*/
public PoijiOptionsBuilder withFormatting(Formatting formatting) {
Objects.requireNonNull(formatting);
this.formatting = formatting;
return this;
}
}
}
|
package io.bootique.tools.release.service.job;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class BatchJobTask<T> extends FutureTask<T> {
private final Object data;
private Runnable listener;
public BatchJobTask(Callable<T> callable) {
super(callable);
if(callable instanceof BatchJobResultCallable) {
data = ((BatchJobResultCallable<?, ?>) callable).getData();
} else {
throw new RuntimeException("BatchJobResultCallable expected, got " + callable);
}
}
public BatchJobTask(Runnable runnable, T value) {
super(runnable, value);
throw new RuntimeException("BatchJobResultCallable expected, got runnable");
}
public void setListener(Runnable listener) {
this.listener = listener;
}
@Override
protected void done() {
listener.run();
}
@SuppressWarnings("unchecked")
public <D> D getData() {
return (D)data;
}
}
|
/*************************************************************************
* *
* EJBCA Community: The OpenSource Certificate Authority *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.cesecore.certificates.ocsp.cache;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.BufferingContentSigner;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.cesecore.certificates.ocsp.extension.OCSPExtension;
import org.cesecore.config.ConfigurationHolder;
import org.cesecore.keys.util.KeyTools;
import org.cesecore.util.CertTools;
import org.cesecore.util.CryptoProviderTools;
import org.cesecore.util.FileTools;
import org.ejbca.core.protocol.ocsp.extension.certhash.OcspCertHashExtension;
import org.ejbca.core.protocol.ocsp.extension.unid.OCSPUnidExtension;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Unit test for the OCSP Extensions cache and
*
* @version $Id: OcspExtensionsTest.java 30570 2018-11-21 14:50:54Z samuellb $
*
*/
public class OcspExtensionsTest {
private static final String OCSP_UNID_OID = "2.16.578.1.16.3.2";
private static final String OCSP_UNID_CLASSNAME = OCSPUnidExtension.class.getName();
private static final String OCSP_CERTHASH_CLASSNAME = OcspCertHashExtension.class.getName();
private static File trustDir;
private static Certificate certificate;
private static File trustedCertificateFile;
private static File caCertificateFile;
@BeforeClass
public static void beforeClass() throws Exception {
CryptoProviderTools.installBCProviderIfNotAvailable();
trustDir = FileTools.createTempDirectory();
caCertificateFile = File.createTempFile("tmp", ".pem");
trustedCertificateFile = File.createTempFile("tmp", ".pem", trustDir);
KeyPair caKeyPair = KeyTools.genKeys("1024", "RSA");
Certificate caCertificate = CertTools.genSelfCert("CN=TESTCA", 10L, null, caKeyPair.getPrivate(), caKeyPair.getPublic(), "SHA256WithRSA", true);
FileOutputStream fileOutputStream = new FileOutputStream(caCertificateFile);
try {
fileOutputStream.write(CertTools.getPemFromCertificateChain(Arrays.asList(caCertificate)));
} finally {
fileOutputStream.close();
}
Date firstDate = new Date();
firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));
Date lastDate = new Date();
lastDate.setTime(lastDate.getTime() + (24 * 60 * 60 * 1000));
byte[] serno = new byte[8];
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(new Date().getTime());
random.nextBytes(serno);
KeyPair certificateKeyPair = KeyTools.genKeys("1024", "RSA");
final SubjectPublicKeyInfo pkinfo = SubjectPublicKeyInfo.getInstance(certificateKeyPair.getPublic().getEncoded());
final String certDn = "CN=TEST,SN=4711";
X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(certDn, false), new BigInteger(serno).abs(),
firstDate, lastDate, CertTools.stringToBcX500Name(certDn, false), pkinfo);
final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA256WithRSA").setProvider(
BouncyCastleProvider.PROVIDER_NAME).build(caKeyPair.getPrivate()), 20480);
final X509CertificateHolder certHolder = certbuilder.build(signer);
certificate = CertTools.getCertfromByteArray(certHolder.getEncoded(), Certificate.class);
fileOutputStream = new FileOutputStream(trustedCertificateFile);
try {
fileOutputStream.write(CertTools.getPemFromCertificateChain(Arrays.asList(certificate)));
} finally {
fileOutputStream.close();
}
ConfigurationHolder.updateConfiguration("ocsp.extensionoid", OCSP_UNID_OID+';'+OcspCertHashExtension.CERT_HASH_OID);
ConfigurationHolder.updateConfiguration("ocsp.extensionclass", OCSP_UNID_CLASSNAME+';'+OCSP_CERTHASH_CLASSNAME);
ConfigurationHolder.updateConfiguration("ocsp.uniddatsource", "foo");
ConfigurationHolder.updateConfiguration("ocsp.unidtrustdir", trustDir.getAbsolutePath());
ConfigurationHolder.updateConfiguration("ocsp.unidcacert", caCertificateFile.getAbsolutePath());
OcspExtensionsCache.INSTANCE.reloadCache();
}
@AfterClass
public static void afterClass() {
FileTools.delete(trustDir);
FileTools.delete(caCertificateFile);
}
/**
* Tests retrieving an ocsp unid extension. Actually processing the request falls under system testing.
*/
@Test
public void testRetrieveOcspUnidExtension() throws IOException {
Map<String, OCSPExtension> extensions = OcspExtensionsCache.INSTANCE.getExtensions();
OCSPExtension ocspUnidExtension = extensions.get(OCSPUnidExtension.OCSP_UNID_OID);
assertNotNull("OCSP Unid extension was not loaded", ocspUnidExtension);
}
/**
* Tests retrieving an ocsp cert hash extension. Actually processing the request falls under system testing.
*/
@Test
public void testRetrieveOcspCertHashExtension() throws IOException {
Map<String, OCSPExtension> extensions = OcspExtensionsCache.INSTANCE.getExtensions();
OCSPExtension ocspCertHashExtension = extensions.get(OcspCertHashExtension.CERT_HASH_OID);
assertNotNull("OCSP CertHash extension was not loaded", ocspCertHashExtension);
}
/**
* Tests retrieving an ocsp CT SCT extension. Actually processing the request falls under system testing.
*/
@Test
public void testRetrieveOcspCtSstListExtension() {
try {
Class.forName("org.ejbca.core.protocol.ocsp.extension.certificatetransparency.OcspCtSctListExtension");
} catch (ClassNotFoundException e) {
assumeTrue("Skipping test on Community Edition (class OcspCtSctListExtension does not exist)", false);
}
// we cant use OcspCtSctListExtension.OCSP_SCTLIST_OID,
// because org.ejbca.core.protocol.ocsp.extension.certificatetransparency.OcspCtSctListExtension is not included in Community edition
final String OCSP_SCTLIST_OID = "1.3.6.1.4.1.11129.2.4.5";
Map<String, OCSPExtension> extensions = OcspExtensionsCache.INSTANCE.getExtensions();
OCSPExtension ocspCtSstListExtension = extensions.get(OCSP_SCTLIST_OID);
assertNotNull("OCSP CtSct extension was not loaded", ocspCtSstListExtension);
}
}
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.governance.rest.api.internal;
import org.apache.commons.io.IOUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/**
* This message body writer is to handle special case where
* a content artifact type consist of application/json data
*/
@Provider
@Consumes({"application/json"})
public class ContentArtifactMessageBodyWriter implements MessageBodyWriter<ByteArrayInputStream> {
@Override
public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return ByteArrayInputStream.class.isAssignableFrom(aClass);
}
@Override
public long getSize(ByteArrayInputStream byteArrayInputStream, Class<?> aClass, Type type, Annotation[] annotations,
MediaType mediaType) {
return 0;
}
@Override
public void writeTo(ByteArrayInputStream byteArrayInputStream, Class<?> aClass, Type type, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> stringObjectMultivaluedMap,
OutputStream outputStream) throws IOException, WebApplicationException {
writeContentArtifact(byteArrayInputStream, outputStream);
}
private void writeContentArtifact(ByteArrayInputStream byteArrayInputStream, OutputStream outputStream)
throws IOException {
IOUtils.copy(byteArrayInputStream, outputStream);
byteArrayInputStream.close();
outputStream.close();
}
}
|
/*
* 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.calcite.materialize;
import org.apache.calcite.jdbc.CalciteSchema;
import org.apache.calcite.rel.type.RelDataType;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import java.util.List;
import java.util.Map;
/**
* Actor that manages the state of materializations in the system.
*/
class MaterializationActor {
// Not an actor yet -- TODO make members private and add request/response
// queues
final Map<MaterializationKey, Materialization> keyMap = Maps.newHashMap();
final Map<QueryKey, MaterializationKey> keyBySql = Maps.newHashMap();
final Map<TileKey, MaterializationKey> keyByTile = Maps.newHashMap();
/** Tiles grouped by dimensionality. We use a
* {@link TileKey} with no measures to represent a
* dimensionality. */
final Multimap<TileKey, TileKey> tilesByDimensionality =
HashMultimap.create();
/** A query materialized in a table, so that reading from the table gives the
* same results as executing the query. */
static class Materialization {
final MaterializationKey key;
final CalciteSchema rootSchema;
CalciteSchema.TableEntry materializedTable;
final String sql;
final RelDataType rowType;
/** Creates a materialization.
*
* @param key Unique identifier of this materialization
* @param materializedTable Table that currently materializes the query.
* That is, executing "select * from table" will
* give the same results as executing the query.
* May be null when the materialization is created;
* materialization service will change the value as
* @param sql Query that is materialized
* @param rowType Row type
*/
Materialization(MaterializationKey key,
CalciteSchema rootSchema,
CalciteSchema.TableEntry materializedTable,
String sql,
RelDataType rowType) {
this.key = key;
this.rootSchema = Preconditions.checkNotNull(rootSchema);
Preconditions.checkArgument(rootSchema.isRoot(), "must be root schema");
this.materializedTable = materializedTable; // may be null
this.sql = sql;
this.rowType = rowType;
}
}
/** A materialization can be re-used if it is the same SQL, on the same
* schema, with the same path for resolving functions. */
static class QueryKey {
final String sql;
final CalciteSchema schema;
final List<String> path;
QueryKey(String sql, CalciteSchema schema, List<String> path) {
this.sql = sql;
this.schema = schema;
this.path = path;
}
@Override public boolean equals(Object obj) {
return obj == this
|| obj instanceof QueryKey
&& sql.equals(((QueryKey) obj).sql)
&& schema.equals(((QueryKey) obj).schema)
&& path.equals(((QueryKey) obj).path);
}
@Override public int hashCode() {
return com.google.common.base.Objects.hashCode(sql, schema, path);
}
}
}
// End MaterializationActor.java
|
/**
* $Id: CompDependsDAO.java,v 1.7 2020/05/07 13:50:16 mmaloney Exp $
*
* $Log: CompDependsDAO.java,v $
* Revision 1.7 2020/05/07 13:50:16 mmaloney
* Also delete from scratchpad when deleting dependencies.
*
* Revision 1.6 2017/08/22 19:58:40 mmaloney
* Refactor
*
* Revision 1.5 2017/07/06 19:06:54 mmaloney
* New method to support comp exec command.
*
* Revision 1.4 2016/12/16 14:31:30 mmaloney
* Added getTriggersFor method.
*
* Revision 1.3 2014/12/19 19:26:57 mmaloney
* Handle version change for column name tsdb_group_member_ts data_id vs. ts_id.
*
* Revision 1.2 2014/07/03 12:53:41 mmaloney
* debug improvements.
*
*
* This software was written by Cove Software, LLC ("COVE") under contract
* to the United States Government.
*
* No warranty is provided or implied other than specific contractual terms
* between COVE and the U.S. Government
*
* Copyright 2014 U.S. Army Corps of Engineers, Hydrologic Engineering Center.
* All rights reserved.
*/
package opendcs.dao;
import ilex.util.Logger;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import opendcs.dai.AlgorithmDAI;
import opendcs.dai.CompDependsDAI;
import opendcs.dai.TimeSeriesDAI;
import opendcs.dai.TsGroupDAI;
import decodes.sql.DbKey;
import decodes.tsdb.BadTimeSeriesException;
import decodes.tsdb.DbAlgoParm;
import decodes.tsdb.DbCompAlgorithm;
import decodes.tsdb.DbCompParm;
import decodes.tsdb.DbComputation;
import decodes.tsdb.DbIoException;
import decodes.tsdb.NoSuchObjectException;
import decodes.tsdb.TimeSeriesIdentifier;
import decodes.tsdb.TsGroup;
import decodes.tsdb.TsdbDatabaseVersion;
public class CompDependsDAO extends DaoBase implements CompDependsDAI
{
private String cpCompDepends_col1 = null;
protected AlgorithmDAI algorithmDAO = null;
protected TsGroupDAI tsGroupDAO = null;
public CompDependsDAO(DatabaseConnectionOwner tsdb)
{
super(tsdb, "CompDependsDAO");
cpCompDepends_col1 = tsdb.isHdb()
|| tsdb.getTsdbVersion() >= TsdbDatabaseVersion.VERSION_9 ?
"TS_ID" : "SITE_DATATYPE_ID";
algorithmDAO = tsdb.makeAlgorithmDAO();
tsGroupDAO = db.makeTsGroupDAO();
}
@Override
public void removeTsDependencies(TimeSeriesIdentifier tsid)
throws DbIoException
{
DbKey key = tsid.getKey();
// Remove any computation dependencies to this time-series.
doModify("DELETE FROM CP_COMP_DEPENDS WHERE " + cpCompDepends_col1 + " = "
+ key);
// Disable any computations that use this time-series as input or
// output.
String q = "select distinct a.computation_id from "
+ "cp_computation a, cp_comp_ts_parm b "
+ "where a.computation_id = b.computation_id "
+ "and a.enabled = 'Y' "
+ "and b.site_datatype_id = " + key;
String mq = "update cp_computation set enabled = 'N' "
+ "where computation_id in (" + q + ")";
doModify(mq);
// If this ts is explicitly included in a group, remove it.
q = "delete from tsdb_group_member_ts where "
+ (db.getTsdbVersion() >= TsdbDatabaseVersion.VERSION_9 ? "ts_id" : "data_id")
+ " = "+key;
doModify(q);
}
@Override
public void writeCompDepends( DbComputation comp )
throws DbIoException
{
try
{
DbKey compId = comp.getId();
debug3("writeCompDepends(" + comp.getName() + ", id=" + compId);
deleteCompDependsForCompId(compId);
if (!comp.isEnabled())
return;
DbCompAlgorithm algo = comp.getAlgorithm();
if (algo == null)
{
String algoName = comp.getAlgorithmName();
if (algoName != null)
algo = algorithmDAO.getAlgorithm(algoName);
}
// If the computation has a group input, get the group and
// expand it.
TsGroup tsGroup = null;
if (!comp.getGroupId().isNull())
{
tsGroup = tsGroupDAO.getTsGroupById(comp.getGroupId());
if (tsGroup != null && !tsGroup.getIsExpanded())
db.expandTsGroup(tsGroup);
}
// Make a HashSet of all possible ts_id's that can be input to this computation.
HashSet<DbKey> dataIds = new HashSet<DbKey>();
for(Iterator<DbCompParm> dcpit = comp.getParms(); dcpit.hasNext(); )
{
DbCompParm dcp = dcpit.next();
String parmType = dcp.getAlgoParmType();
if (parmType == null && algo != null)
{
DbAlgoParm algoParm = algo.getParm(dcp.getRoleName());
if (algoParm != null)
parmType = algoParm.getParmType();
}
if (parmType == null || !parmType.startsWith("i"))
continue;
DbKey sdi = dcp.getSiteDataTypeId();
// If it has an SDI, it means it is fully defined.
if (sdi != null && !sdi.isNull())
{
debug3("writeCompDepends: explicit sdi=" + sdi
+ " for role " + dcp.getRoleName());
dataIds.add(sdi);
}
// Otherwise it is a partial definition, expand by group
else if (tsGroup != null)
{
for(TimeSeriesIdentifier grpTsid : tsGroup.getExpandedList())
{
try
{
TimeSeriesIdentifier tsid =
db.transformTsidByCompParm(grpTsid, dcp, false, false, null);
if (tsid != null)
dataIds.add(tsid.getKey());
}
catch(NoSuchObjectException ex)
{
// No problem -- this potential input doesn't exist. Skip it.
}
catch(BadTimeSeriesException ex)
{
// Invalid tsid. Skip it.
}
}
}
// Otherwise incomplete definition and no group - skip it.
}
debug3("Total dds for dependencies=" + dataIds.size());
for(DbKey dataId : dataIds)
{
String q =
"INSERT INTO CP_COMP_DEPENDS(" + cpCompDepends_col1 + ",COMPUTATION_ID) "
+ "VALUES(" + dataId + ", " + compId + ")";
doModify(q);
}
}
catch(Exception ex)
{
String msg = "Exception populating CP_COMP_DEPENDS table: " + ex;
warning(msg);
ex.printStackTrace(Logger.instance().getLogOutput());
throw new DbIoException(msg);
}
}
@Override
public void deleteCompDependsForTsKey(DbKey timeSeriesKey)
throws DbIoException
{
if (db.isHdb())
return;
// Remove the CP_COMP_DEPENDS records & re-add.
String q = "DELETE FROM CP_COMP_DEPENDS WHERE " + cpCompDepends_col1 + " = "
+ timeSeriesKey;
doModify(q);
doModify("delete from cp_comp_depends_scratchpad where " + cpCompDepends_col1 + " = "
+ timeSeriesKey);
}
@Override
public void deleteCompDependsForCompId(DbKey compId)
throws DbIoException
{
if (db.isHdb())
return;
// Remove the CP_COMP_DEPENDS records & re-add.
String q = "DELETE FROM CP_COMP_DEPENDS WHERE COMPUTATION_ID = " + compId;
doModify(q);
doModify("delete from cp_comp_depends_scratchpad where COMPUTATION_ID = " + compId);
}
public void close()
{
super.close();
algorithmDAO.close();
tsGroupDAO.close();
}
@Override
public ArrayList<TimeSeriesIdentifier> getTriggersFor(DbKey compID)
throws DbIoException
{
String q = "SELECT " + cpCompDepends_col1 + " FROM CP_COMP_DEPENDS "
+ "WHERE COMPUTATION_ID = " + compID;
ResultSet rs = doQuery(q);
TimeSeriesDAI timeSeriesDAO = db.makeTimeSeriesDAO();
ArrayList<TimeSeriesIdentifier> ret = new ArrayList<TimeSeriesIdentifier>();
try
{
while(rs.next())
{
DbKey tsKey = DbKey.createDbKey(rs, 1);
try
{
ret.add(timeSeriesDAO.getTimeSeriesIdentifier(tsKey));
}
catch (NoSuchObjectException e)
{
warning("Bogus Time Series Key " + tsKey + " in CP_COMP_DEPENDS "
+ "for computation " + compID);
}
}
}
catch (SQLException ex)
{
throw new DbIoException("Error executing '" + q + "': " + ex);
}
finally
{
timeSeriesDAO.close();
}
return ret;
}
@Override
public ArrayList<DbKey> getCompIdsFor(Collection<TimeSeriesIdentifier> tsids, DbKey appId)
throws DbIoException
{
ArrayList<DbKey> ret = new ArrayList<DbKey>();
StringBuilder inClause = new StringBuilder(" in (");
int n = 0;
for (TimeSeriesIdentifier tsid : tsids)
{
if (n++ > 0)
inClause.append(", ");
inClause.append(tsid.getKey().toString());
}
inClause.append(")");
if (n == 0)
return ret;
String q = "select a.computation_id from cp_comp_depends a, cp_computation b"
+ " where a.computation_id = b.computation_id"
+ " and a." + cpCompDepends_col1 + inClause.toString();
if (!DbKey.isNull(appId))
q = q + " and b.loading_application_id = " + appId;
try
{
ResultSet rs = doQuery(q);
while (rs.next())
ret.add(DbKey.createDbKey(rs, 1));
}
catch(Exception ex)
{
warning("getCompIdsFor() error in query '" + q + "': " + ex);
}
return ret;
}
}
|
package com.abaya.picacho.biz.account.model;
import com.abaya.picacho.common.model.CommonState;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SystemUser {
private Long id;
private String name;
private String username;
private String department;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDateTime createDateTime;
private CommonState state;
}
|
/*
* SoapUI, Copyright (C) 2004-2016 SmartBear Software
*
* Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequen
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package com.eviware.soapui.support.jnlp;
import java.io.File;
public class WebstartUtilCore extends WebstartUtil {
public static void init() {
if (isWebStart()) {
try {
// if( System.getProperty( "deployment.user.tmp" ) != null
// && System.getProperty( "deployment.user.tmp" ).length() > 0 )
// {
// System.setProperty( "GRE_HOME", System.getProperty(
// "deployment.user.tmp" ) );
// }
// wsi-test-tools
System.setProperty("wsi.dir",
createWebStartDirectory("wsi-test-tools", System.getProperty("wsitesttools.jar.url"))
+ File.separator + "wsi-test-tools");
System.out.println(System.getProperty("wsi.dir"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
package com.nitya.accounter.web.client.ui.grids;
import com.nitya.accounter.web.client.AccounterAsyncCallback;
import com.nitya.accounter.web.client.Global;
import com.nitya.accounter.web.client.core.*;
import com.nitya.accounter.web.client.core.reports.TransactionHistory;
import com.nitya.accounter.web.client.exception.AccounterException;
import com.nitya.accounter.web.client.ui.Accounter;
import com.nitya.accounter.web.client.ui.DataUtils;
import com.nitya.accounter.web.client.ui.UIUtils;
import com.nitya.accounter.web.client.ui.Accounter.AccounterType;
import com.nitya.accounter.web.client.ui.core.ErrorDialogHandler;
import com.nitya.accounter.web.client.ui.reports.ReportsRPC;
public abstract class ConsultantTransactionsHistoryGrid extends
BaseListGrid<TransactionHistory> {
protected ConsultantsDetailsList selectedCustomer;
public ConsultantTransactionsHistoryGrid() {
super(false);
}
boolean isDeleted;
@Override
protected int[] setColTypes() {
return new int[] { ListGrid.COLUMN_TYPE_TEXT,
ListGrid.COLUMN_TYPE_LINK, ListGrid.COLUMN_TYPE_TEXT,
ListGrid.COLUMN_TYPE_TEXT, ListGrid.COLUMN_TYPE_TEXT,
ListGrid.COLUMN_TYPE_TEXT, ListGrid.COLUMN_TYPE_IMAGE, };
}
@Override
protected Object getColumnValue(TransactionHistory transactionHistory,
int col) {
switch (col) {
case 0:
return UIUtils.getDateByCompanyType(transactionHistory.getDate());
case 1:
return transactionHistory.getName();
case 2:
return getTransactionType(transactionHistory.getType());
case 3:
return transactionHistory.getMemo();
case 4:
if (transactionHistory.getDueDate() != null)
return UIUtils.getDateByCompanyType(transactionHistory
.getDueDate());
else
return "";
case 5:
// return null;
// return DataUtils.getAmountAsStringInCurrency(transactionHistory
// .getAmount(),
// getCompany().getCurrency(selectedCustomer.getCurrency())
// .getSymbol());
if(transactionHistory.getInvoicedAmount() != 0)
return transactionHistory.getInvoicedAmount();
else return transactionHistory.getAmount();
case 6:
if (!transactionHistory.getIsVoid())
return Accounter.getFinanceImages().notvoid();
else
return Accounter.getFinanceImages().voided();
default:
break;
}
return null;
}
@Override
protected String[] getColumns() {
return new String[] { messages.date(), messages.customer(), messages.type(),
"Comments", messages.dueDate(), messages.amount(),
messages.status() };
}
@Override
protected String[] setHeaderStyle() {
return new String[] { "date", "customerName", "type", "memo", "dueDate",
"amount", "status" };
}
@Override
protected String[] setRowElementsStyle() {
return new String[] { "dateValue","customerNameValue", "typeValue","memoValue",
"dueDateValue", "amountValue", "statusValue" };
}
@Override
public void onDoubleClick(TransactionHistory obj) {
if (isCanOpenTransactionView(obj.getSavestaus(), obj.getType())) {
ReportsRPC.openTransactionView(obj.getType(),
obj.getTransactionId());
}
}
@Override
protected int getCellWidth(int index) {
switch (index) {
case 0:
return 90;
case 1:
return 105;
case 2:
return 60;
case 3:
return 185;
case 4:
return 90;
case 5:
return 80;
default:
return 50;
}
}
@Override
protected void executeDelete(TransactionHistory object) {
// NOTHING TO DO.
}
@Override
protected void onClick(TransactionHistory obj, int row, int col) {
if (!isCanOpenTransactionView(obj.getSavestaus(), obj.getType())) {
return;
}
if (col == 6 && !obj.getIsVoid()) {
if (obj.getStatus() == ClientTransaction.STATUS_DRAFT) {
Accounter.showError(messages.youCannotVoidDraftedTransaction());
} else {
showWarningDialog(obj, col, row);
}
}
}
private void showWarningDialog(final TransactionHistory obj, final int col,
final int row) {
String msg = null;
if (obj.getStatus() != ClientTransaction.STATUS_DRAFT
&& !obj.getIsVoid() && col == 6) {
msg = messages.doyouwanttoVoidtheTransaction();
} else if (obj.getStatus() == ClientTransaction.STATUS_DRAFT
&& col == 9) {
Accounter.showError(messages.youCannotVoidDraftedTransaction());
return;
}
Accounter.showWarning(msg, AccounterType.WARNING,
new ErrorDialogHandler() {
@Override
public boolean onCancelClick() {
return false;
}
@Override
public boolean onNoClick() {
return true;
}
@Override
public boolean onYesClick() {
if (col == 6) {
voidTransaction(
UIUtils.getAccounterCoreType(obj.getType()),
obj.getTransactionId());
}
return true;
}
});
}
protected void deleteTransaction(final TransactionHistory obj) {
AccounterAsyncCallback<Boolean> callback = new AccounterAsyncCallback<Boolean>() {
@Override
public void onException(AccounterException caught) {
}
@Override
public void onResultSuccess(Boolean result) {
if (result) {
if (viewType.equalsIgnoreCase(messages.open())
|| viewType.equalsIgnoreCase(messages.overDue()))
deleteRecord(obj);
obj.setStatus(ClientTransaction.STATUS_DELETED);
isDeleted = true;
obj.setIsVoid(true);
updateData(obj);
}
}
};
AccounterCoreType type = UIUtils.getAccounterCoreType(obj.getType());
rpcDoSerivce.deleteTransaction(type, obj.getTransactionId(), callback);
}
private String getTransactionType(int type) {
if (type == 8) {
return messages.invoices();
} else if (type == 1) {
return messages.cashSales();
} else if (type == 12) {
return messages.receivedPayments();
} else if (type == 4) {
return messages.CustomerCreditNotes();
} else if (type == 7) {
return messages.quotes() +"/" +messages.credits() +"/"+messages.Charges();
} else if (type == 5) {
return messages.customerRefunds(Global.get().Customer());
} else if (type == 15) {
return messages.cheques();
} else if (type == 38) {
return messages.salesOrders();
}
return "transaction";
}
public AccounterCoreType getAccounterCoreType(TransactionHistory obj) {
return UIUtils.getAccounterCoreType(obj.getType());
}
public void setSelectedCustomer(ConsultantsDetailsList selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
public ConsultantsDetailsList getSelectedCustomer() {
return selectedCustomer;
}
@Override
protected int sort(TransactionHistory obj1, TransactionHistory obj2,
int index) {
switch (index) {
case 0:
ClientFinanceDate date = obj1.getDate();
ClientFinanceDate date2 = obj2.getDate();
return date.compareTo(date2);
case 1:
String name2 = obj1.getName().toLowerCase();
String name = obj2.getName().toLowerCase();
return name2.compareTo(name);
case 2:
Integer num1 = Integer.parseInt(obj1.getNumber());
Integer num2 = Integer.parseInt(obj2.getNumber());
return num1.compareTo(num2);
case 3:
String memo = obj1.getMemo().toLowerCase();
String memo2 = obj2.getMemo().toLowerCase();
return memo.compareTo(memo2);
case 4:
ClientFinanceDate dueDate = obj1.getDueDate();
ClientFinanceDate dueDate2 = obj2.getDueDate();
return dueDate.compareTo(dueDate2);
case 5:
Double amount = obj1.getAmount();
Double amount2 = obj2.getAmount();
return amount.compareTo(amount2);
default:
break;
}
return 0;
}
@Override
public void saveSuccess(IAccounterCore core) {
initListData();
}
public abstract void initListData();
}
|
package radlab.rain.workload.cassandra;
import java.util.List;
import java.util.logging.Logger;
import radlab.rain.Generator;
import radlab.rain.IScoreboard;
import radlab.rain.LoadProfile;
import radlab.rain.Operation;
public abstract class CassandraOperation extends Operation
{
protected String _columnFamilyName = "";
protected String _key = "";
protected byte[] _value = null;
protected int _maxScanRows = 1;
protected CassandraTransport _cassandraClient = null;
public CassandraOperation(boolean interactive, IScoreboard scoreboard)
{
super(interactive, scoreboard);
}
@Override
public void prepare(Generator generator)
{
this._generator = generator;
CassandraGenerator cassandraGenerator = (CassandraGenerator) generator;
this._cassandraClient = cassandraGenerator.getCassandraTransport();
LoadProfile currentLoadProfile = generator.getLatestLoadProfile();
if( currentLoadProfile != null )
this.setGeneratedDuringProfile( currentLoadProfile );
this._columnFamilyName = cassandraGenerator._columnFamilyName;
}
@Override
public void cleanup()
{
this._columnFamilyName = "";
this._key = "";
this._value = null;
this._maxScanRows = 1;
}
public byte[] doGet( String key ) throws Exception
{
return this._cassandraClient.get( this._columnFamilyName, key );
}
public List<byte[]> doScan( String startKey, int maxRows ) throws Exception
{
return this._cassandraClient.scan( startKey, this._columnFamilyName, maxRows );
}
public void doPut( String key, byte[] value ) throws Exception
{
this._operationRequest = key;
this._cassandraClient.put( this._columnFamilyName, key, value );
}
public void doDelete( String key ) throws Exception
{
this._cassandraClient.delete( this._columnFamilyName, key );
}
public CassandraGenerator getGenerator()
{
return (CassandraGenerator) this._generator;
}
public Logger getLogger()
{
return this.getGenerator().getLogger();
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.client.ClusterConnection;
import org.apache.hadoop.hbase.client.HConnectionTestingUtility;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanResponse;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.MiscTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.google.protobuf.RpcController;
import com.google.protobuf.ServiceException;
/**
* Test MetaTableAccessor but without spinning up a cluster.
* We mock regionserver back and forth (we do spin up a zk cluster).
*/
@Category({MiscTests.class, MediumTests.class})
public class TestMetaTableAccessorNoCluster {
private static final Log LOG = LogFactory.getLog(TestMetaTableAccessorNoCluster.class);
private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
private static final Abortable ABORTABLE = new Abortable() {
boolean aborted = false;
@Override
public void abort(String why, Throwable e) {
LOG.info(why, e);
this.aborted = true;
throw new RuntimeException(e);
}
@Override
public boolean isAborted() {
return this.aborted;
}
};
@Before
public void before() throws Exception {
UTIL.startMiniZKCluster();
}
@After
public void after() throws IOException {
UTIL.shutdownMiniZKCluster();
}
@Test
public void testGetHRegionInfo() throws IOException {
assertNull(HRegionInfo.getHRegionInfo(new Result()));
List<Cell> kvs = new ArrayList<Cell>();
Result r = Result.create(kvs);
assertNull(HRegionInfo.getHRegionInfo(r));
byte [] f = HConstants.CATALOG_FAMILY;
// Make a key value that doesn't have the expected qualifier.
kvs.add(new KeyValue(HConstants.EMPTY_BYTE_ARRAY, f,
HConstants.SERVER_QUALIFIER, f));
r = Result.create(kvs);
assertNull(HRegionInfo.getHRegionInfo(r));
// Make a key that does not have a regioninfo value.
kvs.add(new KeyValue(HConstants.EMPTY_BYTE_ARRAY, f,
HConstants.REGIONINFO_QUALIFIER, f));
HRegionInfo hri = HRegionInfo.getHRegionInfo(Result.create(kvs));
assertTrue(hri == null);
// OK, give it what it expects
kvs.clear();
kvs.add(new KeyValue(HConstants.EMPTY_BYTE_ARRAY, f,
HConstants.REGIONINFO_QUALIFIER,
HRegionInfo.FIRST_META_REGIONINFO.toByteArray()));
hri = HRegionInfo.getHRegionInfo(Result.create(kvs));
assertNotNull(hri);
assertTrue(hri.equals(HRegionInfo.FIRST_META_REGIONINFO));
}
/**
* Test that MetaTableAccessor will ride over server throwing
* "Server not running" IOEs.
* @see @link {https://issues.apache.org/jira/browse/HBASE-3446}
* @throws IOException
* @throws InterruptedException
*/
@Test
public void testRideOverServerNotRunning()
throws IOException, InterruptedException, ServiceException {
// Need a zk watcher.
ZooKeeperWatcher zkw = new ZooKeeperWatcher(UTIL.getConfiguration(),
this.getClass().getSimpleName(), ABORTABLE, true);
// This is a servername we use in a few places below.
ServerName sn = ServerName.valueOf("example.com", 1234, System.currentTimeMillis());
ClusterConnection connection = null;
try {
// Mock an ClientProtocol. Our mock implementation will fail a few
// times when we go to open a scanner.
final ClientProtos.ClientService.BlockingInterface implementation =
Mockito.mock(ClientProtos.ClientService.BlockingInterface.class);
// When scan called throw IOE 'Server not running' a few times
// before we return a scanner id. Whats WEIRD is that these
// exceptions do not show in the log because they are caught and only
// printed if we FAIL. We eventually succeed after retry so these don't
// show. We will know if they happened or not because we will ask
// mockito at the end of this test to verify that scan was indeed
// called the wanted number of times.
List<Cell> kvs = new ArrayList<Cell>();
final byte [] rowToVerify = Bytes.toBytes("rowToVerify");
kvs.add(new KeyValue(rowToVerify,
HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER,
HRegionInfo.FIRST_META_REGIONINFO.toByteArray()));
kvs.add(new KeyValue(rowToVerify,
HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER,
Bytes.toBytes(sn.getHostAndPort())));
kvs.add(new KeyValue(rowToVerify,
HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER,
Bytes.toBytes(sn.getStartcode())));
final List<CellScannable> cellScannables = new ArrayList<CellScannable>(1);
cellScannables.add(Result.create(kvs));
final ScanResponse.Builder builder = ScanResponse.newBuilder();
for (CellScannable result : cellScannables) {
builder.addCellsPerResult(((Result)result).size());
}
Mockito.when(implementation.scan((RpcController) Mockito.any(), (ScanRequest) Mockito.any()))
.thenThrow(new ServiceException("Server not running (1 of 3)"))
.thenThrow(new ServiceException("Server not running (2 of 3)"))
.thenThrow(new ServiceException("Server not running (3 of 3)"))
.thenReturn(ScanResponse.newBuilder().setScannerId(1234567890L).build())
.thenAnswer(new Answer<ScanResponse>() {
public ScanResponse answer(InvocationOnMock invocation) throws Throwable {
((PayloadCarryingRpcController) invocation.getArguments()[0]).setCellScanner(CellUtil
.createCellScanner(cellScannables));
return builder.build();
}
}).thenReturn(ScanResponse.newBuilder().setMoreResults(false).build());
// Associate a spied-upon HConnection with UTIL.getConfiguration. Need
// to shove this in here first so it gets picked up all over; e.g. by
// HTable.
connection = HConnectionTestingUtility.getSpiedConnection(UTIL.getConfiguration());
// Fix the location lookup so it 'works' though no network. First
// make an 'any location' object.
final HRegionLocation anyLocation =
new HRegionLocation(HRegionInfo.FIRST_META_REGIONINFO, sn);
final RegionLocations rl = new RegionLocations(anyLocation);
// Return the RegionLocations object when locateRegion
// The ugly format below comes of 'Important gotcha on spying real objects!' from
// http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html
ClusterConnection cConnection =
HConnectionTestingUtility.getSpiedClusterConnection(UTIL.getConfiguration());
Mockito.doReturn(rl).when
(cConnection).locateRegion((TableName)Mockito.any(), (byte[])Mockito.any(),
Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyInt());
// Now shove our HRI implementation into the spied-upon connection.
Mockito.doReturn(implementation).
when(connection).getClient(Mockito.any(ServerName.class));
// Scan meta for user tables and verify we got back expected answer.
NavigableMap<HRegionInfo, Result> hris =
MetaTableAccessor.getServerUserRegions(connection, sn);
assertEquals(1, hris.size());
assertTrue(hris.firstEntry().getKey().equals(HRegionInfo.FIRST_META_REGIONINFO));
assertTrue(Bytes.equals(rowToVerify, hris.firstEntry().getValue().getRow()));
// Finally verify that scan was called four times -- three times
// with exception and then on 4th, 5th and 6th attempt we succeed
Mockito.verify(implementation, Mockito.times(6)).
scan((RpcController)Mockito.any(), (ScanRequest)Mockito.any());
} finally {
if (connection != null && !connection.isClosed()) connection.close();
zkw.close();
}
}
}
|
package com.xy.asyc.test.temp;
public enum JobPriority {
MIN(1),NORM(5),MAX(9);
private int value;
private JobPriority(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
|
/******************************************************************************
* Copyright (c) 2011 GitHub Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kevin Sawicki (GitHub Inc.) - initial API and implementation
*****************************************************************************/
package com.dipien.github;
import java.io.Serializable;
/**
* Tag model class
*/
public class Tag implements Serializable {
/** serialVersionUID */
private static final long serialVersionUID = 8505182933582492676L;
private CommitUser tagger;
private String message;
private String sha;
private String tag;
private String url;
private TypedResource object;
/**
* @return tagger
*/
public CommitUser getTagger() {
return tagger;
}
/**
* @param tagger
* @return this tag
*/
public Tag setTagger(CommitUser tagger) {
this.tagger = tagger;
return this;
}
/**
* @return message
*/
public String getMessage() {
return message;
}
/**
* @param message
* @return this tag
*/
public Tag setMessage(String message) {
this.message = message;
return this;
}
/**
* @return sha
*/
public String getSha() {
return sha;
}
/**
* @param sha
* @return this tag
*/
public Tag setSha(String sha) {
this.sha = sha;
return this;
}
/**
* @return tag
*/
public String getTag() {
return tag;
}
/**
* @param tag
* @return this tag
*/
public Tag setTag(String tag) {
this.tag = tag;
return this;
}
/**
* @return url
*/
public String getUrl() {
return url;
}
/**
* @param url
* @return this tag
*/
public Tag setUrl(String url) {
this.url = url;
return this;
}
/**
* @return object
*/
public TypedResource getObject() {
return object;
}
/**
* @param object
* @return this tag
*/
public Tag setObject(TypedResource object) {
this.object = object;
return this;
}
}
|
package fr.jmini.openapi.openapitools.api;
import fr.jmini.openapi.openapitools.api.*;
import fr.jmini.openapi.openapitools.model.*;
import java.util.List;
import fr.jmini.openapi.openapitools.model.User;
import java.util.List;
import fr.jmini.openapi.openapitools.api.NotFoundException;
import java.io.InputStream;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
public interface UserApiService {
Response createUser(User user,SecurityContext securityContext)
throws NotFoundException;
Response createUsersWithArrayInput(List<User> user,SecurityContext securityContext)
throws NotFoundException;
Response createUsersWithListInput(List<User> user,SecurityContext securityContext)
throws NotFoundException;
Response deleteUser(String username,SecurityContext securityContext)
throws NotFoundException;
Response getUserByName(String username,SecurityContext securityContext)
throws NotFoundException;
Response loginUser(String username,String password,SecurityContext securityContext)
throws NotFoundException;
Response logoutUser(SecurityContext securityContext)
throws NotFoundException;
Response updateUser(String username,User user,SecurityContext securityContext)
throws NotFoundException;
}
|
// Copyright 2014 The Bazel Authors. 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.google.devtools.build.lib.analysis;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.packages.BuildType.NODEP_LABEL;
import static com.google.devtools.build.lib.packages.Type.STRING;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.BuildOptionsView;
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
import com.google.devtools.build.lib.analysis.config.transitions.SplitTransition;
import com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.analysis.util.MockRule;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.packages.Attribute.LabelLateBoundDefault;
import com.google.devtools.build.lib.packages.AttributeTransitionData;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests that check that dependency cycles are reported correctly.
*/
@RunWith(JUnit4.class)
public class CircularDependencyTest extends BuildViewTestCase {
@Test
public void testOneRuleCycle() throws Exception {
checkError(
"cycle",
"foo.g",
//error message
selfEdgeMsg("//cycle:foo.g"),
// Rule
"genrule(name = 'foo.g',",
" outs = ['Foo.java'],",
" srcs = ['foo.g'],",
" cmd = 'cat $(SRCS) > $<' )");
}
@Test
public void testDirectPackageGroupCycle() throws Exception {
checkError(
"cycle",
"melon",
selfEdgeMsg("//cycle:moebius"),
"package_group(name='moebius', packages=[], includes=['//cycle:moebius'])",
"sh_library(name='melon', visibility=[':moebius'])");
}
@Test
public void testThreeLongPackageGroupCycle() throws Exception {
String expectedEvent =
"cycle in dependency graph:\n"
+ " //cycle:superman\n"
+ ".-> //cycle:rock\n"
+ "| //cycle:paper\n"
+ "| //cycle:scissors\n"
+ "`-- //cycle:rock";
checkError(
"cycle",
"superman",
expectedEvent,
"# dummy line",
"package_group(name='paper', includes=['//cycle:scissors'])",
"package_group(name='rock', includes=['//cycle:paper'])",
"package_group(name='scissors', includes=['//cycle:rock'])",
"sh_library(name='superman', visibility=[':rock'])");
Event foundEvent = null;
for (Event event : eventCollector) {
if (event.getMessage().contains(expectedEvent)) {
foundEvent = event;
break;
}
}
assertThat(foundEvent).isNotNull();
assertThat(foundEvent.getLocation().toString()).isEqualTo("/workspace/cycle/BUILD:3:14");
}
@Test
public void cycleThroughVisibility() throws Exception {
String expectedEvent =
"in filegroup rule //cycle:v: cycle in dependency graph:\n"
+ " //cycle:v\n"
+ " //cycle:t\n"
+ ".-> //cycle:v\n"
+ "| //cycle:t\n"
+ "`-- //cycle:v\n"
+ "The cycle is caused by a visibility edge from //cycle:t to the non-package_group"
+ " target //cycle:v. Note that visibility labels are supposed to be package_group"
+ " targets, which prevents cycles of this form.";
checkError(
"cycle",
"v",
expectedEvent,
"filegroup(name='t', visibility=[':v'])",
"filegroup(name='v', srcs=[':t'])");
}
/**
* Test to detect implicit input/output file overlap in rules.
*/
@Test
public void testOneRuleImplicitCycleJava() throws Exception {
Package pkg =
createScratchPackageForImplicitCycle(
"cycle", "java_library(name='jcyc',", " srcs = ['libjcyc.jar', 'foo.java'])");
assertThrows(NoSuchTargetException.class, () -> pkg.getTarget("jcyc"));
assertThat(pkg.containsErrors()).isTrue();
assertContainsEvent("rule 'jcyc' has file 'libjcyc.jar' as both an" + " input and an output");
}
/**
* Test not to detect implicit input/output file overlap in rules,
* when coming from a different package.
*/
@Test
public void testInputOutputConflictDifferentPackage() throws Exception {
Package pkg =
createScratchPackageForImplicitCycle(
"googledata/xxx",
"genrule(name='geo',",
" srcs = ['//googledata/geo:geo_info.txt'],",
" outs = ['geoinfo.txt'],",
" cmd = '$(SRCS) > $@')");
assertThat(pkg.containsErrors()).isFalse();
}
@Test
public void testTwoRuleCycle() throws Exception {
scratchRule("b", "rule2", "cc_library(name='rule2',", " deps=['//a:rule1'])");
checkError(
"a",
"rule1",
"in cc_library rule //a:rule1: cycle in dependency graph:\n"
+ ".-> //a:rule1\n"
+ "| //b:rule2\n"
+ "`-- //a:rule1",
"cc_library(name='rule1',",
" deps=['//b:rule2'])");
}
@Test
public void testTwoRuleCycle2() throws Exception {
reporter.removeHandler(failFastHandler); // expect errors
scratch.file(
"x/BUILD", "java_library(name='x', deps=['y'])", "java_library(name='y', deps=['x'])");
getConfiguredTarget("//x");
assertContainsEvent("in java_library rule //x:x: cycle in dependency graph");
}
@Test
public void testIndirectOneRuleCycle() throws Exception {
scratchRule(
"cycle",
"foo.h",
"genrule(name = 'foo.h',",
" outs = ['bar.h'],",
" srcs = ['foo.h'],",
" cmd = 'cp $< $@')");
checkError(
"main",
"mygenrule",
//error message
selfEdgeMsg("//cycle:foo.h"),
// Rule
"genrule(name='mygenrule',",
" outs = ['baz.h'],",
" srcs = ['//cycle:foo.h'],",
" cmd = 'cp $< $@')");
}
private String selfEdgeMsg(String label) {
return label + " [self-edge]";
}
// Regression test for: "IllegalStateException in
// AbstractConfiguredTarget.initialize()".
// Failure to mark all cycle-forming nodes when there are *two* cycles led to
// an attempt to initialise a node we'd already visited.
@Test
public void testTwoCycles() throws Exception {
reporter.removeHandler(failFastHandler); // expect errors
scratch.file(
"x/BUILD",
"genrule(name='b', srcs=['c'], tools=['c'], outs=['b.out'], cmd=':')",
"genrule(name='c', srcs=['b.out'], outs=[], cmd=':')");
getConfiguredTarget("//x:b"); // doesn't crash!
assertContainsEvent("cycle in dependency graph");
}
@Test
public void testAspectCycle() throws Exception {
reporter.removeHandler(failFastHandler);
scratch.file("x/BUILD",
"load('//x:x.bzl', 'aspected', 'plain')",
// Using data= makes the dependency graph clearer because then the aspect does not propagate
// from aspectdep through a to b (and c)
"plain(name = 'a', noaspect_deps = [':b'])",
"aspected(name = 'b', aspect_deps = ['c'])",
"plain(name = 'c')",
"plain(name = 'aspectdep', aspect_deps = ['a'])");
scratch.file(
"x/x.bzl",
"def _impl(ctx):",
" return []",
"",
"rule_aspect = aspect(",
" implementation = _impl,",
" attr_aspects = ['aspect_deps'],",
" attrs = { '_implicit': attr.label(default = Label('//x:aspectdep')) })",
"",
"plain = rule(",
" implementation = _impl,",
" attrs = { 'aspect_deps': attr.label_list(), 'noaspect_deps': attr.label_list() })",
"",
"aspected = rule(",
" implementation = _impl,",
" attrs = { 'aspect_deps': attr.label_list(aspects = [rule_aspect]) })");
getConfiguredTarget("//x:a");
assertContainsEvent("cycle in dependency graph");
assertContainsEvent("//x:c with aspect //x:x.bzl%rule_aspect");
}
/** A late bound dependency which depends on the 'dep' label if the 'define' is in --defines. */
// TODO(b/65746853): provide a way to do this without passing the entire configuration
private static final LabelLateBoundDefault<BuildConfiguration> LATE_BOUND_DEP =
LabelLateBoundDefault.fromTargetConfiguration(
BuildConfiguration.class,
null,
(rule, attributes, config) ->
config.getCommandLineBuildVariables().containsKey(attributes.get("define", STRING))
? attributes.get("dep", NODEP_LABEL)
: null);
/** A rule which always depends on the given label. */
private static final MockRule NORMAL_DEPENDER =
() -> MockRule.define("normal_dep", attr("dep", LABEL).allowedFileTypes());
/** A rule which depends on a given label only if the given define is set. */
private static final MockRule LATE_BOUND_DEPENDER =
() ->
MockRule.define(
"late_bound_dep",
attr("define", STRING).mandatory(),
attr("dep", NODEP_LABEL).mandatory(),
attr(":late_bound_dep", LABEL).value(LATE_BOUND_DEP));
/** A rule which removes a define from the configuration of its dependency. */
private static final MockRule DEFINE_CLEARER =
() ->
MockRule.define(
"define_clearer",
attr("define", STRING).mandatory(),
attr("dep", LABEL)
.mandatory()
.allowedFileTypes()
.cfg(
new TransitionFactory<AttributeTransitionData>() {
@Override
public SplitTransition create(AttributeTransitionData data) {
return new SplitTransition() {
@Override
public ImmutableSet<Class<? extends FragmentOptions>>
requiresOptionFragments() {
return ImmutableSet.of(CoreOptions.class);
}
@Override
public Map<String, BuildOptions> split(
BuildOptionsView options, EventHandler eventHandler) {
String define = data.attributes().get("define", STRING);
BuildOptionsView newOptions = options.clone();
CoreOptions optionsFragment = newOptions.get(CoreOptions.class);
optionsFragment.commandLineBuildVariables =
optionsFragment.commandLineBuildVariables.stream()
.filter((pair) -> !pair.getKey().equals(define))
.collect(toImmutableList());
return ImmutableMap.of("define_cleaner", newOptions.underlying());
}
};
}
@Override
public boolean isSplit() {
return true;
}
}));
@Override
protected ConfiguredRuleClassProvider createRuleClassProvider() {
ConfiguredRuleClassProvider.Builder builder =
new ConfiguredRuleClassProvider.Builder()
.addRuleDefinition(NORMAL_DEPENDER)
.addRuleDefinition(LATE_BOUND_DEPENDER)
.addRuleDefinition(DEFINE_CLEARER);
TestRuleClassProvider.addStandardRules(builder);
return builder.build();
}
@Test
public void testLateBoundTargetCycleNotConfiguredTargetCycle() throws Exception {
// Target graph: //a -> //b -?> //c -> //a (loop)
// Configured target graph: //a -> //b -> //c -> //a (2) -> //b (2)
scratch.file("a/BUILD", "normal_dep(name = 'a', dep = '//b')");
scratch.file("b/BUILD", "late_bound_dep(name = 'b', dep = '//c', define = 'CYCLE_ON')");
scratch.file("c/BUILD", "define_clearer(name = 'c', dep = '//a', define = 'CYCLE_ON')");
useConfiguration("--define=CYCLE_ON=yes");
getConfiguredTarget("//a");
assertNoEvents();
}
@Test
public void testSelectTargetCycleNotConfiguredTargetCycle() throws Exception {
// Target graph: //a -> //b -?> //c -> //a (loop)
// Configured target graph: //a -> //b -> //c -> //a (2) -> //b (2) -> //b:stop (2)
scratch.file("a/BUILD", "normal_dep(name = 'a', dep = '//b')");
scratch.file("b/BUILD",
"config_setting(name = 'cycle', define_values = {'CYCLE_ON': 'yes'})",
"normal_dep(name = 'stop')",
"normal_dep(name = 'b', dep = select({':cycle': '//c', '//conditions:default': ':stop'}))");
scratch.file("c/BUILD", "define_clearer(name = 'c', dep = '//a', define = 'CYCLE_ON')");
useConfiguration("--define=CYCLE_ON=yes");
getConfiguredTarget("//a");
assertNoEvents();
}
}
|
copyright comp osent composent rights reserved program accompanying materials terms eclipse license accompanies distribution http eclipse org legal epl html contributors comp osent composent initial api implementation org eclipse ecf tests connect java util array list arraylist java util hash map hashmap java util list java util map org eclipse ecf core container factory containerfactory org eclipse ecf core i container icontainer org eclipse ecf core i container listener icontainerlistener org eclipse ecf core events i container connected event icontainerconnectedevent org eclipse ecf core events i container connecting event icontainerconnectingevent org eclipse ecf core events i container disconnected event icontainerdisconnectedevent org eclipse ecf core events i container disconnecting event icontainerdisconnectingevent org eclipse ecf core events i container event icontainerevent org eclipse ecf core security i connect context iconnectcontext org eclipse ecf tests ssl container abstract test case sslcontainerabstracttestcase ssl client container connect test sslclientcontainerconnecttest ssl container abstract test case sslcontainerabstracttestcase list server connect events serverconnectevents array list arraylist list server disconnect events serverdisconnectevents array list arraylist list client connecting events clientconnectingevents array list arraylist list client connected events clientconnectedevents array list arraylist list client disconnecting events clientdisconnectingevents array list arraylist list client disconnected events clientdisconnectedevents array list arraylist javadoc org eclipse ecf tests connect container connect test case containerconnecttestcase create server and clients createserverandclients create server and clients createserverandclients exception client count clientcount create server and clients createserverandclients get server getserver add listener addlistener i container listener icontainerlistener handle event handleevent i container event icontainerevent event event i container connected event icontainerconnectedevent server connect events serverconnectevents add event event i container disconnected event icontainerdisconnectedevent server disconnect events serverdisconnectevents add event i container icontainer create server createserver exception map props hash map hashmap props serverid props need client auth needclientauth container factory containerfactory get default getdefault create container createcontainer get server container name getservercontainername props javadoc junit framework test case testcase set up setup set up setup exception set up setup create server and clients createserverandclients clear client events clearclientevents client connecting events clientconnectingevents clear client connected events clientconnectedevents clear client disconnecting events clientdisconnectingevents clear client disconnected events clientdisconnectedevents clear javadoc junit framework test case testcase tear down teardown tear down teardown exception clean up server and clients cleanupserverandclients tear down teardown server connect events serverconnectevents clear server disconnect events serverdisconnectevents clear clear client events clearclientevents test connect clients testconnectclients exception connect clients connectclients assert true asserttrue server connect events serverconnectevents size get client count getclientcount javadoc org eclipse ecf tests container abstract test case containerabstracttestcase get connect context getconnectcontext i connect context iconnectcontext get connect context getconnectcontext client test clients disconnect testclientsdisconnect exception connect clients connectclients assert true asserttrue server connect events serverconnectevents size get client count getclientcount disconnect clients disconnectclients assert true asserttrue server disconnect events serverdisconnectevents size get client count getclientcount test get connected d testgetconnectedid exception i container icontainer client get clients getclients assert null assertnull client get connected d getconnectedid client connect create server d createserverid assert not null assertnotnull client get connected d getconnectedid client disconnect assert null assertnull client get connected d getconnectedid i container listener icontainerlistener create listener createlistener i container listener icontainerlistener handle event handleevent i container event icontainerevent event event i container connecting event icontainerconnectingevent client connecting events clientconnectingevents add event event i container connected event icontainerconnectedevent client connected events clientconnectedevents add event event i container disconnecting event icontainerdisconnectingevent client disconnecting events clientdisconnectingevents add event event i container disconnected event icontainerdisconnectedevent client disconnected events clientdisconnectedevents add event test client listener testclientlistener exception i container icontainer client get clients getclients client add listener addlistener create listener createlistener assert true asserttrue client connecting events clientconnectingevents size assert true asserttrue client connected events clientconnectedevents size client connect create server d createserverid assert true asserttrue client connecting events clientconnectingevents size assert true asserttrue client connected events clientconnectedevents size assert true asserttrue client disconnecting events clientdisconnectingevents size assert true asserttrue client disconnected events clientdisconnectedevents size sleep client disconnect assert true asserttrue client disconnecting events clientdisconnectingevents size assert true asserttrue client disconnected events clientdisconnectedevents size test listener connecting testlistenerconnecting exception i container icontainer client get clients getclients client add listener addlistener create listener createlistener client connect create server d createserverid object client connecting events clientconnectingevents assert true asserttrue i container connecting event icontainerconnectingevent i container connecting event icontainerconnectingevent cco i container connecting event icontainerconnectingevent assert true asserttrue cco get local container d getlocalcontainerid equals client getid assert true asserttrue cco get target d gettargetid equals create server d createserverid assert true asserttrue cco get data getdata test listener connected testlistenerconnected exception i container icontainer client get clients getclients client add listener addlistener create listener createlistener client connect create server d createserverid object client connected events clientconnectedevents assert true asserttrue i container connected event icontainerconnectedevent i container connected event icontainerconnectedevent cco i container connected event icontainerconnectedevent assert true asserttrue cco get local container d getlocalcontainerid equals client getid assert true asserttrue cco get target d gettargetid equals create server d createserverid test listener disconnected testlistenerdisconnected exception i container icontainer client get clients getclients client add listener addlistener create listener createlistener client connect create server d createserverid client disconnect object client disconnected events clientdisconnectedevents assert true asserttrue i container disconnected event icontainerdisconnectedevent i container disconnected event icontainerdisconnectedevent cco i container disconnected event icontainerdisconnectedevent assert true asserttrue cco get local container d getlocalcontainerid equals client getid assert true asserttrue cco get target d gettargetid equals create server d createserverid test remove listener testremovelistener exception i container icontainer client get clients getclients i container listener icontainerlistener create listener createlistener client add listener addlistener client remove listener removelistener client connect create server d createserverid assert true asserttrue client connecting events clientconnectingevents size
|
/*
* TesterLib
*
* This file was automatically generated for Stamplay by APIMATIC v3.0 ( https://www.apimatic.io ).
*/
package localhost3000.models;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
import java.util.List;
/**
* This is a model class for Signer type.
*/
public class Signer
extends BaseModel {
private String id;
private String url;
private List<String> links;
private String externalSignerId;
private RedirectSettings redirectSettings;
private SignatureType signatureType;
private Ui ui;
private List<String> tags;
private int order;
private boolean required;
/**
* Default constructor.
*/
public Signer() {
}
/**
* Initialization constructor.
* @param id String value for id.
* @param url String value for url.
* @param links List of String value for links.
* @param externalSignerId String value for externalSignerId.
* @param redirectSettings RedirectSettings value for redirectSettings.
* @param signatureType SignatureType value for signatureType.
* @param ui Ui value for ui.
* @param tags List of String value for tags.
* @param order int value for order.
* @param required boolean value for required.
*/
public Signer(
String id,
String url,
List<String> links,
String externalSignerId,
RedirectSettings redirectSettings,
SignatureType signatureType,
Ui ui,
List<String> tags,
int order,
boolean required) {
this.id = id;
this.url = url;
this.links = links;
this.externalSignerId = externalSignerId;
this.redirectSettings = redirectSettings;
this.signatureType = signatureType;
this.ui = ui;
this.tags = tags;
this.order = order;
this.required = required;
}
/**
* Getter for Id.
* @return Returns the String
*/
@JsonGetter("id")
public String getId() {
return id;
}
/**
* Setter for Id.
* @param id Value for String
*/
@JsonSetter("id")
public void setId(String id) {
this.id = id;
}
/**
* Getter for Url.
* @return Returns the String
*/
@JsonGetter("url")
public String getUrl() {
return url;
}
/**
* Setter for Url.
* @param url Value for String
*/
@JsonSetter("url")
public void setUrl(String url) {
this.url = url;
}
/**
* Getter for Links.
* @return Returns the List of String
*/
@JsonGetter("links")
public List<String> getLinks() {
return links;
}
/**
* Setter for Links.
* @param links Value for List of String
*/
@JsonSetter("links")
public void setLinks(List<String> links) {
this.links = links;
}
/**
* Getter for ExternalSignerId.
* @return Returns the String
*/
@JsonGetter("externalSignerId")
public String getExternalSignerId() {
return externalSignerId;
}
/**
* Setter for ExternalSignerId.
* @param externalSignerId Value for String
*/
@JsonSetter("externalSignerId")
public void setExternalSignerId(String externalSignerId) {
this.externalSignerId = externalSignerId;
}
/**
* Getter for RedirectSettings.
* @return Returns the RedirectSettings
*/
@JsonGetter("redirectSettings")
public RedirectSettings getRedirectSettings() {
return redirectSettings;
}
/**
* Setter for RedirectSettings.
* @param redirectSettings Value for RedirectSettings
*/
@JsonSetter("redirectSettings")
public void setRedirectSettings(RedirectSettings redirectSettings) {
this.redirectSettings = redirectSettings;
}
/**
* Getter for SignatureType.
* @return Returns the SignatureType
*/
@JsonGetter("signatureType")
public SignatureType getSignatureType() {
return signatureType;
}
/**
* Setter for SignatureType.
* @param signatureType Value for SignatureType
*/
@JsonSetter("signatureType")
public void setSignatureType(SignatureType signatureType) {
this.signatureType = signatureType;
}
/**
* Getter for Ui.
* @return Returns the Ui
*/
@JsonGetter("ui")
public Ui getUi() {
return ui;
}
/**
* Setter for Ui.
* @param ui Value for Ui
*/
@JsonSetter("ui")
public void setUi(Ui ui) {
this.ui = ui;
}
/**
* Getter for Tags.
* @return Returns the List of String
*/
@JsonGetter("tags")
public List<String> getTags() {
return tags;
}
/**
* Setter for Tags.
* @param tags Value for List of String
*/
@JsonSetter("tags")
public void setTags(List<String> tags) {
this.tags = tags;
}
/**
* Getter for Order.
* @return Returns the int
*/
@JsonGetter("order")
public int getOrder() {
return order;
}
/**
* Setter for Order.
* @param order Value for int
*/
@JsonSetter("order")
public void setOrder(int order) {
this.order = order;
}
/**
* Getter for Required.
* @return Returns the boolean
*/
@JsonGetter("required")
public boolean getRequired() {
return required;
}
/**
* Setter for Required.
* @param required Value for boolean
*/
@JsonSetter("required")
public void setRequired(boolean required) {
this.required = required;
}
/**
* Converts this Signer into string format.
* @return String representation of this class
*/
@Override
public String toString() {
return "Signer [" + "id=" + id + ", url=" + url + ", links=" + links + ", externalSignerId="
+ externalSignerId + ", redirectSettings=" + redirectSettings + ", signatureType="
+ signatureType + ", ui=" + ui + ", tags=" + tags + ", order=" + order
+ ", required=" + required + ", additionalProperties=" + getAdditionalProperties()
+ "]";
}
/**
* Builds a new {@link Signer.Builder} object.
* Creates the instance with the state of the current model.
* @return a new {@link Signer.Builder} object
*/
public Builder toBuilder() {
Builder builder = new Builder(id, url, links, externalSignerId, redirectSettings,
signatureType, ui, tags, order, required);
return builder;
}
/**
* Class to build instances of {@link Signer}.
*/
public static class Builder {
private String id;
private String url;
private List<String> links;
private String externalSignerId;
private RedirectSettings redirectSettings;
private SignatureType signatureType;
private Ui ui;
private List<String> tags;
private int order;
private boolean required;
/**
* Initialization constructor.
*/
public Builder() {
}
/**
* Initialization constructor.
* @param id String value for id.
* @param url String value for url.
* @param links List of String value for links.
* @param externalSignerId String value for externalSignerId.
* @param redirectSettings RedirectSettings value for redirectSettings.
* @param signatureType SignatureType value for signatureType.
* @param ui Ui value for ui.
* @param tags List of String value for tags.
* @param order int value for order.
* @param required boolean value for required.
*/
public Builder(String id, String url, List<String> links, String externalSignerId,
RedirectSettings redirectSettings, SignatureType signatureType, Ui ui,
List<String> tags, int order, boolean required) {
this.id = id;
this.url = url;
this.links = links;
this.externalSignerId = externalSignerId;
this.redirectSettings = redirectSettings;
this.signatureType = signatureType;
this.ui = ui;
this.tags = tags;
this.order = order;
this.required = required;
}
/**
* Setter for id.
* @param id String value for id.
* @return Builder
*/
public Builder id(String id) {
this.id = id;
return this;
}
/**
* Setter for url.
* @param url String value for url.
* @return Builder
*/
public Builder url(String url) {
this.url = url;
return this;
}
/**
* Setter for links.
* @param links List of String value for links.
* @return Builder
*/
public Builder links(List<String> links) {
this.links = links;
return this;
}
/**
* Setter for externalSignerId.
* @param externalSignerId String value for externalSignerId.
* @return Builder
*/
public Builder externalSignerId(String externalSignerId) {
this.externalSignerId = externalSignerId;
return this;
}
/**
* Setter for redirectSettings.
* @param redirectSettings RedirectSettings value for redirectSettings.
* @return Builder
*/
public Builder redirectSettings(RedirectSettings redirectSettings) {
this.redirectSettings = redirectSettings;
return this;
}
/**
* Setter for signatureType.
* @param signatureType SignatureType value for signatureType.
* @return Builder
*/
public Builder signatureType(SignatureType signatureType) {
this.signatureType = signatureType;
return this;
}
/**
* Setter for ui.
* @param ui Ui value for ui.
* @return Builder
*/
public Builder ui(Ui ui) {
this.ui = ui;
return this;
}
/**
* Setter for tags.
* @param tags List of String value for tags.
* @return Builder
*/
public Builder tags(List<String> tags) {
this.tags = tags;
return this;
}
/**
* Setter for order.
* @param order int value for order.
* @return Builder
*/
public Builder order(int order) {
this.order = order;
return this;
}
/**
* Setter for required.
* @param required boolean value for required.
* @return Builder
*/
public Builder required(boolean required) {
this.required = required;
return this;
}
/**
* Builds a new {@link Signer} object using the set fields.
* @return {@link Signer}
*/
public Signer build() {
return new Signer(id, url, links, externalSignerId, redirectSettings, signatureType, ui,
tags, order, required);
}
}
}
|
package pl.zankowski.iextrading4j.api.stocks;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.math.BigDecimal;
public class Ohlc implements Serializable {
private static final long serialVersionUID = -7796960089826811278L;
private final String symbol;
private final Point open;
private final Point close;
private final BigDecimal high;
private final BigDecimal low;
private final BigDecimal volume;
@JsonCreator
public Ohlc(
@JsonProperty("symbol") final String symbol,
@JsonProperty("open") final Point open,
@JsonProperty("close") final Point close,
@JsonProperty("high") final BigDecimal high,
@JsonProperty("low") final BigDecimal low,
@JsonProperty("volume") final BigDecimal volume) {
this.symbol = symbol;
this.open = open;
this.close = close;
this.high = high;
this.low = low;
this.volume = volume;
}
public String getSymbol() {
return symbol;
}
public Point getOpen() {
return open;
}
public Point getClose() {
return close;
}
public BigDecimal getHigh() {
return high;
}
public BigDecimal getLow() {
return low;
}
public BigDecimal getVolume() {
return volume;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Ohlc ohlc = (Ohlc) o;
return Objects.equal(symbol, ohlc.symbol) &&
Objects.equal(open, ohlc.open) &&
Objects.equal(close, ohlc.close) &&
Objects.equal(high, ohlc.high) &&
Objects.equal(low, ohlc.low) &&
Objects.equal(volume, ohlc.volume);
}
@Override
public int hashCode() {
return Objects.hashCode(symbol, open, close, high, low, volume);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("symbol", symbol)
.add("open", open)
.add("close", close)
.add("high", high)
.add("low", low)
.add("volume", volume)
.toString();
}
}
|
import java.io.*;
public class OrderItem {
private String drug;
private int quantity;
public OrderItem(String drug, int quantity) {
this.drug = drug;
this.quantity = quantity;
}
public String getDrug() {
return this.drug;
}
// assumption: quantity is positive
public int getQuantity() {
return this.quantity;
}
public void print() {
System.out.println(String.valueOf(quantity) + " x " + drug);
}
}
|
package com.kiroule.vaadin.bakeryapp.ui.view.admin.product;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.data.BeanValidationBinder;
import com.vaadin.data.ValueContext;
import com.vaadin.spring.annotation.SpringView;
import com.kiroule.vaadin.bakeryapp.backend.data.entity.Product;
import com.kiroule.vaadin.bakeryapp.ui.util.DollarPriceConverter;
import com.kiroule.vaadin.bakeryapp.ui.view.admin.AbstractCrudView;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.Component.Focusable;
import com.vaadin.ui.Grid;
import com.vaadin.ui.TextField;
@SpringView
public class ProductAdminView extends AbstractCrudView<Product> {
private final ProductAdminPresenter presenter;
private final ProductAdminViewDesign userAdminViewDesign;
private final DollarPriceConverter priceToStringConverter;
private static final String PRICE_PROPERTY = "price";
@Autowired
public ProductAdminView(ProductAdminPresenter presenter, DollarPriceConverter priceToStringConverter) {
this.presenter = presenter;
this.priceToStringConverter = priceToStringConverter;
userAdminViewDesign = new ProductAdminViewDesign();
}
@PostConstruct
private void init() {
presenter.init(this);
// Show two columns: "name" and "price".
getGrid().setColumns("name", PRICE_PROPERTY);
// The price column is configured automatically based on the bean. As
// we want a custom converter, we remove the column and configure it
// manually.
getGrid().removeColumn(PRICE_PROPERTY);
getGrid().addColumn(product -> priceToStringConverter.convertToPresentation(product.getPrice(),
new ValueContext(getGrid()))).setSortProperty(PRICE_PROPERTY);
}
@Override
public void bindFormFields(BeanValidationBinder<Product> binder) {
binder.forField(getViewComponent().price).withConverter(priceToStringConverter).bind(PRICE_PROPERTY);
binder.bindInstanceFields(getViewComponent());
}
@Override
public ProductAdminViewDesign getViewComponent() {
return userAdminViewDesign;
}
@Override
protected ProductAdminPresenter getPresenter() {
return presenter;
}
@Override
protected Grid<Product> getGrid() {
return getViewComponent().list;
}
@Override
protected void setGrid(Grid<Product> grid) {
getViewComponent().list = grid;
}
@Override
protected Component getForm() {
return getViewComponent().form;
}
@Override
protected Button getAdd() {
return getViewComponent().add;
}
@Override
protected Button getCancel() {
return getViewComponent().cancel;
}
@Override
protected Button getDelete() {
return getViewComponent().delete;
}
@Override
protected Button getUpdate() {
return getViewComponent().update;
}
@Override
protected TextField getSearch() {
return getViewComponent().search;
}
@Override
protected Focusable getFirstFormField() {
return getViewComponent().name;
}
}
|
package com.bsnbase.sdk.util.sm2;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import java.security.*;
public class Sm2Util {
public static Signature signature;
public static KeyPair keyPair;
public static void createKeyPair() {
// 获取SM2 椭圆曲线推荐参数
X9ECParameters ecParameters = GMNamedCurves.getByName("sm2p256v1");
// 构造EC 算法参数
ECNamedCurveParameterSpec sm2Spec = new ECNamedCurveParameterSpec(
// 设置SM2 算法的 OID
GMObjectIdentifiers.sm2p256v1.toString()
// 设置曲线方程
, ecParameters.getCurve()
// 椭圆曲线G点
, ecParameters.getG()
// 大整数N
, ecParameters.getN());
try {
// 创建 密钥对生成器
KeyPairGenerator gen = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
// 使用SM2的算法区域初始化密钥生成器
gen.initialize(sm2Spec, new SecureRandom());
// 获取密钥对
keyPair = gen.generateKeyPair();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 签名
*
* @param privateKey 签名私钥
* @param plainText 明文
* @return
*/
public static String encrypt(PrivateKey privateKey, String plainText) {
try {
signature.initSign(privateKey);
signature.update(plainText.getBytes());
byte[] bytes = signature.sign();
return new String(bytes, 0, bytes.length, "ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 验证签名
*
* @param publicKey 签名公钥
* @param signResult 签名结果
* @param plainText 明文
* @return
*/
public static boolean verify(PublicKey publicKey, byte[] signResult, String plainText) {
boolean result = false;
try {
signature.initVerify(publicKey);
signature.update(plainText.getBytes());
result = signature.verify(signResult);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
|
package ca.objectscape.depviz.maven;
import java.util.Objects;
import ca.objectscape.depviz.graph.GraphNode;
public class MavenDependencyLink
{
private final MavenComponent source;
private final MavenComponent target;
private GraphNode sourceNode;
private GraphNode targetNode;
MavenDependencyLink(final MavenComponent source, final MavenComponent target) {
this.source = source;
this.target = target;
}
public MavenComponent getSource() {
return source;
}
public MavenComponent getTarget() {
return target;
}
public GraphNode getSourceNode() {
return sourceNode;
}
public void setSourceNode(final GraphNode sourceNode) {
this.sourceNode = sourceNode;
}
public GraphNode getTargetNode() {
return targetNode;
}
public void setTargetNode(final GraphNode targetNode) {
this.targetNode = targetNode;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MavenDependencyLink that = (MavenDependencyLink) o;
return Objects.equals(source, that.source) &&
Objects.equals(target, that.target);
}
@Override
public int hashCode() {
return Objects.hash(source, target);
}
@Override
public String toString() {
return source + " -> " + target;
}
}
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.transform.transforms;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.test.AbstractSerializingTestCase;
import org.elasticsearch.xcontent.XContentParser;
import java.io.IOException;
public class TimeRetentionPolicyConfigTests extends AbstractSerializingTestCase<TimeRetentionPolicyConfig> {
public static TimeRetentionPolicyConfig randomTimeRetentionPolicyConfig() {
return new TimeRetentionPolicyConfig(randomAlphaOfLengthBetween(1, 10), new TimeValue(randomLongBetween(60000, 1_000_000_000L)));
}
@Override
protected TimeRetentionPolicyConfig doParseInstance(XContentParser parser) throws IOException {
return TimeRetentionPolicyConfig.fromXContent(parser, false);
}
@Override
protected TimeRetentionPolicyConfig createTestInstance() {
return randomTimeRetentionPolicyConfig();
}
@Override
protected Reader<TimeRetentionPolicyConfig> instanceReader() {
return TimeRetentionPolicyConfig::new;
}
public void testValidationMin() {
TimeRetentionPolicyConfig timeRetentionPolicyConfig = new TimeRetentionPolicyConfig(
randomAlphaOfLengthBetween(1, 10),
TimeValue.timeValueSeconds(10)
);
ActionRequestValidationException e = timeRetentionPolicyConfig.validate(null);
assertNotNull(e);
assertEquals(1, e.validationErrors().size());
assertEquals("retention_policy.time.max_age must be greater than 60s, found [10s]", e.validationErrors().get(0));
}
public void testValidationMax() {
TimeRetentionPolicyConfig timeRetentionPolicyConfig = new TimeRetentionPolicyConfig(
randomAlphaOfLengthBetween(1, 10),
TimeValue.parseTimeValue("600000000000d", "time value")
);
ActionRequestValidationException e = timeRetentionPolicyConfig.validate(null);
assertNotNull(e);
assertEquals(1, e.validationErrors().size());
assertEquals("retention_policy.time.max_age must not be greater than [106751.9d]", e.validationErrors().get(0));
}
}
|
package com.ruoyi.generator.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.mapper.BaseMapperPlus;
import com.ruoyi.generator.domain.GenTable;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 业务 数据层
*
* @author Lion Li
*/
@InterceptorIgnore(dataPermission = "true")
public interface GenTableMapper extends BaseMapperPlus<GenTableMapper, GenTable, GenTable> {
/**
* 查询据库列表
*
* @param genTable 查询条件
* @return 数据库表集合
*/
Page<GenTable> selectPageDbTableList(@Param("page") Page<GenTable> page, @Param("genTable") GenTable genTable);
/**
* 查询据库列表
*
* @param tableNames 表名称组
* @return 数据库表集合
*/
List<GenTable> selectDbTableListByNames(String[] tableNames);
/**
* 查询所有表信息
*
* @return 表信息集合
*/
List<GenTable> selectGenTableAll();
/**
* 查询表ID业务信息
*
* @param id 业务ID
* @return 业务信息
*/
GenTable selectGenTableById(Long id);
/**
* 查询表名称业务信息
*
* @param tableName 表名称
* @return 业务信息
*/
GenTable selectGenTableByName(String tableName);
}
|
package engine.gameobjects.gamebehaviour.builtin.ui;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import engine.game.GameContainer;
import engine.gameobjects.GameObject;
import engine.gameobjects.gamebehaviour.type.GameBehaviour;
import engine.gameobjects.gamebehaviour.type.UIGameBehaviour;
import engine.io.Logger;
import engine.math.Vector2;
public class RectTransform extends GameBehaviour {
private Vector2 size;
private boolean hasToApplyObjPos = false;
private Vector2 newPos;
private RectTransform parentBounds;
private Vector2 alignment;
private Vector2 alignmentOffset = new Vector2(0);
public RectTransform(Vector2 size, Vector2 align) {
this.size = size;
this.alignment = align;
}
public RectTransform(Vector2 p1, Vector2 p2, Vector2 align) {
this.setBounds(p1, p2);
this.alignment = align;
}
public void setBounds(Vector2 p1, Vector2 p2) {
Vector2 diffVec = new Vector2(p2, p1);
this.size = diffVec.getCopy();
diffVec.multiply(0.5f);
this.newPos = Vector2.add(p1, diffVec);
if (this.started) {
this.gameObject.setPosition(newPos);
} else {
this.hasToApplyObjPos = true;
}
}
public void setSize(Vector2 size) {
this.size = size;
}
public void calcOffset() {
//You could mix "LEFT" & "RIGHT", but the question is,
//is a "if" faster or slowed than "multi"
//X
if (this.alignment.x == Alignment.LEFT_int) {
this.alignmentOffset.x = this.parentBounds.size.x/2 + this.gameObject.getLocalTransform().position.x;
} else if (this.alignment.x == Alignment.RIGHT_int) {
this.alignmentOffset.x = -this.parentBounds.size.x/2 + this.gameObject.getLocalTransform().position.x;
} else if (this.alignment.x == Alignment.SCALE_int) {
//Not positon offset, this will be used for saving the scaling aspect with parent
this.alignmentOffset.x = this.parentBounds.size.x / this.size.x;
}
//Y
if (this.alignment.y == Alignment.LEFT_int) {
this.alignmentOffset.y = this.parentBounds.size.y/2 + this.gameObject.getLocalTransform().position.y;
} else if (this.alignment.y == Alignment.RIGHT_int) {
this.alignmentOffset.y = -this.parentBounds.size.y/2 + this.gameObject.getLocalTransform().position.y;
} else if (this.alignment.y == Alignment.SCALE_int) {
//Not positon offset, this will be used for saving the scaling aspect with parent
this.alignmentOffset.y = this.parentBounds.size.y / this.size.y;
}
}
public void start() {
if (this.hasToApplyObjPos) {
this.gameObject.setPosition(newPos);
}
//Find Parent for Alignment (if there is one)
GameObject parentObj = this.gameObject.getParent();
if (parentObj != null) {
this.parentBounds = (RectTransform) parentObj.getComponent(RectTransform.class);
this.calcOffset();
}
}
public void update() {
}
public void render() {
if (GameContainer.debug) {
this.d.setColor(Color.GREEN);
this.d.drawCircle(new Vector2(10));
this.d.setColor(Color.CYAN);
this.d.drawRect(this);
}
}
public void updateBounds(final RectTransform parent) {
Vector2 pos = this.gameObject.getLocalTransform().position;
//X
if (this.alignment.x == Alignment.LEFT_int) {
this.gameObject.setPosition(new Vector2(-this.parentBounds.size.x/2 + this.alignmentOffset.x, pos.y));
} else if (this.alignment.x == Alignment.RIGHT_int) {
this.gameObject.setPosition(new Vector2(this.parentBounds.size.x/2 + this.alignmentOffset.x, pos.y));
} else if (this.alignment.x == Alignment.SCALE_int) {
this.size.x = this.parentBounds.size.x / this.alignmentOffset.x;
}
pos = this.gameObject.getLocalTransform().position;
//Y
if (this.alignment.y == Alignment.LEFT_int) {
this.gameObject.setPosition(new Vector2(pos.x, -this.parentBounds.size.y/2 + this.alignmentOffset.y));
} else if (this.alignment.y == Alignment.RIGHT_int) {
this.gameObject.setPosition(new Vector2(pos.x, this.parentBounds.size.y/2 + this.alignmentOffset.y));
} else if (this.alignment.y == Alignment.SCALE_int) {
this.size.y = this.parentBounds.size.y / this.alignmentOffset.y;
}
this.updateComponents();
}
public void updateComponents() {
for (GameBehaviour gb : this.gameObject.getComponents()) {
if (gb.getType().equals("ui")) {
UIGameBehaviour uigb = (UIGameBehaviour)gb;
uigb.uiUpdate();
}
}
}
public Vector2 getSize() {
return this.size;
}
public Vector2 getPoint1() {
return new Vector2(-this.size.x/2, -this.size.y/2);
}
public Vector2 getPoint2() {
return new Vector2(this.size.x/2, -this.size.y/2);
}
public Vector2 getPoint3() {
return new Vector2(this.size.x/2, this.size.y/2);
}
public Vector2 getPoint4() {
return new Vector2(-this.size.x/2, this.size.y/2);
}
public Vector2 getAlignment() {
return this.alignment;
}
public String toString() {
return this.size+"";
}
}
|
package es.tearain.mate.model.combat;
public enum DamageType {
ACID,
BLUDGEONING,
COLD,
FIRE,
FORCE,
LIGHTNING,
NECROTIC,
PIERCING,
POSION,
PSYCHIC,
RADIANT,
SLASHING,
THUNDER;
}
|
package cn.ganiner.util;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o,
Exception e) {
CustomException customException = null;
if (e instanceof CustomException){ //此错误是我们预期的错误
customException = (CustomException)e;
}else{ //非预期错误
customException = new CustomException("未知错误");
}
String message = customException.getMessage(); //错误文字信息
ModelAndView modelAndView = new ModelAndView();
//判断请求的类型, 是否是json
HandlerMethod handlerMethod = (HandlerMethod) o;
ResponseBody responseBody = handlerMethod.getMethod().getAnnotation(ResponseBody.class);
//是json请求, 则放回json数据
if (responseBody != null){
//设置状态码和信息
Map<String, Object> responseMap = new HashMap<String, Object>();
responseMap.put("code", "0");
responseMap.put("message", message);
String json = new Gson().toJson(responseMap);
System.out.println(json);
httpServletResponse.setContentType("UTF-8");
httpServletResponse.setContentType("application/json;charset=utf-8");
try{
httpServletResponse.getWriter().write(json);
httpServletResponse.getWriter().flush();;
}catch (IOException e1){
e1.printStackTrace();
}
return modelAndView;
}
modelAndView.addObject("message", message);
//不是json数据, 携带message到跳转到错误页面
modelAndView.setViewName("page/error");
return modelAndView;
}
}
|
/*
* Copyright 2006-2014 smartics, Kronseder & Reiner GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.redhat.rcm.maven.plugin.buildmetadata.util;
import java.io.File;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.doxia.site.decoration.Skin;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
/**
* Utilities for Maven for generating reports.
*
* @author <a href="mailto:robert.reiner@smartics.de">Robert Reiner</a>
* @version $Revision:591 $
*/
public final class ReportUtils
{
// ********************************* Fields *********************************
// --- constants ------------------------------------------------------------
// --- members --------------------------------------------------------------
// ****************************** Initializer *******************************
// ****************************** Constructors ******************************
/**
* Utility class pattern.
*/
private ReportUtils()
{
}
// ****************************** Inner Classes *****************************
// ********************************* Methods ********************************
// --- init -----------------------------------------------------------------
// --- get&set --------------------------------------------------------------
// --- business -------------------------------------------------------------
/**
* Returns a file reference to the default skin useful for rendering
* standalone run reports.
* <p>
* Stolen from the changes plugin.
* </p>
*
* @param project the project of the plugin that calls this method.
* @param localRepository a reference to the local repository to reference to.
* @param resolver to resolve the skin artifact.
* @param factory to resolve dependencies.
* @return a file reference to the default skin.
* @throws MojoExecutionException if the skin artifact cannot be resolved.
*/
public static File getSkinArtifactFile(final MavenProject project,
final ArtifactRepository localRepository,
final ArtifactResolver resolver, final ArtifactFactory factory)
throws MojoExecutionException
{
final Skin skin = Skin.getDefaultSkin();
final String version = determineVersion(skin);
try
{
final VersionRange versionSpec =
VersionRange.createFromVersionSpec(version);
final Artifact artifact =
factory.createDependencyArtifact(skin.getGroupId(),
skin.getArtifactId(), versionSpec, "jar", null, null);
resolver.resolve(artifact, project.getRemoteArtifactRepositories(),
localRepository);
return artifact.getFile();
}
catch (final InvalidVersionSpecificationException e)
{
throw new MojoExecutionException("The skin version '" + version
+ "' is not valid: " + e.getMessage(), e);
}
catch (final ArtifactResolutionException e)
{
throw new MojoExecutionException("Unable to find skin", e);
}
catch (final ArtifactNotFoundException e)
{
throw new MojoExecutionException("The skin does not exist: "
+ e.getMessage(), e);
}
}
/**
* Determines the version of the given skin. If the version is not set in the
* skin, the {@link Artifact#RELEASE_VERSION} is returned.
*
* @param skin the skin whose version is requested.
* @return the version of the skin or {@link Artifact#RELEASE_VERSION} as
* default.
*/
private static String determineVersion(final Skin skin)
{
String version = skin.getVersion();
if (version == null)
{
version = Artifact.RELEASE_VERSION;
}
return version;
}
// --- object basics --------------------------------------------------------
}
|
/*
* Encog(tm) Core v3.0 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2011 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.ml.anneal;
/**
* Simulated annealing is a common training method. This class implements a
* simulated annealing algorithm that can be used both for neural networks, as
* well as more general cases. This class is abstract, so a more specialized
* simulated annealing subclass will need to be created for each intended use.
* This book demonstrates how to use the simulated annealing algorithm to train
* feedforward neural networks, as well as find a solution to the traveling
* salesman problem.
*
* The name and inspiration come from annealing in metallurgy, a technique
* involving heating and controlled cooling of a material to increase the size
* of its crystals and reduce their defects. The heat causes the atoms to become
* unstuck from their initial positions (a local minimum of the internal energy)
* and wander randomly through states of higher energy; the slow cooling gives
* them more chances of finding configurations with lower internal energy than
* the initial one.
*
* @param <UNIT_TYPE>
* What type of data makes up the solution.
*/
public abstract class SimulatedAnnealing<UNIT_TYPE> {
/**
* The starting temperature.
*/
private double startTemperature;
/**
* The ending temperature.
*/
private double stopTemperature;
/**
* The number of cycles that will be used.
*/
private int cycles;
/**
* The current score.
*/
private double score;
/**
* The current temperature.
*/
private double temperature;
/**
* Should the score be minimized.
*/
private boolean shouldMinimize = true;
/**
* Subclasses should provide a method that evaluates the score for the
* current solution. Those solutions with a lower score are better.
*
* @return Return the score.
*/
public abstract double calculateScore();
/**
* Subclasses must provide access to an array that makes up the solution.
*
* @return An array that makes up the solution.
*/
public abstract UNIT_TYPE[] getArray();
/**
* Get a copy of the array.
*
* @return A copy of the array.
*/
public abstract UNIT_TYPE[] getArrayCopy();
/**
* @return the cycles
*/
public final int getCycles() {
return this.cycles;
}
/**
* @return the globalScore
*/
public final double getScore() {
return this.score;
}
/**
* @return the startTemperature
*/
public final double getStartTemperature() {
return this.startTemperature;
}
/**
* @return the stopTemperature
*/
public final double getStopTemperature() {
return this.stopTemperature;
}
/**
* @return the temperature
*/
public final double getTemperature() {
return this.temperature;
}
/**
* @return True if the score should be minimized.
*/
public final boolean isShouldMinimize() {
return this.shouldMinimize;
}
/**
* Called to perform one cycle of the annealing process.
*/
public final void iteration() {
UNIT_TYPE[] bestArray;
setScore(calculateScore());
bestArray = this.getArrayCopy();
this.temperature = this.getStartTemperature();
for (int i = 0; i < this.cycles; i++) {
double curScore;
randomize();
curScore = calculateScore();
if (this.shouldMinimize) {
if (curScore < getScore()) {
bestArray = this.getArrayCopy();
setScore(curScore);
}
} else {
if (curScore > getScore()) {
bestArray = this.getArrayCopy();
setScore(curScore);
}
}
this.putArray(bestArray);
final double ratio = Math.exp(Math.log(getStopTemperature()
/ getStartTemperature())
/ (getCycles() - 1));
this.temperature *= ratio;
}
}
/**
* Store the array.
*
* @param array
* The array to be stored.
*/
public abstract void putArray(UNIT_TYPE[] array);
/**
* Randomize the weight matrix.
*/
public abstract void randomize();
/**
* @param theCycles
* the cycles to set
*/
public final void setCycles(final int theCycles) {
this.cycles = theCycles;
}
/**
* Set the score.
*
* @param theScore
* The score to set.
*/
public final void setScore(final double theScore) {
this.score = theScore;
}
/**
* Should the score be minimized.
*
* @param theShouldMinimize
* True if the score should be minimized.
*/
public final void setShouldMinimize(final boolean theShouldMinimize) {
this.shouldMinimize = theShouldMinimize;
}
/**
* @param theStartTemperature
* the startTemperature to set
*/
public final void setStartTemperature(final double theStartTemperature) {
this.startTemperature = theStartTemperature;
}
/**
* @param theStopTemperature
* the stopTemperature to set
*/
public final void setStopTemperature(final double theStopTemperature) {
this.stopTemperature = theStopTemperature;
}
/**
* @param theTemperature
* the temperature to set
*/
public final void setTemperature(final double theTemperature) {
this.temperature = theTemperature;
}
}
|
/*
* Copyright (C) 2009 Jayway AB
* Copyright (C) 2007-2008 JVending Masa
*
* 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.simpligility.maven.plugins.android.phase08preparepackage;
import com.simpligility.maven.plugins.android.AbstractAndroidMojo;
import com.simpligility.maven.plugins.android.IncludeExcludeSet;
import com.simpligility.maven.plugins.android.CommandExecutor;
import com.simpligility.maven.plugins.android.ExecutionException;
import com.simpligility.maven.plugins.android.common.Const;
import com.simpligility.maven.plugins.android.common.ZipExtractor;
import com.simpligility.maven.plugins.android.configuration.Dex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.jar.JarArchiver;
import org.codehaus.plexus.archiver.util.DefaultFileSet;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.simpligility.maven.plugins.android.InclusionExclusionResolver.filterArtifacts;
import static com.simpligility.maven.plugins.android.common.AndroidExtension.AAR;
import static com.simpligility.maven.plugins.android.common.AndroidExtension.APK;
import static com.simpligility.maven.plugins.android.common.AndroidExtension.APKLIB;
/**
* Converts compiled Java classes to the Android dex format.
*
* @author hugo.josefson@jayway.com
*/
@Mojo(
name = "dex",
defaultPhase = LifecyclePhase.PREPARE_PACKAGE,
requiresDependencyResolution = ResolutionScope.COMPILE
)
public class DexMojo extends AbstractAndroidMojo
{
/**
* Configuration for the dex command execution. It can be configured in the plugin configuration like so
*
* <pre>
* <dex>
* <jvmArguments>
* <jvmArgument>-Xms256m</jvmArgument>
* <jvmArgument>-Xmx512m</jvmArgument>
* </jvmArguments>
* <coreLibrary>true|false</coreLibrary>
* <noLocals>true|false</noLocals>
* <forceJumbo>true|false</forceJumbo>
* <optimize>true|false</optimize>
* <preDex>true|false</preDex>
* <preDexLibLocation>path to predexed libraries, defaults to target/dexedLibs</preDexLibLocation>
* <incremental>true|false</incremental>
* <multiDex>true|false</multiDex>
* <mainDexList>path to class list file</mainDexList>
* <minimalMainDex>true|false</minimalMainDex>
* </dex>
* </pre>
* <p/>
* or via properties dex.* or command line parameters android.dex.*
*/
@Parameter
private Dex dex;
/**
* Extra JVM Arguments. Using these you can e.g. increase memory for the jvm running the build.
*/
@Parameter( property = "android.dex.jvmArguments", defaultValue = "-Xmx1024M" )
private String[] dexJvmArguments;
/**
* Decides whether to pass the --core-library flag to dx.
*/
@Parameter( property = "android.dex.coreLibrary", defaultValue = "false" )
private boolean dexCoreLibrary;
/**
* Decides whether to pass the --no-locals flag to dx.
*/
@Parameter( property = "android.dex.noLocals", defaultValue = "false" )
private boolean dexNoLocals;
/**
* Decides whether to pass the --no-optimize flag to dx.
*/
@Parameter( property = "android.dex.optimize", defaultValue = "true" )
private boolean dexOptimize;
/**
* Decides whether to predex the jars.
*/
@Parameter( property = "android.dex.predex", defaultValue = "false" )
private boolean dexPreDex;
/**
* Decides whether to use force jumbo mode.
*/
@Parameter( property = "android.dex.forcejumbo", defaultValue = "false" )
private boolean dexForceJumbo;
/**
* Path to predexed libraries.
*/
@Parameter(
property = "android.dex.dexPreDexLibLocation",
defaultValue = "${project.build.directory}${file.separator}dexedLibs"
)
private String dexPreDexLibLocation;
/**
* Decides whether to pass the --incremental flag to dx.
*/
@Parameter( property = "android.dex.incremental", defaultValue = "false" )
private boolean dexIncremental;
/**
* The name of the obfuscated JAR.
*/
@Parameter( property = "android.proguard.obfuscatedJar" )
private File obfuscatedJar;
/**
* Decides whether to pass the --multi-dex flag to dx.
*/
@Parameter( property = "android.dex.multidex", defaultValue = "false" )
private boolean dexMultiDex;
/**
* Full path to class list to multi dex
*/
@Parameter( property = "android.dex.maindexlist" )
private String dexMainDexList;
/**
* Decides whether to pass the --minimal-main-dex flag to dx.
*/
@Parameter( property = "android.dex.minimalmaindex", defaultValue = "false" )
private boolean dexMinimalMainDex;
/**
* Additional command line parameters passed to dx.
*/
@Parameter( property = "android.dex.dexarguments" )
private String dexArguments;
/**
* Skips transitive dependencies. May be useful if the target classes directory is populated with the
* {@code maven-dependency-plugin} and already contains all dependency classes.
*/
@Parameter( property = "skipDependencies", defaultValue = "false" )
private boolean skipDependencies;
/**
* Allows to include or exclude artifacts by type. The {@code include} parameter has higher priority than the
* {@code exclude} parameter. These two parameters can be overridden by the {@code artifactSet} parameter. Empty
* strings are ignored. Example:
* <pre>
* <artifactTypeSet>
* <includes>
* <include>aar</include>
* <includes>
* <excludes>
* <exclude>jar</exclude>
* <excludes>
* </artifactTypeSet>
* </pre>
*/
@Parameter( property = "artifactTypeSet" )
private IncludeExcludeSet artifactTypeSet;
/**
* Allows to include or exclude artifacts by {@code groupId}, {@code artifactId}, and {@code versionId}. The
* {@code include} parameter has higher priority than the {@code exclude} parameter. These two parameters can
* override the {@code artifactTypeSet} and {@code skipDependencies} parameters. Artifact {@code groupId},
* {@code artifactId}, and {@code versionId} are specified by a string with the respective values separated using
* a colon character {@code :}. {@code artifactId} and {@code versionId} can be optional covering an artifact
* range. Empty strings are ignored. Example:
* <pre>
* <artifactTypeSet>
* <includes>
* <include>foo-group:foo-artifact:1.0-SNAPSHOT</include>
* <include>bar-group:bar-artifact:1.0-SNAPSHOT</include>
* <include>baz-group:*</include>
* <includes>
* <excludes>
* <exclude>qux-group:qux-artifact:*</exclude>
* <excludes>
* </artifactTypeSet>
* </pre>
*/
@Parameter( property = "artifactSet" )
private IncludeExcludeSet artifactSet;
private String[] parsedJvmArguments;
private boolean parsedCoreLibrary;
private boolean parsedNoLocals;
private boolean parsedOptimize;
private boolean parsedPreDex;
private boolean parsedForceJumbo;
private String parsedPreDexLibLocation;
private boolean parsedIncremental;
private boolean parsedMultiDex;
private String parsedMainDexList;
private boolean parsedMinimalMainDex;
private String parsedDexArguments;
/**
* @throws MojoExecutionException
* @throws MojoFailureException
*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
parseConfiguration();
File outputFile;
if ( parsedMultiDex )
{
outputFile = targetDirectory;
}
else
{
outputFile = new File( targetDirectory, "classes.dex" );
}
if ( generateApk )
{
runDex( executor, outputFile );
}
if ( attachJar )
{
File jarFile = new File( targetDirectory + File.separator
+ finalName + ".jar" );
projectHelper.attachArtifact( project, "jar", project.getArtifact().getClassifier(), jarFile );
}
if ( attachSources )
{
// Also attach an .apksources, containing sources from this project.
final File apksources = createApkSourcesFile();
projectHelper.attachArtifact( project, "apksources", apksources );
}
}
/**
* Gets the input files for dex. This is a combination of directories and jar files.
*
* @return
*/
private Set< File > getDexInputFiles() throws MojoExecutionException
{
Set< File > inputs = new HashSet< File >();
if ( obfuscatedJar != null && obfuscatedJar.exists() )
{
// proguard has been run, use this jar
getLog().debug( "Adding dex input (obfuscatedJar) : " + obfuscatedJar );
inputs.add( obfuscatedJar );
}
else
{
getLog().debug( "Using non-obfuscated input" );
// no proguard, use original config
inputs.add( projectOutputDirectory );
getLog().debug( "Adding dex input : " + project.getBuild().getOutputDirectory() );
for ( Artifact artifact : filterArtifacts( getTransitiveDependencyArtifacts(), skipDependencies,
artifactTypeSet.getIncludes(), artifactTypeSet.getExcludes(), artifactSet.getIncludes(),
artifactSet.getExcludes() ) )
{
if ( artifact.getType().equals( Const.ArtifactType.NATIVE_SYMBOL_OBJECT )
|| artifact.getType().equals( Const.ArtifactType.NATIVE_IMPLEMENTATION_ARCHIVE ) )
{
// Ignore native dependencies - no need for dexer to see those
}
else if ( artifact.getType().equals( APKLIB ) )
{
// Any jars in the libs folder should now be
// automatically included because they will be a transitive dependency.
}
else if ( artifact.getType().equals( AAR ) )
{
// The Aar classes.jar should now be automatically included
// because it will be a transitive dependency. As should any jars in the libs folder.
}
else if ( artifact.getType().equals( APK ) )
{
// We need to dex the APK classes including the APK R.
// But we don't want to add a second instance of the embedded Rs for any of the APK's dependencies
// as they will already have been generated to target/classes. The R values from the APK will be
// the correct ones, so best solution is to extract the APK classes (including all Rs) to
// target/classes overwriting any generated Rs and let dex pick up the values from there.
getLog().debug( "Extracting APK classes to target/classes : " + artifact.getArtifactId() );
final File apkClassesJar = getUnpackedLibHelper().getJarFileForApk( artifact );
getLog().debug( "Extracting APK : " + apkClassesJar + " to " + targetDirectory );
final ZipExtractor extractor = new ZipExtractor( getLog() );
extractor.extract( apkClassesJar, targetDirectory, ".class" );
}
else
{
getLog().debug( "Adding dex input : " + artifact.getFile() );
inputs.add( artifact.getFile().getAbsoluteFile() );
}
}
}
return inputs;
}
private void parseConfiguration()
{
// config in pom found
if ( dex != null )
{
// the if statements make sure that properties/command line
// parameter overrides configuration
// and that the dafaults apply in all cases;
if ( dex.getJvmArguments() == null )
{
parsedJvmArguments = dexJvmArguments;
}
else
{
parsedJvmArguments = dex.getJvmArguments();
}
if ( dex.isCoreLibrary() == null )
{
parsedCoreLibrary = dexCoreLibrary;
}
else
{
parsedCoreLibrary = dex.isCoreLibrary();
}
if ( dex.isNoLocals() == null )
{
parsedNoLocals = dexNoLocals;
}
else
{
parsedNoLocals = dex.isNoLocals();
}
if ( dex.isOptimize() == null )
{
parsedOptimize = dexOptimize;
}
else
{
parsedOptimize = dex.isOptimize();
}
if ( dex.isPreDex() == null )
{
parsedPreDex = dexPreDex;
}
else
{
parsedPreDex = dex.isPreDex();
}
if ( dex.getPreDexLibLocation() == null )
{
parsedPreDexLibLocation = dexPreDexLibLocation;
}
else
{
parsedPreDexLibLocation = dex.getPreDexLibLocation();
}
if ( dex.isIncremental() == null )
{
parsedIncremental = dexIncremental;
}
else
{
parsedIncremental = dex.isIncremental();
}
if ( dex.isForceJumbo() == null )
{
parsedForceJumbo = dexForceJumbo;
}
else
{
parsedForceJumbo = dex.isForceJumbo();
}
if ( dex.isMultiDex() == null )
{
parsedMultiDex = dexMultiDex;
}
else
{
parsedMultiDex = dex.isMultiDex();
}
if ( dex.getMainDexList() == null )
{
parsedMainDexList = dexMainDexList;
}
else
{
parsedMainDexList = dex.getMainDexList();
}
if ( dex.isMinimalMainDex() == null )
{
parsedMinimalMainDex = dexMinimalMainDex;
}
else
{
parsedMinimalMainDex = dex.isMinimalMainDex();
}
if ( dex.getDexArguments() == null )
{
parsedDexArguments = dexArguments;
}
else
{
parsedDexArguments = dex.getDexArguments();
}
}
else
{
parsedJvmArguments = dexJvmArguments;
parsedCoreLibrary = dexCoreLibrary;
parsedNoLocals = dexNoLocals;
parsedOptimize = dexOptimize;
parsedPreDex = dexPreDex;
parsedPreDexLibLocation = dexPreDexLibLocation;
parsedIncremental = dexIncremental;
parsedForceJumbo = dexForceJumbo;
parsedMultiDex = dexMultiDex;
parsedMainDexList = dexMainDexList;
parsedMinimalMainDex = dexMinimalMainDex;
parsedDexArguments = dexArguments;
}
}
private Set< File > preDex( CommandExecutor executor, Set< File > inputFiles ) throws MojoExecutionException
{
Set< File > filtered = new HashSet< File >();
getLog().info( "Pre dex-ing libraries for faster dex-ing of the final application." );
for ( File inputFile : inputFiles )
{
if ( inputFile.getName().matches( ".*\\.jar$" ) )
{
List< String > commands = dexDefaultCommands();
File predexJar = predexJarPath( inputFile );
commands.add( "--output=" + predexJar.getAbsolutePath() );
commands.add( inputFile.getAbsolutePath() );
filtered.add( predexJar );
if ( !predexJar.isFile() || predexJar.lastModified() < inputFile.lastModified() )
{
getLog().info( "Pre-dex ing jar: " + inputFile.getAbsolutePath() );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().debug( javaExecutable + " " + commands.toString() );
try
{
executor.setCaptureStdOut( true );
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
}
}
else
{
filtered.add( inputFile );
}
}
return filtered;
}
private File predexJarPath( File inputFile )
{
final File predexLibsDirectory = new File( parsedPreDexLibLocation.trim() );
predexLibsDirectory.mkdirs();
return new File( predexLibsDirectory, inputFile.getName() );
}
private List< String > dexDefaultCommands() throws MojoExecutionException
{
List< String > commands = new ArrayList< String >();
if ( parsedJvmArguments != null )
{
for ( String jvmArgument : parsedJvmArguments )
{
// preserve backward compatibility allowing argument with or
// without dash (e.g. Xmx512m as well as
// -Xmx512m should work) (see
// http://code.google.com/p/maven-android-plugin/issues/detail?id=153)
if ( !jvmArgument.startsWith( "-" ) )
{
jvmArgument = "-" + jvmArgument;
}
getLog().debug( "Adding jvm argument " + jvmArgument );
commands.add( jvmArgument );
}
}
commands.add( "-jar" );
commands.add( getAndroidSdk().getDxJarPath() );
commands.add( "--dex" );
return commands;
}
private void runDex( CommandExecutor executor, File outputFile )
throws MojoExecutionException
{
final List< String > commands = dexDefaultCommands();
final Set< File > inputFiles = getDexInputFiles();
Set< File > filteredFiles = inputFiles;
if ( parsedPreDex )
{
filteredFiles = preDex( executor, inputFiles );
}
if ( !parsedOptimize )
{
commands.add( "--no-optimize" );
}
if ( parsedCoreLibrary )
{
commands.add( "--core-library" );
}
if ( parsedIncremental )
{
commands.add( "--incremental" );
}
if ( parsedNoLocals )
{
commands.add( "--no-locals" );
}
if ( parsedForceJumbo )
{
commands.add( "--force-jumbo" );
}
if ( parsedMultiDex )
{
commands.add( "--multi-dex" );
if ( parsedMainDexList == null )
{
File generatedMainDexClasses = generateMainDexClassesFile();
commands.add( "--main-dex-list=" + generatedMainDexClasses );
parsedMinimalMainDex = true;
}
else
{
commands.add( "--main-dex-list=" + parsedMainDexList );
}
if ( parsedMinimalMainDex )
{
commands.add( "--minimal-main-dex" );
}
}
if ( parsedDexArguments != null )
{
commands.add( parsedDexArguments );
}
commands.add( "--output=" + outputFile.getAbsolutePath() );
for ( File inputFile : filteredFiles )
{
commands.add( inputFile.getAbsolutePath() );
}
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().debug( javaExecutable + " " + commands.toString() );
getLog().info( "Convert classes to Dex : " + outputFile );
try
{
executor.setCaptureStdOut( true );
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
}
/**
* Figure out the full path to the current java executable.
*
* @return the full path to the current java executable.
*/
private static File getJavaExecutable()
{
final String javaHome = System.getProperty( "java.home" );
final String slash = File.separator;
return new File( javaHome + slash + "bin" + slash + "java" );
}
private File generateMainDexClassesFile() throws MojoExecutionException
{
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( getLog() );
List< String> commands = new ArrayList< String>();
commands.add( "--output" );
File mainDexClasses = new File( targetDirectory, "mainDexClasses.txt" );
commands.add( mainDexClasses.getAbsolutePath() );
Set< File> inputFiles = getDexInputFiles();
StringBuilder sb = new StringBuilder();
sb.append( '"' ).append( StringUtils.join( inputFiles, File.pathSeparatorChar ) ).append( '"' );
commands.add( sb.toString() );
String executable = getAndroidSdk().getMainDexClasses().getAbsolutePath();
try
{
executor.executeCommand( executable, commands, project.getBasedir(), false );
}
catch ( ExecutionException ex )
{
throw new MojoExecutionException( "Failed to execute mainDexClasses", ex );
}
return mainDexClasses;
}
/**
* @return
* @throws MojoExecutionException
*/
protected File createApkSourcesFile() throws MojoExecutionException
{
final File apksources = new File( targetDirectory, finalName
+ ".apksources" );
FileUtils.deleteQuietly( apksources );
try
{
JarArchiver jarArchiver = new JarArchiver();
jarArchiver.setDestFile( apksources );
addDirectory( jarArchiver, assetsDirectory, "assets" );
addDirectory( jarArchiver, resourceDirectory, "res" );
addDirectory( jarArchiver, sourceDirectory, "src/main/java" );
addJavaResources( jarArchiver, resources );
jarArchiver.createArchive();
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "ArchiverException while creating .apksource file.", e );
}
catch ( IOException e )
{
throw new MojoExecutionException( "IOException while creating .apksource file.", e );
}
return apksources;
}
/**
* Makes sure the string ends with "/"
*
* @param prefix
* any string, or null.
* @return the prefix with a "/" at the end, never null.
*/
protected String endWithSlash( String prefix )
{
prefix = StringUtils.defaultIfEmpty( prefix, "/" );
if ( !prefix.endsWith( "/" ) )
{
prefix = prefix + "/";
}
return prefix;
}
/**
* Adds a directory to a {@link JarArchiver} with a directory prefix.
*
* @param jarArchiver
* @param directory
* The directory to add.
* @param prefix
* An optional prefix for where in the Jar file the directory's contents should go.
*/
protected void addDirectory( JarArchiver jarArchiver, File directory, String prefix )
{
if ( directory != null && directory.exists() )
{
final DefaultFileSet fileSet = new DefaultFileSet();
fileSet.setPrefix( endWithSlash( prefix ) );
fileSet.setDirectory( directory );
jarArchiver.addFileSet( fileSet );
}
}
/**
* @param jarArchiver
* @param javaResources
*/
protected void addJavaResources( JarArchiver jarArchiver, List< Resource > javaResources )
{
for ( Resource javaResource : javaResources )
{
addJavaResource( jarArchiver, javaResource );
}
}
/**
* Adds a Java Resources directory (typically "src/main/resources") to a {@link JarArchiver}.
*
* @param jarArchiver
* @param javaResource
* The Java resource to add.
*/
protected void addJavaResource( JarArchiver jarArchiver, Resource javaResource )
{
if ( javaResource != null )
{
final File javaResourceDirectory = new File( javaResource.getDirectory() );
if ( javaResourceDirectory.exists() )
{
final DefaultFileSet javaResourceFileSet = new DefaultFileSet();
javaResourceFileSet.setDirectory( javaResourceDirectory );
javaResourceFileSet.setPrefix( endWithSlash( "src/main/resources" ) );
jarArchiver.addFileSet( javaResourceFileSet );
}
}
}
}
|
package com.tale.exception;
import com.blade.ioc.annotation.Bean;
import com.blade.mvc.WebContext;
import com.blade.mvc.handler.DefaultExceptionHandler;
import com.blade.mvc.ui.RestResponse;
import com.blade.validator.exception.ValidateException;
import lombok.extern.slf4j.Slf4j;
/**
* 全局异常处理
* <p>
* Created by biezhi on 10/07/2017.
*/
@Slf4j
@Bean
public class GolbalExceptionHandler extends DefaultExceptionHandler {
@Override
public void handle(Exception e) {
if (e instanceof ValidateException) {
ValidateException validateException = (ValidateException) e;
String msg = validateException.getErrMsg();
WebContext.response().json(RestResponse.fail(msg));
} else {
super.handle(e);
}
}
}
|
/*
* Copyright (c) 2011-2018, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.abst.feature.associate;
import boofcv.struct.feature.MatchScoreType;
import boofcv.struct.feature.TupleDesc_F64;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Peter Abeles
*/
public class TestScoreAssociateEuclideanSq_F64 extends StandardScoreAssociationChecks<TupleDesc_F64> {
public TestScoreAssociateEuclideanSq_F64() {
super(MatchScoreType.NORM_ERROR);
}
@Override
public ScoreAssociation<TupleDesc_F64> createScore() {
return new ScoreAssociateEuclideanSq_F64();
}
@Override
public TupleDesc_F64 createDescription() {
TupleDesc_F64 a = new TupleDesc_F64(5);
for( int i = 0; i < a.size(); i++ )
a.value[i] = rand.nextDouble()*2;
return a;
}
@Test
public void compareToExpected() {
ScoreAssociateEuclideanSq_F64 score = new ScoreAssociateEuclideanSq_F64();
TupleDesc_F64 a = new TupleDesc_F64(5);
TupleDesc_F64 b = new TupleDesc_F64(5);
a.value=new double[]{1,2,3,4,5};
b.value=new double[]{2,-1,7,-8,10};
assertEquals(195,score.score(a,b),1e-4);
}
}
|
package org.apache.commons.mail;
import junit.framework.TestCase;
import org.junit.Test;
public class TestCase1 extends TestCase{
Email testEmail;
public void setUp() {
testEmail = new SimpleEmail();
}
@Test
public void testAddCc() {
System.out.println("This test class tests the AddCc() function. mjy___");
// tests one parameter call
try {
testEmail.addCc("a@b.com");
} catch (EmailException e) {
fail();
}
assertEquals("a@b.com", testEmail.getCcAddresses().get(0).toString());
}
}
|
package com.tuin.test;
import com.tuin.bean.Rolitemmenu;
public class RolitemmenuFactoryForTest {
private MockValues mockValues = new MockValues();
public Rolitemmenu newRolitemmenu() {
Long id = mockValues.nextLong();
Rolitemmenu rolitemmenu = new Rolitemmenu();
rolitemmenu.setId(id);
return rolitemmenu;
}
}
|
package controllers;
import com.mongodb.BasicDBObject;
import models.Label;
import models.Response;
import models.Service;
import models.User;
import play.Logger;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import views.html.admin;
import java.util.List;
@Security.Authenticated(Secured.class)
public class Admin extends Controller {
public static Result index() {
return ok(admin.render());
}
public static Result indexLabel() {
List<Label> o = Label.collection.find().sort(new BasicDBObject("name",1)).toArray();
return ok(Json.toJson(o));
}
public static Result getLabel(String id) {
try {
Label o = Label.collection.findOneById(id);
return status(202, Json.toJson(o));
} catch (Exception e) {
Logger.error(e.getMessage(), e);
return badRequest(e.getMessage());
}
}
public static Result putLabel() {
try {
Label o = Label.createFromJson(request().body().asJson());
o.update();
return status(202, Json.toJson(o));
} catch (Exception e) {
Logger.error(e.getMessage(), e);
return badRequest(e.getMessage());
}
}
public static Result deleteLabel(String id) {
try {
Label.removeById(id);
return status(202, "Object deleted");
} catch(Exception e) {
Logger.error(e.getMessage(),e);
return badRequest(e.getMessage());
}
}
public static Result indexResponse(int skip) {
return ok(Json.toJson(Response.getPaginatedResponses(skip)));
}
public static Result indexService() {
List<Service> o = Service.collection.find().sort(new BasicDBObject("name",1)).toArray();
return ok(Json.toJson(o));
}
public static Result getService(String id) {
try {
Service o = Service.collection.findOneById(id);
return status(202, Json.toJson(o));
} catch (Exception e) {
Logger.error(e.getMessage(), e);
return badRequest(e.getMessage());
}
}
public static Result putService() {
try {
Service o = Service.createFromJson(request().body().asJson());
o.save();
return status(202, Json.toJson(o));
} catch (Exception e) {
Logger.error(e.getMessage(), e);
return badRequest(e.getMessage());
}
}
public static Result deleteService(String id) {
try {
Service.removeById(id);
return status(202, "Object deleted");
} catch(Exception e) {
Logger.error(e.getMessage(),e);
return badRequest(e.getMessage());
}
}
public static Result changepassword() {
try {
User.changeCurrentUserPassword(request().body().asFormUrlEncoded().get("password")[0]);
} catch(Exception e) {
Logger.error("Error when changing password:"+e.getMessage(),e);
return internalServerError(e.getMessage());
}
return ok("");
}
}
|
/*
* Copyright (c) 2011-2020, hubin (jobob@qq.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.baomidou.mybatisplus.extension.injector.methods;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.injector.LogicAbstractMethod;
/**
* <p>
* 根据 ID 集合删除
* </p>
*
* @author hubin
* @since 2018-06-13
*/
public class LogicDeleteBatchByIds extends LogicAbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
String sql;
SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE_BATCH_BY_IDS;
if (tableInfo.isLogicDelete()) {
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlLogicSet(tableInfo),
tableInfo.getKeyColumn(),
"<foreach item=\"item\" collection=\"coll\" separator=\",\">#{item}</foreach>",
getLogicDeleteSql(true, tableInfo));
} else {
sqlMethod = SqlMethod.DELETE_BATCH_BY_IDS;
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), tableInfo.getKeyColumn(),
"<foreach item=\"item\" collection=\"coll\" separator=\",\">#{item}</foreach>");
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
}
}
|
package cana.codelessautomation.api.resources.globalvariable.service.repositories.daos;
import cana.codelessautomation.api.resources.file.service.repositories.daos.FileDao;
import com.googlecode.jmapper.annotations.JMap;
import lombok.Data;
import javax.persistence.*;
import java.time.OffsetDateTime;
@Data
@Entity
@Table(name = "globalvariable")
public class GlobalVariableDao {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JMap
private String key;
@JMap
private String value;
@JMap
@Enumerated(EnumType.STRING)
private GlobalVariableType valueType;
@JMap
private Long fileId;
@JMap
private OffsetDateTime createdOn;
@JMap
private OffsetDateTime modifiedOn;
@JMap
private String createdBy;
@JMap
private String modifiedBy;
@JMap
private Boolean isActive;
@JMap
private String comments;
@JMap
private Long userId;
@OneToOne(orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "fileId", insertable = false, updatable = false)
private FileDao fileDaos;
}
|
/*
* Copyright 2003-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 jetbrains.mps.openapi.editor.cells.traversal;
import jetbrains.mps.openapi.editor.cells.CellTraversalUtil;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.cells.EditorCell_Collection;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.mps.openapi.util.TreeIterator;
import org.jetbrains.mps.util.Condition;
import org.jetbrains.mps.util.TreeFilterIterator;
import org.junit.Before;
import org.junit.Test;
import java.util.Iterator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CellTreeTraversalTest extends CellTreeTest {
private EditorCell_Collection startA, childB, childF, childI, topX;
private EditorCell leafD, leafE, lastJ, lastY;
private static String traverseWholeTreeFrom(EditorCell cell) {
return traverseSubtreeFrom(null, cell);
}
private static String traverseSubtreeFrom(@Nullable EditorCell root, EditorCell cell) {
return ids(CellTraversalUtil.iterateTree(root, cell, true).iterator());
}
private static String traverseSubtreeWithFilter(EditorCell start, EditorCell filterSubtree) {
return ids(new TreeFilterIterator<>(traverserForSubtree(start), new IsSameAs(filterSubtree)));
}
private static String traverseSubtree(EditorCell start) {
return ids(traverserForSubtree(start));
}
private static String traverseSubtreeSkipping(EditorCell start, EditorCell skipSubtree) {
StringBuilder rv = new StringBuilder();
for (TreeIterator<EditorCell> it = traverserForSubtree(start); it.hasNext(); ) {
EditorCell n = it.next();
if (n == skipSubtree) {
it.skipChildren();
continue;
}
rv.append(n.getCellId());
}
return rv.toString();
}
private static String ids(Iterator<EditorCell> iterator) {
StringBuilder result = new StringBuilder();
while (iterator.hasNext()) {
result.append(iterator.next().getCellId());
}
return result.toString();
}
private static TreeIterator<EditorCell> traverserForSubtree(EditorCell start) {
return CellTraversalUtil.iterateTree(start, start, true).iterator();
}
@Before
public void setUp() {
startA =
newNode("A",
childB = newNode("B",
newNode("C"),
leafD = newNode("D"),
leafE = newNode("E")),
childF = newNode("F",
newNode("G"),
newNode("H")),
childI = newNode("I",
lastJ = newNode("J")));
topX = newNode("X", startA, lastY = newNode("Y"));
}
@Test
public void traverseSubtree_complete() {
assertEquals("ABCDEFGHIJ", traverseSubtree(startA));
}
@Test
public void traverseSubtree_singleElement() {
assertEquals("W", traverseSubtree(newNode("W")));
}
@Test
public void traverseSubtree_skipNonLeaf() {
assertEquals("ABCDEIJ", traverseSubtreeSkipping(startA, childF));
}
@Test
public void traverseSubtree_skipLeafWithoutSibling() {
assertEquals("ABCDFGHIJ", traverseSubtreeSkipping(startA, leafE));
}
@Test
public void traverseSubtree_skipLeafWithSibling() {
assertEquals("ABCEFGHIJ", traverseSubtreeSkipping(startA, leafD));
}
@Test
public void traverseSubtree_skipLastElement() {
assertEquals("ABCDEFGHI", traverseSubtreeSkipping(startA, lastJ));
}
@Test
public void traverseSubtree_skipRoot() {
assertTrue(traverseSubtreeSkipping(startA, startA).isEmpty());
}
@Test
public void traverseSubtree_skipRootOfSingletonTree() {
final EditorCell root = newNode("W");
assertTrue(traverseSubtreeSkipping(root, root).isEmpty());
}
@Test
public void treeFilterIterator_skipNonLeaf() {
assertEquals("ABCDEIJ", traverseSubtreeWithFilter(startA, childF));
}
@Test
public void treeFilterIterator_skipI() {
assertEquals("ABCDEFGH", traverseSubtreeWithFilter(startA, childI));
}
@Test
public void treeFilterIterator_skipStartNode() {
assertEquals("", traverseSubtreeWithFilter(startA, startA));
}
@Test
public void treeFilterIterator_skipLastElement() {
// skip last element (last leaf)
assertEquals("ABCDEFGHI", traverseSubtreeWithFilter(startA, lastJ));
}
@Test
public void treeFilterIterator_skipOutsideNode() {
// skip node which is not from the sub-tree
assertEquals("ABCDEFGHIJ", traverseSubtreeWithFilter(startA, topX));
}
@Test
public void traverseWholeTree_fromLast() {
assertEquals("Y", traverseWholeTreeFrom(lastY));
}
@Test
public void traverseWholeTree_fromBeforeLast() {
assertEquals("JY", traverseWholeTreeFrom(lastJ));
}
@Test
public void traverseWholeTree_fromTop() {
assertEquals("XABCDEFGHIJY", traverseWholeTreeFrom(topX));
}
@Test
public void traverseWholeTree_fromStart() {
assertEquals("ABCDEFGHIJY", traverseWholeTreeFrom(startA));
}
@Test
public void traverseWholeTree_fromMiddle() {
assertEquals("FGHIJY", traverseWholeTreeFrom(childF));
}
@Test
public void traverseWholeTree_fromLeaf() {
assertEquals("DEFGHIJY", traverseWholeTreeFrom(leafD));
}
@Test
public void traverseSubtree_fromStart() {
assertEquals("BCDE", traverseSubtreeFrom(childB, childB));
}
@Test
public void traverseSubtree_fromMiddle() {
assertEquals("DE", traverseSubtreeFrom(childB, leafD));
}
@Test
public void traverseSubtree_fromEnd() {
assertEquals("E", traverseSubtreeFrom(childB, leafE));
}
private static class IsSameAs implements Condition<EditorCell> {
@Nullable
private final EditorCell myCell;
IsSameAs(@Nullable EditorCell cell) {
myCell = cell;
}
@Override
public boolean met(EditorCell object) {
return object == myCell;
}
}
}
|
/* Copyright (c) 2017 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode.MrKTestClasses;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.robotcontroller.external.samples.ConceptVuforiaNavigation;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.RelicRecoveryVuMark;
import org.firstinspires.ftc.robotcore.external.navigation.VuMarkInstanceId;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackableDefaultListener;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
/**
* This OpMode illustrates the basics of using the Vuforia engine to determine
* the identity of Vuforia VuMarks encountered on the field. The code is structured as
* a LinearOpMode. It shares much structure with {@link ConceptVuforiaNavigation}; we do not here
* duplicate the core Vuforia documentation found there, but rather instead focus on the
* differences between the use of Vuforia for navigation vs VuMark identification.
*
* @see ConceptVuforiaNavigation
* @see VuforiaLocalizer
* @see VuforiaTrackableDefaultListener
* see ftc_app/doc/tutorial/FTC_FieldCoordinateSystemDefinition.pdf
*
* Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list.
*
* IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as
* is explained in {@link ConceptVuforiaNavigation}.
*/
@Autonomous(name="Concept: VuMark Id", group ="Concept")
@Disabled
public class TeamVuMarkIdentification extends LinearOpMode {
public static final String TAG = "Vuforia VuMark Sample";
OpenGLMatrix lastLocation = null;
/**
* {@link #vuforia} is the variable we will use to store our instance of the Vuforia
* localization engine.
*/
VuforiaLocalizer vuforia;
@Override public void runOpMode() {
/*
* To start up Vuforia, tell it the view that we wish to use for camera monitor (on the RC phone);
* If no camera monitor is desired, use the parameterless constructor instead (commented out below).
*/
int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId);
// OR... Do Not Activate the Camera Monitor View, to save power
// VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters();
/*
* IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which
* 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.
* A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web site
* and paste it in to your code onthe next line, between the double quotes.
*/
parameters.vuforiaLicenseKey = "AaEsIgD/////AAAAGf7G3beYiEb/llSsLcn8lzUMBhI0WuYTapubA+LFQT4RPEXolykiR+ZMtgfmkH6+armWs/YLoCcuKoJ+Xf7V7AiXxY4aI7fZu9B81ZSC6YZdRNqoAT/UEpKSLWGDHb0zymC3VWqCAoPl2EiTf9R582ZusDVozo04fFJZO+23k9ANRbrXYeT+RAoyFUVtx3tNXfEK+s58ArfqXalvANaV8PYJ7yVoX+sbAihL9TvYMclsbK9oj7gxUKjRX2KKWS6rbcpU30yukhZ0zvKyZyrQK0OB+NHzUnEWGjG6kNwYZteZ9JglqUcGD/3hNBX4JLqr5nJt1bgIZrPHt3Be/Isy9IVR+isGSDbgNPIIEh2aBWvH";
/*
* We also indicate which camera on the RC that we wish to use.
* Here we chose the back (HiRes) camera (for greater range), but
* for a competition robot, the front camera might be more convenient.
*/
parameters.cameraDirection = VuforiaLocalizer.CameraDirection. FRONT;
this.vuforia = ClassFactory.createVuforiaLocalizer(parameters);
/**
* Load the data set containing the VuMarks for Relic Recovery. There's only one trackable
* in this data set: all three of the VuMarks in the game were created from this one template,
* but differ in their instance id information.
* @see VuMarkInstanceId
*/
VuforiaTrackables relicTrackables = this.vuforia.loadTrackablesFromAsset("RelicVuMark");
VuforiaTrackable relicTemplate = relicTrackables.get(0);
relicTemplate.setName("relicVuMarkTemplate"); // can help in debugging; otherwise not necessary
telemetry.addData(">", "Press Play to start");
telemetry.update();
waitForStart();
relicTrackables.activate();
while (opModeIsActive()) {
/**
* See if any of the instances of {@link relicTemplate} are currently visible.
* {@link RelicRecoveryVuMark} is an enum which can have the following values:
* UNKNOWN, LEFT, CENTER, and RIGHT. When a VuMark is visible, something other than
* UNKNOWN will be returned by {@link RelicRecoveryVuMark#from(VuforiaTrackable)}.
*/
RelicRecoveryVuMark vuMark = RelicRecoveryVuMark.from(relicTemplate);
if (vuMark != RelicRecoveryVuMark.UNKNOWN) {
/* Found an instance of the template. In the actual game, you will probably
* loop until this condition occurs, then move on to act accordingly depending
* on which VuMark was visible. */
telemetry.addData("VuMark", "%s visible", vuMark);
/* For fun, we also exhibit the navigational pose. In the Relic Recovery game,
* it is perhaps unlikely that you will actually need to act on this pose information, but
* we illustrate it nevertheless, for completeness. */
OpenGLMatrix pose = ((VuforiaTrackableDefaultListener)relicTemplate.getListener()).getPose();
telemetry.addData("Pose", format(pose));
/* We further illustrate how to decompose the pose into useful rotational and
* translational components */
if (pose != null) {
VectorF trans = pose.getTranslation();
Orientation rot = Orientation.getOrientation(pose, AxesReference.EXTRINSIC, AxesOrder.XYZ, AngleUnit.DEGREES);
// Extract the X, Y, and Z components of the offset of the target relative to the robot
double tX = trans.get(0);
double tY = trans.get(1);
double tZ = trans.get(2);
// Extract the rotational components of the target relative to the robot
double rX = rot.firstAngle;
double rY = rot.secondAngle;
double rZ = rot.thirdAngle;
}
}
else {
telemetry.addData("VuMark", "not visible");
}
telemetry.update();
}
}
String format(OpenGLMatrix transformationMatrix) {
return (transformationMatrix != null) ? transformationMatrix.formatAsTransform() : "null";
}
}
|
package module1775_public.a;
import java.util.logging.*;
import java.util.zip.*;
import javax.annotation.processing.*;
/**
* Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
* labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
* Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
*
* @see javax.net.ssl.ExtendedSSLSession
* @see javax.rmi.ssl.SslRMIClientSocketFactory
* @see java.awt.datatransfer.DataFlavor
*/
@SuppressWarnings("all")
public interface IFoo2<I> extends module1775_public.a.IFoo0<I> {
java.beans.beancontext.BeanContext f0 = null;
java.io.File f1 = null;
java.rmi.Remote f2 = null;
String getName();
void setName(String s);
I get();
void set(I e);
}
|
/*
* Copyright 2015-2020 The OpenZipkin 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 zipkin2;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
/**
* This captures a (usually remote) request and can be used once, either {@link #execute()
* synchronously} or {@link #enqueue(Callback) asynchronously}. At any time, from any thread, you
* can call {@linkplain #cancel()}, which might stop an in-flight request or prevent one from
* occurring.
*
* <p>Implementations should prepare a call such that there's little or no likelihood of late
* runtime exceptions. For example, if the call is to get a trace, the call to {@code listSpans}
* should propagate input errors vs delay them until a call to {@linkplain #execute()} or
* {@linkplain #enqueue(Callback)}.
*
* <p>Ex.
* <pre>{@code
* // Any translation of an input request to remote parameters should happen here, and any related
* // errors should propagate here.
* Call<List<List<Span>>> listTraces = spanStore.listTraces(request);
* // When this executes, it should simply run the remote request.
* List<Span> trace = getTraceCall.execute();
* }</pre>
*
* <p>An instance of call cannot be invoked more than once, but you can {@linkplain #clone()} an
* instance if you need to replay the call. There is no relationship between a call and a number of
* remote requests. For example, an implementation that stores spans may make hundreds of remote
* requests, possibly retrying on your behalf.
*
* <p>This type owes its design to {@code retrofit2.Call}, which is nearly the same, except limited
* to HTTP transports.
*
* @param <V> the success type, typically not null except when {@code V} is {@linkplain Void}.
*/
public abstract class Call<V> implements Cloneable {
/**
* Returns a completed call which has the supplied value. This is useful when input parameters
* imply there's no call needed. For example, an empty input might always result in an empty
* output.
*/
public static <V> Call<V> create(V v) {
return new Constant<V>(v);
}
@SuppressWarnings("unchecked")
public static <T> Call<List<T>> emptyList() {
return Call.create(Collections.<T>emptyList());
}
public interface Mapper<V1, V2> {
V2 map(V1 input);
}
/**
* Maps the result of this call into a different shape, as defined by the {@code mapper} function.
* This is used to convert values from one type to another. For example, you could use this to
* convert between zipkin v1 and v2 span format.
*
* <pre>{@code
* getTracesV1Call = getTracesV2Call.map(traces -> v2TracesConverter);
* }</pre>
*
* <p>This method intends to be used for chaining. That means "this" instance should be discarded
* in favor of the result of this method.
*/
public final <R> Call<R> map(Mapper<V, R> mapper) {
return new Mapping<R, V>(mapper, this);
}
public interface FlatMapper<V1, V2> {
Call<V2> map(V1 input);
}
/**
* Maps the result of this call into another, as defined by the {@code flatMapper} function. This
* is used to chain two remote calls together. For example, you could use this to chain a list IDs
* call to a get by IDs call.
*
* <pre>{@code
* getTracesCall = getIdsCall.flatMap(ids -> getTraces(ids));
*
* // this would now invoke the chain
* traces = getTracesCall.enqueue(tracesCallback);
* }</pre>
*
* Cancelation propagates to the mapped call.
*
* <p>This method intends to be used for chaining. That means "this" instance should be discarded
* in favor of the result of this method.
*/
public final <R> Call<R> flatMap(FlatMapper<V, R> flatMapper) {
return new FlatMapping<R, V>(flatMapper, this);
}
public interface ErrorHandler<V> {
/** Attempts to resolve an error. The user must call the callback. */
void onErrorReturn(Throwable error, Callback<V> callback);
}
/**
* Returns a call which can attempt to resolve an exception. This is useful when a remote call
* returns an error when a resource is not found.
*
* <p>Here's an example of coercing 404 to empty:
* <pre>{@code
* call.handleError((error, callback) -> {
* if (error instanceof HttpException && ((HttpException) error).code == 404) {
* callback.onSuccess(Collections.emptyList());
* } else {
* callback.onError(error);
* }
* });
* }</pre>
*/
public final Call<V> handleError(ErrorHandler<V> errorHandler) {
return new ErrorHandling<V>(errorHandler, this);
}
// Taken from RxJava throwIfFatal, which was taken from scala
public static void propagateIfFatal(Throwable t) {
if (t instanceof VirtualMachineError) {
throw (VirtualMachineError) t;
} else if (t instanceof ThreadDeath) {
throw (ThreadDeath) t;
} else if (t instanceof LinkageError) {
throw (LinkageError) t;
}
}
/**
* Invokes a request, returning a success value or propagating an error to the caller. Invoking
* this more than once will result in an error. To repeat a call, make a copy with {@linkplain
* #clone()}.
*
* <p>Eventhough this is a blocking call, implementations may honor calls to {@linkplain
* #cancel()} from a different thread.
*
* @return a success value. Null is unexpected, except when {@code V} is {@linkplain Void}.
*/
public abstract V execute() throws IOException;
/**
* Invokes a request asynchronously, signaling the {@code callback} when complete. Invoking this
* more than once will result in an error. To repeat a call, make a copy with {@linkplain
* #clone()}.
*/
public abstract void enqueue(Callback<V> callback);
/**
* Requests to cancel this call, even if some implementations may not support it. For example, a
* blocking call is sometimes not cancelable.
*/
// Boolean isn't returned because some implementations may cancel asynchronously.
// Implementing might throw an IOException on execute or callback.onError(IOException)
public abstract void cancel();
/**
* Returns true if {@linkplain #cancel()} was called.
*
* <p>Calls can fail before being canceled, so true does always mean cancelation caused a call to
* fail. That said, successful cancellation does result in a failure.
*/
// isCanceled exists while isExecuted does not because you do not need the latter to implement
// asynchronous bindings, such as rxjava2
public abstract boolean isCanceled();
/** Returns a copy of this object, so you can make an identical follow-up request. */
@Override public abstract Call<V> clone();
static class Constant<V> extends Base<V> { // not final for mock testing
final V v;
Constant(V v) {
this.v = v;
}
@Override protected V doExecute() {
return v;
}
@Override protected void doEnqueue(Callback<V> callback) {
callback.onSuccess(v);
}
@Override public Call<V> clone() {
return new Constant<V>(v);
}
@Override public String toString() {
return "ConstantCall{value=" + v + "}";
}
@Override public boolean equals(Object o) {
if (o == this) return true;
if (o instanceof Constant) {
Constant that = (Constant) o;
return ((this.v == null) ? (that.v == null) : this.v.equals(that.v));
}
return false;
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= (v == null) ? 0 : v.hashCode();
return h;
}
}
static final class Mapping<R, V> extends Base<R> {
final Mapper<V, R> mapper;
final Call<V> delegate;
Mapping(Mapper<V, R> mapper, Call<V> delegate) {
this.mapper = mapper;
this.delegate = delegate;
}
@Override protected R doExecute() throws IOException {
return mapper.map(delegate.execute());
}
@Override protected void doEnqueue(final Callback<R> callback) {
delegate.enqueue(new Callback<V>() {
@Override public void onSuccess(V value) {
try {
callback.onSuccess(mapper.map(value));
} catch (Throwable t) {
callback.onError(t);
}
}
@Override public void onError(Throwable t) {
callback.onError(t);
}
});
}
@Override public String toString() {
return "Mapping{call=" + delegate + ", mapper=" + mapper + "}";
}
@Override public Call<R> clone() {
return new Mapping<R, V>(mapper, delegate.clone());
}
}
static final class FlatMapping<R, V> extends Base<R> {
final FlatMapper<V, R> flatMapper;
final Call<V> delegate;
volatile Call<R> mapped;
FlatMapping(FlatMapper<V, R> flatMapper, Call<V> delegate) {
this.flatMapper = flatMapper;
this.delegate = delegate;
}
@Override protected R doExecute() throws IOException {
return (mapped = flatMapper.map(delegate.execute())).execute();
}
@Override protected void doEnqueue(final Callback<R> callback) {
delegate.enqueue(new Callback<V>() {
@Override public void onSuccess(V value) {
try {
(mapped = flatMapper.map(value)).enqueue(callback);
} catch (Throwable t) {
propagateIfFatal(t);
callback.onError(t);
}
}
@Override public void onError(Throwable t) {
callback.onError(t);
}
});
}
@Override protected void doCancel() {
delegate.cancel();
if (mapped != null) mapped.cancel();
}
@Override public String toString() {
return "FlatMapping{call=" + delegate + ", flatMapper=" + flatMapper + "}";
}
@Override public Call<R> clone() {
return new FlatMapping<R, V>(flatMapper, delegate.clone());
}
}
static final class ErrorHandling<V> extends Base<V> {
static final Object SENTINEL = new Object(); // to differentiate from null
final ErrorHandler<V> errorHandler;
final Call<V> delegate;
ErrorHandling(ErrorHandler<V> errorHandler, Call<V> delegate) {
this.errorHandler = errorHandler;
this.delegate = delegate;
}
@Override protected V doExecute() throws IOException {
try {
return delegate.execute();
} catch (IOException e) {
return handleError(e);
} catch (RuntimeException e) {
return handleError(e);
} catch (Error e) {
Call.propagateIfFatal(e);
return handleError(e);
}
}
<T extends Throwable> V handleError(T e) throws T {
final AtomicReference ref = new AtomicReference(SENTINEL);
errorHandler.onErrorReturn(e, new Callback<V>() {
@Override
public void onSuccess(V value) {
ref.set(value);
}
@Override
public void onError(Throwable t) {
}
});
Object result = ref.get();
if (SENTINEL == result) throw e;
return (V) result;
}
@Override protected void doEnqueue(final Callback<V> callback) {
delegate.enqueue(new Callback<V>() {
@Override public void onSuccess(V value) {
callback.onSuccess(value);
}
@Override public void onError(Throwable t) {
errorHandler.onErrorReturn(t, callback);
}
});
}
@Override protected void doCancel() {
delegate.cancel();
}
@Override public String toString() {
return "ErrorHandling{call=" + delegate + ", errorHandler=" + errorHandler + "}";
}
@Override public Call<V> clone() {
return new ErrorHandling<V>(errorHandler, delegate.clone());
}
}
public static abstract class Base<V> extends Call<V> {
volatile boolean canceled;
boolean executed;
protected Base() {
}
@Override public final V execute() throws IOException {
synchronized (this) {
if (this.executed) throw new IllegalStateException("Already Executed");
this.executed = true;
}
if (isCanceled()) {
throw new IOException("Canceled");
} else {
return this.doExecute();
}
}
protected abstract V doExecute() throws IOException;
@Override public final void enqueue(Callback<V> callback) {
synchronized (this) {
if (this.executed) throw new IllegalStateException("Already Executed");
this.executed = true;
}
if (isCanceled()) {
callback.onError(new IOException("Canceled"));
} else {
this.doEnqueue(callback);
}
}
protected abstract void doEnqueue(Callback<V> callback);
@Override public final void cancel() {
this.canceled = true;
doCancel();
}
protected void doCancel() {
}
@Override public final boolean isCanceled() {
return this.canceled || doIsCanceled();
}
protected boolean doIsCanceled() {
return false;
}
}
}
|
package de.buw.tmdt.plasma.services.kgs.database.neo4j;
import de.buw.tmdt.plasma.services.kgs.database.api.GraphDBDriver;
import de.buw.tmdt.plasma.services.kgs.shared.model.knowledgegraph.RelationConcept;
import de.buw.tmdt.plasma.services.kgs.TestApplication;
import de.buw.tmdt.plasma.services.kgs.database.api.exception.ConceptNameAlreadyExistsException;
import de.buw.tmdt.plasma.services.kgs.database.api.exception.NoElementForIDException;
import de.buw.tmdt.plasma.utilities.collections.ArrayUtilities;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(classes = TestApplication.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class RelationConceptITCase extends Neo4jEnvironment {
private static final String DATABASE_RC_EXAMPLE = "relationconcepts.dump";
@Autowired
private GraphDBDriverFactoryImpl graphDBDriverFactoryImpl;
@Autowired
private GraphDBTestDriverFactoryImpl graphDBTestDriverFactoryImpl;
private GraphDBDriver testee;
@BeforeAll
void beforeAll() {
graphDBTestDriverFactoryImpl.clearDatabase(); //ensure that all tests start with a clean database
testee = graphDBDriverFactoryImpl.getGraphDBDriver(); //initialize the testee
}
@AfterEach
void afterEach() {
graphDBTestDriverFactoryImpl.clearDatabase(); //cleanup after all tests
}
@AfterAll
void afterAll() {
graphDBTestDriverFactoryImpl.clearDatabase(); //cleanup after all tests
graphDBDriverFactoryImpl.closeDriver();
}
@Test
void testRetrieveRelationConceptsWithEmptyPrefix() {
graphDBTestDriverFactoryImpl.getGraphDBTestDriver().loadDatabaseDump(DATABASE_RC_EXAMPLE);
Set<RelationConcept> actual = testee.retrieveRelationConceptsByPrefix("");
assertEquals(5, actual.size());
final Set<String> expectedNames = new HashSet<>(Arrays.asList("paints", "leads", "produces", "presents", "likes"));
final Set<String> actualNames = actual.stream().map(RelationConcept::getLabel).collect(Collectors.toSet());
assertEquals(expectedNames, actualNames);
}
@Test
void testRetrieveCreatedRelationConcept() {
Set<RelationConcept.Property> properties = ArrayUtilities.toCollection(
HashSet::new, RelationConcept.Property.REFLEXIVE, RelationConcept.Property.SYMMETRIC
);
RelationConcept rc = new RelationConcept("relationConceptID", "newRelationConcept", "relationConceptDescription", properties);
RelationConcept createdRelationConcept = testee.createRelationConcept(rc);
//Validate that label, description and properties are valid and that it starts with an RC ID
assertEquals(createdRelationConcept.getLabel(), rc.getLabel());
assertEquals(createdRelationConcept.getDescription(), rc.getDescription());
assertEquals(createdRelationConcept.getProperties(), rc.getProperties());
assertTrue(createdRelationConcept.getId().startsWith(Neo4JModel.RelationConcept.ID_PREFIX));
//try to retrieve RelationConcept with created ID and compare it to the created one
RelationConcept retrievedNewRelationConcept = testee.retrieveRelationConcept(createdRelationConcept.getId());
assertNotNull(retrievedNewRelationConcept);
assertEquals(retrievedNewRelationConcept, createdRelationConcept);
}
@Test
void testRetrieveNonExistentRelationConcept() {
assertThrows(NoElementForIDException.class, () -> testee.retrieveRelationConcept("nonExistentID"));
}
@Test
void testFindRelationConceptByName() {
graphDBTestDriverFactoryImpl.getGraphDBTestDriver().loadDatabaseDump(DATABASE_RC_EXAMPLE);
RelationConcept expectedRelationConcept = new RelationConcept("1", "presents", "Give an exhibition of to an interested audience", new HashSet<>());
Set<RelationConcept> expected = new HashSet<>();
expected.add(expectedRelationConcept);
Set<RelationConcept> actual = testee.retrieveRelationConceptsContainingString("presents");
assertEquals(expected, actual);
}
@Test
void testRelationConceptCreationWithDescriptions() {
RelationConcept rc = new RelationConcept("relationConceptID", "testConcept", "", "kg:rc1", null);
RelationConcept rcWith = new RelationConcept("relationConceptID", "testConcept", "myTestDescription is fancy", "kg:rc2", null);
RelationConcept createdRelationConcept = testee.createRelationConcept(rc);
//Validate that main label, description are valid and that it starts with an EC ID
assertEquals(rc.getLabel(), createdRelationConcept.getLabel());
assertEquals(rc.getDescription(), createdRelationConcept.getDescription());
RelationConcept createdRelationConceptWith = testee.createRelationConcept(rcWith);
assertEquals(rcWith.getLabel(), createdRelationConceptWith.getLabel());
assertEquals(rcWith.getDescription(), createdRelationConceptWith.getDescription());
}
@Test
void testRelationConceptCreationTwice() {
RelationConcept rc = new RelationConcept("relationConceptID", "testConcept", "desc", null);
RelationConcept createdRelationConcept = testee.createRelationConcept(rc);
assertEquals(rc.getLabel(), createdRelationConcept.getLabel());
assertEquals(rc.getDescription(), createdRelationConcept.getDescription());
assertThrows(ConceptNameAlreadyExistsException.class, () -> testee.createRelationConcept(new RelationConcept("", "testConcept", "desc", null)));
}
}
|
package cityguide.geocoder.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import cityguide.geocoder.config.RestServerConfig;
import cityguide.geocoder.dto.AddressDto;
@ExtendWith(MockitoExtension.class)
class DataStorageRestControllerTest {
@Mock
private RestTemplate restTemplate;
private static RestServerConfig restServerConfig;
@BeforeAll
static void setUp() {
restServerConfig = new RestServerConfig();
restServerConfig.setUrl("http://test.com/");
restServerConfig.setShowplacesUri("showplaces");
}
@Test
void shouldThrowExceptionThenResponseNotOkForGetAllAddresses() {
ResponseEntity<AddressDto[]> response = new ResponseEntity<AddressDto[]>((AddressDto[]) null, HttpStatus.BAD_REQUEST);
Mockito.when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(), eq(AddressDto[].class)))
.thenReturn(response);
final var restController = new DataStorageRestControllerImpl(restTemplate, restServerConfig);
assertThatThrownBy(restController::getAddresses).isInstanceOf(GeoCoderRestControllerException.class);
}
@Test
void whenGetAddressesShouldReturnAddressesList() {
final var result = new AddressDto[] { new AddressDto(), new AddressDto() };
final var response = new ResponseEntity<>(result, HttpStatus.OK);
Mockito.when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(), eq(AddressDto[].class)))
.thenReturn(response);
final var restController = new DataStorageRestControllerImpl(restTemplate, restServerConfig);
final var addressList = restController.getAddresses();
assertThat(addressList.toArray()).isEqualTo(result);
}
@Test
void whenGetAddressesShouldReturnEmptySize() {
final var response = new ResponseEntity<>((AddressDto[]) null, HttpStatus.OK);
Mockito.when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(), eq(AddressDto[].class)))
.thenReturn(response);
final var restController = new DataStorageRestControllerImpl(restTemplate, restServerConfig);
final var addressList = restController.getAddresses();
assertThat(addressList.toArray()).isEmpty();
}
@Test
void testSendAddresses() {
final ResponseEntity<String> response = new ResponseEntity<>("", HttpStatus.OK);
Mockito.when(restTemplate.exchange(anyString(), eq(HttpMethod.POST), any(), eq(String.class)))
.thenReturn(response);
final var restController = new DataStorageRestControllerImpl(restTemplate, restServerConfig);
final var addressDto = new AddressDto();
restController.sendAddress(addressDto);
HttpEntity<?> entity = new HttpEntity<>(addressDto);
Mockito.verify(restTemplate).exchange(anyString(), eq(HttpMethod.POST), eq(entity), eq(String.class));
}
@Test
void shouldThrowExceptionThenResponseNotOkForSendData() {
final ResponseEntity<String> response = new ResponseEntity<>("", HttpStatus.BAD_REQUEST);
Mockito.when(restTemplate.exchange(anyString(), eq(HttpMethod.POST), any(), eq(String.class)))
.thenReturn(response);
final var restController = new DataStorageRestControllerImpl(restTemplate, restServerConfig);
assertThatThrownBy(() -> restController.sendAddress(new AddressDto()))
.isInstanceOf(GeoCoderRestControllerException.class);
}
}
|
package uk.yetanother.conrec.testutils;
import uk.yetanother.conrec.domain.ContourLine;
import uk.yetanother.conrec.domain.ContourPolygon;
import uk.yetanother.conrec.domain.Coordinate;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.Set;
class ContourDisplayComponent extends JComponent {
ArrayList<Line2D.Double> lines = new ArrayList<>();
ArrayList<Path2D.Double> polygons = new ArrayList<>();
ContourDisplayComponent(int width, int height) {
super();
setPreferredSize(new Dimension(width, height));
}
public void addLines(Set<ContourLine> contours) {
for (ContourLine contourLine : contours) {
lines.add(new Line2D.Double(contourLine.getStart().getX(), contourLine.getStart().getY(),
contourLine.getEnd().getX(), contourLine.getEnd().getY()));
}
repaint();
}
public void addPolygons(Set<ContourPolygon> polygons) {
for (ContourPolygon polygon : polygons) {
Path2D.Double path = new Path2D.Double();
path.moveTo(polygon.getPoints().get(0).getX(), polygon.getPoints().get(0).getY());
for (Coordinate point : polygon.getPoints()) {
path.lineTo(point.getX(), point.getY());
}
this.polygons.add(path);
}
repaint();
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
Dimension d = getPreferredSize();
g.setColor(Color.black);
for (Line2D.Double line : lines) {
g.drawLine(
(int) line.getX1(),
(int) line.getY1(),
(int) line.getX2(),
(int) line.getY2()
);
}
for (Path2D.Double polygon : polygons) {
g2.draw(polygon);
}
}
}
|
/*
* Copyright (c) 2002-2020, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* https://opensource.org/licenses/BSD-3-Clause
*/
package org.jline.console;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.jline.reader.Completer;
import org.jline.reader.LineReader;
import org.jline.reader.Widget;
/**
* Manage console variables, commands and script executions.
*
* @author <a href="mailto:matti.rintanikkola@gmail.com">Matti Rinta-Nikkola</a>
*/
public interface ConsoleEngine extends CommandRegistry {
/**
* Removes the command name first character if it is colon
* @param command the name of the command to complete
* @return command name without starting colon
*/
static String plainCommand(String command) {
return command.startsWith(":") ? command.substring(1) : command;
}
/**
* Sets lineReader
* @param reader LineReader
*/
void setLineReader(LineReader reader);
/**
* Sets systemRegistry
* @param systemRegistry SystemRegistry
*/
void setSystemRegistry(SystemRegistry systemRegistry);
/**
* Substituting args references with their values.
* @param args the arguments to be expanded
* @return expanded arguments
* @throws Exception in case of error
*/
Object[] expandParameters(String[] args) throws Exception;
/**
* Substitutes command line with system registry invoke method call.
* @param line command line to be expanded
* @return expanded command line
*/
String expandCommandLine(String line);
/**
* Expands parameter list to string
* @param params list of script parameters
* @return expanded parameters list
*/
String expandToList(List<String> params);
/**
* Returns all scripts found from PATH
* @return map keys have script file names and value is true if it is console script
*/
Map<String, Boolean> scripts();
/**
* Sets file name extension used by console scripts
* @param extension console script file extension
*/
void setScriptExtension(String extension);
/**
* Returns true if alias 'name' exists
* @param name alias name
* @return true if alias exists
*/
boolean hasAlias(String name);
/**
* Returns alias 'name' value
* @param name alias name
* @return value of alias
*/
String getAlias(String name);
/**
* Returns defined pipes
* @return map of defined pipes
*/
Map<String,List<String>> getPipes();
/**
* Returns named pipe names
* @return list of named pipe names
*/
List<String> getNamedPipes();
/**
* Returns script and variable completers
* @return script and variable completers
*/
List<Completer> scriptCompleters();
/**
* Persist object to file
* @param file file where object should be written
* @param object object to persist
*/
void persist(Path file, Object object);
/**
* Read object from file
* @param file file from where object should be read
* @return object
* @throws IOException in case of error
*/
Object slurp(Path file) throws IOException;
/**
* Read console option value
* @param <T> option type
* @param option option name
* @param defval default value
* @return option value
*/
<T>T consoleOption(String option, T defval);
/**
* Executes command line that does not contain known command by the system registry.
* If the line is neither JLine or ScriptEngine script it will be evaluated
* as ScriptEngine statement.
* @param name parsed command/script name
* @param rawLine raw command line
* @param args parsed arguments of the command
* @return command line execution result
* @throws Exception in case of error
*/
Object execute(String name, String rawLine, String[] args) throws Exception;
/**
* Executes either JLine or ScriptEngine script.
* @param script script file
* @return script execution result
* @throws Exception in case of error
*/
default Object execute(File script) throws Exception {
return execute(script, "", new String[0]);
}
/**
* Executes either JLine or ScriptEngine script.
* @param script script file
* @param rawLine raw command line
* @param args script arguments
* @return script execution result
* @throws Exception in case of error
*/
Object execute(File script, String rawLine, String[] args) throws Exception;
/**
* Post processes execution result. If result is to be assigned to the console variable
* then method will return null.
* @param line command line
* @param result command result to process
* @param output command redirected output
* @return processed result
*/
ExecutionResult postProcess(String line, Object result, String output);
/**
* Post processes execution result.
* @param result command result to process
* @return processed result
*/
ExecutionResult postProcess(Object result);
/**
* @param object object to print
*/
void trace(Object object);
/**
* Print object.
* @param object object to print
*/
void println(Object object);
/**
* Create console variable
* @param name name of the variable
* @param value value of the variable
*/
void putVariable(String name, Object value);
/**
* Get variable value
* @param name name of the variable
* @return variable value
*/
Object getVariable(String name);
/**
* Test if variable with name exists
* @param name name of the variable
* @return true if variable with name exists
*/
boolean hasVariable(String name);
/**
* Delete temporary console variables
*/
void purge();
/**
* Execute widget function
* @param function to execute
* @return true on success
*/
boolean executeWidget(Object function);
/**
*
* @return true if consoleEngine is executing script
*/
boolean isExecuting();
class ExecutionResult {
final int status;
final Object result;
public ExecutionResult(int status, Object result) {
this.status = status;
this.result = result;
}
public int status() {
return status;
}
public Object result() {
return result;
}
}
class WidgetCreator implements Widget {
private final ConsoleEngine consoleEngine;
private final Object function;
private final String name;
public WidgetCreator(ConsoleEngine consoleEngine, String function) {
this.consoleEngine = consoleEngine;
this.name = function;
this.function = consoleEngine.getVariable(function);
}
@Override
public boolean apply() {
return consoleEngine.executeWidget(function);
}
@Override
public String toString() {
return name;
}
}
}
|
package com.quorum.tessera.api;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import jakarta.xml.bind.annotation.XmlInlineBinaryData;
import java.util.Optional;
/**
* Model representation of a JSON body on incoming HTTP requests
*
* <p>Used when a new raw transaction is to be created where this node is the sender
*/
public class StoreRawRequest {
@Schema(
description = "data to be encrypted and stored",
required = true,
type = "string",
format = "base64")
@Size(min = 1)
@NotNull
@XmlInlineBinaryData
private byte[] payload;
@Schema(
description =
"public key identifying the key pair that will be used in the encryption; if not set, default used",
type = "string",
format = "base64")
@XmlInlineBinaryData
private byte[] from;
@XmlInlineBinaryData
public byte[] getPayload() {
return payload;
}
public void setPayload(byte[] payload) {
this.payload = payload;
}
public Optional<byte[]> getFrom() {
return Optional.ofNullable(from);
}
public void setFrom(byte[] from) {
this.from = from;
}
}
|
package com.example.android.sunshine;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TEXT = "text";
private int prefsMesto;
private DBHelper dbh;
private SimpleDateFormat sdf;
private CustomCursorAdapter myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setElevation(0);
dbh = new DBHelper(this);
sdf = new SimpleDateFormat("dd-MM-yyyy");
PripojAdapter();
}
// pridelenie menu
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_pocasie, menu);
return true;
}
// položky menu
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.pocasie_pridaj:
startActivityForResult(new Intent(this, PridajPocasie.class), 1);
return true;
case R.id.mesto_zmen:
startActivityForResult(new Intent(this, MestoZmen.class), 2);
return true;
case R.id.pocasie_about:
Toast.makeText(getBaseContext(), "Made by Ľudovít Laca", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// nastaví počasie na úvodnej obrazovke
private void UvodnaObrazovka() {
Calendar c = Calendar.getInstance();
String date = sdf.format(c.getTime());
Pocasie p = dbh.getPocasie(date, "" + prefsMesto);
if (p == null) {
TextView uvodDatum = (TextView) findViewById(R.id.uvod_datum);
TextView uvodPredpoved = (TextView) findViewById(R.id.uvod_predpoved);
TextView uvodStupen = (TextView) findViewById(R.id.uvod_stupen);
ImageView uvodImage = (ImageView) findViewById(R.id.uvod_image);
uvodDatum.setText("Pridajte počasie na dneska :)");
uvodPredpoved.setText("");
uvodStupen.setText("");
uvodImage.setImageResource(0);
} else {
Mesto m = dbh.getMesto(p.getID_mesto());
TextView uvodDatum = (TextView) findViewById(R.id.uvod_datum);
TextView uvodPredpoved = (TextView) findViewById(R.id.uvod_predpoved);
TextView uvodStupen = (TextView) findViewById(R.id.uvod_stupen);
ImageView uvodImage = (ImageView) findViewById(R.id.uvod_image);
uvodDatum.setText("Today, " + m.getNazov());
uvodPredpoved.setText(p.getPredpoved());
uvodStupen.setText(p.getStupen() + "°");
myAdapter.predpoved(p.getPredpoved(), uvodImage);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String novyDatum = data.getStringExtra("novyDatum");
String novaPredpoved = data.getStringExtra("novaPredpoved");
String novyStupen = data.getStringExtra("novyStupen");
int idNoveMesto = data.getIntExtra("idNoveMesto", 1);
Pocasie newPocasie = new Pocasie(1, novyDatum, novaPredpoved, novyStupen, idNoveMesto);
dbh.addPocasie(newPocasie);
PripojAdapter();
}
break;
case 2:
if (resultCode == RESULT_OK) {
int noveIdMesto = data.getIntExtra("idMesto", 1);
saveData(noveIdMesto);
loadData();
PripojAdapter();
} else {
PripojAdapter();
}
break;
case 3:
PripojAdapter();
break;
}
}
private void PripojAdapter() {
loadData();
Cursor myCursor = dbh.VratKurzor(prefsMesto);
myAdapter = new CustomCursorAdapter(this, myCursor, 0);
UvodnaObrazovka();
ListView lvItems = (ListView) findViewById(R.id.listView);
lvItems.setAdapter(myAdapter);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(myAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListView lv = (ListView) findViewById(R.id.listView);
Cursor cursor = ((CustomCursorAdapter) lv.getAdapter()).getCursor();
cursor.moveToPosition(position);
int ID = cursor.getInt(cursor.getColumnIndex(MyContrast.Pocasie.COLUMN_ID));
// ukáže detaily počasia
Intent newIntent = new Intent(MainActivity.this, PocasieDetails.class);
newIntent.putExtra("idPocasie", ID);
startActivityForResult(newIntent, 3);
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(parent.getContext());
builder.setMessage("Vymazať naozaj?")
.setTitle("Mazanie ...")
.setPositiveButton("Ano", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ListView lv = (ListView) findViewById(R.id.listView);
Cursor cursor = ((CustomCursorAdapter) lv.getAdapter()).getCursor();
cursor.moveToPosition(position);
int ID = cursor.getInt(cursor.getColumnIndex(MyContrast.Pocasie.COLUMN_ID));
dbh.deletePocasie(ID);
dialog.dismiss();
Toast.makeText(MainActivity.this, "mažem", Toast.LENGTH_SHORT).show();
PripojAdapter();
}
})
.setNegativeButton("Nie", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
return false;
}
});
}
// uloži informaciu o meste, ktoré sa má zobrazovať
public void saveData(int idMesto) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(TEXT, idMesto);
editor.apply();
}
// načita informaciu o meste, ktoré sa má zobrazovať
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
prefsMesto = sharedPreferences.getInt(TEXT, 1);
}
}
|
package com.renheng.elasticjob.lite.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Inherited
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ElasticSimpleJob {
@AliasFor("cron")
public abstract String value() default "";
@AliasFor("value")
public abstract String cron() default "";
public abstract String jobName() default "";
public abstract int shardingTotalCount() default 1;
public abstract String shardingItemParameters() default "";
public abstract String jobParameter() default "";
public abstract String dataSource() default "";
public abstract String description() default "";
public abstract boolean disabled() default false;
public abstract boolean overwrite() default true;
}
|
package lecho.lib.hellocharts.model;
import android.graphics.Typeface;
/**
* Base interface for all chart data models.
*/
public interface ChartData {
/**
* Updates data by scale during animation.
*
* @param scale value from 0 to 1.0
*/
public void update(float scale);
/**
* Inform data that animation finished(data should be update with scale 1.0f).
*/
public void finish();
/**
* @see #setAxisXBottom(Axis)
*/
public Axis getAxisXBottom();
/**
* Set horizontal axis at the bottom of the chart. Pass null to remove that axis.
*
* @param axisX
*/
public void setAxisXBottom(Axis axisX);
/**
* @see #setAxisYLeft(Axis)
*/
public Axis getAxisYLeft();
/**
* Set vertical axis on the left of the chart. Pass null to remove that axis.
*
* @param axisY
*/
public void setAxisYLeft(Axis axisY);
/**
* @see #setAxisXTop(Axis)
*/
public Axis getAxisXTop();
/**
* Set horizontal axis at the top of the chart. Pass null to remove that axis.
*
* @param axisX
*/
public void setAxisXTop(Axis axisX);
/**
* @see #setAxisYRight(Axis)
*/
public Axis getAxisYRight();
/**
* Set vertical axis on the right of the chart. Pass null to remove that axis.
*
* @param axisY
*/
public void setAxisYRight(Axis axisY);
/**
* Returns color used to draw value label text.
*/
public int getValueLabelTextColor();
/**
* Set value label text color, by default Color.WHITE.
*/
public void setValueLabelsTextColor(int labelsTextColor);
/**
* Returns text size for value label in SP units.
*/
public int getValueLabelTextSize();
/**
* Set text size for value label in SP units.
*/
public void setValueLabelTextSize(int labelsTextSize);
/**
* Returns Typeface for value labels.
*
* @return Typeface or null if Typeface is not set.
*/
public Typeface getValueLabelTypeface();
/**
* Set Typeface for all values labels.
*
* @param typeface
*/
public void setValueLabelTypeface(Typeface typeface);
/**
* @see #setValueLabelBackgroundEnabled(boolean)
*/
public boolean isValueLabelBackgroundEnabled();
/**
* Set whether labels should have rectangle background. Default is true.
*/
public void setValueLabelBackgroundEnabled(boolean isValueLabelBackgroundEnabled);
/**
* @see #setValueLabelBackgroundAuto(boolean)
*/
public boolean isValueLabelBackgroundAuto();
/**
* Set false if you want to set custom color for all value labels. Default is true.
*/
public void setValueLabelBackgroundAuto(boolean isValueLabelBackgrountAuto);
/**
* @see #setValueLabelBackgroundColor(int)
*/
public int getValueLabelBackgroundColor();
/**
* Set value labels background. This value is used only if isValueLabelBackgroundAuto returns false. Default is
* green.
*/
public void setValueLabelBackgroundColor(int valueLabelBackgroundColor);
}
|
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2019 iText Group NV
Authors: iText Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: sales@itextpdf.com
*/
package com.itextpdf.html2pdf.css.w3c.css21.normal_flow;
import com.itextpdf.html2pdf.css.w3c.W3CCssTest;
import com.itextpdf.test.annotations.LogMessage;
import com.itextpdf.test.annotations.LogMessages;
@LogMessages(messages = {@LogMessage(messageTemplate = com.itextpdf.io.LogMessageConstant.RECTANGLE_HAS_NEGATIVE_OR_ZERO_SIZES)})
public class MaxWidth048Test extends W3CCssTest {
@Override
protected String getHtmlFileName() {
return "max-width-048.xht";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.